Repository navigation
321 lines (298 loc) · 13.7 KB
/
Copy pathlambda-tests.yml
File metadata and controls
321 lines (298 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
name: Lambda Tests
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
merge_group:
branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: branch_dev
POSTGRES_PASSWORD: password
POSTGRES_DB: branch_db
ports:
- 5432:5432
options: >-
--health-cmd="pg_isready"
--health-interval=10s
--health-timeout=5s
--health-retries=5
strategy:
fail-fast: false
matrix:
lambda:
- apps/backend/lambdas/auth/
- apps/backend/lambdas/donors/
- apps/backend/lambdas/expenditures/
- apps/backend/lambdas/projects/
- apps/backend/lambdas/reports/
- apps/backend/lambdas/users/
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Build the schema and seed
working-directory: apps/backend/db
run: npm ci --no-audit --no-fund && npm run reset
env:
DATABASE_URL: postgres://branch_dev:password@localhost:5432/branch_db
- name: Build shared packages
uses: ./.github/actions/build-shared-packages
- name: Install dependencies
working-directory: ${{ matrix.lambda }}
run: npm ci --legacy-peer-deps
- name: Run tests
working-directory: ${{ matrix.lambda }}
run: |
LAMBDA_NAME=$(basename ${{ matrix.lambda }})
npm run dev &
sleep 5
curl --fail --retry 5 --retry-delay 2 http://localhost:3000/${LAMBDA_NAME}/health
npm test
env:
# No ?options=-csearch_path: the lambdas schema-qualify every query via
# the generated "branch.*" DB keys, and the migrator sets search_path on
# its own connections.
DATABASE_URL: postgres://branch_dev:password@localhost:5432/branch_db
COGNITO_USER_POOL_ID: ${{ secrets.COGNITO_USER_POOL_ID }}
COGNITO_CLIENT_ID: ${{ secrets.COGNITO_CLIENT_ID }}
AWS_REGION: us-east-2
# Cheap checks that do not earn their own runners: migration guards
# (git only), shared-package tests, and a from-scratch migrate+types
# drift check. Sequential on one runner; the lambda matrix stays parallel.
checks:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_USER: branch_dev
POSTGRES_PASSWORD: password
POSTGRES_DB: branch_db
ports:
- 5432:5432
options: >-
--health-cmd="pg_isready"
--health-interval=10s
--health-timeout=5s
--health-retries=5
env:
DATABASE_URL: postgres://branch_dev:password@localhost:5432/branch_db
DIR: apps/backend/db/migrations
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
# push-to-main has nothing meaningful to compare against; resolving to ""
# makes the guards no-op WITHOUT skipping the job, so the lambda-tests gate
# (which requires result == 'success') still passes.
- name: Resolve base sha
id: base
run: |
case "${{ github.event_name }}" in
pull_request) base='${{ github.event.pull_request.base.sha }}' ;;
merge_group) base='${{ github.event.merge_group.base_sha }}' ;;
*) base='' ;;
esac
echo "sha=$base" >> "$GITHUB_OUTPUT"
# Keyed by version, not path: that is what Flyway's history pins.
- name: Applied migrations are immutable
if: steps.base.outputs.sha != ''
env:
BASE: ${{ steps.base.outputs.sha }}
run: |
set -euo pipefail
MB=$(git merge-base "$BASE" HEAD)
TAB=$(printf '\t')
# version<TAB>blob<TAB>name, sorted because `join` requires sorted input.
list() {
git ls-tree -r "$1" -- "$DIR" | while read -r _ _ sha path; do
name=$(basename "$path")
case "$name" in *.sql) ;; *) continue ;; esac
version=$(printf '%s' "$name" | sed -E 's/^V?0*([0-9]+)_+.*/\1/')
printf '%s\t%s\t%s\n' "$version" "$sha" "$name"
done | sort
}
list "$MB" > "$RUNNER_TEMP/was.tsv"
list HEAD > "$RUNNER_TEMP/now.tsv"
fail=0
gone=$(join -t"$TAB" -v1 -j1 "$RUNNER_TEMP/was.tsv" "$RUNNER_TEMP/now.tsv" | cut -f3)
if [ -n "$gone" ]; then
echo "::error::deleted, but already run on production -- add a NEW migration that undoes it: $(echo $gone)"
fail=1
fi
# Rename check only for V-names: adopting Flyway renamed every file once.
join -t"$TAB" -j1 "$RUNNER_TEMP/was.tsv" "$RUNNER_TEMP/now.tsv" > "$RUNNER_TEMP/both.tsv"
awk -F'\t' -v dir="$DIR" '
$2 != $4 {
printf "::error file=%s/%s::contents changed. Flyway checksums every applied migration, so this fails the next deploy. Add a NEW migration that fixes the old one.\n", dir, $5
bad = 1
}
$3 ~ /^V/ && $3 != $5 {
printf "::error file=%s/%s::renamed from %s. Production'"'"'s schema history records the old name, and Flyway rejects the mismatch.\n", dir, $5, $3
bad = 1
}
END { exit bad }
' "$RUNNER_TEMP/both.tsv" || fail=1
exit $fail
- name: New migrations must be named correctly
if: steps.base.outputs.sha != ''
env:
BASE: ${{ steps.base.outputs.sha }}
run: |
set -euo pipefail
export LC_ALL=C
MB=$(git merge-base "$BASE" HEAD)
added=$(git diff --diff-filter=A --name-only "$MB" HEAD -- "$DIR" | xargs -r -n1 basename | sort || true)
last=$(git ls-tree -r --name-only "$MB" -- "$DIR" | xargs -r -n1 basename | sort | tail -1 || true)
fail=0
for f in $added; do
# Flyway's per-script config, e.g. executeInTransaction=false.
case "$f" in
*.sql.conf)
[ -f "$DIR/${f%.conf}" ] || { echo "::error file=$DIR/$f::no ${f%.conf} beside it"; fail=1; }
continue ;;
esac
if ! echo "$f" | grep -qE '^V(0000|[0-9]{14})__[a-z0-9_]+\.sql$'; then
echo "::error file=$DIR/$f::name must be VYYYYMMDDHHMMSS__lower_snake_case.sql -- use 'make new-migration NAME=...' so it is generated for you"
fail=1
fi
# Warning only: outOfOrder is set at runtime.
if [ -n "${last:-}" ] && [ "$f" \< "$last" ]; then
echo "::warning file=$DIR/$f::sorts before $last, which is already on main, so it will be applied out of order. Renaming it to a current UTC timestamp keeps the history readable."
fi
done
exit $fail
- name: No statements that would break the deployed code
if: steps.base.outputs.sha != ''
env:
BASE: ${{ steps.base.outputs.sha }}
run: |
set -euo pipefail
MB=$(git merge-base "$BASE" HEAD)
files=$(git diff --diff-filter=A --name-only "$MB" HEAD -- "$DIR" || true)
fail=0
for f in $files; do
[ -f "$f" ] || continue
# '-- allow-destructive: <reason>' opts a file out, deliberately loudly.
# Read from the raw file: this opt-out is itself a comment.
if grep -qi '^-- allow-destructive:' "$f"; then
echo "::warning file=$f::opted out of the destructive-SQL check"
continue
fi
# Scan SQL, not prose. `make new-migration` scaffolds a header that
# says "CREATE INDEX CONCURRENTLY / VACUUM will not work here", and
# matching that failed every generated migration. Blanking comments
# rather than dropping the lines keeps grep -n line numbers honest.
sql=$(sed 's/--.*//' "$f")
if printf '%s\n' "$sql" | grep -inE '\b(DROP[[:space:]]+SCHEMA|DROP[[:space:]]+DATABASE|TRUNCATE|DROP[[:space:]]+TABLE|DROP[[:space:]]+COLUMN)\b'; then
echo "::error file=$f::destructive statement. Migrations run against production BEFORE the new lambda code deploys, so the currently deployed code would hit the changed schema. See the expand/contract rules in apps/backend/db/README.md. Add '-- allow-destructive: <reason>' only for a contract-phase migration whose expand phase is already live."
fail=1
fi
if printf '%s\n' "$sql" | grep -inE 'CONCURRENTLY'; then
echo "::error file=$f::CONCURRENTLY cannot run inside a transaction, and Flyway wraps each migration in one. This database is tiny -- use a plain CREATE INDEX."
fail=1
fi
if printf '%s\n' "$sql" | grep -inE '^[[:space:]]*INSERT[[:space:]]+INTO[[:space:]]+(branch\.)?users\b'; then
echo "::warning file=$f::inserting users in a migration puts rows in PRODUCTION. Seeded users with a NULL cognito_sub are claimable by POST /auth/register, so this can hand someone an account. Dev seed rows belong in apps/backend/db/seed.sql."
fi
done
exit $fail
- name: Aurora DSQL compatibility
if: steps.base.outputs.sha != ''
env:
BASE: ${{ steps.base.outputs.sha }}
run: |
set -euo pipefail
MB=$(git merge-base "$BASE" HEAD)
files=$(git diff --diff-filter=AM --name-only "$MB" HEAD -- "$DIR" | grep '\.sql$' || true)
[ -n "$files" ] || { echo "no new or changed migrations"; exit 0; }
npm install --prefix "$RUNNER_TEMP/dsql-lint" --no-audit --no-fund @aws/dsql-lint@0.2.20
lint=$RUNNER_TEMP/dsql-lint/node_modules/@aws/dsql-lint/bin/dsql-lint
fail=0
for f in $files; do
[ -f "$f" ] || continue
echo "--- $f"
sed 's/${async}/ASYNC/g' "$f" > "$RUNNER_TEMP/$(basename "$f")"
node "$lint" "$RUNNER_TEMP/$(basename "$f")" || fail=1
# DSQL allows one DDL per transaction and Flyway runs each file as one; only the squash opts out.
[ "$(basename "$f")" = V0000__baseline_schema.sql ] && continue
stmts=$(sed -e 's/--.*//' "$f" | tr '\n' ' ' | sed -E 's/\$\$[^$]*\$\$//g' | tr ';' '\n')
ddl=$(printf '%s\n' "$stmts" | grep -ciE '^[[:space:]]*(CREATE|ALTER|DROP|COMMENT|GRANT|REVOKE)[[:space:]]' || true)
dml=$(printf '%s\n' "$stmts" | grep -ciE '^[[:space:]]*(INSERT|UPDATE|DELETE|WITH)[[:space:]]' || true)
if [ "$ddl" -gt 1 ] || { [ "$ddl" -gt 0 ] && [ "$dml" -gt 0 ]; }; then
echo "::error file=$f::$ddl DDL and $dml DML statements. Aurora DSQL runs one DDL per transaction, and never with DML: split this into one migration per statement."
fail=1
fi
done
exit $fail
- name: Build and test shared packages
uses: ./.github/actions/build-shared-packages
with:
test: true
- name: Install db tooling
run: npm ci --prefix apps/backend/db --no-audit --no-fund
- name: Apply every migration from scratch
run: npm run migrate --prefix apps/backend/db
- name: Schema history must be clean afterwards
run: |
set -o pipefail
npm run --silent migrate:info --prefix apps/backend/db -- -outputType=json > info.json
pending=$(jq '[.migrations[] | select(.state == "Pending")] | length' info.json)
if [ "$pending" != '0' ]; then
echo "::error::$pending migration(s) still pending after a successful migrate run"
jq -r '.migrations[] | select(.state == "Pending") | .filepath' info.json
exit 1
fi
- name: Re-running migrations must be a no-op
run: npm run migrate --prefix apps/backend/db
- name: Applied migrations must still match their checksums
run: npm run migrate:validate --prefix apps/backend/db
- name: Seeds must apply on top of the migrated schema
run: |
npm run fingerprint --prefix apps/backend/db
npm run seed --prefix apps/backend/db
# Drift check: the committed types must be what these migrations produce.
- name: Committed types must match the migrations
run: |
cp shared/types/db-types.d.ts /tmp/committed.d.ts
npm run types --prefix apps/backend/db
if ! diff -u /tmp/committed.d.ts shared/types/db-types.d.ts; then
echo "::error::shared/types/db-types.d.ts is stale. The Schema Change Checks workflow pushes a fix to this PR automatically -- wait for its commit, then this check goes green. Or run 'make types' in apps/backend and commit the result."
exit 1
fi
# NOTE: do not rename this job. infrastructure/github/main.tf lists
# "lambda-tests" as a required status check on main; renaming it here would
# silently disable the gate rather than fail loudly.
lambda-tests:
name: lambda-tests
needs: [test, checks]
if: always()
runs-on: ubuntu-latest
steps:
- name: Check test results
run: |
if [ "${{ needs.test.result }}" != "success" ]; then
echo "Lambda tests failed or were cancelled"
exit 1
fi
if [ "${{ needs.checks.result }}" != "success" ]; then
echo "Shared package, migration, or guard checks failed or were cancelled"
exit 1
fi
echo "All lambda and migration checks passed!"