@sssb/cdk 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/package.json +33 -3
- package/src/assets/placeholder-lambda/run.sh +4 -0
- package/src/database-name.js +118 -0
- package/src/index.d.ts +54 -0
- package/src/index.js +2 -0
- package/src/sssb-app.js +605 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Rice University
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sssb/cdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/safeinsights/sssb.git",
|
|
8
|
+
"directory": "packages/cdk"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"description": "SSSB's deployment construct: SssbApp, an app's server, migrator, database and CDN, composed inside the adopter's own CDK stack. Plain JavaScript; it never depends on @sssb/kit, and reaches it only from the app's own directory (ADR-0014, rule 4).",
|
|
12
|
+
"files": [
|
|
13
|
+
"src",
|
|
14
|
+
"!src/**/*.test.*"
|
|
15
|
+
],
|
|
16
|
+
"exports": {
|
|
17
|
+
"./package.json": "./package.json",
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./src/index.d.ts",
|
|
20
|
+
"default": "./src/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=24"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"aws-cdk-lib": "^2.274.0",
|
|
28
|
+
"constructs": "^10.8.1",
|
|
29
|
+
"@sssb/tools": "0.2.0"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"aws-cdk-lib": "^2.274.0",
|
|
33
|
+
"constructs": "^10.8.1",
|
|
34
|
+
"@sssb/tools": "0.2.0"
|
|
35
|
+
}
|
|
6
36
|
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The database an app's slug names, in a module of its own with no CDK in it, so a caller can refuse the same slugs
|
|
3
|
+
// the construct would without loading CDK (`sssb-app.js` re-exports it as `@sssb/cdk`'s `databaseNameFor`).
|
|
4
|
+
|
|
5
|
+
/** What a slug is: lowercase letters, digits and dashes, from a letter. */
|
|
6
|
+
export const SLUG = /^[a-z][a-z0-9-]*$/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Names Aurora PostgreSQL refuses as a database name although they have its shape: PostgreSQL's reserved key words
|
|
10
|
+
* (the "reserved" column of its SQL Key Words appendix) and the databases RDS and Postgres keep for themselves.
|
|
11
|
+
* Amazon RDS's naming rules say a database name "can't be a word reserved by the database engine".
|
|
12
|
+
*/
|
|
13
|
+
const RESERVED = new Set([
|
|
14
|
+
'all',
|
|
15
|
+
'analyse',
|
|
16
|
+
'analyze',
|
|
17
|
+
'and',
|
|
18
|
+
'any',
|
|
19
|
+
'array',
|
|
20
|
+
'as',
|
|
21
|
+
'asc',
|
|
22
|
+
'asymmetric',
|
|
23
|
+
'both',
|
|
24
|
+
'case',
|
|
25
|
+
'cast',
|
|
26
|
+
'check',
|
|
27
|
+
'collate',
|
|
28
|
+
'column',
|
|
29
|
+
'constraint',
|
|
30
|
+
'create',
|
|
31
|
+
'current_catalog',
|
|
32
|
+
'current_date',
|
|
33
|
+
'current_role',
|
|
34
|
+
'current_time',
|
|
35
|
+
'current_timestamp',
|
|
36
|
+
'current_user',
|
|
37
|
+
'default',
|
|
38
|
+
'deferrable',
|
|
39
|
+
'desc',
|
|
40
|
+
'distinct',
|
|
41
|
+
'do',
|
|
42
|
+
'else',
|
|
43
|
+
'end',
|
|
44
|
+
'except',
|
|
45
|
+
'false',
|
|
46
|
+
'fetch',
|
|
47
|
+
'for',
|
|
48
|
+
'foreign',
|
|
49
|
+
'from',
|
|
50
|
+
'grant',
|
|
51
|
+
'group',
|
|
52
|
+
'having',
|
|
53
|
+
'in',
|
|
54
|
+
'initially',
|
|
55
|
+
'intersect',
|
|
56
|
+
'into',
|
|
57
|
+
'lateral',
|
|
58
|
+
'leading',
|
|
59
|
+
'limit',
|
|
60
|
+
'localtime',
|
|
61
|
+
'localtimestamp',
|
|
62
|
+
'not',
|
|
63
|
+
'null',
|
|
64
|
+
'offset',
|
|
65
|
+
'on',
|
|
66
|
+
'only',
|
|
67
|
+
'or',
|
|
68
|
+
'order',
|
|
69
|
+
'placing',
|
|
70
|
+
'primary',
|
|
71
|
+
'references',
|
|
72
|
+
'returning',
|
|
73
|
+
'select',
|
|
74
|
+
'session_user',
|
|
75
|
+
'some',
|
|
76
|
+
'symmetric',
|
|
77
|
+
'system_user',
|
|
78
|
+
'table',
|
|
79
|
+
'then',
|
|
80
|
+
'to',
|
|
81
|
+
'trailing',
|
|
82
|
+
'true',
|
|
83
|
+
'union',
|
|
84
|
+
'unique',
|
|
85
|
+
'user',
|
|
86
|
+
'using',
|
|
87
|
+
'variadic',
|
|
88
|
+
'when',
|
|
89
|
+
'where',
|
|
90
|
+
'window',
|
|
91
|
+
'with',
|
|
92
|
+
'postgres',
|
|
93
|
+
'rdsadmin',
|
|
94
|
+
'template0',
|
|
95
|
+
'template1',
|
|
96
|
+
])
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The database an app's slug names: the slug with each dash as an underscore. A slug is lowercase letters, digits
|
|
100
|
+
* and dashes, and dashes are ordinary in one (`acme-corp`), but Aurora PostgreSQL's database name (the cluster's
|
|
101
|
+
* `DatabaseName`, from `defaultDatabaseName`) may hold only letters, digits and underscores, start with a letter, run
|
|
102
|
+
* to 63 characters and not be a word the engine reserves: a dashed slug synthesized cleanly and failed at deploy. A
|
|
103
|
+
* slug has no underscore of its own, so two slugs never map to one name, and a slug with no dash maps to itself
|
|
104
|
+
* (`showcase`, `starter`), so an existing deployment's database keeps its name. Throws for anything else.
|
|
105
|
+
* @param {string} slug
|
|
106
|
+
* @returns {string}
|
|
107
|
+
*/
|
|
108
|
+
export function databaseNameFor(slug) {
|
|
109
|
+
if (!SLUG.test(slug)) throw new Error(`SssbApp: slug must be lowercase letters, digits and dashes (got "${slug}")`)
|
|
110
|
+
const name = slug.replaceAll('-', '_')
|
|
111
|
+
if (name.length > 63) {
|
|
112
|
+
throw new Error(`SssbApp: slug "${slug}" is ${slug.length} characters; a database name may have at most 63`)
|
|
113
|
+
}
|
|
114
|
+
if (RESERVED.has(name)) {
|
|
115
|
+
throw new Error(`SssbApp: slug "${slug}" names the database "${name}", a word Aurora PostgreSQL reserves`)
|
|
116
|
+
}
|
|
117
|
+
return name
|
|
118
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type * as cdk from 'aws-cdk-lib'
|
|
2
|
+
import { Construct } from 'constructs'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The database an app's slug names: the slug with each dash as an underscore, since Aurora PostgreSQL's database
|
|
6
|
+
* name may hold only letters, digits and underscores (`acme-corp` → `acme_corp`; `showcase` stays `showcase`). Throws
|
|
7
|
+
* for a string that is not a slug, one over 63 characters, or one whose name the engine reserves (`user`, `select`,
|
|
8
|
+
* `rdsadmin`, …). An adopter's own infra that does not use `SssbApp` names its database with this too.
|
|
9
|
+
*/
|
|
10
|
+
export declare function databaseNameFor(slug: string): string
|
|
11
|
+
|
|
12
|
+
/** How the app reaches Postgres: the app's `params.database.transport` (ADR-0002, addendum 2026-11-16). */
|
|
13
|
+
export type DatabaseTransport = 'pg' | 'data-api'
|
|
14
|
+
|
|
15
|
+
export interface SssbAppProps {
|
|
16
|
+
/**
|
|
17
|
+
* The app's directory: the one whose `package.json` depends on `@sssb/kit` and whose `src/app-config` is
|
|
18
|
+
* its seam. An app's `infra/app.ts` passes its parent. The construct resolves the framework from here and
|
|
19
|
+
* never from its own location (ADR-0014, rule 4).
|
|
20
|
+
*/
|
|
21
|
+
readonly appDir: string
|
|
22
|
+
/**
|
|
23
|
+
* The app's slug (`config/app.ts`'s `APP_SLUG`): the budget's prefix, and the database's name with each dash as an
|
|
24
|
+
* underscore (`databaseNameFor`).
|
|
25
|
+
*/
|
|
26
|
+
readonly slug: string
|
|
27
|
+
/** The app's deployment params (`config/params.ts`); the construct reads `database.transport`. */
|
|
28
|
+
readonly params: { readonly database: { readonly transport: DatabaseTransport } }
|
|
29
|
+
/** The deployment's name, as the app's own policy spells it (`Staging`, `Production`). */
|
|
30
|
+
readonly environment: string
|
|
31
|
+
/** A production deployment: the database keeps a warm writer and the data stores are retained. */
|
|
32
|
+
readonly production: boolean
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* An SSSB app's deployment: the Next standalone server on Lambda behind the Web Adapter and CloudFront, the
|
|
37
|
+
* framework's migrator bundled with the app's own migrations, and Aurora PostgreSQL Serverless v2, in one of
|
|
38
|
+
* two network shapes. Composed inside the adopter's own stack. `cdk synth` fails unless, among other checks
|
|
39
|
+
* (`sssb-app.js` lists them all), the app's `@sssb/kit` is this construct's version, the server's final
|
|
40
|
+
* environment is fail-closed, and the migrator deploys the bundle this synth staged, carrying the app's
|
|
41
|
+
* migrations.
|
|
42
|
+
*/
|
|
43
|
+
export declare class SssbApp extends Construct {
|
|
44
|
+
constructor(scope: Construct, id: string, props: SssbAppProps)
|
|
45
|
+
readonly vpc: cdk.aws_ec2.Vpc
|
|
46
|
+
readonly cluster: cdk.aws_rds.DatabaseCluster
|
|
47
|
+
readonly server: cdk.aws_lambda.Function
|
|
48
|
+
readonly functionUrl: cdk.aws_lambda.FunctionUrl
|
|
49
|
+
readonly migrator: cdk.aws_lambda_nodejs.NodejsFunction
|
|
50
|
+
readonly distribution: cdk.aws_cloudfront.Distribution
|
|
51
|
+
readonly assetsBucket: cdk.aws_s3.Bucket
|
|
52
|
+
readonly storageBucket: cdk.aws_s3.Bucket
|
|
53
|
+
readonly databaseTransport: DatabaseTransport
|
|
54
|
+
}
|
package/src/index.js
ADDED
package/src/sssb-app.js
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { fileURLToPath } from 'node:url'
|
|
6
|
+
// A namespace import, never a default one: aws-cdk-lib is CommonJS, and a loader that compiles this file to
|
|
7
|
+
// CommonJS (tsx, under an app whose infra has no `"type": "module"`) hands it `module.exports` with no `default`.
|
|
8
|
+
import * as cdk from 'aws-cdk-lib'
|
|
9
|
+
import { Construct } from 'constructs'
|
|
10
|
+
import { failClosedEnvironmentProblems, migratorBundleProblems } from '@sssb/tools/assembly-checks'
|
|
11
|
+
import { kitDirOf, kitVersionOf, resolveAppsKit } from '@sssb/tools/kit'
|
|
12
|
+
import { databaseNameFor, SLUG } from './database-name.js'
|
|
13
|
+
|
|
14
|
+
const { aws_budgets, aws_cloudfront, aws_cloudfront_origins, aws_cloudwatch, aws_ec2, aws_lambda } = cdk
|
|
15
|
+
const { aws_lambda_nodejs, aws_rds, aws_s3 } = cdk
|
|
16
|
+
|
|
17
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
18
|
+
|
|
19
|
+
/** This package's own version: the one `@sssb/kit` version the construct was released with (rule 4). */
|
|
20
|
+
const OWN_VERSION = /** @type {{ version: string }} */ (
|
|
21
|
+
JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8'))
|
|
22
|
+
).version
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The version of the `@sssb/tools` this package runs its checks with: its peer, so the adopter's own copy, which pnpm
|
|
26
|
+
* only warns about when it is another release. Read from this package's own resolution.
|
|
27
|
+
*/
|
|
28
|
+
const TOOLS_VERSION = /** @type {{ version: string }} */ (
|
|
29
|
+
JSON.parse(readFileSync(createRequire(import.meta.url).resolve('@sssb/tools/package.json'), 'utf8'))
|
|
30
|
+
).version
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The problem with running this `@sssb/cdk` beside `@sssb/tools` at `tools`, or null: the two are released in lockstep,
|
|
34
|
+
* and the construct's deploy-time checks are that release's. A peer at another version is only a pnpm warning.
|
|
35
|
+
* @param {string} tools
|
|
36
|
+
* @param {string} [own]
|
|
37
|
+
*/
|
|
38
|
+
export function toolsVersionProblem(tools, own = OWN_VERSION) {
|
|
39
|
+
if (tools === own) return null
|
|
40
|
+
return (
|
|
41
|
+
`SssbApp: this @sssb/cdk is ${own}, but the @sssb/tools beside it is ${tools}. SSSB's packages are released in ` +
|
|
42
|
+
`lockstep: depend on @sssb/tools ${own} in the package that takes @sssb/cdk (its peer), then run pnpm install.`
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const TRANSPORTS = /** @type {const} */ (['pg', 'data-api'])
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The migrator entry, a published subpath of `@sssb/kit` (its `exports` map), resolved through that map from the
|
|
50
|
+
* app; and the framework's migration registry, which is not published, so it is named by its path inside the
|
|
51
|
+
* package. The version check below is what makes naming that path safe: this construct is released with that one
|
|
52
|
+
* layout.
|
|
53
|
+
*/
|
|
54
|
+
const KIT_MIGRATOR = 'adapters/real/migrate-handler'
|
|
55
|
+
const KIT_MIGRATIONS_INDEX = 'src/db/migrations/index.ts'
|
|
56
|
+
|
|
57
|
+
/** Where the app's seam lives, and its migration index, relative to the app's directory. */
|
|
58
|
+
const SEAM_DIR = 'src/app-config'
|
|
59
|
+
const SEAM_MIGRATIONS_INDEX = 'db/migrations/index.ts'
|
|
60
|
+
|
|
61
|
+
const LOCK_FILES = ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json', 'bun.lockb', 'bun.lock']
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The lock file nearest above the app: its directory is the root esbuild runs from, and so the base of the
|
|
65
|
+
* path comments the bundle check reads.
|
|
66
|
+
* @param {string} appDir
|
|
67
|
+
* @returns {string}
|
|
68
|
+
*/
|
|
69
|
+
function lockFileAbove(appDir) {
|
|
70
|
+
for (let dir = appDir; ; dir = path.dirname(dir)) {
|
|
71
|
+
const found = LOCK_FILES.map((name) => path.join(dir, name)).find((file) => existsSync(file))
|
|
72
|
+
if (found) return found
|
|
73
|
+
if (path.dirname(dir) === dir) {
|
|
74
|
+
throw new Error(`SssbApp: no lock file (${LOCK_FILES.join(', ')}) at or above ${appDir}`)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* A path as esbuild writes it in a bundle's per-module comment: relative to the root it runs from, with
|
|
81
|
+
* forward slashes.
|
|
82
|
+
* @param {string} root
|
|
83
|
+
* @param {string} file
|
|
84
|
+
*/
|
|
85
|
+
const asBundleComment = (root, file) => path.relative(root, realpathSync(file)).split(path.sep).join('/')
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The app's own migrations, by the names the bundle must carry (the keys Kysely records): the literal keys of the
|
|
89
|
+
* seam's migration index, comments left out. An index with migration files beside it but no literal key (keys
|
|
90
|
+
* computed, or another registry re-exported) would make the check expect nothing, so it is refused instead.
|
|
91
|
+
* @param {string} index
|
|
92
|
+
* @returns {string[]}
|
|
93
|
+
*/
|
|
94
|
+
function seamMigrationNames(index) {
|
|
95
|
+
const source = readFileSync(index, 'utf8')
|
|
96
|
+
.replace(/\/\*[\s\S]*?\*\//g, '')
|
|
97
|
+
.replace(/(^|[^:'"])\/\/.*$/gm, '$1')
|
|
98
|
+
const keys = [...source.matchAll(/['"](\d+_[^'"]+)['"]\s*:/g)].map((match) => /** @type {string} */ (match[1]))
|
|
99
|
+
const files = readdirSync(path.dirname(index)).filter((file) => /^\d+_[^.]+\.(?:ts|mts|js|mjs)$/.test(file))
|
|
100
|
+
if (keys.length === 0 && files.length > 0) {
|
|
101
|
+
throw new Error(
|
|
102
|
+
`SssbApp: ${index} registers none of ${files.join(', ')} under a literal key. Register each migration ` +
|
|
103
|
+
"as `'1001_name': m1001`, so the migrator's bundle can be checked for it.",
|
|
104
|
+
)
|
|
105
|
+
}
|
|
106
|
+
return [...new Set(keys)].sort()
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The app's slug as its `config/app.ts` declares it (`export const APP_SLUG = '…'`), or `undefined` for an app
|
|
111
|
+
* laid out otherwise. Read as text: this package is JavaScript and loads no TypeScript.
|
|
112
|
+
* @param {string} appDir
|
|
113
|
+
* @returns {string | undefined}
|
|
114
|
+
*/
|
|
115
|
+
function declaredSlug(appDir) {
|
|
116
|
+
const file = path.join(appDir, 'config/app.ts')
|
|
117
|
+
if (!existsSync(file)) return undefined
|
|
118
|
+
return /export const APP_SLUG = ['"]([^'"]+)['"]/.exec(readFileSync(file, 'utf8'))?.[1]
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The framework's migrator for one app, resolved from the app's directory, never from this package (rule 4):
|
|
123
|
+
* the entry esbuild bundles, the app's seam it aliases, and what the bundle must then contain.
|
|
124
|
+
* @param {string} appDir
|
|
125
|
+
*/
|
|
126
|
+
function resolveMigrator(appDir) {
|
|
127
|
+
const tools = toolsVersionProblem(TOOLS_VERSION)
|
|
128
|
+
if (tools !== null) throw new Error(tools)
|
|
129
|
+
const kitDir = kitDirOf(appDir)
|
|
130
|
+
const kitVersion = kitVersionOf(appDir)
|
|
131
|
+
if (kitVersion !== OWN_VERSION) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
`SssbApp: ${appDir} resolves @sssb/kit ${kitVersion} (${kitDir}), but this @sssb/cdk is ` +
|
|
134
|
+
`${OWN_VERSION}. SSSB's packages are released in lockstep: install the matching versions.`,
|
|
135
|
+
)
|
|
136
|
+
}
|
|
137
|
+
const entry = resolveAppsKit(appDir, KIT_MIGRATOR)
|
|
138
|
+
const seamDir = path.join(appDir, SEAM_DIR)
|
|
139
|
+
const seamIndex = path.join(seamDir, SEAM_MIGRATIONS_INDEX)
|
|
140
|
+
if (!existsSync(seamIndex)) {
|
|
141
|
+
throw new Error(`SssbApp: ${appDir} has no migration index at ${path.join(SEAM_DIR, SEAM_MIGRATIONS_INDEX)}`)
|
|
142
|
+
}
|
|
143
|
+
const migrations = seamMigrationNames(seamIndex)
|
|
144
|
+
// An app that links its seam as a package (an adopter's, ADR-0014 part 1) must link THIS directory: the
|
|
145
|
+
// server's build resolves the link, and the migrator would otherwise bundle a different seam from the one the
|
|
146
|
+
// server runs on.
|
|
147
|
+
const linked = path.join(appDir, 'node_modules/@sssb/app-config')
|
|
148
|
+
if (existsSync(linked) && realpathSync(linked) !== realpathSync(seamDir)) {
|
|
149
|
+
throw new Error(
|
|
150
|
+
`SssbApp: ${appDir} links @sssb/app-config to ${realpathSync(linked)}, not to its ${SEAM_DIR}, ` +
|
|
151
|
+
'which is the seam the migrator is bundled with. Declare the seam as the workspace package in ' +
|
|
152
|
+
'`src/app-config` (`"@sssb/app-config": "workspace:<name>-app-config@*"`; a `file:` dependency ' +
|
|
153
|
+
'installs a copy).',
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
const lockFile = lockFileAbove(appDir)
|
|
157
|
+
const projectRoot = path.dirname(lockFile)
|
|
158
|
+
// esbuild runs from the project root and CDK refuses an entry outside it; say why, rather than CDK's error.
|
|
159
|
+
const relativeEntry = path.relative(projectRoot, entry)
|
|
160
|
+
if (relativeEntry === '..' || relativeEntry.startsWith(`..${path.sep}`) || path.isAbsolute(relativeEntry)) {
|
|
161
|
+
throw new Error(
|
|
162
|
+
`SssbApp: the @sssb/kit ${appDir} resolves (${kitDir}) is outside the project root ${projectRoot}, ` +
|
|
163
|
+
'where the migrator is bundled from. Install the framework into the project rather than linking a ' +
|
|
164
|
+
'checkout from elsewhere.',
|
|
165
|
+
)
|
|
166
|
+
}
|
|
167
|
+
// CDK bundles with an esbuild its own `require` finds, run from the project root (`pnpm exec esbuild`,
|
|
168
|
+
// `npx --no-install`), else with an `esbuild` on PATH, else in Docker, where the seam alias and the path
|
|
169
|
+
// comments the check reads, both host paths, would name nothing. The first is the one a project installs, so
|
|
170
|
+
// the construct requires it at the project root, and refuses a global esbuild CDK would accept.
|
|
171
|
+
if (!existsSync(path.join(projectRoot, 'node_modules/esbuild/package.json'))) {
|
|
172
|
+
throw new Error(
|
|
173
|
+
`SssbApp: no esbuild at ${projectRoot}, the project root the migrator is bundled from. Add esbuild to ` +
|
|
174
|
+
"that package's devDependencies: the construct bundles locally, never in CDK's Docker fallback.",
|
|
175
|
+
)
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
entry,
|
|
179
|
+
seamDir: realpathSync(seamDir),
|
|
180
|
+
lockFile,
|
|
181
|
+
projectRoot,
|
|
182
|
+
expected: {
|
|
183
|
+
sources: [
|
|
184
|
+
asBundleComment(projectRoot, path.join(kitDir, KIT_MIGRATIONS_INDEX)),
|
|
185
|
+
asBundleComment(projectRoot, seamIndex),
|
|
186
|
+
],
|
|
187
|
+
migrations,
|
|
188
|
+
},
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* A function's properties as they will be deployed: the rendered CloudFormation, escape-hatch overrides included,
|
|
194
|
+
* with every token the stack can resolve resolved.
|
|
195
|
+
* @param {cdk.aws_lambda.Function} fn
|
|
196
|
+
* @returns {{ Environment?: { Variables?: Record<string, unknown> }, Code?: { S3Bucket?: unknown, S3Key?: unknown } }}
|
|
197
|
+
*/
|
|
198
|
+
function renderedProperties(fn) {
|
|
199
|
+
const cfn = /** @type {any} */ (fn.node.defaultChild)
|
|
200
|
+
if (typeof cfn?._toCloudFormation !== 'function') {
|
|
201
|
+
throw new Error(`SssbApp: cannot render ${fn.node.path}'s CloudFormation to check it`)
|
|
202
|
+
}
|
|
203
|
+
const rendered = cdk.Stack.of(fn).resolve(cfn._toCloudFormation())
|
|
204
|
+
return Object.values(rendered.Resources ?? {})[0]?.Properties ?? {}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* The code esbuild staged for a NodejsFunction during this synth, and problems with what it deploys: a `Code`
|
|
209
|
+
* other than the asset this synth staged (an escape-hatch override would deploy something the bundle check never
|
|
210
|
+
* read). Compared with the asset's own bucket and key, as the stack's synthesizer assigned them, so a bucket
|
|
211
|
+
* prefix or a legacy synthesizer's parameters compare equal.
|
|
212
|
+
* @param {cdk.aws_lambda.Function} fn
|
|
213
|
+
* @returns {{ code: string | undefined, problems: string[] }}
|
|
214
|
+
*/
|
|
215
|
+
function stagedBundle(fn) {
|
|
216
|
+
const asset = /** @type {cdk.aws_s3_assets.Asset | undefined} */ (fn.node.tryFindChild('Code'))
|
|
217
|
+
const stage = /** @type {{ absoluteStagedPath?: unknown } | undefined} */ (asset?.node.tryFindChild('Stage'))
|
|
218
|
+
const dir = stage?.absoluteStagedPath
|
|
219
|
+
if (asset === undefined || typeof dir !== 'string') return { code: undefined, problems: [] }
|
|
220
|
+
const file = ['index.mjs', 'index.js'].map((name) => path.join(dir, name)).find((name) => existsSync(name))
|
|
221
|
+
const stack = cdk.Stack.of(fn)
|
|
222
|
+
const staged = JSON.stringify(stack.resolve({ S3Bucket: asset.s3BucketName, S3Key: asset.s3ObjectKey }))
|
|
223
|
+
const deployed = renderedProperties(fn).Code
|
|
224
|
+
const problems =
|
|
225
|
+
// The whole `Code`: an override that adds `ZipFile` or `ImageUri` beside the staged key is caught too.
|
|
226
|
+
JSON.stringify(deployed) === staged
|
|
227
|
+
? []
|
|
228
|
+
: [`it deploys ${JSON.stringify(deployed)}, not the bundle this synth staged (${staged})`]
|
|
229
|
+
return { code: file === undefined ? undefined : readFileSync(file, 'utf8'), problems }
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export { databaseNameFor } from './database-name.js'
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* An SSSB app's deployment (ADR-0001, ADR-0014 part 8): the Next standalone server in one Lambda behind the
|
|
236
|
+
* AWS Lambda Web Adapter, its Function URL behind CloudFront with static assets from S3, the framework's
|
|
237
|
+
* migrator bundled with the app's own migrations, and Aurora PostgreSQL Serverless v2. A construct, not a
|
|
238
|
+
* stack: the adopter composes it inside a stack of their own, beside their own constructs.
|
|
239
|
+
*
|
|
240
|
+
* TWO NETWORK SHAPES, chosen by `params.database.transport` (ADR-0001 and ADR-0002, addenda 2026-11-16).
|
|
241
|
+
* Decide before the first deploy: on an existing stack a switch does not replace anything, it FAILS (the new
|
|
242
|
+
* subnets' CIDRs overlap the old ones) and rolls back, so changing shape means a new stack and a restore from a
|
|
243
|
+
* snapshot.
|
|
244
|
+
* - `pg` (default): both Lambdas run inside the VPC and reach Aurora over a socket; one NAT gateway carries
|
|
245
|
+
* their egress to the hosted auth/email/LLM services.
|
|
246
|
+
* - `data-api` (opt-in): only the database lives in the VPC, in isolated subnets with no NAT. Both Lambdas run
|
|
247
|
+
* outside it and reach Aurora through the RDS Data API, authorised by IAM alone.
|
|
248
|
+
*
|
|
249
|
+
* AT SYNTH it asserts, and `cdk synth` fails otherwise. At construction:
|
|
250
|
+
* - the `@sssb/kit` the app resolves is this construct's own version, installed under the project root (the lock
|
|
251
|
+
* file's directory), which also installs esbuild;
|
|
252
|
+
* - the slug is lowercase letters, digits and dashes, and is the `APP_SLUG` the app's `config/app.ts` declares
|
|
253
|
+
* (where it has one); `environment` is a non-empty name, `production` is a boolean and the transport is `pg` or
|
|
254
|
+
* `data-api`;
|
|
255
|
+
* - the app has a lock file at or above it and a migration index at `src/app-config/db/migrations/index.ts`;
|
|
256
|
+
* - a linked `@sssb/app-config` is the app's own `src/app-config`, whose migration index registers its migrations
|
|
257
|
+
* under literal keys.
|
|
258
|
+
* Then, as a validation over the rendered template, overrides included:
|
|
259
|
+
* - the server's final environment is fail-closed: `APP_MODE` is `real`, and neither `DEMO_MODE` nor `E2E_BUILD`
|
|
260
|
+
* is present; the migrator carries neither switch either;
|
|
261
|
+
* - the migrator deploys the bundle this synth staged, and that bundle carries the app's own migrations, built
|
|
262
|
+
* from the app's seam and no test fixture (when this synth bundles the stack at all: `cdk deploy --exclusively
|
|
263
|
+
* OtherStack` skips it).
|
|
264
|
+
*
|
|
265
|
+
* The migrator is bundled LOCALLY, by the esbuild the project root installs, never in CDK's Docker fallback: the
|
|
266
|
+
* seam alias and the bundle's path comments the check reads are paths on the machine running the synth.
|
|
267
|
+
*
|
|
268
|
+
* Gates before any deploy (docs/cutover-checklist.md): `cloud-accounts` and `recurring-cost` (Aurora, NAT
|
|
269
|
+
* gateway, CloudFront must be approved).
|
|
270
|
+
*/
|
|
271
|
+
export class SssbApp extends Construct {
|
|
272
|
+
/**
|
|
273
|
+
* @param {Construct} scope
|
|
274
|
+
* @param {string} id
|
|
275
|
+
* @param {import('./index.d.ts').SssbAppProps} props
|
|
276
|
+
*/
|
|
277
|
+
constructor(scope, id, props) {
|
|
278
|
+
super(scope, id)
|
|
279
|
+
|
|
280
|
+
// Real, so that the project root, the entry and the seam are all spelled the same way: esbuild and CDK
|
|
281
|
+
// compare them, and the entry comes back from the resolver as a real path.
|
|
282
|
+
const appDir = realpathSync(path.resolve(props.appDir))
|
|
283
|
+
const slug = props.slug
|
|
284
|
+
if (!SLUG.test(slug ?? '')) {
|
|
285
|
+
throw new Error(`SssbApp: slug must be lowercase letters, digits and dashes (got "${String(slug)}")`)
|
|
286
|
+
}
|
|
287
|
+
// The database the migrator migrates and the server reads, named from the slug (databaseNameFor).
|
|
288
|
+
const databaseName = databaseNameFor(slug)
|
|
289
|
+
// The slug names the database the migrator migrates and the server reads, so it must be this app's: a
|
|
290
|
+
// root infra/ composing several apps could otherwise pair one app's directory with another's slug.
|
|
291
|
+
const declared = declaredSlug(appDir)
|
|
292
|
+
if (declared !== undefined && declared !== slug) {
|
|
293
|
+
throw new Error(`SssbApp: slug is "${slug}", but ${appDir}/config/app.ts declares APP_SLUG "${declared}"`)
|
|
294
|
+
}
|
|
295
|
+
const transport = props.params?.database?.transport
|
|
296
|
+
if (!TRANSPORTS.includes(/** @type {any} */ (transport))) {
|
|
297
|
+
throw new Error(
|
|
298
|
+
`SssbApp: params.database.transport must be ${TRANSPORTS.join(' or ')} (got "${String(transport)}")`,
|
|
299
|
+
)
|
|
300
|
+
}
|
|
301
|
+
if (typeof props.environment !== 'string' || props.environment === '') {
|
|
302
|
+
throw new Error('SssbApp: environment must name the deployment (e.g. Staging, Production)')
|
|
303
|
+
}
|
|
304
|
+
// A boolean, never inferred: a JavaScript caller that left it out would otherwise get the destructive
|
|
305
|
+
// non-production defaults (a database destroyed with the stack, buckets that empty themselves).
|
|
306
|
+
if (typeof props.production !== 'boolean') {
|
|
307
|
+
throw new Error(`SssbApp: production must be true or false (got ${JSON.stringify(props.production)})`)
|
|
308
|
+
}
|
|
309
|
+
const isProd = props.production
|
|
310
|
+
const dataApi = transport === 'data-api'
|
|
311
|
+
const removalPolicy = isProd ? cdk.RemovalPolicy.RETAIN : cdk.RemovalPolicy.DESTROY
|
|
312
|
+
const migratorSource = resolveMigrator(appDir)
|
|
313
|
+
|
|
314
|
+
// ---- networking -------------------------------------------------------------------
|
|
315
|
+
// pg: one NAT gateway so the in-VPC Lambdas can reach the hosted auth/email/LLM services —
|
|
316
|
+
// recurring cost, gated by cutover row `recurring-cost`. data-api: nothing but the database is in
|
|
317
|
+
// the VPC, so it needs no route out at all — isolated subnets, no NAT, no public subnets. (Should the
|
|
318
|
+
// secret later get rotation, its rotation Lambda lands in these subnets and needs a Secrets
|
|
319
|
+
// Manager interface endpoint, having no other way to reach the service.)
|
|
320
|
+
const vpc = new aws_ec2.Vpc(
|
|
321
|
+
this,
|
|
322
|
+
'Vpc',
|
|
323
|
+
dataApi
|
|
324
|
+
? {
|
|
325
|
+
maxAzs: 2,
|
|
326
|
+
natGateways: 0,
|
|
327
|
+
subnetConfiguration: [
|
|
328
|
+
{ name: 'Database', subnetType: aws_ec2.SubnetType.PRIVATE_ISOLATED, cidrMask: 24 },
|
|
329
|
+
],
|
|
330
|
+
}
|
|
331
|
+
: { maxAzs: 2, natGateways: 1 },
|
|
332
|
+
)
|
|
333
|
+
const dbSubnetType = dataApi ? aws_ec2.SubnetType.PRIVATE_ISOLATED : aws_ec2.SubnetType.PRIVATE_WITH_EGRESS
|
|
334
|
+
// Where the Lambdas run: inside the VPC for pg, outside any VPC for the Data API.
|
|
335
|
+
const lambdaNetwork = dataApi ? {} : { vpc, vpcSubnets: { subnetType: aws_ec2.SubnetType.PRIVATE_WITH_EGRESS } }
|
|
336
|
+
|
|
337
|
+
// ---- database ---------------------------------------------------------------------
|
|
338
|
+
const db = new aws_rds.DatabaseCluster(this, 'Db', {
|
|
339
|
+
engine: aws_rds.DatabaseClusterEngine.auroraPostgres({
|
|
340
|
+
version: aws_rds.AuroraPostgresEngineVersion.VER_16_10,
|
|
341
|
+
}),
|
|
342
|
+
writer: aws_rds.ClusterInstance.serverlessV2('writer'),
|
|
343
|
+
serverlessV2MinCapacity: isProd ? 1 : 0,
|
|
344
|
+
serverlessV2MaxCapacity: 2,
|
|
345
|
+
vpc,
|
|
346
|
+
vpcSubnets: { subnetType: dbSubnetType },
|
|
347
|
+
// The HTTPS endpoint the data-api transport calls. Left unset for pg, which needs no second way
|
|
348
|
+
// in — unset rather than `false`, so the pg cluster synthesizes exactly as it did before.
|
|
349
|
+
...(dataApi && { enableDataApi: true }),
|
|
350
|
+
defaultDatabaseName: databaseName,
|
|
351
|
+
storageEncrypted: true,
|
|
352
|
+
removalPolicy,
|
|
353
|
+
})
|
|
354
|
+
const secret = /** @type {cdk.aws_secretsmanager.ISecret} */ (db.secret)
|
|
355
|
+
// The cluster's `removalPolicy` does not reach its generated master secret, which CDK synthesizes with
|
|
356
|
+
// `DeletionPolicy: Delete` whatever the cluster does. In production the stack would then keep the database
|
|
357
|
+
// and delete the only credentials to it, so the secret gets the cluster's policy. The logical id is
|
|
358
|
+
// unchanged (a new one would replace the secret, and with it the password the cluster was created with).
|
|
359
|
+
// `db.secret` is not the secret: it is the SecretTargetAttachment that CDK returns from `secret.attach`, so the
|
|
360
|
+
// policy goes on the underlying `AWS::SecretsManager::Secret`, found in the cluster's subtree. Nothing else
|
|
361
|
+
// holds the credentials: no KMS key (the cluster and the secret name none, so they use the account's AWS-managed
|
|
362
|
+
// keys; the buckets use S3's), no rotation schedule, and the attachment names a secret and a cluster
|
|
363
|
+
// and nothing else, the username and password being the secret's own `GenerateSecretString`.
|
|
364
|
+
const generatedSecrets = db.node.findAll().filter((c) => c instanceof cdk.aws_secretsmanager.CfnSecret)
|
|
365
|
+
if (generatedSecrets.length !== 1) {
|
|
366
|
+
throw new Error(
|
|
367
|
+
`SssbApp: expected the database cluster to own one generated secret, found ${generatedSecrets.length}`,
|
|
368
|
+
)
|
|
369
|
+
}
|
|
370
|
+
const [generatedSecret] = /** @type {cdk.aws_secretsmanager.CfnSecret[]} */ (generatedSecrets)
|
|
371
|
+
generatedSecret?.applyRemovalPolicy(removalPolicy)
|
|
372
|
+
|
|
373
|
+
// ---- buckets ----------------------------------------------------------------------
|
|
374
|
+
// CDN-served build assets — written by the deploy pipeline only.
|
|
375
|
+
const assetsBucket = new aws_s3.Bucket(this, 'AssetsBucket', {
|
|
376
|
+
blockPublicAccess: aws_s3.BlockPublicAccess.BLOCK_ALL,
|
|
377
|
+
enforceSSL: true,
|
|
378
|
+
removalPolicy,
|
|
379
|
+
autoDeleteObjects: !isProd,
|
|
380
|
+
})
|
|
381
|
+
// App object storage (StoragePort) — private, NEVER behind CloudFront: sharing the CDN
|
|
382
|
+
// bucket would make app-stored objects publicly fetchable and let the app overwrite
|
|
383
|
+
// served JS.
|
|
384
|
+
const storageBucket = new aws_s3.Bucket(this, 'StorageBucket', {
|
|
385
|
+
blockPublicAccess: aws_s3.BlockPublicAccess.BLOCK_ALL,
|
|
386
|
+
enforceSSL: true,
|
|
387
|
+
encryption: aws_s3.BucketEncryption.S3_MANAGED,
|
|
388
|
+
removalPolicy,
|
|
389
|
+
autoDeleteObjects: !isProd,
|
|
390
|
+
})
|
|
391
|
+
|
|
392
|
+
// The database half of each Lambda's environment (the framework's real adapters read it at boot).
|
|
393
|
+
// data-api builds no DATABASE_URL at all: the credential stays in Secrets Manager, where the Data
|
|
394
|
+
// API reads it, so the `db-credential-not-in-env` concern does not arise on that path.
|
|
395
|
+
/** @type {Record<string, string>} */
|
|
396
|
+
const databaseEnv = dataApi
|
|
397
|
+
? {
|
|
398
|
+
DATABASE_TRANSPORT: 'data-api',
|
|
399
|
+
DATABASE_CLUSTER_ARN: db.clusterArn,
|
|
400
|
+
DATABASE_SECRET_ARN: secret.secretArn,
|
|
401
|
+
DATABASE_NAME: databaseName,
|
|
402
|
+
}
|
|
403
|
+
: {
|
|
404
|
+
DATABASE_TRANSPORT: 'pg',
|
|
405
|
+
// DRAFT: built via CFN dynamic references so the server
|
|
406
|
+
// can actually boot; revisit with the shared secrets constructs at cutover
|
|
407
|
+
// (env-var exposure vs runtime secret fetch).
|
|
408
|
+
DATABASE_URL: `postgres://${secret.secretValueFromJson('username').unsafeUnwrap()}:${secret
|
|
409
|
+
.secretValueFromJson('password')
|
|
410
|
+
.unsafeUnwrap()}@${db.clusterEndpoint.socketAddress}/${databaseName}`,
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// pg: read the secret and open the database port to the function's security group. data-api: the
|
|
414
|
+
// RDS Data API actions on THIS cluster and read on its secret, nothing else; IAM is the whole
|
|
415
|
+
// boundary on that path, so it is scoped to the one cluster (cutover row `data-api-access`).
|
|
416
|
+
/** @param {cdk.aws_lambda.Function} fn */
|
|
417
|
+
const grantDatabase = (fn) => {
|
|
418
|
+
if (dataApi) {
|
|
419
|
+
db.grantDataApiAccess(fn)
|
|
420
|
+
} else {
|
|
421
|
+
secret.grantRead(fn)
|
|
422
|
+
db.connections.allowDefaultPortFrom(fn)
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// ---- app server lambda (web adapter) -----------------------------------------------
|
|
427
|
+
// Code ships as the standalone build zip uploaded by your deploy pipeline — the placeholder asset
|
|
428
|
+
// keeps synth honest until then.
|
|
429
|
+
const server = new aws_lambda.Function(this, 'Server', {
|
|
430
|
+
runtime: aws_lambda.Runtime.NODEJS_22_X,
|
|
431
|
+
architecture: aws_lambda.Architecture.X86_64,
|
|
432
|
+
code: aws_lambda.Code.fromAsset(path.join(HERE, 'assets/placeholder-lambda')),
|
|
433
|
+
handler: 'run.sh',
|
|
434
|
+
memorySize: 1769, // 1 vCPU-second per second — the sweet spot for SSR cold starts
|
|
435
|
+
timeout: cdk.Duration.seconds(30),
|
|
436
|
+
...lambdaNetwork,
|
|
437
|
+
layers: [
|
|
438
|
+
aws_lambda.LayerVersion.fromLayerVersionArn(
|
|
439
|
+
this,
|
|
440
|
+
'WebAdapterLayer',
|
|
441
|
+
// AWS-published public layer
|
|
442
|
+
`arn:aws:lambda:${cdk.Stack.of(this).region}:753240598075:layer:LambdaAdapterLayerX86:24`,
|
|
443
|
+
),
|
|
444
|
+
],
|
|
445
|
+
environment: {
|
|
446
|
+
AWS_LAMBDA_EXEC_WRAPPER: '/opt/bootstrap',
|
|
447
|
+
PORT: '3000',
|
|
448
|
+
APP_MODE: 'real',
|
|
449
|
+
NEXT_TELEMETRY_DISABLED: '1',
|
|
450
|
+
...databaseEnv,
|
|
451
|
+
STORAGE_BUCKET: storageBucket.bucketName,
|
|
452
|
+
},
|
|
453
|
+
})
|
|
454
|
+
grantDatabase(server)
|
|
455
|
+
storageBucket.grantReadWrite(server)
|
|
456
|
+
|
|
457
|
+
// AWS_IAM, not NONE. A Function URL with NONE answers anyone on the internet who has the URL,
|
|
458
|
+
// and putting CloudFront in front of it does not change that — the origin stays directly
|
|
459
|
+
// reachable, so any WAF, geo restriction, rate limit or response-headers policy attached to
|
|
460
|
+
// the distribution later is bypassable by calling the origin instead. Paired with the origin
|
|
461
|
+
// access control below, the distribution is the only caller that can sign a request.
|
|
462
|
+
const functionUrl = server.addFunctionUrl({ authType: aws_lambda.FunctionUrlAuthType.AWS_IAM })
|
|
463
|
+
|
|
464
|
+
// ---- migrator ----------------------------------------------------------------------
|
|
465
|
+
// The framework's migration registry composed with the app's ≥1001 set through the seam. The entry
|
|
466
|
+
// is the `@sssb/kit` the APP resolves, and the seam is passed explicitly as an esbuild alias: the
|
|
467
|
+
// fallback, the nearest tsconfig's `@sssb/app-config/*` mapping, is in SSSB's own repository its test
|
|
468
|
+
// fixture's, which once shipped the fixture's migrations and none of the app's (jpslav/keel#54).
|
|
469
|
+
const migrator = new aws_lambda_nodejs.NodejsFunction(this, 'Migrator', {
|
|
470
|
+
runtime: aws_lambda.Runtime.NODEJS_22_X,
|
|
471
|
+
entry: migratorSource.entry,
|
|
472
|
+
projectRoot: migratorSource.projectRoot,
|
|
473
|
+
depsLockFilePath: migratorSource.lockFile,
|
|
474
|
+
handler: 'handler',
|
|
475
|
+
timeout: cdk.Duration.minutes(5),
|
|
476
|
+
...lambdaNetwork,
|
|
477
|
+
// pg: the handler builds its own connection string from the secret. data-api: the same
|
|
478
|
+
// variables as the server (the handler follows DATABASE_TRANSPORT too).
|
|
479
|
+
// On pg it gets the database's name too: the framework's handler prefers it to the secret's `dbname`,
|
|
480
|
+
// which the synthesized secret does not carry (only the cluster's secret attachment would add it, at deploy).
|
|
481
|
+
environment: dataApi
|
|
482
|
+
? databaseEnv
|
|
483
|
+
: { DATABASE_TRANSPORT: 'pg', DB_SECRET_ARN: secret.secretArn, DATABASE_NAME: databaseName },
|
|
484
|
+
bundling: {
|
|
485
|
+
format: aws_lambda_nodejs.OutputFormat.ESM,
|
|
486
|
+
// pg's optional native/cloudflare shims must stay external or esbuild chokes
|
|
487
|
+
externalModules: ['@aws-sdk/*', 'pg-native', 'cloudflare:sockets'],
|
|
488
|
+
esbuildArgs: { '--alias:@sssb/app-config': migratorSource.seamDir },
|
|
489
|
+
},
|
|
490
|
+
})
|
|
491
|
+
grantDatabase(migrator)
|
|
492
|
+
|
|
493
|
+
// ---- cloudfront ---------------------------------------------------------------------
|
|
494
|
+
// First deploys ride *.cloudfront.net; custom domains + certs are cutover row
|
|
495
|
+
// `domains-and-certs`.
|
|
496
|
+
const distribution = new aws_cloudfront.Distribution(this, 'Distribution', {
|
|
497
|
+
defaultBehavior: {
|
|
498
|
+
// withOriginAccessControl, not the plain constructor: it creates the OAC and grants
|
|
499
|
+
// this distribution — and only this distribution — permission to invoke the URL.
|
|
500
|
+
origin: aws_cloudfront_origins.FunctionUrlOrigin.withOriginAccessControl(functionUrl),
|
|
501
|
+
viewerProtocolPolicy: aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
|
|
502
|
+
allowedMethods: aws_cloudfront.AllowedMethods.ALLOW_ALL,
|
|
503
|
+
cachePolicy: aws_cloudfront.CachePolicy.CACHING_DISABLED,
|
|
504
|
+
originRequestPolicy: aws_cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
|
|
505
|
+
},
|
|
506
|
+
additionalBehaviors: {
|
|
507
|
+
'/_next/static/*': {
|
|
508
|
+
origin: aws_cloudfront_origins.S3BucketOrigin.withOriginAccessControl(assetsBucket),
|
|
509
|
+
cachePolicy: aws_cloudfront.CachePolicy.CACHING_OPTIMIZED,
|
|
510
|
+
},
|
|
511
|
+
'/assets/*': {
|
|
512
|
+
origin: aws_cloudfront_origins.S3BucketOrigin.withOriginAccessControl(assetsBucket),
|
|
513
|
+
cachePolicy: aws_cloudfront.CachePolicy.CACHING_OPTIMIZED,
|
|
514
|
+
},
|
|
515
|
+
},
|
|
516
|
+
})
|
|
517
|
+
|
|
518
|
+
// ---- scheduled-work tick (cutover `scheduled-tick`) ------------------------------
|
|
519
|
+
// The scheduled-jobs due-scan is driven by an EventBridge Scheduler schedule
|
|
520
|
+
// POSTing `/api/webhooks/cron` on a fixed cadence with `Authorization: Bearer $WEBHOOK_SECRET`
|
|
521
|
+
// (the same shared secret as `job-runner`). It is NOT authored here on purpose: the only
|
|
522
|
+
// clean primitive for "POST an arbitrary HTTPS URL with an auth header" is an EventBridge API
|
|
523
|
+
// Destination + Connection, which depends on the WEBHOOK_SECRET Secrets Manager resource that
|
|
524
|
+
// lands with `job-runner` — authoring it half-wired would break `cdk synth`. It rides that
|
|
525
|
+
// secret; see the `scheduled-tick` cutover row for the schedule + connection + verification.
|
|
526
|
+
|
|
527
|
+
// ---- basic alarms ---------------------------------------------------------------------
|
|
528
|
+
// Draft thresholds; replaced by the shared monitoring constructs at cutover.
|
|
529
|
+
new aws_cloudwatch.Alarm(this, 'ServerErrorsAlarm', {
|
|
530
|
+
metric: server.metricErrors({ period: cdk.Duration.minutes(5) }),
|
|
531
|
+
threshold: 5,
|
|
532
|
+
evaluationPeriods: 1,
|
|
533
|
+
treatMissingData: aws_cloudwatch.TreatMissingData.NOT_BREACHING,
|
|
534
|
+
})
|
|
535
|
+
new aws_cloudwatch.Alarm(this, 'ServerThrottlesAlarm', {
|
|
536
|
+
metric: server.metricThrottles({ period: cdk.Duration.minutes(5) }),
|
|
537
|
+
threshold: 1,
|
|
538
|
+
evaluationPeriods: 1,
|
|
539
|
+
treatMissingData: aws_cloudwatch.TreatMissingData.NOT_BREACHING,
|
|
540
|
+
})
|
|
541
|
+
|
|
542
|
+
// ---- budget guard -------------------------------------------------------------------
|
|
543
|
+
new aws_budgets.CfnBudget(this, 'Budget', {
|
|
544
|
+
budget: {
|
|
545
|
+
budgetName: `${slug}-${props.environment.toLowerCase()}`,
|
|
546
|
+
budgetType: 'COST',
|
|
547
|
+
timeUnit: 'MONTHLY',
|
|
548
|
+
budgetLimit: { amount: 50, unit: 'USD' },
|
|
549
|
+
},
|
|
550
|
+
notificationsWithSubscribers: [
|
|
551
|
+
{
|
|
552
|
+
notification: {
|
|
553
|
+
notificationType: 'ACTUAL',
|
|
554
|
+
comparisonOperator: 'GREATER_THAN',
|
|
555
|
+
threshold: 80,
|
|
556
|
+
},
|
|
557
|
+
// cutover `cloud-accounts`: replace with a real alert address from config/params.ts
|
|
558
|
+
subscribers: [{ subscriptionType: 'EMAIL', address: 'PLACEHOLDER_BUDGET_ALERT_EMAIL' }],
|
|
559
|
+
},
|
|
560
|
+
],
|
|
561
|
+
})
|
|
562
|
+
|
|
563
|
+
new cdk.CfnOutput(this, 'DistributionDomain', { value: distribution.distributionDomainName })
|
|
564
|
+
new cdk.CfnOutput(this, 'FunctionUrl', { value: functionUrl.url })
|
|
565
|
+
new cdk.CfnOutput(this, 'DbSecretArn', { value: secret.secretArn })
|
|
566
|
+
new cdk.CfnOutput(this, 'DatabaseTransport', { value: transport })
|
|
567
|
+
|
|
568
|
+
// ---- the synth assertions ---------------------------------------------------------
|
|
569
|
+
// Validations run inside `app.synth()`, after every construct has had its say, so they read the
|
|
570
|
+
// environment and the bundle as they will be deployed, not as this constructor left them.
|
|
571
|
+
this.node.addValidation({
|
|
572
|
+
validate: () => {
|
|
573
|
+
const environment = renderedProperties(server).Environment?.Variables ?? {}
|
|
574
|
+
const problems = failClosedEnvironmentProblems(environment).map(
|
|
575
|
+
(problem) => `the server is not fail-closed: ${problem}`,
|
|
576
|
+
)
|
|
577
|
+
// The migrator runs no adapters, but the same switches have no business on it either.
|
|
578
|
+
const migratorEnvironment = renderedProperties(migrator).Environment?.Variables ?? {}
|
|
579
|
+
for (const name of ['DEMO_MODE', 'E2E_BUILD']) {
|
|
580
|
+
if (name in migratorEnvironment) problems.push(`the migrator's environment sets ${name}`)
|
|
581
|
+
}
|
|
582
|
+
if (cdk.Stack.of(this).bundlingRequired) {
|
|
583
|
+
const bundle = stagedBundle(migrator)
|
|
584
|
+
problems.push(
|
|
585
|
+
...[
|
|
586
|
+
...bundle.problems,
|
|
587
|
+
...migratorBundleProblems({ code: bundle.code, ...migratorSource.expected }),
|
|
588
|
+
].map((problem) => `the migrator bundle is wrong: ${problem}`),
|
|
589
|
+
)
|
|
590
|
+
}
|
|
591
|
+
return problems
|
|
592
|
+
},
|
|
593
|
+
})
|
|
594
|
+
|
|
595
|
+
this.vpc = vpc
|
|
596
|
+
this.cluster = db
|
|
597
|
+
this.server = server
|
|
598
|
+
this.functionUrl = functionUrl
|
|
599
|
+
this.migrator = migrator
|
|
600
|
+
this.distribution = distribution
|
|
601
|
+
this.assetsBucket = assetsBucket
|
|
602
|
+
this.storageBucket = storageBucket
|
|
603
|
+
this.databaseTransport = transport
|
|
604
|
+
}
|
|
605
|
+
}
|
package/README.md
DELETED