@pbvision/cloud-run-service 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.dockerignore ADDED
@@ -0,0 +1,10 @@
1
+ .dockerignore
2
+ .eslintrc.json
3
+ .gcloudignore
4
+ .git/
5
+ .gitignore
6
+ babel.config.cjs
7
+ jest.config.json
8
+ node_modules/
9
+ README.md
10
+ .vscode/
package/.eslintrc.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "root": true,
3
+ "env": {
4
+ "es2023": true,
5
+ "browser": false,
6
+ "commonjs": true,
7
+ "jest": true,
8
+ "node": true
9
+ },
10
+ "extends": [
11
+ "eslint:recommended",
12
+ "standard",
13
+ "plugin:import/recommended",
14
+ "plugin:import/errors",
15
+ "plugin:import/warnings"
16
+ ],
17
+ "plugins": [
18
+ "import"
19
+ ],
20
+ "parser": "@babel/eslint-parser",
21
+ "rules": {
22
+ "import/order": [
23
+ "error",
24
+ {
25
+ "groups": [
26
+ "builtin",
27
+ "external",
28
+ "parent",
29
+ "sibling",
30
+ "index"
31
+ ],
32
+ "alphabetize": {
33
+ "order": "asc",
34
+ "caseInsensitive": true
35
+ },
36
+ "newlines-between": "always"
37
+ }
38
+ ],
39
+ "no-var": "error",
40
+ "multiline-ternary": 1,
41
+ "object-shorthand": "error",
42
+ "import/no-unresolved": ["error", { "commonjs": true }]
43
+ },
44
+ "settings": {
45
+ "import/resolver": {
46
+ "node": {},
47
+ "webpack": {}
48
+ }
49
+ }
50
+ }
package/.gcloudignore ADDED
@@ -0,0 +1,9 @@
1
+ .eslintrc.json
2
+ .gcloudignore
3
+ .git/
4
+ .gitignore
5
+ .npmrc
6
+ babel.config.cjs
7
+ jest.config.json
8
+ node_modules/
9
+ .vscode/
@@ -0,0 +1,35 @@
1
+ name: Check PR
2
+ on:
3
+ pull_request
4
+ jobs:
5
+ check_pr:
6
+ runs-on: ubuntu-latest
7
+ permissions:
8
+ contents: read
9
+ packages: read
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ - uses: actions/setup-node@v4
13
+ with:
14
+ node-version: '20.x'
15
+ registry-url: 'https://registry.npmjs.org'
16
+ - run: yarn install --frozen-lockfile
17
+ shell: bash
18
+ env:
19
+ NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
20
+ - run: yarn lint
21
+ shell: bash
22
+ - name: 'Setup Firestore Emulator'
23
+ run: |
24
+ echo '{ "projects": { "default": "fake-for-testing-only" } }' > ./.firebaserc
25
+ echo '{ "firestore": {} }' > ./firebase.json
26
+ npm install -g firebase-tools
27
+ firebase setup:emulators:firestore
28
+ shell: bash
29
+ - name: 'Run unit tests'
30
+ run: |
31
+ echo 'yarn test-without-starting-db' > ./test.sh
32
+ chmod u+x ./test.sh
33
+ echo "process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8080'" >> ./node_modules/@pbvision/firestore-orm/environment.js
34
+ firebase emulators:exec --only firestore ./test.sh
35
+ shell: bash
@@ -0,0 +1,42 @@
1
+ name: Publish to PUBLIC NPM Package Registry
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ jobs:
6
+ publish:
7
+ if: github.repository == 'pbv-public/cloud-run-service'
8
+ runs-on: ubuntu-latest
9
+ steps:
10
+ - uses: actions/checkout@v4
11
+ with:
12
+ fetch-depth: 0
13
+ - uses: actions/setup-node@v4
14
+ with:
15
+ node-version: '20.x'
16
+ registry-url: 'https://registry.npmjs.org'
17
+ scope: '@pbvision'
18
+ - name: Publish
19
+ run: |
20
+ before=${{ github.event.before }}
21
+ after=${{ github.event.after }}
22
+ echo from ${before} to ${after}
23
+ zero='0000000000000000000000000000000000000000'
24
+ if [ "$before" = "$zero" ]; then
25
+ changed=1 # first push to this branch — always publish
26
+ else
27
+ git diff ${before} ${after} -- package.json | fgrep '"version": "' && changed=1 || changed=0
28
+ fi
29
+ if [ "$changed" = "1" ]; then
30
+ pkg=$(node -p "require('./package.json').name")
31
+ ver=$(node -p "require('./package.json').version")
32
+ if curl -fsS "https://registry.npmjs.org/${pkg}/${ver}" >/dev/null 2>&1; then
33
+ echo "${pkg}@${ver} already on npmjs, skipping publish"
34
+ else
35
+ npm publish --access public
36
+ fi
37
+ else
38
+ echo 'version was not changed; nothing to publish'
39
+ fi
40
+ shell: bash
41
+ env:
42
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
@@ -0,0 +1,9 @@
1
+ {
2
+ "recommendations": [
3
+ "dbaeumer.vscode-eslint",
4
+ "esbenp.prettier-vscode",
5
+ "standard.vscode-standard",
6
+ "streetsidesoftware.code-spell-checker",
7
+ "yzhang.markdown-all-in-one"
8
+ ]
9
+ }
@@ -0,0 +1,36 @@
1
+ {
2
+ "[javascript]": {
3
+ "editor.formatOnSave": false,
4
+ "editor.tabSize": 2
5
+ },
6
+ "[json]": {
7
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
8
+ "editor.formatOnSave": true,
9
+ "editor.tabSize": 2
10
+ },
11
+ "[markdown]": {
12
+ "editor.formatOnSave": true,
13
+ "editor.formatOnPaste": true
14
+ },
15
+ "editor.codeActionsOnSave": {
16
+ "source.fixAll.eslint": "explicit",
17
+ "source.fixAll.markdownlint": "explicit"
18
+ },
19
+ "editor.rulers": [79],
20
+ "eslint.validate": ["javascript"],
21
+ "files.eol": "\n",
22
+ "files.trimTrailingWhitespace": true,
23
+ "files.insertFinalNewline": true,
24
+ "standard.autoFixOnSave": true,
25
+ "standard.usePackageJson": true,
26
+ "cSpell.words": [
27
+ "cloudtasks",
28
+ "esbenp",
29
+ "fastify",
30
+ "firestore",
31
+ "gserviceaccount",
32
+ "INDEBUGGER",
33
+ "oidc",
34
+ "pino"
35
+ ]
36
+ }
package/Dockerfile ADDED
@@ -0,0 +1,18 @@
1
+ FROM node:20-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # install production packages first
6
+ COPY .npmrc package.json yarn.lock ./
7
+ RUN yarn install --frozen-lockfile --production
8
+
9
+ ARG PROJECT
10
+ ENV PROJECT=${PROJECT}
11
+ ARG GIT_HASH
12
+ ENV GIT_HASH=${GIT_HASH}
13
+
14
+ # copy source files second (after dependencies are installed so rebuilds are
15
+ # super fast whenever only the source code changes)
16
+ COPY src ./src/
17
+ RUN rm ./src/placeholder.js
18
+ ENTRYPOINT [ "node", "src/main.js" ]
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # Cloud Run Service library
2
+
3
+ ## Setup
4
+
5
+ 1. `yarn setup`
6
+ 1. Install recommended vscode extensions
7
+ - Open the Extensions tab in vscode
8
+ - In the filter box, type "@recommended" and press enter to search
9
+ - Make sure all recommended extensions are installed
10
+
11
+ ## Requirements
12
+
13
+ - Must run with a service account named
14
+ `cr-${process.env.SERVICE}@${process.env.PROJECT}.iam.gserviceaccount.com`
15
+ with at least these permissions (along with whatever else your service
16
+ requires):
17
+ - `roles/run.invoker` - if the service needs to call other services
18
+ - `cloudtasks.tasks.create` - if the service needs to enqueue tasks
19
+ - roles/iam.serviceAccountUser - if the tasks need to be able to invoke an
20
+ internal cloud run service (i.e., one which restricts invokers to
21
+ specific service accounts, to include this service's account)
22
+
23
+ - Environment variables:
24
+ - Required:
25
+ - `GIT_HASH` - the commit from which the current code was generated
26
+ - `K_REVISION` - provided by cloud run (the revision ID)
27
+ - Can be `localhost`
28
+ - `NODE_ENV`
29
+ - If this is `localhost` then `isLocalhost()` will return true.
30
+ - If this is `dev` then `isDev()` will return true.
31
+ - If this is `prod` then `isProd()` will return true.
32
+ - `PROJECT` - the project ID this service is running in
33
+ - Other endings are not allowed.
34
+ - `REGION` - the region this service's cloud run is located in
35
+ - `SERVICE` - the name of this service
36
+ - Optional:
37
+ - `CLOUD_RUN_HOSTNAME_SUFFIX` - the hostname of our cloud run instances in
38
+ this region, excluding the `SERVICE` name portion at the beginning. Only
39
+ required if using the `callServiceAPI()` function.
40
+ - `COOKIE_SECRET` - used to sign cookie data (cookies are disabled if omitted)
41
+ - `PORT` - defaults to 8080 if omitted
42
+ - `SENTRY_DSN` - the Sentry URL to report errors to (not used on localhost)
@@ -0,0 +1,12 @@
1
+ module.exports = {
2
+ presets: [
3
+ [
4
+ '@babel/preset-env',
5
+ {
6
+ targets: {
7
+ node: '20'
8
+ }
9
+ }
10
+ ]
11
+ ]
12
+ }
@@ -0,0 +1,76 @@
1
+ steps:
2
+ - id: set up npmrc for private package access
3
+ name: bash
4
+ args: ['-c', 'echo -e "//npm.pkg.github.com/:_authToken=$$GITHUB_TOKEN\n@your-org:registry=https://npm.pkg.github.com/" > .npmrc']
5
+ secretEnv: ['GITHUB_TOKEN']
6
+
7
+ - id: "build image"
8
+ name: "gcr.io/cloud-builders/docker"
9
+ args:
10
+ [
11
+ "build",
12
+ "--build-arg",
13
+ "PROJECT=$PROJECT_ID",
14
+ "--build-arg",
15
+ "GIT_HASH=$COMMIT_SHA",
16
+ "--tag",
17
+ "$_REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/service-$_SERVICE_NAME:$_PR_NUMBER-$SHORT_SHA",
18
+ ".",
19
+ ]
20
+
21
+ - id: "push image"
22
+ name: "gcr.io/cloud-builders/docker"
23
+ args:
24
+ [
25
+ "push",
26
+ "$_REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/service-$_SERVICE_NAME",
27
+ "--all-tags",
28
+ ]
29
+
30
+ - id: "deploy revision with tag"
31
+ name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
32
+ entrypoint: "gcloud"
33
+ args:
34
+ [
35
+ "run",
36
+ "deploy",
37
+ "$_SERVICE_NAME",
38
+ "--platform",
39
+ "managed",
40
+ "--region",
41
+ "$_REGION",
42
+ "--tag",
43
+ "pr-$_PR_NUMBER",
44
+ "--allow-unauthenticated",
45
+ "--image",
46
+ "$_REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/service-$_SERVICE_NAME:$_PR_NUMBER-$SHORT_SHA",
47
+ "--no-traffic",
48
+ ]
49
+
50
+ - id: "link revision on pull request"
51
+ name: "$_REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/deployment-previews"
52
+ secretEnv: ["GITHUB_TOKEN"]
53
+ args:
54
+ [
55
+ "set",
56
+ "--project-id",
57
+ "${PROJECT_ID}",
58
+ "--region",
59
+ "$_REGION",
60
+ "--service",
61
+ "$_SERVICE_NAME",
62
+ "--pull-request",
63
+ "$_PR_NUMBER",
64
+ "--repo-name",
65
+ "$REPO_FULL_NAME",
66
+ "--commit-sha",
67
+ "$SHORT_SHA",
68
+ ]
69
+
70
+ options:
71
+ logging: CLOUD_LOGGING_ONLY
72
+
73
+ availableSecrets:
74
+ secretManager:
75
+ - versionName: projects/$PROJECT_ID/secrets/github_token/versions/latest
76
+ env: "GITHUB_TOKEN"
@@ -0,0 +1,74 @@
1
+ steps:
2
+ - id: set up npmrc for private package access
3
+ name: bash
4
+ args: ['-c', 'echo -e "//npm.pkg.github.com/:_authToken=$$GITHUB_TOKEN\n@your-org:registry=https://npm.pkg.github.com/" > .npmrc']
5
+ secretEnv: ['GITHUB_TOKEN']
6
+
7
+ - id: "build image"
8
+ name: "gcr.io/cloud-builders/docker"
9
+ args:
10
+ [
11
+ "build",
12
+ "--build-arg",
13
+ "PROJECT=$PROJECT_ID",
14
+ "--build-arg",
15
+ "GIT_HASH=$COMMIT_SHA",
16
+ "--tag",
17
+ "$_REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/service-$_SERVICE_NAME:$COMMIT_SHA",
18
+ "--tag",
19
+ "$_REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/service-$_SERVICE_NAME:latest",
20
+ ".",
21
+ ]
22
+
23
+ - id: "push image"
24
+ name: "gcr.io/cloud-builders/docker"
25
+ args:
26
+ [
27
+ "push",
28
+ "$_REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/service-$_SERVICE_NAME",
29
+ "--all-tags",
30
+ ]
31
+
32
+ - id: "deploy revision with tag"
33
+ name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
34
+ entrypoint: "gcloud"
35
+ args:
36
+ [
37
+ "run",
38
+ "deploy",
39
+ "$_SERVICE_NAME",
40
+ "--platform",
41
+ "managed",
42
+ "--region",
43
+ "$_REGION",
44
+ "--tag",
45
+ "sha-$SHORT_SHA",
46
+ "--allow-unauthenticated",
47
+ "--image",
48
+ "$_REGION-docker.pkg.dev/$PROJECT_ID/docker-repo/service-$_SERVICE_NAME:$COMMIT_SHA",
49
+ ]
50
+
51
+ # Force the new revision to serve 100% of traffic.
52
+ - id: "ensure prod service live"
53
+ name: "gcr.io/google.com/cloudsdktool/cloud-sdk"
54
+ entrypoint: "gcloud"
55
+ args:
56
+ [
57
+ "run",
58
+ "services",
59
+ "update-traffic",
60
+ "$_SERVICE_NAME",
61
+ "--to-latest",
62
+ "--platform",
63
+ "managed",
64
+ "--region",
65
+ "$_REGION",
66
+ ]
67
+
68
+ options:
69
+ logging: CLOUD_LOGGING_ONLY
70
+
71
+ availableSecrets:
72
+ secretManager:
73
+ - versionName: projects/$PROJECT_ID/secrets/github_token/versions/latest
74
+ env: "GITHUB_TOKEN"
@@ -0,0 +1,24 @@
1
+ {
2
+ "collectCoverageFrom": ["<rootDir>/src/**/*.js"],
3
+ "coverageDirectory": "/tmp/coverage",
4
+ "coverageReporters": ["lcov", "text", "json"],
5
+ "coverageThreshold": {
6
+ "global": {
7
+ "branches": 100,
8
+ "functions": 100,
9
+ "lines": 100,
10
+ "statements": 100
11
+ }
12
+ },
13
+ "roots": ["<rootDir>/src", "<rootDir>/test"],
14
+ "modulePathIgnorePatterns": ["node_modules"],
15
+ "testPathIgnorePatterns": ["node_modules"],
16
+ "testMatch": ["<rootDir>/test/*(*/)unit-test*.js"],
17
+ "reporters": [
18
+ "@pbvision/jest-unit-test/src/custom-reporter.js",
19
+ "@pbvision/jest-unit-test/src/summary-reporter.js"
20
+ ],
21
+ "watchPathIgnorePatterns": ["node_modules"],
22
+ "verbose": false,
23
+ "noStackTrace": false
24
+ }
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@pbvision/cloud-run-service",
3
+ "version": "0.0.1",
4
+ "description": "fastify-firestore-service Web Framework on Cloud Run",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "exports": "./src/index.js",
11
+ "scripts": {
12
+ "coverage": "yarn -s start-local-db && yarn -s test --coverage",
13
+ "debug": "yarn -s start-local-db && INDEBUGGER=1 NODE_ENV=localhost PORT=8080 K_REVISION=unittest REGION=us-central1 PROJECT=xyz-dev GIT_HASH=`git rev-parse HEAD` SERVICE=tbd ./node_modules/nodemon/bin/nodemon.js --no-lazy --legacy-watch --watch ./src --watch ./test --inspect=9229 node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config=./jest.config.json --runInBand",
14
+ "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
15
+ "setup": "yarn install --frozen-lockfile",
16
+ "start-docker": "wd=`pwd`; tag=`basename $wd`; docker build --build-arg PROJECT=xyz-dev --build-arg GIT_HASH=`git rev-parse HEAD` . --tag $tag && docker run -p 127.0.0.1:8080:8080/tcp --env REGION us-central1 --env PORT=8080 --env K_REVISION=localhost --env SERVICE=tbd $tag:latest",
17
+ "start-local-db": "./node_modules/@pbvision/firestore-orm/scripts/start-local-db.sh",
18
+ "test": "yarn -s start-local-db && yarn -s test-without-starting-db",
19
+ "test-without-starting-db": "NODE_ENV=localhost PORT=8080 K_REVISION='unittest' REGION=us-central1 PROJECT=xyz-dev GIT_HASH=`git rev-parse HEAD` SERVICE=tbd node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config=./jest.config.json",
20
+ "start-local": "yarn -s start-local-db && FIRESTORE_EMULATOR_HOST=[::1]:8404 NODE_ENV=localhost PROJECT=xyz-dev REGION=us-central1 PORT=8080 K_REVISION=localhost PROJECT=xyz-dev GIT_HASH=`git rev-parse HEAD` node src/main.js",
21
+ "watch": "yarn -s test --watch"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/pbv-public/cloud-run-service"
26
+ },
27
+ "publishConfig": {
28
+ "registry": "https://registry.npmjs.org"
29
+ },
30
+ "dependencies": {
31
+ "@google-cloud/tasks": "^4.0.1",
32
+ "@pbvision/fastify-firestore-service": "^0.0.19",
33
+ "google-auth-library": "^9.4.2"
34
+ },
35
+ "devDependencies": {
36
+ "@babel/core": "^7.17.12",
37
+ "@babel/eslint-parser": "^7.17.0",
38
+ "@babel/preset-env": "^7.17.12",
39
+ "@pbvision/jest-unit-test": "^0.2.3",
40
+ "babel-loader": "^9.1.3",
41
+ "eslint": "^8.22.0",
42
+ "eslint-config-standard": "17.1.0",
43
+ "eslint-import-resolver-webpack": "^0.13.8",
44
+ "eslint-plugin-import": "^2.22.0",
45
+ "eslint-plugin-n": "^16.6.2",
46
+ "eslint-plugin-node": "^11.1.0",
47
+ "eslint-plugin-promise": "^6.0.0",
48
+ "jest": "^29.7.0",
49
+ "standard": "^17.1.0",
50
+ "superagent": "^8",
51
+ "superagent-defaults": "^0.1.14",
52
+ "supertest": "^6.3.4",
53
+ "webpack": "^5.89.0"
54
+ },
55
+ "standard": {
56
+ "envs": [
57
+ "jest"
58
+ ],
59
+ "globals": [
60
+ "fail"
61
+ ],
62
+ "ignore": [
63
+ "**/node_modules/**"
64
+ ],
65
+ "parser": "@babel/eslint-parser"
66
+ }
67
+ }
package/src/app.js ADDED
@@ -0,0 +1,32 @@
1
+ import { makeService } from '@pbvision/fastify-firestore-service'
2
+
3
+ import { port } from './port.js'
4
+ import { isProd } from './utils.js'
5
+
6
+ export async function makePBVService (components, customizePinoOpts) {
7
+ const isProdEnv = isProd()
8
+ return makeService({
9
+ service: process.env.SERVICE,
10
+ components,
11
+ cookie: {
12
+ secret: process.env.COOKIE_SECRET
13
+ },
14
+ healthCheck: {
15
+ path: '/_healthcheck'
16
+ },
17
+ latencyTracker: {
18
+ disabled: isProdEnv
19
+ },
20
+ logging: {
21
+ customizePinoOpts,
22
+ reportErrorDetail: !isProdEnv,
23
+ reportAllErrors: true,
24
+ sentryDSN: process.env.sentryDSN
25
+ },
26
+ swagger: {
27
+ disabled: isProdEnv,
28
+ servers: [`http://localhost:${port}`],
29
+ routePrefix: '/app/docs'
30
+ }
31
+ })
32
+ }
@@ -0,0 +1,27 @@
1
+ // add helper method to call APIs on this or other services; if the service is
2
+ // internal then we'll make the request with our authorization token (only
3
+ // works if this service has been granted access to the target service!)
4
+ import { GoogleAuth } from 'google-auth-library'
5
+
6
+ import { getServiceHost } from './utils.js'
7
+
8
+ const auth = new GoogleAuth()
9
+
10
+ // This function will be added to the API class.
11
+ export async function callServiceAPI ({
12
+ path, service: serviceName,
13
+ body = undefined, qsParams = undefined,
14
+ method = 'POST', headers = {}, isServiceInternal = true
15
+ }) {
16
+ const host = getServiceHost(serviceName)
17
+ // istanbul ignore next
18
+ const protocol = host === 'localhost' ? 'https' : 'http'
19
+ const url = `${protocol}://${host}${path}`
20
+ if (isServiceInternal) {
21
+ const targetAudience = `https://${host}/`
22
+ const client = await auth.getIdTokenClient(targetAudience)
23
+ const token = await client.idTokenProvider.fetchIdToken(targetAudience)
24
+ headers.Authorization = `Bearer ${token}`
25
+ }
26
+ return this.callAPI({ method, headers, url, body, qsParams })
27
+ }
package/src/index.js ADDED
@@ -0,0 +1,9 @@
1
+ import { runService } from './main.js'
2
+ import { enqueueCloudTask } from './tasks.js'
3
+ import * as utils from './utils.js'
4
+
5
+ export {
6
+ enqueueCloudTask,
7
+ runService,
8
+ utils
9
+ }
package/src/main.js ADDED
@@ -0,0 +1,82 @@
1
+ import assert from 'node:assert'
2
+
3
+ import { API } from '@pbvision/fastify-firestore-service'
4
+
5
+ import { makePBVService } from './app.js'
6
+ import { callServiceAPI } from './call-service-api.js'
7
+ import { port } from './port.js'
8
+
9
+ API.prototype.callServiceAPI = callServiceAPI
10
+
11
+ let service
12
+ const project = process.env.PROJECT
13
+
14
+ function verifyEnvironmentVariables () {
15
+ const requiredEnvKeys = [
16
+ 'GIT_HASH', 'K_REVISION', 'NODE_ENV', 'PROJECT', 'REGION', 'SERVICE']
17
+ for (const k of requiredEnvKeys) {
18
+ assert(process.env[k], `${k} environment variable must be set`)
19
+ }
20
+ assert(['localhost', 'dev', 'prod'].indexOf(process.env.NODE_ENV) !== -1,
21
+ `invalid NODE_ENV: ${process.env.NODE_ENV}`)
22
+ }
23
+
24
+ function makeCustomizeLoggingOptionsFunction () {
25
+ return options => {
26
+ options.formatters = {
27
+ level (label) {
28
+ return { severity: label }
29
+ },
30
+ // set messageKey to "message" for automatic parsing by GCP logs
31
+ messageKey: 'message'
32
+ }
33
+ const originalReqSerializer = options.serializers.req
34
+ options.serializers.req = req => {
35
+ const reqLog = originalReqSerializer(req)
36
+
37
+ // include the trace ID so logging can coordinate multiple logs from the
38
+ // same request per: https://github.com/GoogleCloudPlatform/cloud-run-microservice-template-nodejs/blob/main/utils/logging.js
39
+ const traceHeader = req.headers['X-Cloud-Trace-Context']
40
+ let trace
41
+ // istanbul ignore if
42
+ if (traceHeader) {
43
+ const [traceId] = traceHeader.split('/')
44
+ trace = `projects/${project}/traces/${traceId}`
45
+ reqLog['logging.googleapis.com/trace'] = trace
46
+ }
47
+ return reqLog
48
+ }
49
+ return options
50
+ }
51
+ }
52
+
53
+ export async function makeService (components = {}) {
54
+ verifyEnvironmentVariables()
55
+ return makePBVService(components, makeCustomizeLoggingOptionsFunction())
56
+ }
57
+
58
+ // istanbul ignore next
59
+ export async function runService (components) {
60
+ if (process.env.K_REVISION !== 'unittest') {
61
+ // if the instance tells us it will shutdown, try to shut down gracefully (for
62
+ // example flushing logs)
63
+ process.on('SIGTERM', () => {
64
+ if (!service) {
65
+ return
66
+ }
67
+ // cloud run sends SIGTERM 10sec before killing the instance, so give the
68
+ // instance a little more time to finish any current requests then close
69
+ // the fastify instance (which kills any remaining requests, and should
70
+ // flush the logs and other clean up, if time permits)
71
+ setTimeout(() =>
72
+ service.close().then(() => {
73
+ console.log('successfully closed!')
74
+ }, (err) => {
75
+ console.log('an error happened', err)
76
+ }), 7000)
77
+ })
78
+ // start the server
79
+ service = await makeService(components)
80
+ service.listen({ port, host: '0.0.0.0' })
81
+ }
82
+ }
@@ -0,0 +1,37 @@
1
+ // APIs in this file are not included in Docker builds so they never are
2
+ // shipped to Cloud Run. They only exist for local testing.
3
+ import assert from 'node:assert'
4
+
5
+ import { API } from '@pbvision/fastify-firestore-service'
6
+ import S from '@pbvision/schema'
7
+
8
+ import { isUnitTesting, now } from './utils.js'
9
+
10
+ export class TestAPI extends API {
11
+ static METHOD = 'GET'
12
+ static PATH = '/time'
13
+ static DESC = 'Just for testing'
14
+ static RESPONSE = {
15
+ epoch: S.int
16
+ }
17
+
18
+ async computeResponse () {
19
+ return { epoch: now() }
20
+ }
21
+ }
22
+
23
+ export class TestCallServiceAPI extends API {
24
+ static PATH = '/callService'
25
+ static DESC = 'This is used by unit tests only to test callServiceAPI.'
26
+ static BODY = S.obj()
27
+ static RESPONSE = { code: S.int, body: S.str }
28
+
29
+ async computeResponse () {
30
+ assert(isUnitTesting())
31
+ const resp = await this.callServiceAPI(this.req.body)
32
+ return {
33
+ code: resp.code,
34
+ body: typeof resp.data === 'object' ? JSON.stringify(resp.data) : (resp.data ?? '')
35
+ }
36
+ }
37
+ }
package/src/port.js ADDED
@@ -0,0 +1,2 @@
1
+ // istanbul ignore next
2
+ export const port = process.env.PORT ?? 8080
package/src/tasks.js ADDED
@@ -0,0 +1,72 @@
1
+ import { CloudTasksClient } from '@google-cloud/tasks'
2
+
3
+ import { getServiceHost } from './utils.js'
4
+
5
+ const tasksClient = new CloudTasksClient()
6
+
7
+ /**
8
+ * Add a Task to a Cloud Tasks queue.
9
+ *
10
+ * The task will be routed to the internal API service on a path that matches
11
+ * the queue name (with hyphens replaced by underscores).
12
+ *
13
+ * @param {Object} task the task to enqueue
14
+ * @param {string} queue the name of the queue to add the task to
15
+ * @param {any} payload the data to convert to JSON add send as the task's body
16
+ * @param {string} [name] if provided, a name that is reused (on the same queue)
17
+ * within about an hour will be rejected (TaskNameAlreadyExistsError)
18
+ * @param {string} [service="internal"] the service name that the task request
19
+ * will be routed to
20
+ * @param {boolean} [ignoreNameAlreadyUsedError=false] if true, no error is
21
+ * thrown due to a name already having been used
22
+ * @returns {boolean} true if a new task was added; false if the task name was
23
+ * already recently used (no new task added, but a task was recently added
24
+ * with this name)
25
+ */
26
+ export async function enqueueCloudTask ({
27
+ queue, payload,
28
+ service = 'internal',
29
+ name = undefined, ignoreNameAlreadyUsedError = false
30
+ }) {
31
+ const parent = tasksClient.queuePath(
32
+ process.env.PROJECT, process.env.REGION, queue)
33
+ const task = {
34
+ httpRequest: {
35
+ headers: {
36
+ 'Content-Type': 'application/json'
37
+ },
38
+ httpMethod: 'POST',
39
+ url: `https://${getServiceHost(service)}/${queue.replace(/-/g, '_')}`,
40
+ body: Buffer.from(JSON.stringify(payload)).toString('base64'),
41
+ oidcToken: {
42
+ serviceAccountEmail: `cr-${process.env.SERVICE}@${process.env.PROJECT}.iam.gserviceaccount.com`
43
+ }
44
+ }
45
+ }
46
+ if (name) {
47
+ const fqName = tasksClient.taskPath(process.env.PROJECT, process.env.REGION, queue, name)
48
+ task.name = fqName
49
+ }
50
+ const request = { parent, task }
51
+ try {
52
+ await tasksClient.createTask(request)
53
+ return true
54
+ } catch (e) {
55
+ if (e.code === 6 && e.message.startsWith('6 ALREADY_EXISTS')) {
56
+ if (ignoreNameAlreadyUsedError) {
57
+ return false
58
+ } else {
59
+ throw new TaskNameAlreadyExistsError(name, e)
60
+ }
61
+ }
62
+ throw e
63
+ }
64
+ }
65
+
66
+ export class TaskNameAlreadyExistsError extends Error {
67
+ constructor (name, e) {
68
+ super(`task name already used recently: ${name}`)
69
+ this.taskName = name
70
+ this.originalError = e
71
+ }
72
+ }
package/src/utils.js ADDED
@@ -0,0 +1,40 @@
1
+ import assert from 'node:assert'
2
+
3
+ import { port as portForThisService } from './port.js'
4
+
5
+ export function getServiceHost (serviceName) {
6
+ if (isLocalhost()) {
7
+ if (process.env.SERVICE === serviceName) {
8
+ return `localhost:${portForThisService}`
9
+ }
10
+ const portMapping = JSON.parse(process.env.LOCAL_SERVICE_PORT_MAP ?? 'null')
11
+ const port = portMapping[serviceName]
12
+ assert(port, `unknown service or missing port for localhost ${serviceName}`)
13
+ return `localhost:${port}`
14
+ } else {
15
+ return serviceName + process.env.CLOUD_RUN_HOSTNAME_SUFFIX
16
+ }
17
+ }
18
+
19
+ export function isLocalhost () {
20
+ assert(process.env.NODE_ENV)
21
+ return process.env.NODE_ENV === 'localhost'
22
+ }
23
+
24
+ export function isUnitTesting () {
25
+ const ret = process.env.K_REVISION === 'unittest'
26
+ assert(!ret || isLocalhost(), 'must on localhost if in unit tests')
27
+ return ret
28
+ }
29
+
30
+ export function isProd () {
31
+ assert(process.env.NODE_ENV)
32
+ return process.env.NODE_ENV === 'prod'
33
+ }
34
+
35
+ export function isDev () {
36
+ assert(process.env.NODE_ENV)
37
+ return process.env.NODE_ENV === 'dev'
38
+ }
39
+
40
+ export const now = () => Math.floor(new Date().getTime() / 1000)
@@ -0,0 +1,13 @@
1
+ import { BaseAppTest, BaseTest, runTests } from '../node_modules/@pbvision/fastify-firestore-service/test/base-test.js'
2
+ const { TestAPI, TestCallServiceAPI } = await import('../src/placeholder.js')
3
+
4
+ export {
5
+ BaseTest, runTests
6
+ }
7
+
8
+ export class AppTest extends BaseAppTest {
9
+ async getMakeServiceFunc () {
10
+ const { makeService } = await import('../src/main.js')
11
+ return () => makeService({ TestAPI, TestCallServiceAPI })
12
+ }
13
+ }
@@ -0,0 +1,96 @@
1
+ import { jest } from '@jest/globals'
2
+ import { GoogleAuth } from 'google-auth-library'
3
+
4
+ import { AppTest, runTests } from './base-test.js'
5
+
6
+ class TestCallServiceAPI extends AppTest {
7
+ async beforeAll () {
8
+ await super.beforeAll()
9
+
10
+ // mock GoogleAuth because we can't actually get a token during testing
11
+ this.fetchIdToken = jest.fn().mockReturnValue('fake-token')
12
+ jest.spyOn(GoogleAuth.prototype, 'getIdTokenClient').mockImplementation(() => ({
13
+ idTokenProvider: {
14
+ fetchIdToken: this.fetchIdToken
15
+ }
16
+ }))
17
+ }
18
+
19
+ async beforeEach () {
20
+ await super.beforeEach()
21
+ // mock using node-fetch to request an API
22
+ this.fetchMock.mockResp()
23
+ this.fetchIdToken.mockClear()
24
+ GoogleAuth.prototype.getIdTokenClient.mockClear()
25
+ }
26
+
27
+ async afterAll () {
28
+ await super.afterAll()
29
+ jest.restoreAllMocks()
30
+ }
31
+
32
+ async check (args, respBody = '', expCode = 200, expPort = 8080) {
33
+ const result = await this.app.post('/callService').send(args).expect(200)
34
+ const resp = result.body
35
+ expect(resp.code).toBe(expCode)
36
+ expect(resp.body).toEqual(respBody)
37
+
38
+ const shouldHaveToken = args.isServiceInternal ?? true
39
+ const expHeaders = args.headers ?? {}
40
+ if (shouldHaveToken) {
41
+ expHeaders.Authorization = 'Bearer fake-token'
42
+ }
43
+ expect(this.fetchMock).toHaveBeenCalledWith(
44
+ `http://localhost:${expPort}${args.path}`, {
45
+ body: args.body,
46
+ headers: expHeaders,
47
+ method: args.method ?? 'POST',
48
+ compress: false
49
+ })
50
+
51
+ // make sure Google Auth was called with appropriate arguments (or not, if
52
+ // this wasn't an internal call)
53
+ if (shouldHaveToken) {
54
+ const targetAudience = `https://localhost:${expPort}/`
55
+ expect(GoogleAuth.prototype.getIdTokenClient).toHaveBeenCalledWith(targetAudience)
56
+ expect(this.fetchIdToken).toHaveBeenCalledWith(targetAudience)
57
+ } else {
58
+ expect(GoogleAuth.prototype.getIdTokenClient).not.toHaveBeenCalled()
59
+ }
60
+ }
61
+
62
+ async testServiceCallingItsOwnInternalAPI () {
63
+ await this.check({
64
+ service: process.env.SERVICE,
65
+ path: '/someAPI',
66
+ isServiceInternal: true
67
+ })
68
+ }
69
+
70
+ async testServiceCallingItsOwnPublicAPI () {
71
+ await this.check({
72
+ service: process.env.SERVICE,
73
+ path: '/someAPI',
74
+ isServiceInternal: false
75
+ })
76
+ }
77
+
78
+ async testServiceCallingAnotherOneOfItsAPIs () {
79
+ this.fetchMock.mockResp({ x: 3 })
80
+ await this.check({
81
+ service: process.env.SERVICE,
82
+ path: '/x/y/z'
83
+ }, JSON.stringify({ x: 3 }))
84
+ }
85
+
86
+ async testServiceCallingAnotherService () {
87
+ process.env.LOCAL_SERVICE_PORT_MAP = JSON.stringify({ notMe: 9999 })
88
+ this.fetchMock.mockResp('test resp', 222)
89
+ await this.check({
90
+ service: 'notMe',
91
+ path: '/x'
92
+ }, 'test resp', 222, 9999)
93
+ }
94
+ }
95
+
96
+ runTests(TestCallServiceAPI)
@@ -0,0 +1,10 @@
1
+ import { AppTest, runTests } from './base-test'
2
+
3
+ class PlaceholderTest extends AppTest {
4
+ async testTime () {
5
+ const ret = await this.app.get('/time').expect(200)
6
+ expect(Object.keys(ret.body)).toEqual(['epoch'])
7
+ }
8
+ }
9
+
10
+ runTests(PlaceholderTest)
@@ -0,0 +1,104 @@
1
+ import { CloudTasksClient } from '@google-cloud/tasks'
2
+ import { jest } from '@jest/globals'
3
+
4
+ import { enqueueCloudTask } from '../src/tasks.js'
5
+
6
+ import { BaseTest, runTests } from './base-test.js'
7
+
8
+ class TestTasks extends BaseTest {
9
+ async beforeAll () {
10
+ await super.beforeAll()
11
+
12
+ process.env.LOCAL_SERVICE_PORT_MAP = JSON.stringify({ internal: 8888 })
13
+
14
+ // mock GoogleAuth because we can't actually get a token during testing
15
+ this.createTaskReturnValue = new Promise(resolve => resolve())
16
+ jest.spyOn(CloudTasksClient.prototype, 'createTask').mockImplementation(
17
+ () => this.createTaskReturnValue)
18
+ }
19
+
20
+ async beforeEach () {
21
+ await super.beforeEach()
22
+ CloudTasksClient.prototype.createTask.mockClear()
23
+ }
24
+
25
+ async afterAll () {
26
+ await super.afterAll()
27
+ jest.restoreAllMocks()
28
+ }
29
+
30
+ async check (args, taskExpectations = {}, expRejectionMsg = null) {
31
+ const promise = enqueueCloudTask({
32
+ queue: 'test-queue',
33
+ ...args
34
+ })
35
+ if (expRejectionMsg) {
36
+ await expect(promise).rejects.toThrow(expRejectionMsg)
37
+ } else {
38
+ await promise
39
+ }
40
+ expect(CloudTasksClient.prototype.createTask).toHaveBeenCalledWith({
41
+ // assuming values for project (xyz-dev) and region (us-central1) and
42
+ // service (tbd)
43
+ parent: 'projects/xyz-dev/locations/us-central1/queues/test-queue',
44
+ task: {
45
+ httpRequest: {
46
+ body: Buffer.from(JSON.stringify(args.payload)).toString('base64'),
47
+ headers: { 'Content-Type': 'application/json' },
48
+ httpMethod: 'POST',
49
+ oidcToken: {
50
+ serviceAccountEmail: 'cr-tbd@xyz-dev.iam.gserviceaccount.com'
51
+ },
52
+ url: 'https://localhost:8888/test_queue'
53
+ },
54
+ ...taskExpectations
55
+ }
56
+ })
57
+ }
58
+
59
+ async testEnqueueTask () {
60
+ await this.check({ payload: { x: 3 } })
61
+ }
62
+
63
+ async testEnqueueTaskWithName () {
64
+ await this.check(
65
+ { name: 'x', payload: { x: 3 } },
66
+ { name: 'projects/xyz-dev/locations/us-central1/queues/test-queue/tasks/x' })
67
+ }
68
+
69
+ async testEnqueueTaskWithNameThatWasRecentlyUsedNOTOkay () {
70
+ this.createTaskReturnValue = new Promise((resolve, reject) => {
71
+ const err = new Error('6 ALREADY_EXISTS and other random details')
72
+ err.code = 6
73
+ reject(err)
74
+ })
75
+ await this.check(
76
+ { name: 'x', payload: { x: 3 }, ignoreNameAlreadyUsedError: true },
77
+ { name: 'projects/xyz-dev/locations/us-central1/queues/test-queue/tasks/x' })
78
+ }
79
+
80
+ async testEnqueueTaskWithNameThatWasRecentlyUsedAndThatsOkay () {
81
+ this.createTaskReturnValue = new Promise((resolve, reject) => {
82
+ const err = new Error('6 ALREADY_EXISTS and other random details')
83
+ err.code = 6
84
+ reject(err)
85
+ })
86
+ await this.check(
87
+ { name: 'x', payload: { x: 3 } },
88
+ { name: 'projects/xyz-dev/locations/us-central1/queues/test-queue/tasks/x' },
89
+ 'task name already used recently: x')
90
+ }
91
+
92
+ async testEnqueueTaskThrowsUnknownExceptions () {
93
+ this.createTaskReturnValue = new Promise((resolve, reject) => {
94
+ const err = new Error('ALREADY_EXISTS but not in right format')
95
+ reject(err)
96
+ })
97
+ await this.check(
98
+ { name: 'x', payload: { x: 3 } },
99
+ { name: 'projects/xyz-dev/locations/us-central1/queues/test-queue/tasks/x' },
100
+ 'not in right format')
101
+ }
102
+ }
103
+
104
+ runTests(TestTasks)
@@ -0,0 +1,51 @@
1
+ import { jest } from '@jest/globals'
2
+
3
+ import { BaseTest, runTests } from '../node_modules/@pbvision/fastify-firestore-service/test/base-test.js'
4
+ import { port } from '../src/port.js'
5
+ import { getServiceHost, isDev, isLocalhost, isProd } from '../src/utils.js'
6
+
7
+ const ORIG_ENV = process.env
8
+
9
+ class TestUtils extends BaseTest {
10
+ beforeEach () {
11
+ jest.resetModules()
12
+ process.env = { ...ORIG_ENV }
13
+ }
14
+
15
+ afterEach () {
16
+ process.env = ORIG_ENV
17
+ }
18
+
19
+ testEnv () {
20
+ expect(process.env.K_REVISION).toBe('unittest')
21
+ expect(process.env.NODE_ENV).toBe('localhost')
22
+ expect(isLocalhost()).toBe(true)
23
+ expect(isProd()).toBe(false)
24
+ expect(isDev()).toBe(false)
25
+
26
+ process.env.NODE_ENV = 'dev'
27
+ expect(isLocalhost()).toBe(false)
28
+ expect(isProd()).toBe(false)
29
+ expect(isDev()).toBe(true)
30
+
31
+ process.env.NODE_ENV = 'prod'
32
+ expect(isLocalhost()).toBe(false)
33
+ expect(isProd()).toBe(true)
34
+ expect(isDev()).toBe(false)
35
+ }
36
+
37
+ testGetServiceHost () {
38
+ expect(getServiceHost(process.env.SERVICE)).toBe(`localhost:${port}`)
39
+ expect(() => getServiceHost('unknown')).toThrow()
40
+ process.env.LOCAL_SERVICE_PORT_MAP = JSON.stringify({ unknown: 8088 })
41
+ expect(getServiceHost('unknown')).toBe('localhost:8088')
42
+ expect(() => getServiceHost('actually_unknown')).toThrow()
43
+
44
+ process.env.NODE_ENV = 'dev'
45
+ const testSuffix = '-tbd-uc.a.run.app'
46
+ process.env.CLOUD_RUN_HOSTNAME_SUFFIX = testSuffix
47
+ expect(getServiceHost('unknown')).toBe('unknown' + testSuffix)
48
+ }
49
+ }
50
+
51
+ runTests(TestUtils)