@sssb/kit 0.0.0 → 0.3.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/dist/core/webhook-hmac.d.ts +69 -0
- package/dist/release.json +1 -0
- package/dist/testing/e2e.d.ts +15 -0
- package/dist/testing/e2e.js +195 -0
- package/package.json +212 -5
- package/src/adapters/README.md +6 -0
- package/src/adapters/dev-server.ts +21 -0
- package/src/adapters/fake/agreements.ts +81 -0
- package/src/adapters/fake/analytics.ts +93 -0
- package/src/adapters/fake/atomic-write.ts +161 -0
- package/src/adapters/fake/audit.ts +58 -0
- package/src/adapters/fake/auth.ts +313 -0
- package/src/adapters/fake/clock.ts +54 -0
- package/src/adapters/fake/data-dir.ts +27 -0
- package/src/adapters/fake/db.ts +88 -0
- package/src/adapters/fake/email.ts +46 -0
- package/src/adapters/fake/jobs.ts +248 -0
- package/src/adapters/fake/llm.ts +230 -0
- package/src/adapters/fake/pglite-dialect.ts +124 -0
- package/src/adapters/fake/service-auth.ts +145 -0
- package/src/adapters/fake/simulator-admin.ts +203 -0
- package/src/adapters/fake/simulator.ts +93 -0
- package/src/adapters/fake/sms.ts +43 -0
- package/src/adapters/fake/storage.ts +288 -0
- package/src/adapters/fake/webhooks.ts +98 -0
- package/src/adapters/index.ts +142 -0
- package/src/adapters/lazy-jobs.ts +25 -0
- package/src/adapters/proxy.ts +34 -0
- package/src/adapters/real/absent.ts +41 -0
- package/src/adapters/real/accept-invite-form.tsx +77 -0
- package/src/adapters/real/analytics.ts +28 -0
- package/src/adapters/real/auth.ts +216 -0
- package/src/adapters/real/clerk-proxy.ts +111 -0
- package/src/adapters/real/contract-data-api.ts +104 -0
- package/src/adapters/real/contract-postgres.ts +167 -0
- package/src/adapters/real/database-transport.ts +34 -0
- package/src/adapters/real/db-data-api.ts +61 -0
- package/src/adapters/real/db-port.ts +26 -0
- package/src/adapters/real/db.ts +69 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +139 -0
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +33 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -0
- package/src/adapters/real/optional-ports.ts +78 -0
- package/src/adapters/real/providers.tsx +12 -0
- package/src/adapters/real/rds-data-codec.ts +508 -0
- package/src/adapters/real/rds-data-dialect.ts +470 -0
- package/src/adapters/real/rds-data-emulator.ts +351 -0
- package/src/adapters/real/s3-storage.ts +233 -0
- package/src/adapters/real/sign-in-form.tsx +59 -0
- package/src/adapters/real/storage.ts +10 -0
- package/src/adapters/run-mode.ts +11 -0
- package/src/adapters/sentry/baseline.ts +90 -0
- package/src/adapters/sentry/client.ts +17 -0
- package/src/adapters/sentry/init.ts +17 -0
- package/src/authz/app-exemptions.ts +226 -0
- package/src/authz/authorize.ts +214 -0
- package/src/authz/route-policy.ts +153 -0
- package/src/authz/route-scan.ts +1516 -0
- package/src/components/agreements/acceptances-section.tsx +55 -0
- package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
- package/src/components/agreements/agreement-body.tsx +34 -0
- package/src/components/agreements/agreement-gate.tsx +45 -0
- package/src/components/app-header.tsx +45 -0
- package/src/components/auth/accept-invite-screen.tsx +126 -0
- package/src/components/auth/auth-icons.tsx +68 -0
- package/src/components/auth/org-switcher.tsx +76 -0
- package/src/components/auth/people-picker.tsx +50 -0
- package/src/components/auth/preview-row.tsx +64 -0
- package/src/components/auth/sign-in-screen.tsx +24 -0
- package/src/components/auth/user-menu.tsx +64 -0
- package/src/components/demo-badge.tsx +20 -0
- package/src/components/demo-banner.tsx +14 -0
- package/src/components/gates/gate-interstitial.tsx +23 -0
- package/src/components/job-timeline.tsx +64 -0
- package/src/components/notifications/notification-bell.tsx +120 -0
- package/src/components/notifications/notification-prefs-section.tsx +112 -0
- package/src/components/org-screen.tsx +197 -0
- package/src/components/profile-screen.tsx +100 -0
- package/src/components/simulator/actor-runtime.ts +180 -0
- package/src/components/simulator/actor-shell.tsx +275 -0
- package/src/components/simulator/actors-app.tsx +119 -0
- package/src/components/simulator/errors-app.tsx +84 -0
- package/src/components/simulator/events-app.tsx +210 -0
- package/src/components/simulator/format-when.ts +20 -0
- package/src/components/simulator/hooks-app.tsx +319 -0
- package/src/components/simulator/inbound-app.tsx +210 -0
- package/src/components/simulator/jobs-app.tsx +471 -0
- package/src/components/simulator/mail-app.tsx +290 -0
- package/src/components/simulator/messages-app.tsx +64 -0
- package/src/components/simulator/people-app.tsx +140 -0
- package/src/components/simulator/people-dimensions.ts +16 -0
- package/src/components/simulator/simulator-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +704 -0
- package/src/components/simulator/snapshots-app.tsx +398 -0
- package/src/components/simulator/tab-mount.ts +25 -0
- package/src/components/simulator/tours-app.tsx +105 -0
- package/src/components/webhook-endpoints-card.tsx +172 -0
- package/src/core/abilities.ts +464 -0
- package/src/core/agreements.ts +139 -0
- package/src/core/gates.ts +157 -0
- package/src/core/greeting.ts +11 -0
- package/src/core/inbound-email.ts +129 -0
- package/src/core/jobs.ts +51 -0
- package/src/core/keyset.ts +227 -0
- package/src/core/llm-models.ts +10 -0
- package/src/core/locale.ts +3 -0
- package/src/core/notifications.ts +182 -0
- package/src/core/presets.ts +456 -0
- package/src/core/roles.ts +47 -0
- package/src/core/same-origin-path.ts +20 -0
- package/src/core/schedules.ts +147 -0
- package/src/core/standard-schema.ts +56 -0
- package/src/core/state-machine.ts +43 -0
- package/src/core/webhook-events.ts +86 -0
- package/src/core/webhook-hmac.ts +248 -0
- package/src/core/webhook-signing.ts +27 -0
- package/src/cutover/rows.json +101 -0
- package/src/db/agreements.ts +176 -0
- package/src/db/app-roles.ts +197 -0
- package/src/db/audit.ts +356 -0
- package/src/db/inbound-email.ts +145 -0
- package/src/db/jobs.ts +300 -0
- package/src/db/jsonb.ts +18 -0
- package/src/db/keyset.ts +179 -0
- package/src/db/migrate.ts +73 -0
- package/src/db/migrations/0001_tenants.ts +25 -0
- package/src/db/migrations/0003_organizations.ts +27 -0
- package/src/db/migrations/0004_jobs.ts +64 -0
- package/src/db/migrations/0005_service_keys.ts +33 -0
- package/src/db/migrations/0008_audit_events.ts +51 -0
- package/src/db/migrations/0009_job_schedules.ts +52 -0
- package/src/db/migrations/0010_webhooks.ts +100 -0
- package/src/db/migrations/0011_notifications.ts +98 -0
- package/src/db/migrations/0012_inbound_email.ts +74 -0
- package/src/db/migrations/0013_agreements.ts +98 -0
- package/src/db/migrations/0014_audit_credential.ts +29 -0
- package/src/db/migrations/0015_app_user_grant.ts +67 -0
- package/src/db/migrations/0016_audit_detail.ts +26 -0
- package/src/db/migrations/index.ts +49 -0
- package/src/db/notifications.ts +185 -0
- package/src/db/org-lookup.ts +104 -0
- package/src/db/owner-pass.ts +252 -0
- package/src/db/rls-coverage.ts +259 -0
- package/src/db/rls-proof-runner.ts +94 -0
- package/src/db/rls-proofs.ts +1176 -0
- package/src/db/schedules.ts +187 -0
- package/src/db/schema.ts +235 -0
- package/src/db/seed.ts +176 -0
- package/src/db/service-keys.ts +50 -0
- package/src/db/tenant-lookup.ts +13 -0
- package/src/db/webhooks.ts +483 -0
- package/src/db/with-tenant.ts +26 -0
- package/src/demo-static/actor-drivers.ts +161 -0
- package/src/demo-static/assistant-replay.ts +61 -0
- package/src/demo-static/contracts.ts +282 -0
- package/src/demo-static/email-html.ts +58 -0
- package/src/demo-static/hash-route.ts +24 -0
- package/src/demo-static/rows.ts +105 -0
- package/src/demo-static/shell.tsx +440 -0
- package/src/demo-static/tour/contracts.ts +97 -0
- package/src/demo-static/tour/driver.ts +320 -0
- package/src/demo-static/tour/tour-overlay.tsx +226 -0
- package/src/demo-static/tour/use-tours.tsx +394 -0
- package/src/demo-static/world.ts +1480 -0
- package/src/email/send.ts +12 -0
- package/src/email/templates/digest-email.tsx +61 -0
- package/src/email/templates/invite-email.tsx +57 -0
- package/src/email/templates/notification-email.tsx +39 -0
- package/src/guide.md +132 -0
- package/src/i18n/messages/en.json +373 -0
- package/src/i18n/messages/es.json +373 -0
- package/src/i18n/messages.ts +34 -0
- package/src/i18n/namespaces.ts +32 -0
- package/src/i18n/request.ts +34 -0
- package/src/i18n/routing.ts +7 -0
- package/src/inbound-email/handlers.ts +67 -0
- package/src/inbound-email/intake.ts +180 -0
- package/src/jobs/digest-email.ts +112 -0
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +44 -0
- package/src/ports/README.md +8 -0
- package/src/ports/analytics.ts +8 -0
- package/src/ports/auth.ts +87 -0
- package/src/ports/db.ts +27 -0
- package/src/ports/email.ts +14 -0
- package/src/ports/errors.ts +46 -0
- package/src/ports/jobs.ts +69 -0
- package/src/ports/llm.ts +85 -0
- package/src/ports/storage.ts +132 -0
- package/src/seed/contracts.ts +129 -0
- package/src/server-lib/assistant.ts +45 -0
- package/src/server-lib/defer.ts +57 -0
- package/src/server-lib/demo-presets.ts +85 -0
- package/src/server-lib/invite.ts +92 -0
- package/src/server-lib/notify-deps.ts +15 -0
- package/src/server-lib/notify.ts +252 -0
- package/src/server-lib/preset-operations.ts +121 -0
- package/src/server-lib/scheduled-tick.ts +48 -0
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +80 -0
- package/src/service-auth/webhook.ts +69 -0
- package/src/testing/checks.json +103 -0
- package/src/testing/conformance/authz.ts +46 -0
- package/src/testing/conformance/db.ts +258 -0
- package/src/testing/conformance/demo-presets.ts +295 -0
- package/src/testing/conformance/i18n.ts +80 -0
- package/src/testing/conformance/register.ts +200 -0
- package/src/testing/conformance/seam-map.ts +205 -0
- package/src/testing/conformance/suite.ts +59 -0
- package/src/testing/conformance/types.ts +18 -0
- package/src/testing/contract.ts +200 -0
- package/src/testing/e2e.ts +15 -0
- package/src/testing/index.ts +6 -0
- package/src/testing/seam-specifiers.json +22 -0
- package/src/testing/tmp-dir-marker.d.mts +4 -0
- package/src/testing/tmp-dir-marker.mjs +5 -0
- package/src/testing/tmp-dir.ts +182 -0
- package/src/theme.ts +28 -0
- package/README.md +0 -3
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import {
|
|
3
|
+
BeginTransactionCommand,
|
|
4
|
+
CommitTransactionCommand,
|
|
5
|
+
ExecuteStatementCommand,
|
|
6
|
+
RollbackTransactionCommand,
|
|
7
|
+
type BeginTransactionCommandOutput,
|
|
8
|
+
type CommitTransactionCommandOutput,
|
|
9
|
+
type ExecuteStatementCommandOutput,
|
|
10
|
+
} from '@aws-sdk/client-rds-data'
|
|
11
|
+
import {
|
|
12
|
+
AbortedTransactionError,
|
|
13
|
+
CompiledQuery,
|
|
14
|
+
PostgresAdapter,
|
|
15
|
+
sql,
|
|
16
|
+
PostgresIntrospector,
|
|
17
|
+
PostgresQueryCompiler,
|
|
18
|
+
type DatabaseConnection,
|
|
19
|
+
type Dialect,
|
|
20
|
+
type Driver,
|
|
21
|
+
type Kysely,
|
|
22
|
+
type QueryResult,
|
|
23
|
+
type TransactionSettings,
|
|
24
|
+
} from 'kysely'
|
|
25
|
+
import {
|
|
26
|
+
castPlaceholder,
|
|
27
|
+
commitOutcome,
|
|
28
|
+
decodeRow,
|
|
29
|
+
describableSql,
|
|
30
|
+
leadingKeyword,
|
|
31
|
+
normalizeDatabaseError,
|
|
32
|
+
RdsDataUnsupportedError,
|
|
33
|
+
rewritePlaceholders,
|
|
34
|
+
toSqlParameter,
|
|
35
|
+
unsupportedStatement,
|
|
36
|
+
} from './rds-data-codec'
|
|
37
|
+
|
|
38
|
+
/** The four calls this dialect makes. `RDSDataClient` satisfies it, and so does the test emulator. */
|
|
39
|
+
export type RdsDataCommand =
|
|
40
|
+
BeginTransactionCommand | CommitTransactionCommand | RollbackTransactionCommand | ExecuteStatementCommand
|
|
41
|
+
|
|
42
|
+
export interface RdsDataClientLike {
|
|
43
|
+
send(command: RdsDataCommand): Promise<unknown>
|
|
44
|
+
destroy?(): void
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface RdsDataDialectConfig {
|
|
48
|
+
client: RdsDataClientLike
|
|
49
|
+
/** The Aurora cluster's ARN (the Data API must be enabled on it). */
|
|
50
|
+
resourceArn: string
|
|
51
|
+
/** The Secrets Manager secret holding the database user's credentials. */
|
|
52
|
+
secretArn: string
|
|
53
|
+
database: string
|
|
54
|
+
/** How long a SQL shape's inferred parameter types are trusted; `TYPE_CACHE_TTL_MS` when omitted. */
|
|
55
|
+
typeCacheTtlMs?: number | undefined
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Kysely over the Amazon RDS Data API: Postgres's adapter, compiler and introspector, with a driver that
|
|
60
|
+
* speaks HTTPS to the Data API instead of the wire protocol to a socket. ADR-0002's addendum of
|
|
61
|
+
* 2026-11-16 records why it exists (a Lambda outside any VPC, with no NAT, reaching Aurora) and why it is
|
|
62
|
+
* written here rather than taken from the community `kysely-data-api`.
|
|
63
|
+
*
|
|
64
|
+
* A "connection" is a handle with an optional transaction id; there is no socket and nothing to pool.
|
|
65
|
+
* Statements outside a transaction are independent HTTPS calls, each autocommitted, and the Data API
|
|
66
|
+
* resets the session (`DISCARD ALL`) between them — so session state exists only inside a transaction,
|
|
67
|
+
* which is the one place SSSB ever sets it (`runWithTenant`'s one statement setting `role` and
|
|
68
|
+
* `app.current_tenant`, both with `set_config(…, true)`). What it cannot do fails loudly: streaming
|
|
69
|
+
* (`RdsDataConnection.streamQuery` below), and (./rds-data-codec.ts, `unsupportedStatement`) transaction
|
|
70
|
+
* control in SQL and session state outside a transaction (session-level advisory locks included — which is
|
|
71
|
+
* why the migrator runs in one transaction, ./db-data-api.ts).
|
|
72
|
+
*
|
|
73
|
+
* AUTHORED — CUTOVER (`data-api`): proven against real Postgres through a strict emulator
|
|
74
|
+
* (./rds-data-emulator.ts, `pnpm test:contract`); never run against the Data API itself.
|
|
75
|
+
*/
|
|
76
|
+
export class RdsDataDialect implements Dialect {
|
|
77
|
+
private readonly config: RdsDataDialectConfig
|
|
78
|
+
|
|
79
|
+
constructor(config: RdsDataDialectConfig) {
|
|
80
|
+
this.config = config
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
createAdapter() {
|
|
84
|
+
return new RdsDataPostgresAdapter()
|
|
85
|
+
}
|
|
86
|
+
createDriver(): Driver {
|
|
87
|
+
return new RdsDataDriver(this.config)
|
|
88
|
+
}
|
|
89
|
+
createQueryCompiler() {
|
|
90
|
+
return new PostgresQueryCompiler()
|
|
91
|
+
}
|
|
92
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
|
|
93
|
+
createIntrospector(db: Kysely<any>) {
|
|
94
|
+
return new PostgresIntrospector(db)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Kysely's own Postgres migration-lock id, so a `pg` migrator and a Data API one exclude each other. */
|
|
99
|
+
const MIGRATION_LOCK_ID = '3853314791062309107'
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Postgres's adapter with a TRANSACTION-scoped migration lock. Kysely's takes a session-level
|
|
103
|
+
* `pg_advisory_lock` on `db.connection()`, outside the migration transaction — which on the Data API is a
|
|
104
|
+
* separate autocommitted call whose lock the connection reset (`DISCARD ALL`) drops at once, so two
|
|
105
|
+
* migrators would not exclude each other at all. Here the lock is `pg_advisory_xact_lock`, taken inside
|
|
106
|
+
* the one transaction the migrations run in (./db-data-api.ts hands the Migrator a Transaction), and
|
|
107
|
+
* released by its commit or rollback, so there is nothing to release by hand — and no unlock statement to
|
|
108
|
+
* fail in an aborted transaction and replace the migration's own error.
|
|
109
|
+
*/
|
|
110
|
+
class RdsDataPostgresAdapter extends PostgresAdapter {
|
|
111
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's DialectAdapter signature
|
|
112
|
+
override async acquireMigrationLock(db: Kysely<any>): Promise<void> {
|
|
113
|
+
// Outside a transaction a transaction-scoped lock autocommits and is gone at once, so a Migrator
|
|
114
|
+
// handed the plain db (an adopter's own migrate-down script, say) would run unlocked. Refuse it.
|
|
115
|
+
if (!db.isTransaction) {
|
|
116
|
+
throw new RdsDataUnsupportedError(
|
|
117
|
+
'run the Migrator inside one transaction on the Data API (the db port’s migrateToLatest does), or its lock is released at once',
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
await lockMigrations(db)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
override async releaseMigrationLock(): Promise<void> {}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Takes the migration lock for the rest of the current transaction. ./db-data-api.ts calls it as the
|
|
128
|
+
* migration transaction's FIRST statement, because Kysely creates its own bookkeeping tables before it
|
|
129
|
+
* asks the adapter for the lock — and two migrators doing that inside two open transactions collide on
|
|
130
|
+
* the catalog, which aborts the loser's transaction (Kysely's tolerance for that race assumes autocommit).
|
|
131
|
+
* Advisory locks stack within a transaction, so the adapter taking it again is harmless.
|
|
132
|
+
*/
|
|
133
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- any Kysely or Transaction will do
|
|
134
|
+
export async function lockMigrations(db: Kysely<any>): Promise<void> {
|
|
135
|
+
await sql`select pg_advisory_xact_lock(${sql.raw(MIGRATION_LOCK_ID)})`.execute(db)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** How many SQL texts' parameter types are remembered before the cache starts over. */
|
|
139
|
+
const TYPE_CACHE_LIMIT = 2000
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* How long a SQL shape's inferred types are trusted: five minutes. A cached type outlives a schema change
|
|
143
|
+
* SILENTLY — a `date` column changed to `timestamptz` goes on receiving midnight through a warm cache,
|
|
144
|
+
* where node-postgres stores the instant (ADR-0002's addendum of 2026-11-16 states the limit) — so the
|
|
145
|
+
* cache must forget. Five minutes bounds that window to about the time a deploy's migration takes to
|
|
146
|
+
* settle, and costs one describe per shape per five minutes per warm process (three extra calls inside a
|
|
147
|
+
* transaction, five outside): for three hundred shapes all in use, one describe a second. Shorter buys
|
|
148
|
+
* little and spends round trips on every request; longer leaves an out-of-band migration's mismatch live.
|
|
149
|
+
*/
|
|
150
|
+
const TYPE_CACHE_TTL_MS = 5 * 60 * 1000
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* A paused Aurora Serverless v2 (min capacity 0, as SSSB's non-production stack runs) answers the first
|
|
154
|
+
* call with DatabaseResumingException: the request was cancelled, not run, so retrying it is safe. Every
|
|
155
|
+
* other failure is NOT retried — the SDK's own retries are off (`maxAttempts: 1` in ./db-data-api.ts) because AWS
|
|
156
|
+
* warns that a retried statement whose first attempt actually finished can write twice.
|
|
157
|
+
*/
|
|
158
|
+
const RESUME_DELAYS_MS = [1000, 2000, 4000, 8000]
|
|
159
|
+
|
|
160
|
+
class RdsDataDriver implements Driver {
|
|
161
|
+
readonly #types = new Map<string, { readonly types: readonly string[]; readonly at: number }>()
|
|
162
|
+
|
|
163
|
+
private readonly config: RdsDataDialectConfig
|
|
164
|
+
|
|
165
|
+
constructor(config: RdsDataDialectConfig) {
|
|
166
|
+
this.config = config
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
async init(): Promise<void> {}
|
|
170
|
+
|
|
171
|
+
async acquireConnection(): Promise<DatabaseConnection> {
|
|
172
|
+
return new RdsDataConnection(this)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async releaseConnection(): Promise<void> {}
|
|
176
|
+
|
|
177
|
+
async beginTransaction(connection: DatabaseConnection, settings: TransactionSettings): Promise<void> {
|
|
178
|
+
const conn = asConnection(connection)
|
|
179
|
+
if (conn.transactionId) throw new RdsDataUnsupportedError('a transaction is already open on this connection')
|
|
180
|
+
const { resourceArn, secretArn, database } = this.config
|
|
181
|
+
const begun = (await this.call(
|
|
182
|
+
new BeginTransactionCommand({ resourceArn, secretArn, database }),
|
|
183
|
+
)) as BeginTransactionCommandOutput
|
|
184
|
+
if (!begun.transactionId) throw new Error('RDS Data API: BeginTransaction returned no transaction id')
|
|
185
|
+
conn.transactionId = begun.transactionId
|
|
186
|
+
conn.failed = false
|
|
187
|
+
// BeginTransaction takes no isolation level or access mode; Postgres accepts them as the
|
|
188
|
+
// transaction's first statement instead. If that fails, Kysely never learns the transaction began
|
|
189
|
+
// and will not roll it back — so this does, rather than strand it for the three idle minutes.
|
|
190
|
+
const modes = [
|
|
191
|
+
settings.isolationLevel ? `isolation level ${settings.isolationLevel}` : '',
|
|
192
|
+
settings.accessMode ?? '',
|
|
193
|
+
].filter(Boolean)
|
|
194
|
+
if (modes.length > 0) {
|
|
195
|
+
try {
|
|
196
|
+
await conn.executeQuery(CompiledQuery.raw(`set transaction ${modes.join(' ')}`))
|
|
197
|
+
} catch (error) {
|
|
198
|
+
await this.rollbackTransaction(conn).catch(() => undefined)
|
|
199
|
+
throw error
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* A commit can fail — a deferred constraint, a serialization failure, a transaction the Data API
|
|
206
|
+
* already timed out — and Kysely then calls rollbackTransaction. Whatever that call does must not
|
|
207
|
+
* replace the commit's own error, whose `code` callers act on. Two defences, either one sufficient:
|
|
208
|
+
* the id is cleared only after a successful commit (so the rollback finds the transaction, and a
|
|
209
|
+
* "gone" answer is swallowed), and a rollback with no id is a no-op. The contract suite's deferred-
|
|
210
|
+
* constraint case goes red only when both are undone as the bug they replaced had it: the id cleared
|
|
211
|
+
* before the commit, AND a rollback with no id that throws. Merely deleting the no-op leaves it green,
|
|
212
|
+
* because the emulator answers a rollback with no id as TransactionNotFoundException, which is swallowed.
|
|
213
|
+
*/
|
|
214
|
+
async commitTransaction(connection: DatabaseConnection): Promise<void> {
|
|
215
|
+
const conn = asConnection(connection)
|
|
216
|
+
const transactionId = conn.transactionId
|
|
217
|
+
if (!transactionId) throw new Error('RDS Data API: no transaction is open on this connection')
|
|
218
|
+
// A statement failed and the caller carried on (it caught the error). Postgres has aborted the
|
|
219
|
+
// transaction, and a COMMIT would quietly roll it back — node-postgres sees that as a ROLLBACK tag
|
|
220
|
+
// and Kysely's pg driver throws. The Data API's answer to such a commit is unknown, so this does not
|
|
221
|
+
// ask it: it rolls back and throws the same error the pg driver does.
|
|
222
|
+
if (conn.failed) {
|
|
223
|
+
await this.rollbackTransaction(conn)
|
|
224
|
+
throw new AbortedTransactionError()
|
|
225
|
+
}
|
|
226
|
+
const { resourceArn, secretArn } = this.config
|
|
227
|
+
const answer = (await this.call(
|
|
228
|
+
new CommitTransactionCommand({ resourceArn, secretArn, transactionId }),
|
|
229
|
+
)) as CommitTransactionCommandOutput
|
|
230
|
+
conn.transactionId = undefined
|
|
231
|
+
// The call returning is not the transaction committing: the answer says which it did. Either way the
|
|
232
|
+
// transaction is over, so the id is cleared first and Kysely's follow-up rollback is a no-op.
|
|
233
|
+
const outcome = commitOutcome(answer.transactionStatus)
|
|
234
|
+
if (outcome === 'rolled back') throw new AbortedTransactionError()
|
|
235
|
+
if (outcome === 'unknown') {
|
|
236
|
+
throw new Error(
|
|
237
|
+
`RDS Data API: CommitTransaction answered ${JSON.stringify(answer.transactionStatus)}, not "Transaction Committed" — the transaction's writes may not be saved`,
|
|
238
|
+
)
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async rollbackTransaction(connection: DatabaseConnection): Promise<void> {
|
|
243
|
+
const conn = asConnection(connection)
|
|
244
|
+
const transactionId = conn.transactionId
|
|
245
|
+
if (!transactionId) return
|
|
246
|
+
conn.transactionId = undefined
|
|
247
|
+
const { resourceArn, secretArn } = this.config
|
|
248
|
+
try {
|
|
249
|
+
await this.call(new RollbackTransactionCommand({ resourceArn, secretArn, transactionId }))
|
|
250
|
+
} catch (error) {
|
|
251
|
+
// Already gone means already rolled back: the Data API rolls a transaction back itself when it
|
|
252
|
+
// idles for three minutes or reaches an hour, and a failed commit ends it too. Rethrowing would
|
|
253
|
+
// only replace the error that made Kysely roll back with one that says nothing about it.
|
|
254
|
+
if (isTransactionGone(error)) return
|
|
255
|
+
throw error
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async savepoint(connection: DatabaseConnection, name: string): Promise<void> {
|
|
260
|
+
await connection.executeQuery(CompiledQuery.raw(`savepoint ${quoteIdent(name)}`))
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async rollbackToSavepoint(connection: DatabaseConnection, name: string): Promise<void> {
|
|
264
|
+
await connection.executeQuery(CompiledQuery.raw(`rollback to savepoint ${quoteIdent(name)}`))
|
|
265
|
+
// Rolling back to a savepoint is how Postgres recovers an aborted transaction.
|
|
266
|
+
asConnection(connection).failed = false
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async releaseSavepoint(connection: DatabaseConnection, name: string): Promise<void> {
|
|
270
|
+
await connection.executeQuery(CompiledQuery.raw(`release savepoint ${quoteIdent(name)}`))
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async destroy(): Promise<void> {
|
|
274
|
+
this.config.client.destroy?.()
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async execute(compiled: CompiledQuery, transactionId: string | undefined): Promise<QueryResult<unknown>> {
|
|
278
|
+
const problem = unsupportedStatement(compiled.sql, transactionId !== undefined)
|
|
279
|
+
if (problem) throw new RdsDataUnsupportedError(problem)
|
|
280
|
+
|
|
281
|
+
let sql = compiled.sql
|
|
282
|
+
let parameters: ReturnType<typeof toSqlParameter>[] | undefined
|
|
283
|
+
if (compiled.parameters.length > 0) {
|
|
284
|
+
const types = await this.parameterTypes(compiled.sql, transactionId)
|
|
285
|
+
if (types.length !== compiled.parameters.length) {
|
|
286
|
+
throw new Error(
|
|
287
|
+
`RDS Data API: Postgres reports ${types.length} parameters for a statement sent ${compiled.parameters.length}`,
|
|
288
|
+
)
|
|
289
|
+
}
|
|
290
|
+
sql = rewritePlaceholders(compiled.sql, (n) => castPlaceholder(n, types[n - 1]))
|
|
291
|
+
parameters = compiled.parameters.map((value, i) => toSqlParameter(i + 1, value))
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
const out = await this.statement(sql, transactionId, parameters)
|
|
295
|
+
const columns = out.columnMetadata ?? []
|
|
296
|
+
const rows = (out.records ?? []).map((record) => decodeRow(record, columns))
|
|
297
|
+
const keyword = leadingKeyword(compiled.sql)
|
|
298
|
+
const updated = out.numberOfRecordsUpdated
|
|
299
|
+
const isDml = keyword === 'insert' || keyword === 'update' || keyword === 'delete' || keyword === 'merge'
|
|
300
|
+
return {
|
|
301
|
+
rows,
|
|
302
|
+
...(isDml || (keyword === 'with' && updated !== undefined && updated > 0)
|
|
303
|
+
? { numAffectedRows: BigInt(updated ?? 0) }
|
|
304
|
+
: {}),
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* The types Postgres infers for `sql`'s `$n` placeholders — the same inference node-postgres relies
|
|
310
|
+
* on — read back from `pg_prepared_statements` after a PREPARE, and cached by SQL text (Kysely
|
|
311
|
+
* compiles one text per query shape, so a warm process asks once per shape) for `TYPE_CACHE_TTL_MS`.
|
|
312
|
+
*
|
|
313
|
+
* Inside a transaction it asks there, so a table the transaction has just created is visible to the
|
|
314
|
+
* PREPARE; a PREPARE that fails has found the same error the statement would have, and aborts the
|
|
315
|
+
* transaction exactly as the statement would. Outside one it opens a short transaction of its own,
|
|
316
|
+
* because PREPARE and the read of `pg_prepared_statements` must share a connection.
|
|
317
|
+
*/
|
|
318
|
+
private async parameterTypes(sql: string, transactionId: string | undefined): Promise<readonly string[]> {
|
|
319
|
+
const cached = this.#types.get(sql)
|
|
320
|
+
const ttl = this.config.typeCacheTtlMs ?? TYPE_CACHE_TTL_MS
|
|
321
|
+
if (cached && Date.now() - cached.at < ttl) return cached.types
|
|
322
|
+
|
|
323
|
+
const name = `sssb_describe_${randomUUID().replace(/-/g, '')}`
|
|
324
|
+
const describe = async (txId: string): Promise<readonly string[]> => {
|
|
325
|
+
await this.statement(`PREPARE ${name} AS ${describableSql(sql)}`, txId)
|
|
326
|
+
// format_type(t, -1), not t::text: regtype prints `character` and `bit`, which a CAST reads as
|
|
327
|
+
// char(1) and bit(1). And a domain is walked down to its base type first: an explicit cast to a
|
|
328
|
+
// domain over char(3) or varchar(3) truncates, where node-postgres's input path errors on the
|
|
329
|
+
// same value. Cast to the length-free base, and storing the value in a column (or passing it to
|
|
330
|
+
// a function) checks length and constraints as it does for node-postgres. An explicit
|
|
331
|
+
// `::domain` cast written in the SQL still truncates: an accepted limit (ADR-0002's addendum).
|
|
332
|
+
const out = await this.statement(
|
|
333
|
+
`WITH RECURSIVE params AS (
|
|
334
|
+
SELECT u.i, u.t::oid AS oid FROM pg_prepared_statements p,
|
|
335
|
+
unnest(p.parameter_types) WITH ORDINALITY AS u(t, i) WHERE p.name = '${name}'
|
|
336
|
+
), walk AS (
|
|
337
|
+
SELECT i, oid FROM params
|
|
338
|
+
UNION ALL
|
|
339
|
+
SELECT w.i, ty.typbasetype FROM walk w JOIN pg_type ty ON ty.oid = w.oid WHERE ty.typtype = 'd'
|
|
340
|
+
)
|
|
341
|
+
SELECT array(
|
|
342
|
+
SELECT format_type(w.oid, -1) FROM walk w JOIN pg_type ty ON ty.oid = w.oid
|
|
343
|
+
WHERE ty.typtype <> 'd' ORDER BY w.i
|
|
344
|
+
) AS types`,
|
|
345
|
+
txId,
|
|
346
|
+
)
|
|
347
|
+
await this.statement(`DEALLOCATE ${name}`, txId)
|
|
348
|
+
const types = out.records?.[0]?.[0]?.arrayValue?.stringValues
|
|
349
|
+
if (!types || types.some((type) => type === null)) {
|
|
350
|
+
throw new Error('RDS Data API: could not read the parameter types Postgres inferred')
|
|
351
|
+
}
|
|
352
|
+
return types as string[]
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
let types: readonly string[]
|
|
356
|
+
if (transactionId) {
|
|
357
|
+
types = await describe(transactionId)
|
|
358
|
+
} else {
|
|
359
|
+
const { resourceArn, secretArn, database } = this.config
|
|
360
|
+
const begun = (await this.call(
|
|
361
|
+
new BeginTransactionCommand({ resourceArn, secretArn, database }),
|
|
362
|
+
)) as BeginTransactionCommandOutput
|
|
363
|
+
const txId = begun.transactionId!
|
|
364
|
+
try {
|
|
365
|
+
types = await describe(txId)
|
|
366
|
+
} finally {
|
|
367
|
+
await this.call(new RollbackTransactionCommand({ resourceArn, secretArn, transactionId: txId })).catch(
|
|
368
|
+
() => undefined,
|
|
369
|
+
)
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
if (this.#types.size >= TYPE_CACHE_LIMIT) this.#types.clear()
|
|
374
|
+
this.#types.set(sql, { types, at: Date.now() })
|
|
375
|
+
return types
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
private async statement(
|
|
379
|
+
sql: string,
|
|
380
|
+
transactionId: string | undefined,
|
|
381
|
+
parameters?: ReturnType<typeof toSqlParameter>[],
|
|
382
|
+
): Promise<ExecuteStatementCommandOutput> {
|
|
383
|
+
const { resourceArn, secretArn, database } = this.config
|
|
384
|
+
return (await this.call(
|
|
385
|
+
new ExecuteStatementCommand({
|
|
386
|
+
resourceArn,
|
|
387
|
+
secretArn,
|
|
388
|
+
database,
|
|
389
|
+
sql,
|
|
390
|
+
parameters,
|
|
391
|
+
transactionId,
|
|
392
|
+
includeResultMetadata: true,
|
|
393
|
+
// int8 and numeric come back as strings, as node-postgres returns them, instead of a JS
|
|
394
|
+
// number that silently loses precision past 2^53.
|
|
395
|
+
resultSetOptions: { decimalReturnType: 'STRING', longReturnType: 'STRING' },
|
|
396
|
+
}),
|
|
397
|
+
)) as ExecuteStatementCommandOutput
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
private async call(command: RdsDataCommand): Promise<unknown> {
|
|
401
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
402
|
+
try {
|
|
403
|
+
return await this.config.client.send(command)
|
|
404
|
+
} catch (error) {
|
|
405
|
+
const resuming = error instanceof Error && error.name === 'DatabaseResumingException'
|
|
406
|
+
if (resuming && attempt < RESUME_DELAYS_MS.length) {
|
|
407
|
+
await new Promise((resolve) => setTimeout(resolve, RESUME_DELAYS_MS[attempt]))
|
|
408
|
+
continue
|
|
409
|
+
}
|
|
410
|
+
throw normalizeDatabaseError(error)
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
class RdsDataConnection implements DatabaseConnection {
|
|
417
|
+
transactionId: string | undefined
|
|
418
|
+
/**
|
|
419
|
+
* A statement in the open transaction failed, so Postgres has likely aborted it (see commitTransaction).
|
|
420
|
+
* Not set for a refusal made before any call, nor for the Data API's own request validation, neither of
|
|
421
|
+
* which reaches the database. That validation error is recognised by the name `ValidationException`,
|
|
422
|
+
* which the emulator uses and the SDK does not model; step 4 of docs/runbooks/data-api.md records the
|
|
423
|
+
* name AWS actually sends. Cleared by a successful `ROLLBACK TO SAVEPOINT`, Postgres's way back.
|
|
424
|
+
*/
|
|
425
|
+
failed = false
|
|
426
|
+
|
|
427
|
+
private readonly driver: RdsDataDriver
|
|
428
|
+
|
|
429
|
+
constructor(driver: RdsDataDriver) {
|
|
430
|
+
this.driver = driver
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {
|
|
434
|
+
let result: QueryResult<unknown>
|
|
435
|
+
try {
|
|
436
|
+
result = await this.driver.execute(compiledQuery, this.transactionId)
|
|
437
|
+
} catch (error) {
|
|
438
|
+
const neverReachedDatabase =
|
|
439
|
+
error instanceof RdsDataUnsupportedError ||
|
|
440
|
+
(error instanceof Error && error.name === 'ValidationException')
|
|
441
|
+
if (this.transactionId && !neverReachedDatabase) this.failed = true
|
|
442
|
+
throw error
|
|
443
|
+
}
|
|
444
|
+
// Inside a transaction only `ROLLBACK TO SAVEPOINT` gets past unsupportedStatement with this keyword,
|
|
445
|
+
// and when it succeeds the transaction is usable again — whether Kysely's savepoint API sent it or
|
|
446
|
+
// raw SQL did (inside db.transaction() and withTenant, raw SQL is the only way to send it).
|
|
447
|
+
if (this.transactionId && leadingKeyword(compiledQuery.sql) === 'rollback') this.failed = false
|
|
448
|
+
return result as QueryResult<R>
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// eslint-disable-next-line require-yield -- an async generator that refuses before its first chunk
|
|
452
|
+
async *streamQuery(): AsyncIterableIterator<never> {
|
|
453
|
+
throw new RdsDataUnsupportedError('the Data API returns whole result sets (at most 1 MiB); it cannot stream')
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function asConnection(connection: DatabaseConnection): RdsDataConnection {
|
|
458
|
+
if (!(connection instanceof RdsDataConnection)) throw new Error('not an RDS Data API connection')
|
|
459
|
+
return connection
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** TransactionNotFoundException by name, or by the message older Data API versions sent in a BadRequest. */
|
|
463
|
+
function isTransactionGone(error: unknown): boolean {
|
|
464
|
+
if (!(error instanceof Error)) return false
|
|
465
|
+
return error.name === 'TransactionNotFoundException' || /transaction\b.*\bnot found/i.test(error.message)
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function quoteIdent(name: string): string {
|
|
469
|
+
return `"${name.replace(/"/g, '""')}"`
|
|
470
|
+
}
|