@sssb/kit 0.6.0 → 0.7.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/configured-auth.ts +24 -4
- package/src/adapters/fake/atomic-write.ts +1 -1
- package/src/adapters/fake/simulated-auth.ts +7 -1
- package/src/adapters/real/account-refused-form.tsx +32 -0
- package/src/adapters/real/auth.ts +3 -2
- package/src/adapters/real/database-transport.ts +17 -0
- package/src/adapters/real/db-data-api.ts +5 -2
- package/src/adapters/real/index.ts +16 -4
- package/src/adapters/real/migrate-handler.ts +4 -0
- package/src/adapters/real/rds-data-dialect.ts +193 -16
- package/src/adapters/real/rds-data-emulator.ts +35 -1
- package/src/adapters/real/rds-data-resume.ts +197 -0
- package/src/components/auth/account-refused.tsx +53 -0
- package/src/components/auth/initials.ts +20 -0
- package/src/components/auth/preview-row.tsx +8 -2
- package/src/components/auth/user-menu.tsx +11 -3
- package/src/db/family.ts +1 -1
- package/src/db/org-lookup.ts +18 -0
- package/src/guide.md +9 -0
- package/src/i18n/messages/en.json +5 -1
- package/src/i18n/messages/es.json +5 -1
- package/src/ports/auth.ts +16 -0
- package/src/ports/errors.ts +28 -0
- package/src/testing/conformance/auth-provider.ts +1 -0
package/dist/release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"commit":"
|
|
1
|
+
{"commit":"1afa32103ec8db683cacb679224809baa89457b6"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sssb/kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -37,6 +37,7 @@
|
|
|
37
37
|
"./adapters/index": "./src/adapters/index.ts",
|
|
38
38
|
"./adapters/proxy": "./src/adapters/proxy.ts",
|
|
39
39
|
"./adapters/real/accept-invite-form": "./src/adapters/real/accept-invite-form.tsx",
|
|
40
|
+
"./adapters/real/account-refused-form": "./src/adapters/real/account-refused-form.tsx",
|
|
40
41
|
"./adapters/real/index": "./src/adapters/real/index.ts",
|
|
41
42
|
"./adapters/real/llm": "./src/adapters/real/llm.ts",
|
|
42
43
|
"./adapters/real/migrate-handler": "./src/adapters/real/migrate-handler.ts",
|
|
@@ -51,6 +52,7 @@
|
|
|
51
52
|
"./components/agreements/agreement-gate": "./src/components/agreements/agreement-gate.tsx",
|
|
52
53
|
"./components/app-header": "./src/components/app-header.tsx",
|
|
53
54
|
"./components/auth/accept-invite-screen": "./src/components/auth/accept-invite-screen.tsx",
|
|
55
|
+
"./components/auth/account-refused": "./src/components/auth/account-refused.tsx",
|
|
54
56
|
"./components/auth/org-switcher": "./src/components/auth/org-switcher.tsx",
|
|
55
57
|
"./components/auth/people-picker": "./src/components/auth/people-picker.tsx",
|
|
56
58
|
"./components/auth/sign-in-screen": "./src/components/auth/sign-in-screen.tsx",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isRestricted } from '../core/roles'
|
|
2
2
|
import type { Locale } from '../core/locale'
|
|
3
|
-
import type { AuthPort, AuthUser, CreatedInvite, MemberStanding, Membership, OrgRef } from '../ports/auth'
|
|
3
|
+
import type { AuthPort, AuthRefusal, AuthUser, CreatedInvite, MemberStanding, Membership, OrgRef } from '../ports/auth'
|
|
4
4
|
import { AuthRequiredError, ForbiddenError } from '../ports/errors'
|
|
5
5
|
import { type AuthSettings, fixedOrgProblem } from './auth-tenancy'
|
|
6
6
|
|
|
@@ -42,7 +42,8 @@ export interface ProviderIdentitySource {
|
|
|
42
42
|
* slug, is no user at all, and has no standing anywhere as a credential (`getMember`): that is a multi-tenant instance
|
|
43
43
|
* switched to this mode by mistake, and admitting them would put another tenant's people in this one. Refused without
|
|
44
44
|
* signing out: this runs while server components render, where a session cookie cannot be changed, and on a shared
|
|
45
|
-
* instance it would end their session in the other product.
|
|
45
|
+
* instance it would end their session in the other product. `refusal` says why to the sign-in page, which offers the
|
|
46
|
+
* person an explicit sign-out (`@sssb/kit/components/auth/account-refused`). Over the provider's organizations, every method is
|
|
46
47
|
* otherwise the adapter's, with its organizations, roles, members and invitations; the ones that act for the signed-in
|
|
47
48
|
* person (`updateProfile`, `createInvite`, `listMyOrgs`, `setActiveOrg`) run the tenant guard first, and `getMember`
|
|
48
49
|
* runs it after the provider's membership.
|
|
@@ -60,7 +61,8 @@ export interface ProviderIdentitySource {
|
|
|
60
61
|
* needs a non-restricted member), so such a job is one the app's own rules let the person start.
|
|
61
62
|
* - `createInvite`: refused. Anyone the provider signs in is already placed in the home org; an app adds people through
|
|
62
63
|
* its provider's own sign-up.
|
|
63
|
-
* - `listMyOrgs`: the home org alone, named by its
|
|
64
|
+
* - `listMyOrgs`: the home org alone, named by its org row's name, which the caller supplies a lookup for (`orgName`;
|
|
65
|
+
* the slug when the row is missing). `setActiveOrg`: the home org
|
|
64
66
|
* is accepted and changes nothing; any other is refused.
|
|
65
67
|
*
|
|
66
68
|
* `signInPath` and `signOut` are always the adapter's, and `updateProfile` writes through it after the guard.
|
|
@@ -70,6 +72,11 @@ export function configuredAuth(
|
|
|
70
72
|
settings: AuthSettings,
|
|
71
73
|
source: ProviderIdentitySource,
|
|
72
74
|
staffOrgSlug: string,
|
|
75
|
+
/**
|
|
76
|
+
* The display name of an org, by its tenant's slug and its own, or null when there is no such row: how a fixed org
|
|
77
|
+
* source names its home org, since this module knows it only by slug. Left out (a test), the slug is the name.
|
|
78
|
+
*/
|
|
79
|
+
orgName?: (tenantSlug: string, orgSlug: string) => Promise<string | null>,
|
|
73
80
|
): AuthPort {
|
|
74
81
|
const { tenancy, orgSource } = settings
|
|
75
82
|
if (tenancy.kind === 'multi' && orgSource.kind === 'provider') return base
|
|
@@ -169,10 +176,23 @@ export function configuredAuth(
|
|
|
169
176
|
async listMyOrgs(): Promise<OrgRef[]> {
|
|
170
177
|
const user = await port.getCurrentUser()
|
|
171
178
|
if (!user) return []
|
|
172
|
-
if (fixed)
|
|
179
|
+
if (fixed) {
|
|
180
|
+
// The org row's name, read per call (a rename shows at once); the slug when the row is missing,
|
|
181
|
+
// which the cutover row `auth-tenancy` says to create.
|
|
182
|
+
// A failed read falls back too: a display name never takes the page down.
|
|
183
|
+
const name =
|
|
184
|
+
(await orgName?.(user.tenantSlug, fixed.homeOrgSlug).catch(() => null)) ?? fixed.homeOrgSlug
|
|
185
|
+
return [{ slug: fixed.homeOrgSlug, name, role: fixed.role }]
|
|
186
|
+
}
|
|
173
187
|
return base.listMyOrgs()
|
|
174
188
|
},
|
|
175
189
|
|
|
190
|
+
async refusal(): Promise<AuthRefusal | null> {
|
|
191
|
+
// The guard's own reason, from the same identity read. Its callers are the sign-in pages, not every request.
|
|
192
|
+
const identity = await source.current()
|
|
193
|
+
return identity && !admitted(identity.tenantClaim) ? { reason: 'other-tenant' } : null
|
|
194
|
+
},
|
|
195
|
+
|
|
176
196
|
async setActiveOrg(orgSlug: string): Promise<void> {
|
|
177
197
|
await port.requireUser()
|
|
178
198
|
if (!fixed) return base.setActiveOrg(orgSlug)
|
|
@@ -8,7 +8,7 @@ import { copyFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
|
8
8
|
*
|
|
9
9
|
* WHY this exists: every fake adapter persists its state as a flat file, and under concurrent
|
|
10
10
|
* requests two writers can land on the SAME file at once (see
|
|
11
|
-
*
|
|
11
|
+
* safeinsights/sssb#99). Plain `writeFileSync`/`writeFile`
|
|
12
12
|
* TRUNCATE the file and then stream the new bytes in — so if writer A (shorter payload) and writer
|
|
13
13
|
* B (longer payload) interleave, a reader can observe B's truncate landing after A has already
|
|
14
14
|
* written, leaving A's shorter content followed by the tail of B's longer content: neither writer's
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { staffOrgSlug } from '@sssb/app-config/abilities'
|
|
2
2
|
import type { AuthPort } from '../../ports/auth'
|
|
3
3
|
import { authSettings } from '../auth-tenancy'
|
|
4
|
+
import { orgNameForSlugs } from '../../db/org-lookup'
|
|
4
5
|
import { configuredAuth } from '../configured-auth'
|
|
5
6
|
import { fakeAuth, fakeIdentitySource } from './auth'
|
|
7
|
+
import { fakeDb } from './db'
|
|
6
8
|
|
|
7
9
|
let cached: AuthPort | undefined
|
|
8
10
|
|
|
@@ -19,6 +21,10 @@ let cached: AuthPort | undefined
|
|
|
19
21
|
* reach, and the replay says so.
|
|
20
22
|
*/
|
|
21
23
|
export function simulatedAuth(): AuthPort {
|
|
22
|
-
if (cached === undefined)
|
|
24
|
+
if (cached === undefined) {
|
|
25
|
+
cached = configuredAuth(fakeAuth, authSettings(), fakeIdentitySource, staffOrgSlug, (tenant, org) =>
|
|
26
|
+
orgNameForSlugs(fakeDb, tenant, org),
|
|
27
|
+
)
|
|
28
|
+
}
|
|
23
29
|
return cached
|
|
24
30
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
import { useAuth, useClerk } from '@clerk/nextjs'
|
|
4
|
+
import { AccountRefused } from '../../components/auth/account-refused'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The refused-account screen in real mode (`@sssb/kit/components/auth/account-refused`), signing out through Clerk's
|
|
8
|
+
* client. Revoking the session on the server alone leaves the browser's short-lived session token in place, which the
|
|
9
|
+
* middleware still verifies until it lapses, so the page would come back refused. Clerk's client sign-out ends this one
|
|
10
|
+
* session (`sessionId`), clears its cookies, and then sends the browser back to this page (`redirectUrl`), which now
|
|
11
|
+
* shows the sign-in form.
|
|
12
|
+
*
|
|
13
|
+
* Only on the person's click, as the screen says: on an identity-provider instance shared with another product, this
|
|
14
|
+
* session may be that product's too. Until Clerk has loaded and knows the session, a click signs nobody out and says
|
|
15
|
+
* so: before then Clerk only queues the call, and with no session id it would end every session on the device.
|
|
16
|
+
*
|
|
17
|
+
* AUTHORED — CUTOVER (`auth-tenancy`): never run against a real Clerk instance. Lives in packages/kit/src/adapters
|
|
18
|
+
* because it imports the vendor SDK; mount it under `RealAuthProviders`.
|
|
19
|
+
*/
|
|
20
|
+
export function RealAccountRefused() {
|
|
21
|
+
const { signOut } = useClerk()
|
|
22
|
+
const { isLoaded, sessionId } = useAuth()
|
|
23
|
+
return (
|
|
24
|
+
<AccountRefused
|
|
25
|
+
onSignOut={async () => {
|
|
26
|
+
if (!isLoaded || !sessionId) return false
|
|
27
|
+
await signOut({ sessionId, redirectUrl: window.location.href })
|
|
28
|
+
return true
|
|
29
|
+
}}
|
|
30
|
+
/>
|
|
31
|
+
)
|
|
32
|
+
}
|
|
@@ -159,7 +159,8 @@ export const realAuth: AuthPort = {
|
|
|
159
159
|
},
|
|
160
160
|
|
|
161
161
|
async signOut(): Promise<void> {
|
|
162
|
-
// Server-side revocation
|
|
162
|
+
// Server-side revocation only: the browser keeps its short-lived session token until it lapses, so a page that must
|
|
163
|
+
// show the person signed out at once also signs out through Clerk's client (./account-refused-form.tsx does).
|
|
163
164
|
const { sessionId } = await auth()
|
|
164
165
|
if (!sessionId) return
|
|
165
166
|
const client = await clerkClient()
|
|
@@ -261,7 +262,7 @@ export const realAuth: AuthPort = {
|
|
|
261
262
|
*
|
|
262
263
|
* The page goes to Clerk as a PATH, which Clerk's `redirectUrl` accepts ("The full URL or path"), never as the
|
|
263
264
|
* absolute URL it arrives as: that is built from the request's URL, whose host behind `SssbApp` is the server's own
|
|
264
|
-
* (`localhost`), not the app's (
|
|
265
|
+
* (`localhost`), not the app's (safeinsights/sssb#131).
|
|
265
266
|
*/
|
|
266
267
|
async createInvite(invite: InviteInput): Promise<CreatedInvite> {
|
|
267
268
|
const { userId } = await auth()
|
|
@@ -32,3 +32,20 @@ export function databaseTransport(): DatabaseTransport {
|
|
|
32
32
|
}
|
|
33
33
|
return value as DatabaseTransport
|
|
34
34
|
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* DATABASE_RESUME_BUDGET_MS, optional and read on `data-api` only: how long a call waits for a paused cluster to
|
|
38
|
+
* resume (docs/runbooks/data-api.md, step 6). Undefined when unset or empty, so that the dialect's default holds. At
|
|
39
|
+
* most 15 minutes, far past any server's timeout, so that a wrong unit fails at boot.
|
|
40
|
+
*/
|
|
41
|
+
export function databaseResumeBudgetMs(): number | undefined {
|
|
42
|
+
const value = process.env['DATABASE_RESUME_BUDGET_MS']
|
|
43
|
+
if (!value) return undefined
|
|
44
|
+
const ms = /^\d+$/.test(value) ? Number(value) : NaN
|
|
45
|
+
if (!(ms <= 900_000)) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
`DATABASE_RESUME_BUDGET_MS must be a whole number of milliseconds from 0 to 900000 (got "${value}")`,
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
return ms
|
|
51
|
+
}
|
|
@@ -18,6 +18,8 @@ export interface DataApiDbConfig {
|
|
|
18
18
|
client?: RdsDataClientLike
|
|
19
19
|
/** How long inferred parameter types are trusted; the dialect's `TYPE_CACHE_TTL_MS` when omitted. */
|
|
20
20
|
typeCacheTtlMs?: number
|
|
21
|
+
/** How long a call waits for a paused cluster to resume; the dialect's `RESUME_BUDGET_MS` when omitted. */
|
|
22
|
+
resumeBudgetMs?: number | undefined
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
/**
|
|
@@ -29,8 +31,8 @@ export interface DataApiDbConfig {
|
|
|
29
31
|
* deployment never loads the RDS Data SDK; ./index.test.ts proves it.
|
|
30
32
|
*
|
|
31
33
|
* `maxAttempts: 1` turns the SDK's automatic retries off, on AWS's own advice: a statement whose call
|
|
32
|
-
* timed out may still have finished, and retrying it can write twice.
|
|
33
|
-
*
|
|
34
|
+
* timed out may still have finished, and retrying it can write twice. What is safe to
|
|
35
|
+
* send again while a paused Serverless v2 resumes, the dialect sends again itself.
|
|
34
36
|
*/
|
|
35
37
|
export function createRealDataApiDb(config: DataApiDbConfig): DbPort {
|
|
36
38
|
const client =
|
|
@@ -42,6 +44,7 @@ export function createRealDataApiDb(config: DataApiDbConfig): DbPort {
|
|
|
42
44
|
secretArn: config.secretArn,
|
|
43
45
|
database: config.database,
|
|
44
46
|
typeCacheTtlMs: config.typeCacheTtlMs,
|
|
47
|
+
resumeBudgetMs: config.resumeBudgetMs,
|
|
45
48
|
})
|
|
46
49
|
const db = new Kysely<DB>({ dialect })
|
|
47
50
|
return {
|
|
@@ -10,8 +10,9 @@ import type { StoragePort } from '../../ports/storage'
|
|
|
10
10
|
import { absentEmail, absentJobs, absentLlm, absentStorage } from './absent'
|
|
11
11
|
import { authRequiredEnv, authSettings, fixedOrgProblem } from '../auth-tenancy'
|
|
12
12
|
import { configuredAuth } from '../configured-auth'
|
|
13
|
+
import { orgNameForSlugs } from '../../db/org-lookup'
|
|
13
14
|
import { clerkIdentitySource, realAuth } from './auth'
|
|
14
|
-
import { DATABASE_ENV, databaseTransport } from './database-transport'
|
|
15
|
+
import { DATABASE_ENV, databaseResumeBudgetMs, databaseTransport } from './database-transport'
|
|
15
16
|
import { noAnalytics } from './no-analytics'
|
|
16
17
|
import { optionalPortsEnv, portChoice } from './optional-ports'
|
|
17
18
|
import { assertEndpoint, parseForcePathStyle, parseUploadTarget } from './storage-settings'
|
|
@@ -73,6 +74,13 @@ export function assertRealEnv(): void {
|
|
|
73
74
|
throw new CutoverPendingError(['storage-compatible-store'], (error as Error).message)
|
|
74
75
|
}
|
|
75
76
|
}
|
|
77
|
+
if (transport === 'data-api') {
|
|
78
|
+
try {
|
|
79
|
+
databaseResumeBudgetMs()
|
|
80
|
+
} catch (error) {
|
|
81
|
+
throw new CutoverPendingError(['data-api'], (error as Error).message)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
76
84
|
// The auth settings: an unknown choice, a malformed slug, key or role, a setting its choice does not use, or a fixed
|
|
77
85
|
// org source that would hand everyone the staff org's manage-all.
|
|
78
86
|
let problem: string | null
|
|
@@ -108,9 +116,6 @@ interface RealPortsHooks {
|
|
|
108
116
|
export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealPorts> {
|
|
109
117
|
assertRealEnv()
|
|
110
118
|
const env = process.env
|
|
111
|
-
// Clerk, placed as the auth settings say (../auth-tenancy.ts), and Clerk itself on the defaults. Every port that
|
|
112
|
-
// reaches the people (the in-process runner's job context included) is handed this one.
|
|
113
|
-
const auth: AuthPort = configuredAuth(realAuth, authSettings(), clerkIdentitySource, staffOrgSlug)
|
|
114
119
|
// assertRealEnv above already proved every required variable is set; this narrows the type.
|
|
115
120
|
const need = (name: string): string => {
|
|
116
121
|
const value = env[name]
|
|
@@ -128,8 +133,15 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
|
|
|
128
133
|
secretArn: need('DATABASE_SECRET_ARN'),
|
|
129
134
|
database: need('DATABASE_NAME'),
|
|
130
135
|
region: need('AWS_REGION'),
|
|
136
|
+
resumeBudgetMs: databaseResumeBudgetMs(),
|
|
131
137
|
})
|
|
132
138
|
: (await import('./db')).createRealDb(need('DATABASE_URL'))
|
|
139
|
+
// Clerk, placed as the auth settings say (../auth-tenancy.ts), and Clerk itself on the defaults. Every port that
|
|
140
|
+
// reaches the people (the in-process runner's job context included) is handed this one. A fixed org source names
|
|
141
|
+
// its home org from the database's org row.
|
|
142
|
+
const auth: AuthPort = configuredAuth(realAuth, authSettings(), clerkIdentitySource, staffOrgSlug, (tenant, org) =>
|
|
143
|
+
orgNameForSlugs(db, tenant, org),
|
|
144
|
+
)
|
|
133
145
|
const storageChoice = portChoice('storage')
|
|
134
146
|
const storage =
|
|
135
147
|
storageChoice === 's3'
|
|
@@ -2,6 +2,9 @@ import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-sec
|
|
|
2
2
|
import { databaseTransport } from './database-transport'
|
|
3
3
|
import { createRealDb } from './db'
|
|
4
4
|
|
|
5
|
+
/** How long the migrator waits for a paused cluster: no user is waiting, and its Lambda has five minutes (SssbApp). */
|
|
6
|
+
const MIGRATOR_RESUME_BUDGET_MS = 120_000
|
|
7
|
+
|
|
5
8
|
/**
|
|
6
9
|
* Migrator Lambda handler (ADR-0001): runs the same migration registry the app, unit tests, and
|
|
7
10
|
* contract tests use. Invoked by the CD pipeline before each release shifts traffic.
|
|
@@ -36,6 +39,7 @@ export async function handler(): Promise<{ ok: true }> {
|
|
|
36
39
|
resourceArn: DATABASE_CLUSTER_ARN,
|
|
37
40
|
secretArn: DATABASE_SECRET_ARN,
|
|
38
41
|
database: DATABASE_NAME,
|
|
42
|
+
resumeBudgetMs: MIGRATOR_RESUME_BUDGET_MS,
|
|
39
43
|
})
|
|
40
44
|
await db.migrateToLatest()
|
|
41
45
|
return { ok: true }
|
|
@@ -16,12 +16,18 @@ import {
|
|
|
16
16
|
PostgresIntrospector,
|
|
17
17
|
PostgresQueryCompiler,
|
|
18
18
|
type DatabaseConnection,
|
|
19
|
+
type ColumnMetadata,
|
|
20
|
+
type DatabaseIntrospector,
|
|
21
|
+
type DatabaseMetadataOptions,
|
|
19
22
|
type Dialect,
|
|
20
23
|
type Driver,
|
|
21
24
|
type Kysely,
|
|
22
25
|
type QueryResult,
|
|
26
|
+
type SchemaMetadata,
|
|
27
|
+
type TableMetadata,
|
|
23
28
|
type TransactionSettings,
|
|
24
29
|
} from 'kysely'
|
|
30
|
+
import { DEFAULT_MIGRATION_LOCK_TABLE, DEFAULT_MIGRATION_TABLE } from 'kysely/migration'
|
|
25
31
|
import {
|
|
26
32
|
castPlaceholder,
|
|
27
33
|
commitOutcome,
|
|
@@ -34,6 +40,8 @@ import {
|
|
|
34
40
|
toSqlParameter,
|
|
35
41
|
unsupportedStatement,
|
|
36
42
|
} from './rds-data-codec'
|
|
43
|
+
import { DatabaseUnavailableError } from '../../ports/errors'
|
|
44
|
+
import { RESUME_BUDGET_MS, ResumeWait, unavailable, unavailableReason, wasCancelledUnrun } from './rds-data-resume'
|
|
37
45
|
|
|
38
46
|
/** The four calls this dialect makes. `RDSDataClient` satisfies it, and so does the test emulator. */
|
|
39
47
|
export type RdsDataCommand =
|
|
@@ -53,6 +61,11 @@ export interface RdsDataDialectConfig {
|
|
|
53
61
|
database: string
|
|
54
62
|
/** How long a SQL shape's inferred parameter types are trusted; `TYPE_CACHE_TTL_MS` when omitted. */
|
|
55
63
|
typeCacheTtlMs?: number | undefined
|
|
64
|
+
/**
|
|
65
|
+
* How long one call waits for a paused cluster to resume, in milliseconds, counted from its first refusal or its
|
|
66
|
+
* first wait; `RESUME_BUDGET_MS` when omitted, and 0 to fail at once. It bounds the wait, not the calls themselves.
|
|
67
|
+
*/
|
|
68
|
+
resumeBudgetMs?: number | undefined
|
|
56
69
|
}
|
|
57
70
|
|
|
58
71
|
/**
|
|
@@ -91,8 +104,119 @@ export class RdsDataDialect implements Dialect {
|
|
|
91
104
|
}
|
|
92
105
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
|
|
93
106
|
createIntrospector(db: Kysely<any>) {
|
|
94
|
-
return new
|
|
107
|
+
return new RdsDataIntrospector(db)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Kysely's Postgres introspector, with the one column the Data API cannot return cast to text. Kysely's `getTables`
|
|
113
|
+
* selects `pg_class.relkind`, a one-byte `"char"`, which the Data API refuses whole ("The result contains the
|
|
114
|
+
* unsupported data type "CHAR"", ./rds-data-emulator.ts's `REFUSED_RESULT_TYPES`), and its Migrator calls it before
|
|
115
|
+
* anything else, to see whether its own tables exist. So this is Kysely 0.29's query and its reading of the rows, with
|
|
116
|
+
* `relkind::text` for `relkind`; `getSchemas` reads only `nspname`, a `name`, and is Kysely's own. The contract suite
|
|
117
|
+
* (./rds-data.contract.test.ts) holds it to Kysely's introspector on the same database, so an upgrade of Kysely that
|
|
118
|
+
* changes what `getTables` returns fails there.
|
|
119
|
+
*/
|
|
120
|
+
export class RdsDataIntrospector implements DatabaseIntrospector {
|
|
121
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
|
|
122
|
+
readonly #db: Kysely<any>
|
|
123
|
+
readonly #postgres: PostgresIntrospector
|
|
124
|
+
|
|
125
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- kysely's Dialect interface signature
|
|
126
|
+
constructor(db: Kysely<any>) {
|
|
127
|
+
this.#db = db
|
|
128
|
+
this.#postgres = new PostgresIntrospector(db)
|
|
95
129
|
}
|
|
130
|
+
|
|
131
|
+
getSchemas(): Promise<SchemaMetadata[]> {
|
|
132
|
+
return this.#postgres.getSchemas()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async getTables(options: DatabaseMetadataOptions = { withInternalKyselyTables: false }): Promise<TableMetadata[]> {
|
|
136
|
+
let query = this.#db
|
|
137
|
+
.selectFrom('pg_catalog.pg_attribute as a')
|
|
138
|
+
.innerJoin('pg_catalog.pg_class as c', 'a.attrelid', 'c.oid')
|
|
139
|
+
.innerJoin('pg_catalog.pg_namespace as ns', 'c.relnamespace', 'ns.oid')
|
|
140
|
+
.innerJoin('pg_catalog.pg_type as typ', 'a.atttypid', 'typ.oid')
|
|
141
|
+
.innerJoin('pg_catalog.pg_namespace as dtns', 'typ.typnamespace', 'dtns.oid')
|
|
142
|
+
.select([
|
|
143
|
+
'a.attname as column',
|
|
144
|
+
'a.attnotnull as not_null',
|
|
145
|
+
'a.atthasdef as has_default',
|
|
146
|
+
'c.relname as table',
|
|
147
|
+
sql<string>`c.relkind::text`.as('table_type'),
|
|
148
|
+
'ns.nspname as schema',
|
|
149
|
+
'typ.typname as type',
|
|
150
|
+
'dtns.nspname as type_schema',
|
|
151
|
+
sql<string | null>`col_description(a.attrelid, a.attnum)`.as('column_description'),
|
|
152
|
+
sql<
|
|
153
|
+
string | null
|
|
154
|
+
>`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(
|
|
155
|
+
'auto_incrementing',
|
|
156
|
+
),
|
|
157
|
+
])
|
|
158
|
+
.where('c.relkind', 'in', ['r', 'v', 'p', 'f'])
|
|
159
|
+
.where('ns.nspname', '!~', '^pg_')
|
|
160
|
+
.where('ns.nspname', '!=', 'information_schema')
|
|
161
|
+
.where('ns.nspname', '!=', 'crdb_internal')
|
|
162
|
+
.where(sql<boolean>`has_schema_privilege(ns.nspname, 'USAGE')`)
|
|
163
|
+
.where('a.attnum', '>=', 0)
|
|
164
|
+
.where('a.attisdropped', '!=', true)
|
|
165
|
+
.orderBy('ns.nspname')
|
|
166
|
+
.orderBy('c.relname')
|
|
167
|
+
.orderBy('a.attnum')
|
|
168
|
+
.$castTo<IntrospectedColumn>()
|
|
169
|
+
if (!options.withInternalKyselyTables) {
|
|
170
|
+
query = query
|
|
171
|
+
.where('c.relname', '!=', DEFAULT_MIGRATION_TABLE)
|
|
172
|
+
.where('c.relname', '!=', DEFAULT_MIGRATION_LOCK_TABLE)
|
|
173
|
+
}
|
|
174
|
+
const tables: TableMetadata[] = []
|
|
175
|
+
const bySchema = new Map<string, Map<string, TableMetadata>>()
|
|
176
|
+
for (const column of await query.execute()) {
|
|
177
|
+
let schema = bySchema.get(column.schema)
|
|
178
|
+
if (!schema) bySchema.set(column.schema, (schema = new Map()))
|
|
179
|
+
let table = schema.get(column.table)
|
|
180
|
+
if (!table) {
|
|
181
|
+
table = Object.freeze({
|
|
182
|
+
columns: [],
|
|
183
|
+
isForeign: column.table_type === 'f',
|
|
184
|
+
isView: column.table_type === 'v',
|
|
185
|
+
name: column.table,
|
|
186
|
+
schema: column.schema,
|
|
187
|
+
})
|
|
188
|
+
schema.set(column.table, table)
|
|
189
|
+
tables.push(table)
|
|
190
|
+
}
|
|
191
|
+
table.columns.push(
|
|
192
|
+
// `comment` present and undefined on an uncommented column, as Kysely's is: the cast is
|
|
193
|
+
// exactOptionalPropertyTypes', which Kysely's own type does not satisfy either.
|
|
194
|
+
Object.freeze({
|
|
195
|
+
comment: column.column_description ?? undefined,
|
|
196
|
+
dataType: column.type,
|
|
197
|
+
dataTypeSchema: column.type_schema,
|
|
198
|
+
hasDefaultValue: column.has_default,
|
|
199
|
+
isAutoIncrementing: column.auto_incrementing !== null,
|
|
200
|
+
isNullable: !column.not_null,
|
|
201
|
+
name: column.column,
|
|
202
|
+
} as ColumnMetadata),
|
|
203
|
+
)
|
|
204
|
+
}
|
|
205
|
+
return tables
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
interface IntrospectedColumn {
|
|
210
|
+
column: string
|
|
211
|
+
not_null: boolean
|
|
212
|
+
has_default: boolean
|
|
213
|
+
table: string
|
|
214
|
+
table_type: string
|
|
215
|
+
schema: string
|
|
216
|
+
type: string
|
|
217
|
+
type_schema: string
|
|
218
|
+
column_description: string | null
|
|
219
|
+
auto_incrementing: string | null
|
|
96
220
|
}
|
|
97
221
|
|
|
98
222
|
/** Kysely's own Postgres migration-lock id, so a `pg` migrator and a Data API one exclude each other. */
|
|
@@ -149,21 +273,21 @@ const TYPE_CACHE_LIMIT = 2000
|
|
|
149
273
|
*/
|
|
150
274
|
const TYPE_CACHE_TTL_MS = 5 * 60 * 1000
|
|
151
275
|
|
|
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
276
|
class RdsDataDriver implements Driver {
|
|
161
277
|
readonly #types = new Map<string, { readonly types: readonly string[]; readonly at: number }>()
|
|
162
278
|
|
|
279
|
+
/** Transactions in which a statement has run, so their sessions have existed. */
|
|
280
|
+
readonly #usedTransactions = new Set<string>()
|
|
281
|
+
readonly #resume: ResumeWait
|
|
282
|
+
|
|
163
283
|
private readonly config: RdsDataDialectConfig
|
|
164
284
|
|
|
165
285
|
constructor(config: RdsDataDialectConfig) {
|
|
166
286
|
this.config = config
|
|
287
|
+
const { client, resourceArn, secretArn, database } = config
|
|
288
|
+
this.#resume = new ResumeWait(() =>
|
|
289
|
+
client.send(new ExecuteStatementCommand({ resourceArn, secretArn, database, sql: 'SELECT 1' })),
|
|
290
|
+
)
|
|
167
291
|
}
|
|
168
292
|
|
|
169
293
|
async init(): Promise<void> {}
|
|
@@ -250,8 +374,10 @@ class RdsDataDriver implements Driver {
|
|
|
250
374
|
} catch (error) {
|
|
251
375
|
// Already gone means already rolled back: the Data API rolls a transaction back itself when it
|
|
252
376
|
// 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.
|
|
377
|
+
// only replace the error that made Kysely roll back with one that says nothing about it. A cluster that
|
|
378
|
+
// answers that it is resuming was paused, and a paused one has no open transaction.
|
|
254
379
|
if (isTransactionGone(error)) return
|
|
380
|
+
if (error instanceof DatabaseUnavailableError && error.reason === 'resuming') return
|
|
255
381
|
throw error
|
|
256
382
|
}
|
|
257
383
|
}
|
|
@@ -397,20 +523,67 @@ class RdsDataDriver implements Driver {
|
|
|
397
523
|
)) as ExecuteStatementCommandOutput
|
|
398
524
|
}
|
|
399
525
|
|
|
526
|
+
/**
|
|
527
|
+
* Sends a command, waiting out a cluster that is resuming (SSSB's non-production stack pauses: min capacity 0). A
|
|
528
|
+
* call outside a transaction that has not been sent yet waits first if a resume is known to be under way. What may
|
|
529
|
+
* be sent again is `mayResend`'s to say; nothing else is, here or in the SDK (`maxAttempts: 1` in ./db-data-api.ts): AWS
|
|
530
|
+
* warns that a retried statement whose first attempt actually finished can write twice.
|
|
531
|
+
*/
|
|
400
532
|
private async call(command: RdsDataCommand): Promise<unknown> {
|
|
401
|
-
|
|
533
|
+
let deadline: number | undefined
|
|
534
|
+
const wait = (error?: unknown): Promise<void> => {
|
|
535
|
+
deadline ??= Date.now() + (this.config.resumeBudgetMs ?? RESUME_BUDGET_MS)
|
|
536
|
+
return this.#resume.join(deadline, error)
|
|
537
|
+
}
|
|
538
|
+
const opensWork = transactionIdOf(command) === undefined
|
|
539
|
+
for (;;) {
|
|
540
|
+
while (opensWork && this.#resume.resuming) await wait()
|
|
402
541
|
try {
|
|
403
|
-
return await this.
|
|
542
|
+
return await this.send(command)
|
|
404
543
|
} catch (error) {
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
await new Promise((resolve) => setTimeout(resolve, RESUME_DELAYS_MS[attempt]))
|
|
544
|
+
if (this.mayResend(command, error)) {
|
|
545
|
+
await wait(error)
|
|
408
546
|
continue
|
|
409
547
|
}
|
|
410
|
-
|
|
548
|
+
const reason = unavailableReason(error)
|
|
549
|
+
throw reason ? unavailable(reason, error) : normalizeDatabaseError(error)
|
|
411
550
|
}
|
|
412
551
|
}
|
|
413
552
|
}
|
|
553
|
+
|
|
554
|
+
private async send(command: RdsDataCommand): Promise<unknown> {
|
|
555
|
+
const transactionId = transactionIdOf(command)
|
|
556
|
+
const runsStatement = command instanceof ExecuteStatementCommand
|
|
557
|
+
try {
|
|
558
|
+
const answer = await this.config.client.send(command)
|
|
559
|
+
if (transactionId && runsStatement) this.#usedTransactions.add(transactionId)
|
|
560
|
+
return answer
|
|
561
|
+
} finally {
|
|
562
|
+
if (transactionId && !runsStatement) this.#usedTransactions.delete(transactionId)
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Whether sending `command` again can't repeat anything.
|
|
568
|
+
*
|
|
569
|
+
* - A BeginTransaction runs no statement: at worst the failed attempt left an empty transaction, which the Data API
|
|
570
|
+
* rolls back after three idle minutes. So it is sent again after any answer that the database is resuming, and
|
|
571
|
+
* after a throttle, which an adopter's log shows while a cluster resumes (docs/decision-log.md, 2026-11-24).
|
|
572
|
+
* - A statement only after `DatabaseResumingException` itself, which AWS documents as cancelled. AWS's Data API
|
|
573
|
+
* pages do not say that a throttled statement did not run, so a throttled one is not sent again.
|
|
574
|
+
* - In a transaction, only until a statement has succeeded in it. After that the session existed, and a pause has
|
|
575
|
+
* ended it and the work in it: there is no transaction left to go on with.
|
|
576
|
+
* - A commit or a rollback, never.
|
|
577
|
+
*/
|
|
578
|
+
private mayResend(command: RdsDataCommand, error: unknown): boolean {
|
|
579
|
+
if (command instanceof BeginTransactionCommand) {
|
|
580
|
+
const reason = unavailableReason(error)
|
|
581
|
+
return reason === 'resuming' || reason === 'throttled'
|
|
582
|
+
}
|
|
583
|
+
if (!(command instanceof ExecuteStatementCommand) || !wasCancelledUnrun(error)) return false
|
|
584
|
+
const { transactionId } = command.input
|
|
585
|
+
return transactionId === undefined || !this.#usedTransactions.has(transactionId)
|
|
586
|
+
}
|
|
414
587
|
}
|
|
415
588
|
|
|
416
589
|
class RdsDataConnection implements DatabaseConnection {
|
|
@@ -465,6 +638,10 @@ function isTransactionGone(error: unknown): boolean {
|
|
|
465
638
|
return error.name === 'TransactionNotFoundException' || /transaction\b.*\bnot found/i.test(error.message)
|
|
466
639
|
}
|
|
467
640
|
|
|
641
|
+
function transactionIdOf(command: RdsDataCommand): string | undefined {
|
|
642
|
+
return 'transactionId' in command.input ? command.input.transactionId : undefined
|
|
643
|
+
}
|
|
644
|
+
|
|
468
645
|
function quoteIdent(name: string): string {
|
|
469
646
|
return `"${name.replace(/"/g, '""')}"`
|
|
470
647
|
}
|
|
@@ -30,7 +30,10 @@ import type { RdsDataClientLike, RdsDataCommand } from './rds-data-dialect'
|
|
|
30
30
|
* - a statement inside a transaction runs on that transaction's one connection, until Commit/Rollback;
|
|
31
31
|
* - a response over 1 MiB is refused, and an unknown transaction id is TransactionNotFoundException;
|
|
32
32
|
* - database errors come back as a message only, WITHOUT a SQLSTATE — the least the Data API is
|
|
33
|
-
* reported to give, so what is proven is that SSSB's error handling survives the worst case
|
|
33
|
+
* reported to give, so what is proven is that SSSB's error handling survives the worst case;
|
|
34
|
+
* - a result with a column of a type the Data API refuses is refused whole, rows or none, with its
|
|
35
|
+
* `UnsupportedResultException`, after the statement has run (REFUSED_RESULT_TYPES says which types, and on what
|
|
36
|
+
* evidence, some of it inferred).
|
|
34
37
|
*
|
|
35
38
|
* What it cannot know is AWS's exact wire format (column `typeName`s, timestamp strings, error wording).
|
|
36
39
|
* It follows PgJDBC's conventions, which the Data API is built on; the `data-api` cutover row is the live
|
|
@@ -44,6 +47,30 @@ export interface EmulatedCall {
|
|
|
44
47
|
|
|
45
48
|
const RESPONSE_LIMIT_BYTES = 1024 * 1024
|
|
46
49
|
|
|
50
|
+
/**
|
|
51
|
+
* Result column types the Data API refuses, seen or inferred, by `pg_type.typname`, with the name its error gives them. AWS lists none:
|
|
52
|
+
* "The Data API doesn't support all data types", and the fix it gives is a cast to TEXT (the Aurora User Guide's
|
|
53
|
+
* "Troubleshooting Amazon RDS Data API", "Unsupported result exception"). What is here is evidence:
|
|
54
|
+
*
|
|
55
|
+
* - `char`, Postgres's one-byte "char" (`pg_class.relkind`): refused live on Aurora PostgreSQL with
|
|
56
|
+
* `UnsupportedResultException: The result contains the unsupported data type "CHAR"`, for a result of no rows (Kysely's
|
|
57
|
+
* introspector, on a database with no tables yet), so the refusal reads the columns, not the values;
|
|
58
|
+
* - `bpchar`, `char(n)`: the same JDBC type, `CHAR`, in PgJDBC's type map, on which the Data API is built, so the same
|
|
59
|
+
* error, if the error's "CHAR" is that JDBC type and not the type's own name upper-cased; inferred, not observed;
|
|
60
|
+
* - `_char` and `_bpchar`, arrays of the two, whose elements the Data API would have to return as the same type;
|
|
61
|
+
* inferred, not observed.
|
|
62
|
+
*
|
|
63
|
+
* Strict where unobserved, so a query passes here only if it passes on the evidence's worst reading; a cast to text
|
|
64
|
+
* costs nothing. The `data-api` cutover row's smoke run (`docs/runbooks/data-api.md`, step 3) records what AWS does
|
|
65
|
+
* with each, and a type it answers leaves this map, as one it refuses joins it.
|
|
66
|
+
*/
|
|
67
|
+
const REFUSED_RESULT_TYPES: ReadonlyMap<string, string> = new Map([
|
|
68
|
+
['char', 'CHAR'],
|
|
69
|
+
['bpchar', 'CHAR'],
|
|
70
|
+
['_char', 'CHAR'],
|
|
71
|
+
['_bpchar', 'CHAR'],
|
|
72
|
+
])
|
|
73
|
+
|
|
47
74
|
export class RdsDataEmulator implements RdsDataClientLike {
|
|
48
75
|
/** Every call, in order — the contract suite asserts on the transaction sequence. */
|
|
49
76
|
readonly calls: EmulatedCall[] = []
|
|
@@ -161,6 +188,13 @@ export class RdsDataEmulator implements RdsDataClientLike {
|
|
|
161
188
|
client,
|
|
162
189
|
result.fields.map((field) => field.dataTypeID),
|
|
163
190
|
)
|
|
191
|
+
const refused = result.fields.find((field) =>
|
|
192
|
+
REFUSED_RESULT_TYPES.has(typeNames.get(field.dataTypeID) ?? ''),
|
|
193
|
+
)
|
|
194
|
+
if (refused) {
|
|
195
|
+
const name = REFUSED_RESULT_TYPES.get(typeNames.get(refused.dataTypeID)!)
|
|
196
|
+
throw awsError('UnsupportedResultException', `The result contains the unsupported data type "${name}"`)
|
|
197
|
+
}
|
|
164
198
|
const longAsString = input.resultSetOptions?.longReturnType === 'STRING'
|
|
165
199
|
const columns: ColumnMetadata[] = result.fields.map((field) => ({
|
|
166
200
|
name: field.name,
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { DatabaseUnavailableError, type DatabaseUnavailableReason } from '../../ports/errors'
|
|
2
|
+
import { normalizeDatabaseError, RdsDataDatabaseError } from './rds-data-codec'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What the Data API's "the database can't serve this now" errors are, and the one wait a process makes while a paused
|
|
6
|
+
* cluster resumes. No AWS SDK at run time: errors are read by name. Which command may be sent again is
|
|
7
|
+
* ./rds-data-dialect.ts's to say (`mayResend`).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* How long one call waits for a resuming cluster before it fails: 18 seconds, inside SssbApp's 30 s server timeout.
|
|
12
|
+
* AWS puts a typical resume at about 15 s, and measured ones took 12 to 14 s. The measured cold request took 26 s; a
|
|
13
|
+
* 12 to 14 s resume was then seen at 15, so about 11 s went elsewhere (the failed calls themselves, a fresh database's
|
|
14
|
+
* first queries): 18 leaves 12. A resume after more than 24 hours paused can take 30 s or longer (AWS's auto-pause
|
|
15
|
+
* page), which no budget inside 30 s covers. docs/runbooks/data-api.md says how to change it.
|
|
16
|
+
*/
|
|
17
|
+
export const RESUME_BUDGET_MS = 18_000
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The waits between probes, the last one repeating. One second from the seventh second on: no measured resume was
|
|
21
|
+
* shorter, and a longer step there is what made a resume at 12 s unseen until 15.
|
|
22
|
+
*/
|
|
23
|
+
const PROBE_DELAYS_MS = [1000, 2000, 4000, 1000] as const
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* How long one probe holds up the next. The SDK's client has no request timeout, so without this a probe on a dead
|
|
27
|
+
* connection (a Lambda frozen with one in flight) would hold every call that joined, with the database up.
|
|
28
|
+
*/
|
|
29
|
+
const PROBE_TIMEOUT_MS = 2000
|
|
30
|
+
|
|
31
|
+
/** The Data API's exceptions that mean the database can't serve the call now, by name. */
|
|
32
|
+
const REASONS: Readonly<Record<string, DatabaseUnavailableReason>> = {
|
|
33
|
+
DatabaseResumingException: 'resuming',
|
|
34
|
+
ThrottlingException: 'throttled',
|
|
35
|
+
StatementTimeoutException: 'timed-out',
|
|
36
|
+
DatabaseUnavailableException: 'unavailable',
|
|
37
|
+
ServiceUnavailableError: 'unavailable',
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Why the database can't serve a call, read from the error or the first error in its cause chain that says; undefined
|
|
42
|
+
* when the failure is something else. An error recognised as being about the SQL ends the search, so
|
|
43
|
+
* that neither its text, which can quote a row, nor anything under it makes it look like a paused database.
|
|
44
|
+
*/
|
|
45
|
+
export function unavailableReason(error: unknown): DatabaseUnavailableReason | undefined {
|
|
46
|
+
const seen = new Set<unknown>()
|
|
47
|
+
for (let link = error; link instanceof Error && !seen.has(link); link = link.cause) {
|
|
48
|
+
seen.add(link)
|
|
49
|
+
const reason = Object.hasOwn(REASONS, link.name) ? REASONS[link.name] : undefined
|
|
50
|
+
if (reason) return reason
|
|
51
|
+
// "This exception is deprecated" (the API reference); taken as a resume when it says "is resuming",
|
|
52
|
+
// which no AWS page confirms or denies. One recognised as a SQL error is not read: its text can quote a row.
|
|
53
|
+
if (link.name === 'BadRequestException') {
|
|
54
|
+
const aboutSql = /\bERROR:/.test(link.message) || isSqlError(link)
|
|
55
|
+
return !aboutSql && /\bis resuming\b/i.test(link.message) ? 'resuming' : undefined
|
|
56
|
+
}
|
|
57
|
+
if (link.name === 'DatabaseErrorException') return undefined
|
|
58
|
+
}
|
|
59
|
+
return undefined
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function isSqlError(error: Error): boolean {
|
|
63
|
+
const normalized = normalizeDatabaseError(error)
|
|
64
|
+
return normalized instanceof RdsDataDatabaseError && normalized.code !== undefined
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The one failure AWS documents as cancelled. The error itself, never a cause: a wrapper may be a later failure. */
|
|
68
|
+
export function wasCancelledUnrun(error: unknown): boolean {
|
|
69
|
+
return error instanceof Error && error.name === 'DatabaseResumingException'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The error an app sees. `cause` is AWS's own error. */
|
|
73
|
+
export function unavailable(reason: DatabaseUnavailableReason, error: unknown): DatabaseUnavailableError {
|
|
74
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
75
|
+
return new DatabaseUnavailableError(reason, `RDS Data API: the database is not available (${reason}): ${detail}`, {
|
|
76
|
+
cause: error,
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface Wake {
|
|
81
|
+
readonly ended: Promise<void>
|
|
82
|
+
readonly end: () => void
|
|
83
|
+
waiters: number
|
|
84
|
+
lastError: unknown
|
|
85
|
+
/** The database has said it is resuming, where a wait may also have been started by a throttle. */
|
|
86
|
+
resuming: boolean
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* One wait for a resuming cluster, for the driver that makes it (the db port builds one per process). The first call
|
|
91
|
+
* that finds it resuming starts a poll of `probe`; every call that joins before the poll ends waits on the same one, each
|
|
92
|
+
* for no longer than its own deadline. The poll ends when the probe answers or fails for another reason (the joined
|
|
93
|
+
* calls then go and get their own answers), or when nobody waits for it any more. A probe that does not answer holds up
|
|
94
|
+
* the next for `PROBE_TIMEOUT_MS`. A poll that has ended, and one nobody waits on, is never joined.
|
|
95
|
+
*/
|
|
96
|
+
export class ResumeWait {
|
|
97
|
+
#current: Wake | undefined
|
|
98
|
+
|
|
99
|
+
/** Must be safe to run any number of times: it is repeated after failures of every kind. */
|
|
100
|
+
private readonly probe: () => Promise<unknown>
|
|
101
|
+
|
|
102
|
+
constructor(probe: () => Promise<unknown>) {
|
|
103
|
+
this.probe = probe
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A wait is under way for a database that said it is resuming: a call not sent yet would only be refused. */
|
|
107
|
+
get resuming(): boolean {
|
|
108
|
+
return this.#current?.resuming === true
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Waits until the database answers; throws DatabaseUnavailableError at `deadline` (a `Date.now()` time). */
|
|
112
|
+
async join(deadline: number, error?: unknown): Promise<void> {
|
|
113
|
+
const remaining = deadline - Date.now()
|
|
114
|
+
if (remaining <= 0) throw this.#expired(error ?? this.#current?.lastError)
|
|
115
|
+
const wake = this.#current ?? this.#start()
|
|
116
|
+
if (error !== undefined) this.#saw(wake, error)
|
|
117
|
+
wake.waiters += 1
|
|
118
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
119
|
+
try {
|
|
120
|
+
const expired = await Promise.race([
|
|
121
|
+
wake.ended.then(() => false),
|
|
122
|
+
new Promise<boolean>((resolve) => {
|
|
123
|
+
timer = setTimeout(() => resolve(true), remaining)
|
|
124
|
+
}),
|
|
125
|
+
])
|
|
126
|
+
if (expired) throw this.#expired(wake.lastError)
|
|
127
|
+
} finally {
|
|
128
|
+
clearTimeout(timer)
|
|
129
|
+
wake.waiters -= 1
|
|
130
|
+
if (wake.waiters === 0) this.#forget(wake)
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
#expired(error: unknown): DatabaseUnavailableError {
|
|
135
|
+
return unavailable(unavailableReason(error) ?? 'resuming', error)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
#saw(wake: Wake, error: unknown): void {
|
|
139
|
+
wake.lastError = error
|
|
140
|
+
if (unavailableReason(error) === 'resuming') wake.resuming = true
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
#forget(wake: Wake): void {
|
|
144
|
+
if (this.#current === wake) this.#current = undefined
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
#finish(wake: Wake): void {
|
|
148
|
+
this.#forget(wake)
|
|
149
|
+
wake.end()
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
#start(): Wake {
|
|
153
|
+
let end: () => void = () => {}
|
|
154
|
+
const ended = new Promise<void>((resolve) => {
|
|
155
|
+
end = resolve
|
|
156
|
+
})
|
|
157
|
+
const wake: Wake = { ended, end, waiters: 0, lastError: undefined, resuming: false }
|
|
158
|
+
this.#current = wake
|
|
159
|
+
void this.#poll(wake).finally(() => this.#finish(wake))
|
|
160
|
+
return wake
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Ends when the database answers, or fails a probe for another reason, or nobody waits any more. */
|
|
164
|
+
async #poll(wake: Wake): Promise<void> {
|
|
165
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
166
|
+
await sleep(PROBE_DELAYS_MS[Math.min(attempt, PROBE_DELAYS_MS.length - 1)])
|
|
167
|
+
if (wake.waiters === 0) return
|
|
168
|
+
let over = false
|
|
169
|
+
let inTurn = true
|
|
170
|
+
// Ends the wait also when this probe outlasted its turn and a later one is in flight.
|
|
171
|
+
const finish = (): void => {
|
|
172
|
+
over = true
|
|
173
|
+
this.#finish(wake)
|
|
174
|
+
}
|
|
175
|
+
const probed = Promise.resolve()
|
|
176
|
+
.then(() => this.probe())
|
|
177
|
+
.then(finish, (error: unknown) => {
|
|
178
|
+
if (!unavailableReason(error)) finish()
|
|
179
|
+
else if (inTurn) this.#saw(wake, error)
|
|
180
|
+
})
|
|
181
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
182
|
+
await Promise.race([
|
|
183
|
+
probed,
|
|
184
|
+
new Promise((resolve) => {
|
|
185
|
+
timer = setTimeout(resolve, PROBE_TIMEOUT_MS)
|
|
186
|
+
}),
|
|
187
|
+
])
|
|
188
|
+
clearTimeout(timer)
|
|
189
|
+
inTurn = false
|
|
190
|
+
if (over) return
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function sleep(ms: number | undefined): Promise<void> {
|
|
196
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
197
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
import { Alert, Button, Stack, Text } from '@mantine/core'
|
|
4
|
+
import { useTranslations } from 'next-intl'
|
|
5
|
+
import { useState } from 'react'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The sign-in card's body for a person the identity provider has signed in but this app refuses
|
|
9
|
+
* (`AuthPort.refusal`): their account names another tenant, or holds something that is not a tenant at all, so it is
|
|
10
|
+
* taken to belong to another site. It says so, and offers one
|
|
11
|
+
* explicit sign-out. Never automatic: on a provider instance shared with another product, signing out ends the
|
|
12
|
+
* person's session there too, which the copy says before they choose.
|
|
13
|
+
*
|
|
14
|
+
* `onSignOut` answers whether the sign-out went through: `false` (or a rejection) shows the error and lets them try
|
|
15
|
+
* again; anything else keeps the spinner while the page navigates (a reload, or the provider's own redirect).
|
|
16
|
+
*/
|
|
17
|
+
export function AccountRefused({ onSignOut }: { onSignOut: () => void | Promise<boolean | void> }) {
|
|
18
|
+
const t = useTranslations('auth')
|
|
19
|
+
const [busy, setBusy] = useState(false)
|
|
20
|
+
const [failed, setFailed] = useState(false)
|
|
21
|
+
|
|
22
|
+
async function signOut() {
|
|
23
|
+
setBusy(true)
|
|
24
|
+
setFailed(false)
|
|
25
|
+
try {
|
|
26
|
+
if ((await onSignOut()) === false) {
|
|
27
|
+
setBusy(false)
|
|
28
|
+
setFailed(true)
|
|
29
|
+
}
|
|
30
|
+
} catch {
|
|
31
|
+
setBusy(false)
|
|
32
|
+
setFailed(true)
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return (
|
|
37
|
+
<Stack gap="sm" data-testid="account-refused">
|
|
38
|
+
<Text fw={600}>{t('refusedTitle')}</Text>
|
|
39
|
+
<Text size="sm">{t('refusedBody')}</Text>
|
|
40
|
+
<Text size="sm" c="gray.7">
|
|
41
|
+
{t('refusedSignOutNote')}
|
|
42
|
+
</Text>
|
|
43
|
+
{failed ? (
|
|
44
|
+
<Alert color="red" role="alert">
|
|
45
|
+
{t('refusedSignOutError')}
|
|
46
|
+
</Alert>
|
|
47
|
+
) : null}
|
|
48
|
+
<Button onClick={() => void signOut()} loading={busy} data-testid="account-refused-signout">
|
|
49
|
+
{t('signOut')}
|
|
50
|
+
</Button>
|
|
51
|
+
</Stack>
|
|
52
|
+
)
|
|
53
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The letters an avatar shows for a person (or an org): the first letters of the first and last words
|
|
3
|
+
* of `name` that start with a letter (Unicode `\p{L}`), uppercased. One such word gives one letter.
|
|
4
|
+
* Punctuation or digits that open a word never count, so `Ana (Bea) Cruz` is `AC`, not `A(`, which
|
|
5
|
+
* is what Mantine's own `name` prop would show.
|
|
6
|
+
*
|
|
7
|
+
* With no such word the first letter (or digit) of `fallback`, the email where a caller has one, is
|
|
8
|
+
* used; with neither, the result is empty and the `Avatar` draws its placeholder icon.
|
|
9
|
+
*/
|
|
10
|
+
export function avatarInitials(name: string, fallback = ''): string {
|
|
11
|
+
const letterWords = name.split(/\s+/).filter((word) => /^\p{L}/u.test(word))
|
|
12
|
+
if (letterWords.length > 0) {
|
|
13
|
+
const first = letterWords[0]!
|
|
14
|
+
const last = letterWords[letterWords.length - 1]!
|
|
15
|
+
// `Array.from` takes a code point, so a letter outside the BMP is not split in half.
|
|
16
|
+
return (Array.from(first)[0]! + (letterWords.length > 1 ? Array.from(last)[0]! : '')).toUpperCase()
|
|
17
|
+
}
|
|
18
|
+
const lead = fallback.match(/[\p{L}\p{N}]/u)?.[0]
|
|
19
|
+
return lead ? lead.toUpperCase() : ''
|
|
20
|
+
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import { Avatar, Group, Stack, Text } from '@mantine/core'
|
|
4
4
|
import type { ReactNode } from 'react'
|
|
5
|
+
import { avatarInitials } from './initials'
|
|
5
6
|
|
|
6
7
|
// Avatars are a dark filled neutral (white initials on near-black): the hash-colored
|
|
7
8
|
// `color="initials"` variants — and even Mantine's default gray placeholder — land at ~3.7–4.4:1 for
|
|
@@ -15,6 +16,7 @@ import type { ReactNode } from 'react'
|
|
|
15
16
|
*/
|
|
16
17
|
export function PreviewRow({
|
|
17
18
|
name,
|
|
19
|
+
fallback,
|
|
18
20
|
title,
|
|
19
21
|
subtitle,
|
|
20
22
|
badge,
|
|
@@ -23,6 +25,9 @@ export function PreviewRow({
|
|
|
23
25
|
}: {
|
|
24
26
|
/** Seeds the initials avatar (org name or person name). */
|
|
25
27
|
name: string
|
|
28
|
+
/** Where the initials come from when `name` has no word that starts with a letter (a person's email).
|
|
29
|
+
* The title when omitted. */
|
|
30
|
+
fallback?: string
|
|
26
31
|
title: string
|
|
27
32
|
subtitle?: ReactNode
|
|
28
33
|
badge?: ReactNode
|
|
@@ -34,7 +39,6 @@ export function PreviewRow({
|
|
|
34
39
|
return (
|
|
35
40
|
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
|
|
36
41
|
<Avatar
|
|
37
|
-
name={name}
|
|
38
42
|
radius={rounded ? 'xl' : 'sm'}
|
|
39
43
|
size={dim}
|
|
40
44
|
// Decorative: the title beside it already says the name, so assistive tech skips the
|
|
@@ -43,7 +47,9 @@ export function PreviewRow({
|
|
|
43
47
|
styles={{
|
|
44
48
|
placeholder: { color: '#fff', background: 'var(--mantine-color-dark-6)' },
|
|
45
49
|
}}
|
|
46
|
-
|
|
50
|
+
>
|
|
51
|
+
{avatarInitials(name, fallback ?? title)}
|
|
52
|
+
</Avatar>
|
|
47
53
|
<Stack gap={2} style={{ minWidth: 0 }}>
|
|
48
54
|
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
|
49
55
|
{/* Explicit dark color: inside Mantine's Menu.Label (user menu header) an
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { Avatar, Menu, UnstyledButton, VisuallyHidden } from '@mantine/core'
|
|
4
4
|
import { useTranslations } from 'next-intl'
|
|
5
5
|
import { SignOutIcon, UserIcon } from './auth-icons'
|
|
6
|
+
import { avatarInitials } from './initials'
|
|
6
7
|
import { PreviewRow } from './preview-row'
|
|
7
8
|
|
|
8
9
|
export interface MenuUser {
|
|
@@ -38,16 +39,23 @@ export function UserMenu({
|
|
|
38
39
|
<UnstyledButton data-testid="user-menu">
|
|
39
40
|
<VisuallyHidden>{t('userMenuLabel', { name: user.name.trim() || user.email })}</VisuallyHidden>
|
|
40
41
|
<Avatar
|
|
41
|
-
name={user.name}
|
|
42
42
|
aria-hidden
|
|
43
43
|
radius="xl"
|
|
44
44
|
styles={{ placeholder: { color: '#fff', background: 'var(--mantine-color-dark-6)' } }}
|
|
45
|
-
|
|
45
|
+
>
|
|
46
|
+
{avatarInitials(user.name, user.email)}
|
|
47
|
+
</Avatar>
|
|
46
48
|
</UnstyledButton>
|
|
47
49
|
</Menu.Target>
|
|
48
50
|
<Menu.Dropdown>
|
|
49
51
|
<Menu.Label>
|
|
50
|
-
<PreviewRow
|
|
52
|
+
<PreviewRow
|
|
53
|
+
name={user.name}
|
|
54
|
+
fallback={user.email}
|
|
55
|
+
title={user.name}
|
|
56
|
+
subtitle={user.email}
|
|
57
|
+
rounded
|
|
58
|
+
/>
|
|
51
59
|
</Menu.Label>
|
|
52
60
|
<Menu.Divider />
|
|
53
61
|
{onProfile ? (
|
package/src/db/family.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { runWithTenant } from './with-tenant'
|
|
|
8
8
|
/**
|
|
9
9
|
* The database family (ADR-0015, second addendum, point 3): what is specific to one database engine, gathered behind
|
|
10
10
|
* one object so the framework's logic stays generic over the engine. SSSB has one family today, Postgres, with three
|
|
11
|
-
* transports (pglite, node-postgres, the RDS Data API); a second family (libsql,
|
|
11
|
+
* transports (pglite, node-postgres, the RDS Data API); a second family (libsql, safeinsights/sssb#174)
|
|
12
12
|
* is a second object of this shape, not a fork of the data layer.
|
|
13
13
|
*
|
|
14
14
|
* A family owns:
|
package/src/db/org-lookup.ts
CHANGED
|
@@ -102,3 +102,21 @@ export async function listOrgsInTenant(
|
|
|
102
102
|
.orderBy('name', 'asc')
|
|
103
103
|
.execute()
|
|
104
104
|
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* An org's display name, by its tenant's slug and its own: the same RLS-free raw read of the `organizations` infra
|
|
108
|
+
* table as the lookups above. The auth port's fixed org source names its home org with it (`listMyOrgs`), since the
|
|
109
|
+
* port knows the org only by slug. Null when the tenant has no such org.
|
|
110
|
+
*/
|
|
111
|
+
export async function orgNameForSlugs(db: DbPort, tenantSlug: string, orgSlug: string): Promise<string | null> {
|
|
112
|
+
await db.ready()
|
|
113
|
+
const row = await db
|
|
114
|
+
.getDb()
|
|
115
|
+
.selectFrom('organizations')
|
|
116
|
+
.innerJoin('tenants', 'tenants.id', 'organizations.tenant_id')
|
|
117
|
+
.select('organizations.name as name')
|
|
118
|
+
.where('tenants.slug', '=', tenantSlug)
|
|
119
|
+
.where('organizations.slug', '=', orgSlug)
|
|
120
|
+
.executeTakeFirst()
|
|
121
|
+
return row?.name ?? null
|
|
122
|
+
}
|
package/src/guide.md
CHANGED
|
@@ -123,6 +123,15 @@ preset, SSSB's conformance suite or `sssb doctor`; keep the rest by hand.
|
|
|
123
123
|
- In `appAbilityRules`, grant org-scoped access through the `sameOrg` you are handed, never by a role alone: `sameOrg` is
|
|
124
124
|
false for a person without standing, and a rule that grants because a role is not some other role would grant
|
|
125
125
|
`none` too.
|
|
126
|
+
- Under a fixed org source (`params.auth.orgSource` `'fixed'`) everyone has the role `none` or `restricted`, and both
|
|
127
|
+
are restricted (`AuthUser.restricted` and the actor's `restricted`), so `restricted` cannot tell your own admins from
|
|
128
|
+
anyone else. Grant your own people from your own data (a field on the subject, such as its publishers; your own table
|
|
129
|
+
in a route or screen) BEFORE any denial on `restricted`, in `appAbilityRules` and wherever a route or screen reads
|
|
130
|
+
`user.restricted`: a check that denies on `restricted` first locks out everyone, your own admins included. Key that
|
|
131
|
+
grant on `actor.userId`, never an email, which another product on a shared instance may let anyone claim. Every
|
|
132
|
+
person credential reaches your rules (a token, an inbound email: the same `userId`), so a grant meant for the person
|
|
133
|
+
at the keyboard also checks `actor.credential?.kind === 'session'`. Your rules see `none` in no org (`sameOrg` is
|
|
134
|
+
false), so a grant that must be scoped to the home org needs `defaultRole: 'restricted'`.
|
|
126
135
|
|
|
127
136
|
## UI
|
|
128
137
|
|
|
@@ -15,7 +15,11 @@
|
|
|
15
15
|
"mfaNotImplemented": "This account requires MFA, which arrives with a later slice.",
|
|
16
16
|
"userMenuLabel": "{name}, account menu",
|
|
17
17
|
"profileLink": "Profile",
|
|
18
|
-
"signOut": "Sign out"
|
|
18
|
+
"signOut": "Sign out",
|
|
19
|
+
"refusedTitle": "This account belongs to another site",
|
|
20
|
+
"refusedBody": "You are signed in, but your account is registered with another site that uses the same sign-in, so it cannot be used here.",
|
|
21
|
+
"refusedSignOutNote": "Signing out here also signs you out of any other site that shares this sign-in.",
|
|
22
|
+
"refusedSignOutError": "You could not be signed out. Try again."
|
|
19
23
|
},
|
|
20
24
|
"profile": {
|
|
21
25
|
"title": "Your profile",
|
|
@@ -15,7 +15,11 @@
|
|
|
15
15
|
"mfaNotImplemented": "Esta cuenta requiere MFA, que llegará en una fase posterior.",
|
|
16
16
|
"userMenuLabel": "{name}, menú de la cuenta",
|
|
17
17
|
"profileLink": "Perfil",
|
|
18
|
-
"signOut": "Cerrar sesión"
|
|
18
|
+
"signOut": "Cerrar sesión",
|
|
19
|
+
"refusedTitle": "Esta cuenta pertenece a otro sitio",
|
|
20
|
+
"refusedBody": "Has iniciado sesión, pero tu cuenta está registrada en otro sitio que usa el mismo inicio de sesión, así que no se puede usar aquí.",
|
|
21
|
+
"refusedSignOutNote": "Al cerrar sesión aquí también la cierras en cualquier otro sitio que comparta este inicio de sesión.",
|
|
22
|
+
"refusedSignOutError": "No se pudo cerrar la sesión. Inténtalo de nuevo."
|
|
19
23
|
},
|
|
20
24
|
"profile": {
|
|
21
25
|
"title": "Tu perfil",
|
package/src/ports/auth.ts
CHANGED
|
@@ -79,6 +79,15 @@ export interface CreatedInvite extends Membership {
|
|
|
79
79
|
acceptUrl: string | null
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Why a person the identity provider has signed in is not a user here. `other-tenant`: their account names another
|
|
84
|
+
* tenant under the deployment's metadata key, or holds there something that is not a slug (a single tenancy's guard),
|
|
85
|
+
* so it is taken to belong to another site.
|
|
86
|
+
*/
|
|
87
|
+
export interface AuthRefusal {
|
|
88
|
+
reason: 'other-tenant'
|
|
89
|
+
}
|
|
90
|
+
|
|
82
91
|
/**
|
|
83
92
|
* Server-side auth port (ADR-0003). Sized to what the app needs — never to Clerk's API.
|
|
84
93
|
* The custom Mantine auth UI is the ONLY auth UI; both adapters sit behind it.
|
|
@@ -112,4 +121,11 @@ export interface AuthPort {
|
|
|
112
121
|
listMyOrgs(): Promise<OrgRef[]>
|
|
113
122
|
/** @throws ForbiddenError when the user has no membership in that org */
|
|
114
123
|
setActiveOrg(orgSlug: string): Promise<void>
|
|
124
|
+
/**
|
|
125
|
+
* Why the person signed in to the identity provider on this request is refused here, or null when nobody is
|
|
126
|
+
* signed in or nobody is refused: what tells a refused person apart from a signed-out one, which `getCurrentUser`
|
|
127
|
+
* answers alike (null). Optional: only a port that refuses people has it (a single tenancy's guard). The sign-in
|
|
128
|
+
* page reads it to say why, and to offer an explicit sign-out (`@sssb/kit/components/auth/account-refused`).
|
|
129
|
+
*/
|
|
130
|
+
refusal?(): Promise<AuthRefusal | null>
|
|
115
131
|
}
|
package/src/ports/errors.ts
CHANGED
|
@@ -34,6 +34,34 @@ export class PreconditionFailedError extends Error {
|
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Why the database can't serve a call now. `resuming`: a paused cluster is starting. `throttled`: it refused the call
|
|
39
|
+
* for load, as it may while a cluster resumes. `timed-out`: a statement ran past the transport's limit. `unavailable`:
|
|
40
|
+
* the writer or the database service is not available.
|
|
41
|
+
*/
|
|
42
|
+
export type DatabaseUnavailableReason = 'resuming' | 'throttled' | 'timed-out' | 'unavailable'
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Thrown when the database can't serve a call now and may soon: a paused cluster that outlasted the transport's wait,
|
|
46
|
+
* a throttled or timed-out call, a writer or a database service that is not available. On the RDS Data API a few
|
|
47
|
+
* answers that the database is resuming throw it at once, as `resuming`, without a wait: to a commit, whose outcome is
|
|
48
|
+
* then unknown, so never assume that it failed; to a statement after another has succeeded in its transaction; and to
|
|
49
|
+
* a statement as a `BadRequestException`. Route glue answers a 503 with `Retry-After: retryAfterSeconds`. It does not
|
|
50
|
+
* say the work did not happen: treat a throttled or timed-out statement or commit as if it may have run. So a caller
|
|
51
|
+
* repeats a read by itself, and a write only when a person, or an idempotent request, asks for it again. `cause` is
|
|
52
|
+
* the vendor's error. Raised by the RDS Data API transport; `pg` has no equivalent today.
|
|
53
|
+
*/
|
|
54
|
+
export class DatabaseUnavailableError extends Error {
|
|
55
|
+
readonly reason: DatabaseUnavailableReason
|
|
56
|
+
readonly retryAfterSeconds = 5
|
|
57
|
+
|
|
58
|
+
constructor(reason: DatabaseUnavailableReason, message = 'database unavailable', options?: { cause?: unknown }) {
|
|
59
|
+
super(message, options)
|
|
60
|
+
this.name = 'DatabaseUnavailableError'
|
|
61
|
+
this.reason = reason
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
37
65
|
/** Thrown by real adapters when their cutover items are unfilled (fail-fast for dev:real). */
|
|
38
66
|
export class CutoverPendingError extends Error {
|
|
39
67
|
readonly cutoverItems: string[]
|
|
@@ -31,6 +31,7 @@ import type { CheckImpl } from './types'
|
|
|
31
31
|
const FORMS: ReadonlySet<string> = new Set([
|
|
32
32
|
'@sssb/kit/adapters/real/sign-in-form',
|
|
33
33
|
'@sssb/kit/adapters/real/accept-invite-form',
|
|
34
|
+
'@sssb/kit/adapters/real/account-refused-form',
|
|
34
35
|
])
|
|
35
36
|
const PROVIDER = '@sssb/kit/adapters/real/providers'
|
|
36
37
|
/**
|