@fabrika/app 0.9.0-dev.4 → 0.9.0-dev.6

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.
Files changed (113) hide show
  1. package/package.json +9 -9
  2. package/skill/SKILL.md +41 -14
  3. package/skill/references/app-setup.md +43 -12
  4. package/skill/references/dev.md +2 -1
  5. package/skill/references/endpoint.md +30 -24
  6. package/skill/references/errors.md +40 -35
  7. package/skill/references/files.md +4 -2
  8. package/skill/references/jobs.md +21 -4
  9. package/skill/references/table-and-migration.md +19 -2
  10. package/skill/references/tests.md +40 -1
  11. package/skill/references/webhooks-links-connectors.md +1 -1
  12. package/src/build-recipe.ts +198 -0
  13. package/src/build.ts +60 -4
  14. package/src/bun.ts +181 -13
  15. package/src/cloudflare/application.ts +822 -0
  16. package/src/cloudflare/bindings.ts +159 -0
  17. package/src/cloudflare/export.ts +621 -0
  18. package/src/cloudflare/import.ts +1013 -0
  19. package/src/cloudflare/maintenance.ts +518 -0
  20. package/src/cloudflare/names.ts +16 -0
  21. package/src/cloudflare/ops.ts +375 -0
  22. package/src/cloudflare/r2-files.ts +172 -0
  23. package/src/cloudflare/restore.ts +167 -0
  24. package/src/cloudflare/tracker.ts +192 -0
  25. package/src/cloudflare.ts +100 -146
  26. package/src/contract/app-id.ts +5 -0
  27. package/src/contract/artifact-schema.ts +9 -1
  28. package/src/contract/build.ts +40 -2
  29. package/src/contract/compile.ts +1 -0
  30. package/src/contract/context.ts +35 -9
  31. package/src/contract/declaration.ts +2 -0
  32. package/src/contract/defaults.ts +22 -2
  33. package/src/contract/define.ts +29 -3
  34. package/src/contract/kit.ts +4 -1
  35. package/src/contract/platform.ts +3 -2
  36. package/src/contract/vocabulary.ts +26 -8
  37. package/src/dev/launcher.ts +50 -4
  38. package/src/disk-assets.ts +8 -3
  39. package/src/files/archive.ts +2 -2
  40. package/src/files/job-names.ts +12 -0
  41. package/src/files/kinds.ts +73 -31
  42. package/src/files/scan.ts +3 -4
  43. package/src/files/streams.ts +3 -1
  44. package/src/implement/anonymous.ts +12 -11
  45. package/src/implement/boot.ts +75 -6
  46. package/src/implement/bounded.ts +21 -2
  47. package/src/implement/capability.ts +15 -3
  48. package/src/implement/dispatch.ts +419 -177
  49. package/src/implement/failures.ts +17 -1
  50. package/src/implement/faults.ts +1 -0
  51. package/src/implement/index.ts +1 -0
  52. package/src/implement/invocation.ts +58 -10
  53. package/src/implement/principal.ts +25 -2
  54. package/src/implement/terminals.ts +93 -0
  55. package/src/implement/workload.ts +42 -16
  56. package/src/jobs/mail.ts +8 -0
  57. package/src/jobs/report.ts +5 -1
  58. package/src/jobs/runner.ts +672 -113
  59. package/src/jobs/schedule.ts +7 -1
  60. package/src/jobs/scrub.ts +14 -1
  61. package/src/jobs/types.ts +6 -0
  62. package/src/spa-fallback.ts +12 -0
  63. package/src/testing/endpoint-access.ts +307 -152
  64. package/src/testing/isolation.ts +8 -1
  65. package/src/testing/kit.ts +80 -2
  66. package/src/testing/proxy.ts +15 -10
  67. package/types/src/build-recipe.d.ts +70 -0
  68. package/types/src/build.d.ts +19 -1
  69. package/types/src/bun.d.ts +34 -1
  70. package/types/src/cloudflare/application.d.ts +73 -0
  71. package/types/src/cloudflare/bindings.d.ts +33 -0
  72. package/types/src/cloudflare/export.d.ts +16 -0
  73. package/types/src/cloudflare/import.d.ts +51 -0
  74. package/types/src/cloudflare/maintenance.d.ts +117 -0
  75. package/types/src/cloudflare/names.d.ts +11 -0
  76. package/types/src/cloudflare/ops.d.ts +81 -0
  77. package/types/src/cloudflare/r2-files.d.ts +9 -0
  78. package/types/src/cloudflare/restore.d.ts +9 -0
  79. package/types/src/cloudflare/tracker.d.ts +29 -0
  80. package/types/src/cloudflare.d.ts +12 -18
  81. package/types/src/contract/app-id.d.ts +2 -0
  82. package/types/src/contract/artifact-schema.d.ts +2 -0
  83. package/types/src/contract/context.d.ts +35 -11
  84. package/types/src/contract/declaration.d.ts +4 -0
  85. package/types/src/contract/defaults.d.ts +19 -1
  86. package/types/src/contract/define.d.ts +20 -3
  87. package/types/src/contract/kit.d.ts +2 -1
  88. package/types/src/contract/platform.d.ts +2 -2
  89. package/types/src/contract/vocabulary.d.ts +9 -7
  90. package/types/src/disk-assets.d.ts +4 -1
  91. package/types/src/files/job-names.d.ts +9 -0
  92. package/types/src/files/kinds.d.ts +21 -14
  93. package/types/src/files/scan.d.ts +1 -3
  94. package/types/src/implement/anonymous.d.ts +2 -4
  95. package/types/src/implement/boot.d.ts +17 -1
  96. package/types/src/implement/bounded.d.ts +11 -1
  97. package/types/src/implement/capability.d.ts +4 -2
  98. package/types/src/implement/dispatch.d.ts +34 -1
  99. package/types/src/implement/failures.d.ts +5 -0
  100. package/types/src/implement/faults.d.ts +1 -0
  101. package/types/src/implement/index.d.ts +1 -0
  102. package/types/src/implement/invocation.d.ts +22 -7
  103. package/types/src/implement/principal.d.ts +6 -1
  104. package/types/src/implement/terminals.d.ts +33 -0
  105. package/types/src/implement/workload.d.ts +5 -0
  106. package/types/src/jobs/runner.d.ts +66 -2
  107. package/types/src/jobs/schedule.d.ts +2 -0
  108. package/types/src/jobs/types.d.ts +6 -0
  109. package/types/src/spa-fallback.d.ts +2 -0
  110. package/types/src/testing/endpoint-access.d.ts +37 -5
  111. package/types/src/testing/isolation.d.ts +1 -1
  112. package/types/src/testing/kit.d.ts +22 -1
  113. package/types/src/testing/proxy.d.ts +4 -4
@@ -2,7 +2,7 @@
2
2
  // fixed codes and bounded identifiers only, never an error's name or message: application code, drivers and even the
3
3
  // framework's own refusals can put request data there. The event adds what was thrown as its cause chain, scrubbed of
4
4
  // the environment's secrets and of credential patterns, a framework failure's message replaced by its catalog text
5
- // (ADR-0059).
5
+ // (ADR-0059). A writing invocation that held its Durable Object's transaction too long is an event on the same budget.
6
6
 
7
7
  import { CAPABILITY_ERRORS, CapabilityError, QUERY_REFUSALS, QueryRefusedError } from '@fabrika/db/framework'
8
8
  import { isStructuralError } from '../errors'
@@ -127,4 +127,20 @@ export class FailureReports {
127
127
  error: failure.error,
128
128
  })
129
129
  }
130
+
131
+ /**
132
+ * A writing invocation that held its object's transaction past `@fabrika/db`'s report threshold, which already
133
+ * logged it. Never rejects; the delivery may outlive the response like a failure's.
134
+ */
135
+ held(endpoint: string, heldMs: number): Promise<void> {
136
+ if (this.#reporter === null || !this.#budget.admit()) {
137
+ return Promise.resolve()
138
+ }
139
+ return this.#reporter.report({
140
+ fingerprint: ['fabrika-transaction-held', endpoint],
141
+ type: 'TransactionHeld',
142
+ message: `endpoint '${endpoint}' held its object's transaction for ${heldMs} ms`,
143
+ tags: { endpoint, code: 'transaction_held', held_ms: String(heldMs) },
144
+ })
145
+ }
130
146
  }
@@ -19,6 +19,7 @@ export const SERVER_FAULTS = {
19
19
  webhook_unverifiable: 'a webhook verifies a signature over its public URL (Twilio), and the environment has no FABRIKA_APP_ORIGIN',
20
20
  webhook_claim_lost: "a delivery's claim expired and another copy of the delivery took it over before this one committed; nothing it wrote is kept",
21
21
  workload_unauthorized: "the workload's key or token does not carry the authority its declaration needs",
22
+ terminal_refused: "IAM refused the application's own credential for an identification at a terminal",
22
23
  request_cancelled: 'the request was cancelled or outlived its budget before its transaction committed; nothing it wrote is kept',
23
24
  file_object_missing: "a file's object is missing from storage",
24
25
  file_object_mismatch: "a file's object has another size than its row records",
@@ -53,6 +53,7 @@ export type {
53
53
  } from './membership'
54
54
  export type { AppPrincipal, LinkHolder, Principal, PrincipalOf, PublicPrincipal, ServicePrincipal, UserPrincipal } from './principal'
55
55
  export { type AppDeps, defineDeps, serve, type ServeOptions } from './serve'
56
+ export type { AssertedIdentity, OpenIdentification, TerminalIdentification } from './terminals'
56
57
  export type {
57
58
  AccessContext,
58
59
  ConnectCall,
@@ -10,6 +10,7 @@ import {
10
10
  type DataSite,
11
11
  type FileBinding,
12
12
  type InvocationTransaction,
13
+ type NewWake,
13
14
  type QueryRefusal,
14
15
  QueryRefusedError,
15
16
  type Session,
@@ -321,6 +322,14 @@ export class Invocation {
321
322
  return { check: boundTo(this.#frame, () => transaction.ended, handle), session: () => transaction.session() }
322
323
  }
323
324
 
325
+ /**
326
+ * Runs `work`, from the handler to `commit`, in this invocation's transaction. On SQLite it encloses `work`, and a
327
+ * hold past `@fabrika/db`'s report threshold reaches `held`, logged under `site`.
328
+ */
329
+ enclose<T>(work: () => Promise<T>, site: string, held: (heldMs: number) => void): Promise<T> {
330
+ return this.#transaction.enclose(work, { site, held })
331
+ }
332
+
324
333
  /** Commits; a request the caller abandoned meanwhile rolls back instead. */
325
334
  async commit(signal: AbortSignal | null): Promise<void> {
326
335
  if (signal?.aborted === true) {
@@ -458,22 +467,61 @@ export function jobSql(frame: RequestFrame, data: DataAccess, mode: SqlMode, ses
458
467
  return data.sql({ mode, check: boundTo(frame, ended, 'tx.sql'), session: async () => session, fail: () => session.fail() })
459
468
  }
460
469
 
470
+ /** The kicks of one invocation, as `ctx.kick` recorded them. */
471
+ export interface KickRecorder {
472
+ readonly kick: (job: string, options?: unknown) => void
473
+ /** The jobs kicked without `at`, each once: what the dispatcher starts after the commit. */
474
+ readonly kicked: () => readonly string[]
475
+ /** Whether the invocation kicked anything, now or for later. */
476
+ readonly recorded: () => boolean
477
+ /**
478
+ * Every kick's wake, one per job and due second (`kick:<job>:<due second>`); a kick without `at` is due at `now`. The
479
+ * site writes them in its transaction, so a rollback leaves none.
480
+ */
481
+ readonly wakes: (now: Date) => readonly NewWake[]
482
+ }
483
+
484
+ /** A kick's due time: `undefined` for one without options; anything but `{ at: <valid Date> }` is refused. */
485
+ function kickAt(site: string, options: unknown): Date | undefined {
486
+ if (options === undefined) {
487
+ return undefined
488
+ }
489
+ const keys = isPlainObject(options) ? Object.keys(options) : null
490
+ const at: unknown = isPlainObject(options) ? ownField(options, 'at') : undefined
491
+ if (keys === null || keys.length !== 1 || keys[0] !== 'at' || !(at instanceof Date) || Number.isNaN(at.getTime())) {
492
+ throw new QueryRefusedError('invalid_argument', `${site}: ctx.kick takes a job and optionally { at: <Date> }; a kick carries nothing else`)
493
+ }
494
+ return new Date(at.getTime())
495
+ }
496
+
497
+ const kickKey = (job: string, due: Date): string => `kick:${job}:${Math.floor(due.getTime() / 1_000)}`
498
+
461
499
  /**
462
- * `ctx.kick` of one invocation: it names only a declared job, and records it; the dispatcher sends each recorded job once,
463
- * after the commit, and nothing on a rollback.
500
+ * `ctx.kick` of one invocation: it names only a declared job, and records it; the site writes each kick's wake in its
501
+ * transaction, and the dispatcher starts each job kicked without `at` once, after the commit, and nothing on a rollback.
464
502
  */
465
- export function kickRecorder(
466
- site: string,
467
- declared: readonly string[],
468
- ): { readonly kick: (job: string) => void; readonly kicked: () => readonly string[] } {
469
- const kicked = new Set<string>()
503
+ export function kickRecorder(site: string, declared: readonly string[]): KickRecorder {
504
+ const kicks: { readonly job: string; readonly at: Date | undefined }[] = []
470
505
  return {
471
- kick: (job: string) => {
506
+ kick: (job: string, options?: unknown) => {
472
507
  if (!declared.includes(job)) {
473
508
  throw new CapabilityRefusedError('undeclared_kick', `${site} does not declare kicks: ['${String(job)}']`)
474
509
  }
475
- kicked.add(job)
510
+ kicks.push({ job, at: kickAt(site, options) })
511
+ },
512
+ kicked: () => [...new Set(kicks.filter((kick) => kick.at === undefined).map((kick) => kick.job))],
513
+ recorded: () => kicks.length > 0,
514
+ wakes: (now: Date) => {
515
+ const wakes = new Map<string, NewWake>()
516
+ for (const { job, at } of kicks) {
517
+ const dueAt = at ?? now
518
+ const dedupe = kickKey(job, dueAt)
519
+ const kept = wakes.get(dedupe)
520
+ if (kept === undefined || dueAt < kept.dueAt) {
521
+ wakes.set(dedupe, { job, reason: 'kick', dueAt, dedupe })
522
+ }
523
+ }
524
+ return [...wakes.values()]
476
525
  },
477
- kicked: () => [...kicked],
478
526
  }
479
527
  }
@@ -1,6 +1,15 @@
1
1
  // Who called: the caller kind a verified token presents, and the principal a handler sees for it.
2
2
 
3
- import { type AccessTokenClaims, APP_CALLER_PREFIX, type Caller, callerOf, matchAction, OAUTH_CALLER, type PermissionEntry } from '@fabrika/auth-core'
3
+ import {
4
+ type AccessTokenClaims,
5
+ APP_CALLER_PREFIX,
6
+ type Caller,
7
+ callerOf,
8
+ matchAction,
9
+ OAUTH_CALLER,
10
+ type PermissionEntry,
11
+ type TerminalTokenClaims,
12
+ } from '@fabrika/auth-core'
4
13
  import type { PageCaller } from '../client/caller'
5
14
 
6
15
  /** A person: the IAM session, or a `px_` key bound to a user principal. */
@@ -11,6 +20,11 @@ export interface UserPrincipal {
11
20
  readonly label: string
12
21
  /** The mailbox IAM recorded for the person, lower-cased: the one to mail, not proof of possession. Only a person has one. */
13
22
  readonly email: string
23
+ /**
24
+ * The enrolled terminal the person signed in on, when an application asserted them there (ADR-0067); absent for every
25
+ * other sign-in. Information for the handler: what the session may do is in its permissions already.
26
+ */
27
+ readonly terminal?: TerminalTokenClaims
14
28
  }
15
29
 
16
30
  /** A machine: a `px_` key bound to a service principal. */
@@ -65,7 +79,16 @@ export function presentedBy(claims: AccessTokenClaims): Presented | Unpresented
65
79
  switch (caller) {
66
80
  case 'human':
67
81
  if (claims.email === undefined) return 'no_mailbox'
68
- return { caller, principal: { kind: 'user', id: claims.sub, label: claims.label ?? claims.sub, email: claims.email } }
82
+ return {
83
+ caller,
84
+ principal: {
85
+ kind: 'user',
86
+ id: claims.sub,
87
+ label: claims.label ?? claims.sub,
88
+ email: claims.email,
89
+ ...(claims.terminal === undefined ? {} : { terminal: Object.freeze({ id: claims.terminal.id, label: claims.terminal.label }) }),
90
+ },
91
+ }
69
92
  case 'machine':
70
93
  return { caller, principal: { kind: 'service', id: claims.sub, label: claims.label ?? claims.sub } }
71
94
  case 'link':
@@ -0,0 +1,93 @@
1
+ // `ctx.terminals`: the identification of a person at an enrolled terminal (ADR-0067). The application's identification
2
+ // page sends what the person entered to its own procedure, which asks IAM through these calls. The framework presents
3
+ // the request's credential (a public procedure's workload token), and IAM takes the asserting application from the
4
+ // verified transport. Throttling guesses is the application's: `inspect` hands it the terminal to key them on.
5
+
6
+ import type { IamTerminalRpc, IdentificationTerminal, MembershipCaller, TerminalFailure } from '@fabrika/auth-core'
7
+ import { ServerFault } from './faults'
8
+
9
+ /** An identification id longer than this is none IAM issued, so no call is made for it. */
10
+ const MAX_IDENTIFICATION_ID_LENGTH = 200
11
+
12
+ /** An open identification: the terminal it was opened on and when it expires (unix seconds). */
13
+ export interface OpenIdentification {
14
+ readonly terminal: IdentificationTerminal
15
+ readonly expiresAt: number
16
+ }
17
+
18
+ /**
19
+ * IAM's answer to an assertion: the URL the browser goes to next, or why IAM refused. `not_found` is an identification
20
+ * that is unknown, expired, used, cancelled or no longer open to this application; `invalid_principal` a principal
21
+ * that cannot sign in on a terminal (unknown, disabled, not a person, or external).
22
+ */
23
+ export type AssertedIdentity =
24
+ | { readonly ok: true; readonly completionUrl: string }
25
+ | { readonly ok: false; readonly reason: 'not_found' | 'invalid_principal' }
26
+
27
+ /** `ctx.terminals` of an application that declares `terminal: { identify }`. */
28
+ export interface TerminalIdentification {
29
+ /** The open identification `id` (the page's `identification` query parameter), or null when there is none. */
30
+ inspect(id: string): Promise<OpenIdentification | null>
31
+ /**
32
+ * The application's word that `principalId` stands at the identification's terminal. IAM uses the identification up
33
+ * and, on `ok`, the handler sends the browser to `completionUrl`: IAM signs the person in there, and only on the
34
+ * terminal's own browser.
35
+ */
36
+ assert(id: string, principalId: string): Promise<AssertedIdentity>
37
+ /** Ends an identification the person abandoned; one that is no longer open is already ended. */
38
+ cancel(id: string): Promise<void>
39
+ }
40
+
41
+ /** `ctx.terminals` for one request: every call carries the request's credential and correlation id. */
42
+ export function terminalIdentification(rpc: IamTerminalRpc, caller: MembershipCaller): TerminalIdentification {
43
+ return Object.freeze({
44
+ async inspect(id: string): Promise<OpenIdentification | null> {
45
+ if (!isIdentificationId(id)) return null
46
+ const result = await ask(() => rpc.inspectIdentification({ ...caller, id }), 'inspect an identification')
47
+ if (!result.ok) return null
48
+ return Object.freeze({ terminal: Object.freeze({ id: result.terminal.id, label: result.terminal.label }), expiresAt: result.expiresAt })
49
+ },
50
+ async assert(id: string, principalId: string): Promise<AssertedIdentity> {
51
+ if (!isIdentificationId(id)) return { ok: false, reason: 'not_found' }
52
+ const result = await ask(() => rpc.assertIdentity({ ...caller, id, principalId }), 'assert an identity')
53
+ return result.ok ? { ok: true, completionUrl: result.completionUrl } : { ok: false, reason: result.reason }
54
+ },
55
+ async cancel(id: string): Promise<void> {
56
+ if (isIdentificationId(id)) {
57
+ await ask(() => rpc.cancelIdentification({ ...caller, id }), 'cancel an identification')
58
+ }
59
+ },
60
+ })
61
+ }
62
+
63
+ function isIdentificationId(id: string): boolean {
64
+ return id !== '' && id.length <= MAX_IDENTIFICATION_ID_LENGTH
65
+ }
66
+
67
+ /**
68
+ * Runs one IAM call. A transport failure is a 503 that names nothing; IAM refusing the application's own credential is
69
+ * a server fault, because the visitor cannot change it. What remains is the handler's answer.
70
+ */
71
+ async function ask<T extends { readonly ok: true }>(
72
+ work: () => Promise<T | TerminalFailure>,
73
+ operation: string,
74
+ ): Promise<T | { readonly ok: false; readonly reason: 'not_found' | 'invalid_principal' }> {
75
+ let result: T | TerminalFailure
76
+ try {
77
+ result = await work()
78
+ } catch {
79
+ throw new ServerFault('iam_unavailable', `IAM could not be asked to ${operation}`, 503)
80
+ }
81
+ if (result.ok) {
82
+ return result
83
+ }
84
+ switch (result.reason) {
85
+ case 'not_found':
86
+ case 'invalid_principal':
87
+ return { ok: false, reason: result.reason }
88
+ case 'missing_token':
89
+ case 'invalid_token':
90
+ case 'not_allowed':
91
+ throw new ServerFault('terminal_refused', `IAM refused the application's credential to ${operation}: ${result.reason}`)
92
+ }
93
+ }
@@ -16,6 +16,7 @@ import {
16
16
  } from '@fabrika/auth-core'
17
17
  import type { TokenVerifier } from '@fabrika/jwks'
18
18
  import { z } from 'zod/v4'
19
+ import { deadline } from './bounded'
19
20
 
20
21
  export type WorkloadKindOf = OwnWorkloadKind
21
22
 
@@ -39,20 +40,30 @@ export function issuerWorkloadTokens(
39
40
  ): WorkloadTokenSource {
40
41
  return {
41
42
  async exchange(input) {
42
- const response = await fetcher(
43
- new Request(new URL(WORKLOAD_TOKEN_PATH, issuer), {
44
- method: 'POST',
45
- headers: { authorization: `Bearer ${input.key}`, 'content-type': 'application/json' },
46
- body: JSON.stringify({ app: input.app }),
47
- redirect: 'manual',
48
- signal: AbortSignal.timeout(EXCHANGE_TIMEOUT_MS),
49
- }),
50
- )
51
- const parsed = response.status === 200 ? mintResultSchema.safeParse(await response.json()) : null
52
- if (parsed === null || !parsed.success) {
53
- throw new Error(`IAM answered the workload token exchange with ${response.status}`)
43
+ const timer = deadline(EXCHANGE_TIMEOUT_MS)
44
+ try {
45
+ const response = await fetcher(
46
+ new Request(new URL(WORKLOAD_TOKEN_PATH, issuer), {
47
+ method: 'POST',
48
+ headers: { authorization: `Bearer ${input.key}`, 'content-type': 'application/json' },
49
+ body: JSON.stringify({ app: input.app }),
50
+ redirect: 'manual',
51
+ signal: timer.signal,
52
+ }),
53
+ )
54
+ if (response.status !== 200) {
55
+ // Nothing reads a refusal's body, and once the deadline is cleared nothing else would end its stream.
56
+ await response.body?.cancel().catch(() => {})
57
+ throw new Error(`IAM answered the workload token exchange with ${response.status}`)
58
+ }
59
+ const parsed = mintResultSchema.safeParse(await response.json())
60
+ if (!parsed.success) {
61
+ throw new Error(`IAM answered the workload token exchange with ${response.status}`)
62
+ }
63
+ return parsed.data
64
+ } finally {
65
+ timer.clear()
54
66
  }
55
- return parsed.data
56
67
  },
57
68
  }
58
69
  }
@@ -91,12 +102,27 @@ export class WorkloadCredential {
91
102
  if (cached !== null && cached.exp - Math.floor(Date.now() / 1000) > TOKEN_REFRESH_SKEW_SECONDS) {
92
103
  return Promise.resolve({ ok: true, perms: cached.perms, token: cached.token })
93
104
  }
94
- this.#pending ??= this.#exchange().finally(() => {
95
- this.#pending = null
96
- })
105
+ if (this.#pending === null) {
106
+ const pending: Promise<WorkloadAuthority> = this.#exchange().finally(() => {
107
+ if (this.#pending === pending) {
108
+ this.#pending = null
109
+ }
110
+ })
111
+ this.#pending = pending
112
+ }
97
113
  return this.#pending
98
114
  }
99
115
 
116
+ /**
117
+ * The caller stopped waiting for `pending`, an answer of `authority()` (its attempt timed out or was stopped): the
118
+ * next call exchanges afresh instead of waiting on an exchange that may never answer.
119
+ */
120
+ abandon(pending: Promise<WorkloadAuthority>): void {
121
+ if (this.#pending === pending) {
122
+ this.#pending = null
123
+ }
124
+ }
125
+
100
126
  async #exchange(): Promise<WorkloadAuthority> {
101
127
  const { kind, name, key, audience, source, verifier } = this.#options
102
128
  let minted: MintFromKeyResult
package/src/jobs/mail.ts CHANGED
@@ -93,6 +93,10 @@ export function jobMail(input: JobMailInput): AppMail {
93
93
  if (typeof key !== 'string' || !APP_MAIL_KEY.test(key)) {
94
94
  throw new EmailDeliveryError(`Email idempotency key is not 1..${MAX_APP_MAIL_KEY_LENGTH} visible ASCII characters`, { code: 'invalid_message' })
95
95
  }
96
+ // Checked here, not left to the sender: one written before `broadcast` existed would send it as transactional mail.
97
+ if (available && message.broadcast === true && sender.capabilities.broadcast !== true) {
98
+ throw new EmailDeliveryError('This mail transport sends no broadcast email', { code: 'invalid_message' })
99
+ }
96
100
  // Without a transport the send fails `mail_not_configured` below, and no file is read for it.
97
101
  const attachments = available ? await readAttachments(message.attachments ?? [], sender.capabilities.maxAttachmentBytes, open) : []
98
102
  const transported: EmailMessage = {
@@ -104,6 +108,7 @@ export function jobMail(input: JobMailInput): AppMail {
104
108
  ...(message.replyTo === undefined ? {} : { replyTo: message.replyTo }),
105
109
  ...(message.fromName === undefined ? {} : { fromName: message.fromName }),
106
110
  ...(message.unsubscribe === undefined ? {} : { unsubscribeUrl: message.unsubscribe.url }),
111
+ ...(message.broadcast === true ? { broadcast: true } : {}),
107
112
  ...(attachments.length === 0 ? {} : { attachments }),
108
113
  }
109
114
  try {
@@ -309,6 +314,9 @@ const SenderCapabilities = z.object({
309
314
  maxBatch: z.int().positive(),
310
315
  listUnsubscribe: z.boolean().optional(),
311
316
  maxAttachmentBytes: z.int().positive().optional(),
317
+ refusedAttachmentExtensions: z.array(z.string()).readonly().optional(),
318
+ minBodyLength: z.int().positive().optional(),
319
+ broadcast: z.boolean().optional(),
312
320
  })
313
321
 
314
322
  /** What `serve`'s `mail` returned: a sender, `null` for none, `undefined` for anything else. */
@@ -3,6 +3,7 @@
3
3
  // groups a framework report by its fingerprint and raises its new-issue and regression alerts, so each kind of
4
4
  // failure becomes one issue. What was thrown travels scrubbed as the report's cause chain (ADR-0059).
5
5
 
6
+ import { deadline } from '../implement/bounded'
6
7
  import { exceptionChain, type ReportedException } from './exception'
7
8
  import type { Scrubber } from './scrub'
8
9
 
@@ -136,6 +137,7 @@ export function crashEnvelope(kind: CrashKind, error: unknown, options: Envelope
136
137
 
137
138
  async function deliver(options: OperationsReporterOptions, body: string): Promise<void> {
138
139
  const send = options.fetch ?? ((request: Request) => fetch(request))
140
+ const timer = deadline(DELIVERY_TIMEOUT_MS)
139
141
  const request = new Request(options.target.envelopeUrl, {
140
142
  method: 'POST',
141
143
  headers: {
@@ -143,7 +145,7 @@ async function deliver(options: OperationsReporterOptions, body: string): Promis
143
145
  'x-sentry-auth': `Sentry sentry_version=7, sentry_key=${options.target.publicKey}`,
144
146
  },
145
147
  body,
146
- signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),
148
+ signal: timer.signal,
147
149
  })
148
150
  try {
149
151
  const response = await send(request)
@@ -154,6 +156,8 @@ async function deliver(options: OperationsReporterOptions, body: string): Promis
154
156
  } catch {
155
157
  // The error may quote the ingest URL with its key.
156
158
  console.error('fabrika: a report to Operations could not be delivered')
159
+ } finally {
160
+ timer.clear()
157
161
  }
158
162
  }
159
163