@sssb/kit 0.3.0 → 0.5.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/dist/release.json +1 -1
- package/package.json +3 -1
- package/src/adapters/email-message.ts +30 -0
- package/src/adapters/fake/analytics.ts +1 -1
- package/src/adapters/fake/auth.ts +31 -4
- package/src/adapters/fake/data-dir.ts +32 -2
- package/src/adapters/fake/db.ts +4 -2
- package/src/adapters/fake/email.ts +2 -0
- package/src/adapters/real/absent.ts +13 -0
- package/src/adapters/real/accept-invite-form.tsx +86 -21
- package/src/adapters/real/analytics.ts +30 -3
- package/src/adapters/real/auth.ts +82 -20
- package/src/adapters/real/contract-postgres.ts +15 -11
- package/src/adapters/real/db-port.ts +3 -2
- package/src/adapters/real/email.ts +2 -0
- package/src/adapters/real/index.ts +49 -12
- package/src/adapters/real/jobs-in-process.ts +32 -14
- package/src/adapters/real/jobs.ts +6 -3
- package/src/adapters/real/migrate-handler.ts +3 -1
- package/src/adapters/real/no-analytics.ts +17 -0
- package/src/adapters/real/optional-ports.ts +35 -1
- package/src/adapters/real/rds-data-codec.ts +88 -4
- package/src/adapters/real/rds-data-emulator.ts +12 -4
- package/src/adapters/real/s3-storage.ts +7 -1
- package/src/adapters/real/sign-in-form.tsx +29 -13
- package/src/adapters/real/storage-settings.ts +37 -0
- package/src/adapters/real/storage.ts +65 -0
- package/src/authz/app-exemptions.ts +79 -9
- package/src/authz/route-scan.ts +626 -55
- package/src/components/auth/accept-invite-screen.tsx +5 -1
- package/src/components/auth/people-picker.tsx +20 -2
- package/src/components/profile-screen.tsx +27 -2
- package/src/core/inbound-email.ts +41 -6
- package/src/cutover/rows.json +13 -1
- package/src/db/audit.ts +2 -2
- package/src/db/family-suite.ts +42 -0
- package/src/db/family.ts +91 -0
- package/src/db/jobs.ts +19 -9
- package/src/db/keyset.ts +19 -30
- package/src/db/migrations/0015_app_user_grant.ts +1 -1
- package/src/db/notifications.ts +2 -2
- package/src/db/rls-coverage.ts +51 -17
- package/src/db/rls-proof-runner.ts +3 -2
- package/src/db/schedules.ts +11 -4
- package/src/db/webhooks.ts +4 -4
- package/src/demo-static/actor-drivers.ts +8 -2
- package/src/demo-static/email-html.ts +9 -0
- package/src/demo-static/tour/use-tours.tsx +8 -2
- package/src/demo-static/world.ts +76 -37
- package/src/email/send.ts +6 -2
- package/src/guide.md +26 -7
- package/src/i18n/messages/en.json +3 -0
- package/src/i18n/messages/es.json +3 -0
- package/src/i18n/messages.ts +3 -2
- package/src/ports/auth.ts +21 -2
- package/src/ports/db.ts +19 -0
- package/src/server-lib/invite.ts +34 -26
- package/src/server-lib/scheduled-tick.ts +5 -1
- package/src/server-lib/webhook-dispatch.ts +3 -0
- package/src/service-auth/mailgun.ts +19 -4
- package/src/testing/checks.json +9 -0
- package/src/testing/conformance/auth-provider.ts +308 -0
- package/src/testing/conformance/authz.ts +6 -2
- package/src/testing/conformance/db.ts +6 -5
- package/src/testing/conformance/i18n.ts +99 -5
- package/src/testing/conformance/suite.ts +65 -3
- package/src/testing/contract.ts +6 -4
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { Kysely,
|
|
2
|
-
import { Pool } from 'pg'
|
|
1
|
+
import { type Kysely, sql } from 'kysely'
|
|
3
2
|
import type { Login } from '../../db/owner-pass'
|
|
4
3
|
import type { DB } from '../../db/schema'
|
|
5
4
|
import { makeTestTmpDir } from '../../testing/tmp-dir'
|
|
@@ -33,7 +32,11 @@ export interface ContractServer {
|
|
|
33
32
|
readonly maintenanceDatabase: string
|
|
34
33
|
/** The URL of `database` on this server, as the superuser, or as `login` when given. */
|
|
35
34
|
urlFor(database: string, login?: { user: string; password: string }): string
|
|
36
|
-
/**
|
|
35
|
+
/**
|
|
36
|
+
* A pooled connection for a login to a database, through the REAL adapter (`createRealDb`: its pool, its type
|
|
37
|
+
* parsers, its connection-error listener), so a contract pass proves the driver configuration an app deploys.
|
|
38
|
+
* Closed by its caller, or by `stop`.
|
|
39
|
+
*/
|
|
37
40
|
connect(login: Login): Kysely<DB>
|
|
38
41
|
/** The superuser's connection to `database`. */
|
|
39
42
|
connectAsSuperuser(database: string): Kysely<DB>
|
|
@@ -104,6 +107,10 @@ export async function startContractServer(label: string, options: ContractServer
|
|
|
104
107
|
serverUrl = `postgres://postgres:postgres@localhost:${port}/postgres`
|
|
105
108
|
}
|
|
106
109
|
|
|
110
|
+
// Loaded here, not at the top: ./db reaches the migration registry, which imports the app's seam
|
|
111
|
+
// (`@sssb/app-config/*`), and a module that only needs this file's helpers (contractDatabaseName, say) must load
|
|
112
|
+
// without one.
|
|
113
|
+
const { createRealDb } = await import('./db')
|
|
107
114
|
const parsed = new URL(serverUrl)
|
|
108
115
|
const superuser = { user: decodeURIComponent(parsed.username), password: decodeURIComponent(parsed.password) }
|
|
109
116
|
const maintenanceDatabase = parsed.pathname.slice(1) || 'postgres'
|
|
@@ -120,14 +127,11 @@ export async function startContractServer(label: string, options: ContractServer
|
|
|
120
127
|
}
|
|
121
128
|
|
|
122
129
|
const connect = (login: Login): Kysely<DB> => {
|
|
123
|
-
|
|
124
|
-
//
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
|
|
128
|
-
pool.on('connect', (client) => client.on('error', (error) => console.warn(`contract db: ${error.message}`)))
|
|
129
|
-
pool.on('error', () => undefined)
|
|
130
|
-
const db = new Kysely<DB>({ dialect: new PostgresDialect({ pool }) })
|
|
130
|
+
// The real adapter's own pool, parsers and listeners: it used to be a bare `pg` Pool here, so an app's contract
|
|
131
|
+
// run proved a different driver configuration from the one it deploys (a `date` column came back as a JS Date
|
|
132
|
+
// here and as a string from the deployed adapter). Destroying the Kysely ends the pool, which `stop` does for
|
|
133
|
+
// every one still open.
|
|
134
|
+
const db = createRealDb(urlFor(login.database, login)).getDb()
|
|
131
135
|
open.push(db)
|
|
132
136
|
return db
|
|
133
137
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { Kysely, Transaction } from 'kysely'
|
|
2
2
|
import { migrateToLatest } from '../../db/migrate'
|
|
3
3
|
import type { DB } from '../../db/schema'
|
|
4
|
-
import {
|
|
4
|
+
import { family } from '../../db/family'
|
|
5
5
|
import type { DbPort } from '../../ports/db'
|
|
6
6
|
|
|
7
7
|
/**
|
|
@@ -10,6 +10,7 @@ import type { DbPort } from '../../ports/db'
|
|
|
10
10
|
*/
|
|
11
11
|
export function dbPortFor(db: Kysely<DB>): DbPort {
|
|
12
12
|
return {
|
|
13
|
+
isolation: family.isolation,
|
|
13
14
|
getDb() {
|
|
14
15
|
return db
|
|
15
16
|
},
|
|
@@ -17,7 +18,7 @@ export function dbPortFor(db: Kysely<DB>): DbPort {
|
|
|
17
18
|
// Real databases are provisioned/migrated by the deploy pipeline, not lazily.
|
|
18
19
|
},
|
|
19
20
|
async withTenant<T>(tenantId: string, fn: (trx: Transaction<DB>) => Promise<T>): Promise<T> {
|
|
20
|
-
return runWithTenant(db, tenantId, fn)
|
|
21
|
+
return family.runWithTenant(db, tenantId, fn)
|
|
21
22
|
},
|
|
22
23
|
async migrateToLatest() {
|
|
23
24
|
await migrateToLatest(db)
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import Mailgun from 'mailgun.js'
|
|
2
2
|
import type { EmailPort } from '../../ports/email'
|
|
3
|
+
import { assertSendableMessage } from '../email-message'
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* AUTHORED — CUTOVER (`email-outbound`): typechecked against mailgun.js, never sent for real.
|
|
@@ -10,6 +11,7 @@ export function createRealEmail(domain: string, apiKey: string, from: string): E
|
|
|
10
11
|
|
|
11
12
|
return {
|
|
12
13
|
async send(message) {
|
|
14
|
+
assertSendableMessage(message)
|
|
13
15
|
await client.messages.create(domain, {
|
|
14
16
|
from,
|
|
15
17
|
to: [message.to],
|
|
@@ -6,12 +6,12 @@ import { CutoverPendingError } from '../../ports/errors'
|
|
|
6
6
|
import type { JobsPort } from '../../ports/jobs'
|
|
7
7
|
import type { LlmPort } from '../../ports/llm'
|
|
8
8
|
import type { StoragePort } from '../../ports/storage'
|
|
9
|
-
import {
|
|
10
|
-
import { absentEmail, absentJobs, absentLlm } from './absent'
|
|
9
|
+
import { absentEmail, absentJobs, absentLlm, absentStorage } from './absent'
|
|
11
10
|
import { realAuth } from './auth'
|
|
12
11
|
import { DATABASE_ENV, databaseTransport } from './database-transport'
|
|
12
|
+
import { noAnalytics } from './no-analytics'
|
|
13
13
|
import { optionalPortsEnv, portChoice } from './optional-ports'
|
|
14
|
-
import {
|
|
14
|
+
import { assertEndpoint, parseForcePathStyle, parseUploadTarget } from './storage-settings'
|
|
15
15
|
|
|
16
16
|
interface RealPorts {
|
|
17
17
|
auth: AuthPort
|
|
@@ -26,19 +26,30 @@ interface RealPorts {
|
|
|
26
26
|
/**
|
|
27
27
|
* Env var -> cutover-checklist row, for what every real deployment needs. Fails fast with the full list, not one var
|
|
28
28
|
* at a time. The database's variables follow DATABASE_TRANSPORT (./database-transport.ts), and the optional ports'
|
|
29
|
-
* (LLM, outbound and inbound email, the job runner) follow their switches (./optional-ports.ts).
|
|
29
|
+
* (LLM, outbound and inbound email, the job runner, storage) follow their switches (./optional-ports.ts).
|
|
30
30
|
*/
|
|
31
31
|
const REQUIRED_ENV: Record<string, string> = {
|
|
32
32
|
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: 'auth-dev',
|
|
33
33
|
CLERK_SECRET_KEY: 'auth-dev',
|
|
34
|
-
STORAGE_BUCKET: 'cloud-accounts',
|
|
35
|
-
AWS_REGION: 'cloud-accounts',
|
|
36
34
|
// The shared secret the cron route (the scheduled tick) and the jobs webhook verify (`withWebhookSecret`).
|
|
37
35
|
WEBHOOK_SECRET: 'job-runner',
|
|
38
36
|
}
|
|
39
37
|
|
|
38
|
+
/**
|
|
39
|
+
* The Data API transport's region. Not in DATABASE_ENV, whose every variable SssbApp sets on the server: on Lambda the
|
|
40
|
+
* runtime sets AWS_REGION, a variable a function may not set itself. The optional ports that call AWS require it too
|
|
41
|
+
* (./optional-ports.ts).
|
|
42
|
+
*/
|
|
43
|
+
const DATA_API_REGION_ENV: Record<string, string> = { AWS_REGION: 'cloud-accounts' }
|
|
44
|
+
|
|
40
45
|
export function assertRealEnv(): void {
|
|
41
|
-
const
|
|
46
|
+
const transport = databaseTransport()
|
|
47
|
+
const required = {
|
|
48
|
+
...REQUIRED_ENV,
|
|
49
|
+
...DATABASE_ENV[transport],
|
|
50
|
+
...(transport === 'data-api' ? DATA_API_REGION_ENV : {}),
|
|
51
|
+
...optionalPortsEnv(),
|
|
52
|
+
}
|
|
42
53
|
const missing = Object.keys(required).filter((name) => !process.env[name])
|
|
43
54
|
if (missing.length > 0) {
|
|
44
55
|
const rows = [...new Set(missing.map((name) => required[name]))]
|
|
@@ -47,6 +58,17 @@ export function assertRealEnv(): void {
|
|
|
47
58
|
`Missing env: ${missing.join(', ')}. See docs/cutover-checklist.md.`,
|
|
48
59
|
)
|
|
49
60
|
}
|
|
61
|
+
// Present is not enough for the settings that choose behaviour: refuse here what the adapter would refuse at boot,
|
|
62
|
+
// in the same form (a CutoverPendingError, which `sssb check-real-env` prints), naming the row that holds them.
|
|
63
|
+
if (portChoice('storage') === 's3-compatible') {
|
|
64
|
+
try {
|
|
65
|
+
parseUploadTarget(process.env['STORAGE_UPLOAD_TARGET'] ?? '')
|
|
66
|
+
parseForcePathStyle(process.env['STORAGE_FORCE_PATH_STYLE'])
|
|
67
|
+
assertEndpoint(process.env['STORAGE_ENDPOINT'] ?? '')
|
|
68
|
+
} catch (error) {
|
|
69
|
+
throw new CutoverPendingError(['storage-compatible-store'], (error as Error).message)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
50
72
|
}
|
|
51
73
|
|
|
52
74
|
/**
|
|
@@ -81,8 +103,8 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
|
|
|
81
103
|
}
|
|
82
104
|
// Each database transport, PostHog and every optional adapter below is a dynamic import, so a deployment loads
|
|
83
105
|
// the SDK of what it chose and nothing else: a `pg` deployment never loads the RDS Data SDK and a Data API one never
|
|
84
|
-
// loads `pg`, PostHog loads only with a key, and a port switched off (`none`) never loads its vendor's
|
|
85
|
-
//
|
|
106
|
+
// loads `pg`, PostHog loads only with a key, and a port switched off (`none`) never loads its vendor's (storage's
|
|
107
|
+
// S3 SDK included). Auth (Clerk) serves every deployment, so it is imported as this module is.
|
|
86
108
|
const db =
|
|
87
109
|
databaseTransport() === 'data-api'
|
|
88
110
|
? (await import('./db-data-api')).createRealDataApiDb({
|
|
@@ -92,7 +114,21 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
|
|
|
92
114
|
region: need('AWS_REGION'),
|
|
93
115
|
})
|
|
94
116
|
: (await import('./db')).createRealDb(need('DATABASE_URL'))
|
|
95
|
-
const
|
|
117
|
+
const storageChoice = portChoice('storage')
|
|
118
|
+
const storage =
|
|
119
|
+
storageChoice === 's3'
|
|
120
|
+
? (await import('./storage')).createRealStorage(need('STORAGE_BUCKET'), need('AWS_REGION'))
|
|
121
|
+
: storageChoice === 's3-compatible'
|
|
122
|
+
? (await import('./storage')).createCompatibleStorage({
|
|
123
|
+
bucket: need('STORAGE_BUCKET'),
|
|
124
|
+
endpoint: need('STORAGE_ENDPOINT'),
|
|
125
|
+
region: need('STORAGE_REGION'),
|
|
126
|
+
accessKeyId: need('STORAGE_ACCESS_KEY_ID'),
|
|
127
|
+
secretAccessKey: need('STORAGE_SECRET_ACCESS_KEY'),
|
|
128
|
+
uploadTarget: need('STORAGE_UPLOAD_TARGET'),
|
|
129
|
+
forcePathStyle: env['STORAGE_FORCE_PATH_STYLE'],
|
|
130
|
+
})
|
|
131
|
+
: absentStorage
|
|
96
132
|
const llm =
|
|
97
133
|
portChoice('llm') === 'anthropic' ? (await import('./llm')).createRealLlm(need('ANTHROPIC_API_KEY')) : absentLlm
|
|
98
134
|
const email =
|
|
@@ -110,10 +146,11 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
|
|
|
110
146
|
: runner === 'in-process'
|
|
111
147
|
? await inProcessJobs(hooks, { db, storage, email, llm, auth: realAuth })
|
|
112
148
|
: absentJobs
|
|
113
|
-
// PostHog only where a key is configured (staging/prod per ADR-0010);
|
|
149
|
+
// PostHog only where a key is configured (staging/prod per ADR-0010); a no-op otherwise (./no-analytics.ts), never
|
|
150
|
+
// the simulated world's fake, which writes under `.data/`.
|
|
114
151
|
const analytics = env['POSTHOG_KEY']
|
|
115
152
|
? (await import('./analytics')).createRealAnalytics(env['POSTHOG_KEY'], env['POSTHOG_HOST'] ?? '')
|
|
116
|
-
:
|
|
153
|
+
: noAnalytics
|
|
117
154
|
return {
|
|
118
155
|
auth: realAuth,
|
|
119
156
|
db,
|
|
@@ -36,6 +36,15 @@ export const IN_PROCESS_LOST_AFTER_MS = 5 * 60_000
|
|
|
36
36
|
* another runner holds `running` (a service caller's, through its status route, or one the jobs webhook is walking
|
|
37
37
|
* to its end) is left to it.
|
|
38
38
|
*
|
|
39
|
+
* The sweep also fails a job still `queued` after `IN_PROCESS_LOST_AFTER_MS`: its row committed but `start` never
|
|
40
|
+
* claimed it (the invocation ended between the two, the runner failed to load, the request's `start` threw). A queued
|
|
41
|
+
* job carries no claim, so age alone decides, and that is sound for this runner only: with `JOBS_RUNNER=in-process`
|
|
42
|
+
* every job is this runner's, and `start` claims it in the invocation that committed it, within that invocation's
|
|
43
|
+
* 30-second limit, so a job queued for minutes will never start. It is failed, never run: a handler is written to run
|
|
44
|
+
* at most once, and the request or tick that submitted it may have reported it already. The CodeBuild runner has no
|
|
45
|
+
* sweep (a build may wait in CodeBuild's own queue), and neither does the simulated world, whose held jobs stay
|
|
46
|
+
* `queued` on purpose.
|
|
47
|
+
*
|
|
39
48
|
* A terminal status notifies the job's org admins as the jobs webhook route does, through `notify`, which the adapter
|
|
40
49
|
* registry passes in (the notification modules import the registry). Best effort: `notifyJobTerminal` swallows its
|
|
41
50
|
* own failures, and anything else `notify` throws is logged; neither fails a job that already finished.
|
|
@@ -68,22 +77,28 @@ export function createInProcessJobs(ports: JobRunPorts, notify: NotifyJobTermina
|
|
|
68
77
|
return 0
|
|
69
78
|
}
|
|
70
79
|
for (const tenant of tenants) {
|
|
71
|
-
let lost: { id: string }[]
|
|
80
|
+
let lost: { id: string; status: string }[]
|
|
72
81
|
try {
|
|
73
82
|
lost = await ports.db.withTenant(tenant.id, (trx) =>
|
|
74
83
|
trx
|
|
75
84
|
.selectFrom('jobs')
|
|
76
|
-
.select('jobs.id')
|
|
77
|
-
.where('jobs.status', '=', 'running')
|
|
85
|
+
.select(['jobs.id', 'jobs.status'])
|
|
78
86
|
.where('jobs.updated_at', '<', before)
|
|
79
|
-
.where((
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
.
|
|
85
|
-
|
|
86
|
-
|
|
87
|
+
.where((eb) =>
|
|
88
|
+
eb.or([
|
|
89
|
+
eb('jobs.status', '=', 'queued'),
|
|
90
|
+
eb.and([
|
|
91
|
+
eb('jobs.status', '=', 'running'),
|
|
92
|
+
eb.exists(
|
|
93
|
+
eb
|
|
94
|
+
.selectFrom('job_status_changes')
|
|
95
|
+
.select('job_status_changes.id')
|
|
96
|
+
.whereRef('job_status_changes.job_id', '=', 'jobs.id')
|
|
97
|
+
.where('job_status_changes.status', '=', 'running')
|
|
98
|
+
.where('job_status_changes.message', '=', IN_PROCESS_CLAIM),
|
|
99
|
+
),
|
|
100
|
+
]),
|
|
101
|
+
]),
|
|
87
102
|
)
|
|
88
103
|
.execute(),
|
|
89
104
|
)
|
|
@@ -91,10 +106,13 @@ export function createInProcessJobs(ports: JobRunPorts, notify: NotifyJobTermina
|
|
|
91
106
|
console.warn(`SSSB jobs: the in-process sweep skipped tenant ${tenant.id}: ${messageOf(error)}`)
|
|
92
107
|
continue
|
|
93
108
|
}
|
|
94
|
-
for (const { id } of lost) {
|
|
109
|
+
for (const { id, status } of lost) {
|
|
95
110
|
try {
|
|
96
111
|
await recordJobStatus(ports.db, tenant.id, id, 'failed', {
|
|
97
|
-
error:
|
|
112
|
+
error:
|
|
113
|
+
status === 'queued'
|
|
114
|
+
? 'lost: never started; the in-process runner did not claim it'
|
|
115
|
+
: 'lost: the server stopped before the in-process runner recorded an outcome',
|
|
98
116
|
})
|
|
99
117
|
} catch (error) {
|
|
100
118
|
if (!(error instanceof InvalidTransitionError)) {
|
|
@@ -102,7 +120,7 @@ export function createInProcessJobs(ports: JobRunPorts, notify: NotifyJobTermina
|
|
|
102
120
|
`SSSB jobs: the in-process sweep could not fail job ${id}: ${messageOf(error)}`,
|
|
103
121
|
)
|
|
104
122
|
}
|
|
105
|
-
continue // InvalidTransitionError: it finished, or another sweep failed it, meanwhile
|
|
123
|
+
continue // InvalidTransitionError: it started or finished, or another sweep failed it, meanwhile
|
|
106
124
|
}
|
|
107
125
|
failed += 1
|
|
108
126
|
await notifyBestEffort(tenant.id, id, 'failed')
|
|
@@ -8,9 +8,11 @@ import type { JobsPort } from '../../ports/jobs'
|
|
|
8
8
|
* the deployment's CloudFront replaces with its own signature) and
|
|
9
9
|
* `{ jobId, tenantId, status: 'completed' | 'failed', resultKey?, error? }`, which records the
|
|
10
10
|
* terminal transition via packages/kit/src/db/jobs.recordWebhookCompletion (idempotent under redelivery). The
|
|
11
|
-
* build receives its context through environment overrides, mirroring
|
|
12
|
-
*
|
|
13
|
-
* to
|
|
11
|
+
* build receives its context through environment overrides, mirroring a handler's `JobContext`: JOB_ID, JOB_KIND,
|
|
12
|
+
* JOB_TENANT_ID, which the webhook echoes back as `tenantId` so the completion is scoped to the right tenant without the
|
|
13
|
+
* build having to look it up, JOB_ORG_ID (empty for a job with no org), and JOB_PAYLOAD. Every override is PLAINTEXT,
|
|
14
|
+
* readable in the CodeBuild console and in CloudTrail, so a job's payload must never carry a secret or personal data:
|
|
15
|
+
* pass an id the build reads with its own access instead.
|
|
14
16
|
*/
|
|
15
17
|
export function createRealJobs(project: string, region: string): JobsPort {
|
|
16
18
|
const client = new CodeBuildClient({ region })
|
|
@@ -24,6 +26,7 @@ export function createRealJobs(project: string, region: string): JobsPort {
|
|
|
24
26
|
{ name: 'JOB_ID', value: job.id, type: 'PLAINTEXT' },
|
|
25
27
|
{ name: 'JOB_KIND', value: job.kind, type: 'PLAINTEXT' },
|
|
26
28
|
{ name: 'JOB_TENANT_ID', value: job.tenantId, type: 'PLAINTEXT' },
|
|
29
|
+
{ name: 'JOB_ORG_ID', value: job.orgId ?? '', type: 'PLAINTEXT' },
|
|
27
30
|
{ name: 'JOB_PAYLOAD', value: JSON.stringify(job.payload ?? {}), type: 'PLAINTEXT' },
|
|
28
31
|
],
|
|
29
32
|
}),
|
|
@@ -58,8 +58,10 @@ export async function handler(): Promise<{ ok: true }> {
|
|
|
58
58
|
// for infra that does not, and is there only if the cluster's secret attachment added it.
|
|
59
59
|
const database = process.env['DATABASE_NAME'] ?? dbname
|
|
60
60
|
if (!database) throw new Error('neither DATABASE_NAME nor the secret names the database to migrate')
|
|
61
|
+
// Every part a secret or a deployment supplies is encoded: a database name with a `/`, `?`, `#` or `%`
|
|
62
|
+
// would otherwise be read as a path, a query or an escape, and connect to a different database.
|
|
61
63
|
const db = createRealDb(
|
|
62
|
-
`postgres://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}/${database}`,
|
|
64
|
+
`postgres://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}/${encodeURIComponent(database)}`,
|
|
63
65
|
)
|
|
64
66
|
await db.migrateToLatest()
|
|
65
67
|
return { ok: true }
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AnalyticsPort } from '../../ports/analytics'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Analytics in a real deployment that configures no PostHog key (ADR-0010 enables PostHog in staging and production
|
|
5
|
+
* only). It captures nothing, and every flag answers the default its caller declares, as the PostHog adapter does when
|
|
6
|
+
* PostHog cannot be reached (./analytics.ts): a flag read is never load-bearing.
|
|
7
|
+
*
|
|
8
|
+
* Never the simulated world's fake (../fake/analytics.ts), which writes each capture and reads each flag under `.data/`
|
|
9
|
+
* in the working directory. On Lambda that directory is the deployment package, which is read-only, so the fake threw
|
|
10
|
+
* into whatever called it there: sending an invite awaits a capture.
|
|
11
|
+
*/
|
|
12
|
+
export const noAnalytics: AnalyticsPort = {
|
|
13
|
+
async capture() {},
|
|
14
|
+
async isFlagEnabled(_flag, defaultValue = false) {
|
|
15
|
+
return defaultValue
|
|
16
|
+
},
|
|
17
|
+
}
|
|
@@ -10,6 +10,20 @@
|
|
|
10
10
|
* with (`@sssb/kit/service-auth/mailgun`). Without it that route refuses every request, as it always has.
|
|
11
11
|
* - `JOBS_RUNNER`: `codebuild` (the default), `in-process` or `none`. The `jobs` port: a CodeBuild build per job, the
|
|
12
12
|
* job's handler run in the server itself (./jobs-in-process.ts), or no jobs at all.
|
|
13
|
+
* - `STORAGE_PROVIDER`: `s3` (the default), `s3-compatible` or `none`. The `storage` port: an S3 bucket
|
|
14
|
+
* (./s3-storage.ts), the same adapter on another store that speaks the S3 API (Cloudflare R2, MinIO, Backblaze B2),
|
|
15
|
+
* or no object storage at all. The framework itself stores nothing; an app's attachments, uploads and job artifacts
|
|
16
|
+
* do. `s3-compatible` is a choice of its own, not `s3` reading an endpoint when one is set: which settings happen
|
|
17
|
+
* to be set never picks behaviour (below). Beyond the required settings it reads `STORAGE_FORCE_PATH_STYLE`
|
|
18
|
+
* (`true` or `false`; unset leaves the SDK's own, virtual-hosted addressing), and requires `STORAGE_UPLOAD_TARGET`:
|
|
19
|
+
* `post` if the store accepts a presigned POST, which `createUploadTarget` is, or `none` if it does not (R2 does
|
|
20
|
+
* not), so that `createUploadTarget` fails naming the setting. Explicit and with no default, because either default
|
|
21
|
+
* would be a guess that fails on some store only when a browser first uploads.
|
|
22
|
+
*
|
|
23
|
+
* `AWS_REGION` is required by the choices that call AWS (`s3`, `codebuild`) and by the Data API transport
|
|
24
|
+
* (./index.ts), not by every deployment: one on `pg` with no storage and no CodeBuild runner calls no AWS API.
|
|
25
|
+
* `s3-compatible` reads `STORAGE_REGION` and its own key pair instead of `AWS_REGION` and the AWS keys, which Lambda
|
|
26
|
+
* reserves for the function's own role and region.
|
|
13
27
|
*
|
|
14
28
|
* An unset switch is its default, which is what real mode required before the switches existed, so a deployment that
|
|
15
29
|
* sets none of them boots as it did. `none` makes the port ABSENT (./absent.ts): its settings are not required, its
|
|
@@ -46,7 +60,27 @@ export const OPTIONAL_PORTS = {
|
|
|
46
60
|
jobs: {
|
|
47
61
|
variable: 'JOBS_RUNNER',
|
|
48
62
|
default: 'codebuild',
|
|
49
|
-
env: {
|
|
63
|
+
env: {
|
|
64
|
+
codebuild: { JOBS_CODEBUILD_PROJECT: 'job-runner', AWS_REGION: 'cloud-accounts' },
|
|
65
|
+
'in-process': {},
|
|
66
|
+
none: {},
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
storage: {
|
|
70
|
+
variable: 'STORAGE_PROVIDER',
|
|
71
|
+
default: 's3',
|
|
72
|
+
env: {
|
|
73
|
+
s3: { STORAGE_BUCKET: 'cloud-accounts', AWS_REGION: 'cloud-accounts' },
|
|
74
|
+
's3-compatible': {
|
|
75
|
+
STORAGE_BUCKET: 'storage-compatible-store',
|
|
76
|
+
STORAGE_ENDPOINT: 'storage-compatible-store',
|
|
77
|
+
STORAGE_REGION: 'storage-compatible-store',
|
|
78
|
+
STORAGE_UPLOAD_TARGET: 'storage-compatible-store',
|
|
79
|
+
STORAGE_ACCESS_KEY_ID: 'storage-compatible-credentials',
|
|
80
|
+
STORAGE_SECRET_ACCESS_KEY: 'storage-compatible-credentials',
|
|
81
|
+
},
|
|
82
|
+
none: {},
|
|
83
|
+
},
|
|
50
84
|
},
|
|
51
85
|
} as const satisfies Record<
|
|
52
86
|
string,
|
|
@@ -67,7 +67,13 @@ export function sqlSegments(sql: string): SqlSegment[] {
|
|
|
67
67
|
literal(blockCommentEnd(sql, i))
|
|
68
68
|
} else if (ch === "'") {
|
|
69
69
|
const escapes = (prev === 'E' || prev === 'e') && !IDENT_CHAR.test(i > 1 ? sql[i - 2]! : '')
|
|
70
|
-
|
|
70
|
+
// Two string constants separated only by whitespace holding a newline are one constant, and a
|
|
71
|
+
// continued E-string keeps its backslash escapes: `E'a'<newline>'\' $1'` is one string.
|
|
72
|
+
let end = quotedEnd(sql, i, "'", escapes)
|
|
73
|
+
for (let gap = CONTINUATION.exec(sql.slice(end)); gap; gap = CONTINUATION.exec(sql.slice(end))) {
|
|
74
|
+
end = quotedEnd(sql, end + gap[0].length - 1, "'", escapes)
|
|
75
|
+
}
|
|
76
|
+
literal(end)
|
|
71
77
|
} else if (ch === '"') {
|
|
72
78
|
literal(quotedEnd(sql, i, '"', false))
|
|
73
79
|
} else if (ch === '$' && !IDENT_CHAR.test(prev) && !/^\$\d/.test(sql.slice(i, i + 2))) {
|
|
@@ -88,6 +94,14 @@ export function sqlSegments(sql: string): SqlSegment[] {
|
|
|
88
94
|
return segments
|
|
89
95
|
}
|
|
90
96
|
|
|
97
|
+
/**
|
|
98
|
+
* Whitespace holding at least one newline (`\n` or a bare `\r`, both newlines to Postgres's lexer), then the `'` that
|
|
99
|
+
* continues a string constant. A known limit: Postgres
|
|
100
|
+
* also allows a `-- comment` in that gap (`'a' -- note<newline>'b'`), which this does not, so such SQL is split into
|
|
101
|
+
* two literals here. Hand-written SQL only; Kysely never writes it.
|
|
102
|
+
*/
|
|
103
|
+
const CONTINUATION = /^[ \t\f]*[\r\n]\s*'/
|
|
104
|
+
|
|
91
105
|
const PLACEHOLDER = new RegExp(`(?<!${IDENT_CHAR.source})\\$(\\d+)`, 'g')
|
|
92
106
|
|
|
93
107
|
/**
|
|
@@ -311,12 +325,26 @@ function serializeScalar(value: unknown): string {
|
|
|
311
325
|
if (typeof value === 'boolean') return value ? 'true' : 'false'
|
|
312
326
|
if (value instanceof Date) {
|
|
313
327
|
if (Number.isNaN(value.getTime())) throw new TypeError('cannot send an invalid Date to the database')
|
|
314
|
-
return value
|
|
328
|
+
return postgresInstant(value)
|
|
315
329
|
}
|
|
316
330
|
if (value instanceof Uint8Array) return `\\x${Buffer.from(value).toString('hex')}`
|
|
317
331
|
return JSON.stringify(value)
|
|
318
332
|
}
|
|
319
333
|
|
|
334
|
+
/**
|
|
335
|
+
* A Date as an instant Postgres's timestamp input reads. `toISOString` writes a year outside 1-9999 in its
|
|
336
|
+
* expanded form (`-000043-…`, `+010000-…`), which Postgres refuses ("time zone displacement out of range"), where
|
|
337
|
+
* node-postgres sends such a Date and Postgres stores it. So a year before 1 is written as its BC year (JavaScript's
|
|
338
|
+
* year 0 is 1 BC, -43 is 44 BC) with Postgres's ` BC` suffix, and a year after 9999 with its digits unpadded.
|
|
339
|
+
*/
|
|
340
|
+
function postgresInstant(value: Date): string {
|
|
341
|
+
const year = value.getUTCFullYear()
|
|
342
|
+
const iso = value.toISOString()
|
|
343
|
+
if (year >= 1 && year <= 9999) return iso
|
|
344
|
+
const rest = iso.slice(iso.indexOf('-', 1))
|
|
345
|
+
return year < 1 ? `${String(1 - year).padStart(4, '0')}${rest} BC` : `${year}${rest}`
|
|
346
|
+
}
|
|
347
|
+
|
|
320
348
|
function arrayLiteral(values: readonly unknown[]): string {
|
|
321
349
|
const items = values.map((item) => {
|
|
322
350
|
if (item === null || item === undefined) return 'NULL'
|
|
@@ -334,7 +362,8 @@ function arrayLiteral(values: readonly unknown[]): string {
|
|
|
334
362
|
* One result row, keyed by column label, each value decoded to what node-postgres returns through SSSB's
|
|
335
363
|
* pg adapter (../real/db.ts): `int8`/`numeric` as strings (but `numeric[]` elements as numbers, as
|
|
336
364
|
* node-postgres has it), `json`/`jsonb` parsed, `timestamptz` as a `Date` (`±Infinity` for infinity),
|
|
337
|
-
* `date` as the wire string, `bytea` as a Buffer, arrays element by element
|
|
365
|
+
* `date` as the wire string, `bytea` as a Buffer, arrays element by element (but an array of a type node-postgres
|
|
366
|
+
* has no array parser for, an enum's say, as Postgres's text form, `{happy,sad}`). Types SSSB's migrations do
|
|
338
367
|
* not use and node-postgres parses into objects (`interval`) come back as the Data API's string.
|
|
339
368
|
*/
|
|
340
369
|
export function decodeRow(record: readonly Field[], columns: readonly ColumnMetadata[]): Record<string, unknown> {
|
|
@@ -348,11 +377,66 @@ export function decodeRow(record: readonly Field[], columns: readonly ColumnMeta
|
|
|
348
377
|
export function decodeField(field: Field | undefined, typeName: string): unknown {
|
|
349
378
|
if (!field || field.isNull) return null
|
|
350
379
|
const type = typeName.toLowerCase().replace(/^"|"$/g, '')
|
|
351
|
-
if (field.arrayValue !== undefined)
|
|
380
|
+
if (field.arrayValue !== undefined) {
|
|
381
|
+
const baseType = type.replace(/^_/, '')
|
|
382
|
+
// node-postgres returns an array of a type it has no parser for (an enum's, `bit[]`, `name[]`) as Postgres's
|
|
383
|
+
// text form, `{happy,sad}`, not as a JS array: so does this, or the two transports would disagree.
|
|
384
|
+
if (!PG_PARSED_ARRAYS.has(baseType)) return arrayText(field.arrayValue)
|
|
385
|
+
return decodeArray(field.arrayValue, baseType)
|
|
386
|
+
}
|
|
352
387
|
const raw = field.stringValue ?? field.longValue ?? field.doubleValue ?? field.booleanValue ?? field.blobValue
|
|
353
388
|
return decodeScalar(raw, type)
|
|
354
389
|
}
|
|
355
390
|
|
|
391
|
+
/**
|
|
392
|
+
* The element types whose arrays node-postgres parses into a JS array: pg-types' text parsers (pg 8), named as
|
|
393
|
+
* `pg_type.typname` names them (`bpchar` is `char(n)`; `char`, the one-byte type, has none).
|
|
394
|
+
*/
|
|
395
|
+
const PG_PARSED_ARRAYS: ReadonlySet<string> = new Set([
|
|
396
|
+
'bool',
|
|
397
|
+
'bpchar',
|
|
398
|
+
'bytea',
|
|
399
|
+
'cidr',
|
|
400
|
+
'date',
|
|
401
|
+
'float4',
|
|
402
|
+
'float8',
|
|
403
|
+
'inet',
|
|
404
|
+
'int2',
|
|
405
|
+
'int4',
|
|
406
|
+
'int8',
|
|
407
|
+
'interval',
|
|
408
|
+
'json',
|
|
409
|
+
'jsonb',
|
|
410
|
+
'macaddr',
|
|
411
|
+
'money',
|
|
412
|
+
'numeric',
|
|
413
|
+
'numrange',
|
|
414
|
+
'oid',
|
|
415
|
+
'point',
|
|
416
|
+
'regproc',
|
|
417
|
+
'text',
|
|
418
|
+
'time',
|
|
419
|
+
'timestamp',
|
|
420
|
+
'timestamptz',
|
|
421
|
+
'timetz',
|
|
422
|
+
'uuid',
|
|
423
|
+
'varchar',
|
|
424
|
+
])
|
|
425
|
+
|
|
426
|
+
/** An array as Postgres's text output writes it: `{a,"b c",NULL,{1,2}}`. */
|
|
427
|
+
function arrayText(value: ArrayValue): string {
|
|
428
|
+
if (value.arrayValues) return `{${value.arrayValues.map((inner) => (inner ? arrayText(inner) : 'NULL')).join(',')}}`
|
|
429
|
+
const items: readonly unknown[] =
|
|
430
|
+
value.stringValues ?? value.longValues ?? value.doubleValues ?? value.booleanValues ?? []
|
|
431
|
+
return `{${items.map((item) => (item === null || item === undefined ? 'NULL' : arrayTextItem(String(item)))).join(',')}}`
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** One element of Postgres's array output: quoted, with `"` and `\` escaped, when it would not read back bare. */
|
|
435
|
+
function arrayTextItem(item: string): string {
|
|
436
|
+
if (item !== '' && !/[{}",\\\s]/.test(item) && item.toUpperCase() !== 'NULL') return item
|
|
437
|
+
return `"${item.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
|
|
438
|
+
}
|
|
439
|
+
|
|
356
440
|
function decodeArray(value: ArrayValue, baseType: string): unknown[] {
|
|
357
441
|
if (value.arrayValues) return value.arrayValues.map((inner) => (inner ? decodeArray(inner, baseType) : null))
|
|
358
442
|
const items: readonly unknown[] =
|
|
@@ -150,7 +150,6 @@ export class RdsDataEmulator implements RdsDataClientLike {
|
|
|
150
150
|
}
|
|
151
151
|
|
|
152
152
|
try {
|
|
153
|
-
const typeNames = await this.#types(client)
|
|
154
153
|
let result
|
|
155
154
|
try {
|
|
156
155
|
result = await client.query({ text, values, rowMode: 'array' })
|
|
@@ -158,6 +157,10 @@ export class RdsDataEmulator implements RdsDataClientLike {
|
|
|
158
157
|
// Message only, no SQLSTATE: the worst case the Data API is reported to return.
|
|
159
158
|
throw awsError('DatabaseErrorException', `ERROR: ${(error as Error).message}`, error)
|
|
160
159
|
}
|
|
160
|
+
const typeNames = await this.#types(
|
|
161
|
+
client,
|
|
162
|
+
result.fields.map((field) => field.dataTypeID),
|
|
163
|
+
)
|
|
161
164
|
const longAsString = input.resultSetOptions?.longReturnType === 'STRING'
|
|
162
165
|
const columns: ColumnMetadata[] = result.fields.map((field) => ({
|
|
163
166
|
name: field.name,
|
|
@@ -199,10 +202,15 @@ export class RdsDataEmulator implements RdsDataClientLike {
|
|
|
199
202
|
}
|
|
200
203
|
}
|
|
201
204
|
|
|
202
|
-
/**
|
|
205
|
+
/**
|
|
206
|
+
* `pg_type.typname` by oid, which is what PgJDBC reports as a column's type name (`_text` for text[]). Read again
|
|
207
|
+
* when a result has an oid the cached map lacks: a type a migration created after the first read (an enum, its
|
|
208
|
+
* array) would otherwise be `unknown` for ever, and a value of it would come back in whatever shape `unknown`
|
|
209
|
+
* gets, hiding what the real Data API sends for it.
|
|
210
|
+
*/
|
|
203
211
|
// On the connection already held — with `maxConnections: 1` a second checkout would wait forever.
|
|
204
|
-
async #types(client: PoolClient): Promise<Map<number, string>> {
|
|
205
|
-
if (!this.#typeNames) {
|
|
212
|
+
async #types(client: PoolClient, oids: readonly number[]): Promise<Map<number, string>> {
|
|
213
|
+
if (!this.#typeNames || oids.some((oid) => !this.#typeNames!.has(oid))) {
|
|
206
214
|
const { rows } = await client.query<{ oid: string; typname: string }>('SELECT oid, typname FROM pg_type')
|
|
207
215
|
this.#typeNames = new Map(rows.map((row) => [Number(row.oid), row.typname]))
|
|
208
216
|
}
|
|
@@ -43,9 +43,15 @@ export interface S3StorageOptions {
|
|
|
43
43
|
credentials?: S3ClientConfig['credentials'] | undefined
|
|
44
44
|
/** Address the bucket in the path (`https://host/bucket/key`), as most S3-compatible endpoints need. */
|
|
45
45
|
forcePathStyle?: boolean | undefined
|
|
46
|
+
/**
|
|
47
|
+
* When the client adds a checksum to a request, and checks one on a response (the SDK's own: `WHEN_SUPPORTED`).
|
|
48
|
+
* `WHEN_REQUIRED` is for stores that reject the checksum headers the default adds.
|
|
49
|
+
*/
|
|
50
|
+
requestChecksumCalculation?: S3ClientConfig['requestChecksumCalculation'] | undefined
|
|
51
|
+
responseChecksumValidation?: S3ClientConfig['responseChecksumValidation'] | undefined
|
|
46
52
|
/**
|
|
47
53
|
* A client the caller built, used as it is: for a client shared with other code, or one a test controls.
|
|
48
|
-
* Given with any of `region`, `endpoint`, `credentials` or
|
|
54
|
+
* Given with any of `region`, `endpoint`, `credentials`, `forcePathStyle` or a checksum setting, it is refused, since those would be
|
|
49
55
|
* silently ignored.
|
|
50
56
|
*/
|
|
51
57
|
client?: S3Client | undefined
|