@sssb/kit 0.6.1 → 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 CHANGED
@@ -1 +1 @@
1
- {"commit":"993193893bda13fc98aaaeba0ad004092482c039"}
1
+ {"commit":"1afa32103ec8db683cacb679224809baa89457b6"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/kit",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -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. The one failure that is safe to
33
- * retry (a paused Serverless v2 resuming) is retried by the dialect itself.
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 {
@@ -12,7 +12,7 @@ import { authRequiredEnv, authSettings, fixedOrgProblem } from '../auth-tenancy'
12
12
  import { configuredAuth } from '../configured-auth'
13
13
  import { orgNameForSlugs } from '../../db/org-lookup'
14
14
  import { clerkIdentitySource, realAuth } from './auth'
15
- import { DATABASE_ENV, databaseTransport } from './database-transport'
15
+ import { DATABASE_ENV, databaseResumeBudgetMs, databaseTransport } from './database-transport'
16
16
  import { noAnalytics } from './no-analytics'
17
17
  import { optionalPortsEnv, portChoice } from './optional-ports'
18
18
  import { assertEndpoint, parseForcePathStyle, parseUploadTarget } from './storage-settings'
@@ -74,6 +74,13 @@ export function assertRealEnv(): void {
74
74
  throw new CutoverPendingError(['storage-compatible-store'], (error as Error).message)
75
75
  }
76
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
+ }
77
84
  // The auth settings: an unknown choice, a malformed slug, key or role, a setting its choice does not use, or a fixed
78
85
  // org source that would hand everyone the staff org's manage-all.
79
86
  let problem: string | null
@@ -126,6 +133,7 @@ export async function createRealPorts(hooks: RealPortsHooks = {}): Promise<RealP
126
133
  secretArn: need('DATABASE_SECRET_ARN'),
127
134
  database: need('DATABASE_NAME'),
128
135
  region: need('AWS_REGION'),
136
+ resumeBudgetMs: databaseResumeBudgetMs(),
129
137
  })
130
138
  : (await import('./db')).createRealDb(need('DATABASE_URL'))
131
139
  // Clerk, placed as the auth settings say (../auth-tenancy.ts), and Clerk itself on the defaults. Every port that
@@ -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 }
@@ -40,6 +40,8 @@ import {
40
40
  toSqlParameter,
41
41
  unsupportedStatement,
42
42
  } from './rds-data-codec'
43
+ import { DatabaseUnavailableError } from '../../ports/errors'
44
+ import { RESUME_BUDGET_MS, ResumeWait, unavailable, unavailableReason, wasCancelledUnrun } from './rds-data-resume'
43
45
 
44
46
  /** The four calls this dialect makes. `RDSDataClient` satisfies it, and so does the test emulator. */
45
47
  export type RdsDataCommand =
@@ -59,6 +61,11 @@ export interface RdsDataDialectConfig {
59
61
  database: string
60
62
  /** How long a SQL shape's inferred parameter types are trusted; `TYPE_CACHE_TTL_MS` when omitted. */
61
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
62
69
  }
63
70
 
64
71
  /**
@@ -266,21 +273,21 @@ const TYPE_CACHE_LIMIT = 2000
266
273
  */
267
274
  const TYPE_CACHE_TTL_MS = 5 * 60 * 1000
268
275
 
269
- /**
270
- * A paused Aurora Serverless v2 (min capacity 0, as SSSB's non-production stack runs) answers the first
271
- * call with DatabaseResumingException: the request was cancelled, not run, so retrying it is safe. Every
272
- * other failure is NOT retried — the SDK's own retries are off (`maxAttempts: 1` in ./db-data-api.ts) because AWS
273
- * warns that a retried statement whose first attempt actually finished can write twice.
274
- */
275
- const RESUME_DELAYS_MS = [1000, 2000, 4000, 8000]
276
-
277
276
  class RdsDataDriver implements Driver {
278
277
  readonly #types = new Map<string, { readonly types: readonly string[]; readonly at: number }>()
279
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
+
280
283
  private readonly config: RdsDataDialectConfig
281
284
 
282
285
  constructor(config: RdsDataDialectConfig) {
283
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
+ )
284
291
  }
285
292
 
286
293
  async init(): Promise<void> {}
@@ -367,8 +374,10 @@ class RdsDataDriver implements Driver {
367
374
  } catch (error) {
368
375
  // Already gone means already rolled back: the Data API rolls a transaction back itself when it
369
376
  // idles for three minutes or reaches an hour, and a failed commit ends it too. Rethrowing would
370
- // 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.
371
379
  if (isTransactionGone(error)) return
380
+ if (error instanceof DatabaseUnavailableError && error.reason === 'resuming') return
372
381
  throw error
373
382
  }
374
383
  }
@@ -514,20 +523,67 @@ class RdsDataDriver implements Driver {
514
523
  )) as ExecuteStatementCommandOutput
515
524
  }
516
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
+ */
517
532
  private async call(command: RdsDataCommand): Promise<unknown> {
518
- for (let attempt = 0; ; attempt += 1) {
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()
519
541
  try {
520
- return await this.config.client.send(command)
542
+ return await this.send(command)
521
543
  } catch (error) {
522
- const resuming = error instanceof Error && error.name === 'DatabaseResumingException'
523
- if (resuming && attempt < RESUME_DELAYS_MS.length) {
524
- await new Promise((resolve) => setTimeout(resolve, RESUME_DELAYS_MS[attempt]))
544
+ if (this.mayResend(command, error)) {
545
+ await wait(error)
525
546
  continue
526
547
  }
527
- throw normalizeDatabaseError(error)
548
+ const reason = unavailableReason(error)
549
+ throw reason ? unavailable(reason, error) : normalizeDatabaseError(error)
528
550
  }
529
551
  }
530
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
+ }
531
587
  }
532
588
 
533
589
  class RdsDataConnection implements DatabaseConnection {
@@ -582,6 +638,10 @@ function isTransactionGone(error: unknown): boolean {
582
638
  return error.name === 'TransactionNotFoundException' || /transaction\b.*\bnot found/i.test(error.message)
583
639
  }
584
640
 
641
+ function transactionIdOf(command: RdsDataCommand): string | undefined {
642
+ return 'transactionId' in command.input ? command.input.transactionId : undefined
643
+ }
644
+
585
645
  function quoteIdent(name: string): string {
586
646
  return `"${name.replace(/"/g, '""')}"`
587
647
  }
@@ -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,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 name={user.name} title={user.name} subtitle={user.email} rounded />
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 ? (
@@ -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[]