pipework 0.275.0 → 0.277.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/REFERENCE.md +11 -4
  3. package/dist/async/jobs/run-script.d.ts.map +1 -1
  4. package/dist/async/jobs/run-script.js +3 -0
  5. package/dist/async/jobs/run-script.js.map +1 -1
  6. package/dist/core/lifecycle/startup.d.ts.map +1 -1
  7. package/dist/core/lifecycle/startup.js +2 -0
  8. package/dist/core/lifecycle/startup.js.map +1 -1
  9. package/dist/data/db/pool.d.ts +6 -0
  10. package/dist/data/db/pool.d.ts.map +1 -1
  11. package/dist/data/db/pool.js +23 -0
  12. package/dist/data/db/pool.js.map +1 -1
  13. package/dist/data/migrate/internal-definitions.d.ts.map +1 -1
  14. package/dist/data/migrate/internal-definitions.js +2 -1
  15. package/dist/data/migrate/internal-definitions.js.map +1 -1
  16. package/dist/infra/alerts/handle.d.ts +10 -0
  17. package/dist/infra/alerts/handle.d.ts.map +1 -1
  18. package/dist/infra/alerts/handle.js +34 -3
  19. package/dist/infra/alerts/handle.js.map +1 -1
  20. package/dist/infra/alerts/release.d.ts +6 -0
  21. package/dist/infra/alerts/release.d.ts.map +1 -0
  22. package/dist/infra/alerts/release.js +25 -0
  23. package/dist/infra/alerts/release.js.map +1 -0
  24. package/dist/infra/alerts/schema.d.ts +22 -0
  25. package/dist/infra/alerts/schema.d.ts.map +1 -1
  26. package/dist/infra/alerts/schema.js +7 -0
  27. package/dist/infra/alerts/schema.js.map +1 -1
  28. package/dist/infra/credits/schema.d.ts +1 -1
  29. package/dist/request/context/run-in-transaction.d.ts.map +1 -1
  30. package/dist/request/context/run-in-transaction.js +28 -15
  31. package/dist/request/context/run-in-transaction.js.map +1 -1
  32. package/dist/request/http/aborted.d.ts +7 -0
  33. package/dist/request/http/aborted.d.ts.map +1 -1
  34. package/dist/request/http/aborted.js +20 -0
  35. package/dist/request/http/aborted.js.map +1 -1
  36. package/dist/request/http/namespace.d.ts +1 -1
  37. package/dist/request/http/namespace.d.ts.map +1 -1
  38. package/dist/request/http/namespace.js +1 -1
  39. package/dist/request/http/namespace.js.map +1 -1
  40. package/dist/request/http/server.d.ts.map +1 -1
  41. package/dist/request/http/server.js +38 -9
  42. package/dist/request/http/server.js.map +1 -1
  43. package/dist/test/plugin.d.ts.map +1 -1
  44. package/dist/test/plugin.js +1 -0
  45. package/dist/test/plugin.js.map +1 -1
  46. package/package.json +1 -1
  47. package/src/async/jobs/run-script.ts +2 -0
  48. package/src/core/lifecycle/startup.ts +2 -0
  49. package/src/data/db/pool.ts +29 -0
  50. package/src/data/migrate/internal-definitions.ts +2 -1
  51. package/src/infra/alerts/handle.ts +43 -3
  52. package/src/infra/alerts/release.ts +28 -0
  53. package/src/infra/alerts/schema.ts +8 -0
  54. package/src/request/context/run-in-transaction.ts +26 -17
  55. package/src/request/http/aborted.ts +19 -0
  56. package/src/request/http/namespace.ts +1 -1
  57. package/src/request/http/server.ts +37 -9
  58. package/src/test/plugin.ts +1 -0
@@ -36,6 +36,8 @@ export const alerts = define('pipework_alerts', {
36
36
  issueUrl: field.text().nullable(),
37
37
  traceIds: field.custom(schema.col.text('trace_ids').array(), schema.check.array(schema.check.string())).default('{}'),
38
38
  resendAfterMs: field.integer().nullable(),
39
+ resendOnNewRelease: field.boolean().nullable(),
40
+ lastSentRelease: field.text().nullable(),
39
41
  resolveAfterQuietMs: field.integer().nullable(),
40
42
  updatedAt: field.timestamp().default('now'),
41
43
  }, {
@@ -44,6 +46,12 @@ export const alerts = define('pipework_alerts', {
44
46
  }),
45
47
  })
46
48
 
49
+ // One row per release a process running alerts has recorded, with when it was first seen; `resendOnNewRelease` compares these.
50
+ export const alertReleases = define('pipework_alert_releases', {
51
+ release: field.text().primaryKey(),
52
+ firstSeenAt: field.timestamp().default('now'),
53
+ })
54
+
47
55
  // One row per raise, kept for `occurrenceRetentionMs`.
48
56
  export const alertOccurrences = define('pipework_alert_occurrences', {
49
57
  id: field.uuid().defaultRandom().primaryKey(),
@@ -48,14 +48,14 @@ export async function executeInTransaction<T>(
48
48
 
49
49
  await propagateLocals(tx, ctx, tenant)
50
50
 
51
- const disarm = await armCancellation(conn, tx, signal)
51
+ const cancellation = await armCancellation(conn, tx, signal)
52
52
  try {
53
53
  const result = await runInContext(childCtx, run)
54
54
  // Idle at the abort, nothing failed: throwing here rolls back instead of committing.
55
55
  signal?.throwIfAborted()
56
56
  return result
57
57
  } finally {
58
- disarm()
58
+ await cancellation.settle()
59
59
  }
60
60
  })
61
61
  }
@@ -90,10 +90,15 @@ export async function executeInTransaction<T>(
90
90
  conn.drizzle.transaction(async (tx) => {
91
91
  childCtx.transactions.set(dbName, bindTransaction(ctx, dbName, tx, signal))
92
92
  await propagateLocals(tx, ctx, tenant)
93
- disarms.push(await armCancellation(conn, tx, signal))
93
+ const cancellation = await armCancellation(conn, tx, signal)
94
+ disarms.push(cancellation.disarm)
94
95
  readyDatabases.add(dbName)
95
96
  signalReady()
96
- await donePromise
97
+ try {
98
+ await donePromise
99
+ } finally {
100
+ await cancellation.settle()
101
+ }
97
102
  }),
98
103
  )
99
104
  }
@@ -142,34 +147,38 @@ export async function executeInTransaction<T>(
142
147
  * Arms server-side cancellation for one transaction: on abort, a separate
143
148
  * pooled connection issues `pg_cancel_backend` against the backend this
144
149
  * transaction holds, so an in-flight query fails with `query_canceled` and the
145
- * transaction unwinds. Returns a disarm function — always call it, or the
146
- * listener outlives the transaction and cancels a backend the pool has since
147
- * handed to someone else.
150
+ * transaction unwinds. Always call `settle()` before the transaction ends: it
151
+ * removes the listener and waits for a cancel already sent to be delivered, so
152
+ * none reaches a backend the pool has since handed to someone else. `disarm()`
153
+ * only removes the listener.
148
154
  */
149
155
  async function armCancellation(
150
156
  conn: ManagedConnection,
151
157
  tx: DB,
152
158
  signal: AbortSignal | undefined,
153
- ): Promise<() => void> {
154
- if (signal === undefined) return () => {}
159
+ ): Promise<{ disarm: () => void; settle: () => Promise<void> }> {
160
+ const none = { disarm: () => {}, settle: async () => {} }
161
+ if (signal === undefined) return none
155
162
 
156
163
  const [row] = await tx.execute(sql`SELECT pg_backend_pid() AS pid`)
157
164
  const pid = Number((row as { pid?: unknown } | undefined)?.pid)
158
- if (!Number.isInteger(pid)) return () => {}
165
+ if (!Number.isInteger(pid)) return none
159
166
 
167
+ let pending: Promise<void> | undefined
160
168
  const cancel = (): void => {
161
169
  // Best effort: the backend may already have finished, and a failed cancel
162
170
  // must not replace the abort the caller is about to see.
163
- void conn.drizzle.execute(sql`SELECT pg_cancel_backend(${pid})`).catch(() => {})
171
+ pending = (conn.cancelBackend?.(pid) ?? conn.drizzle.execute(sql`SELECT pg_cancel_backend(${pid})`)).then(() => {}, () => {})
164
172
  }
165
-
166
- if (signal.aborted) {
167
- cancel()
168
- return () => {}
173
+ const disarm = (): void => { signal.removeEventListener('abort', cancel) }
174
+ const settle = async (): Promise<void> => {
175
+ disarm()
176
+ await pending
169
177
  }
170
178
 
171
- signal.addEventListener('abort', cancel, { once: true })
172
- return () => { signal.removeEventListener('abort', cancel) }
179
+ if (signal.aborted) cancel()
180
+ else signal.addEventListener('abort', cancel, { once: true })
181
+ return { disarm, settle }
173
182
  }
174
183
 
175
184
  /**
@@ -13,3 +13,22 @@ export class RequestAbortedError extends PipeworkError {
13
13
  super(`[pipework] The client closed the connection before the response was sent (${method} ${route}).`, { method, route })
14
14
  }
15
15
  }
16
+
17
+ /**
18
+ * Whether `error` is something the abort itself caused: anywhere in its `cause`
19
+ * chain, the signal's reason, a `RequestAbortedError`, an `AbortError`, or a
20
+ * Postgres `query_canceled` (57014) / `in_failed_sql_transaction` (25P02).
21
+ * Any other error after an abort is a real failure.
22
+ */
23
+ export function isAbortCaused(error: unknown, signal: AbortSignal): boolean {
24
+ const seen = new Set<unknown>()
25
+ let current: unknown = error
26
+ while (current !== null && current !== undefined && !seen.has(current)) {
27
+ seen.add(current)
28
+ if (current === signal.reason || current instanceof RequestAbortedError) return true
29
+ const { name, code, cause } = current as { name?: unknown; code?: unknown; cause?: unknown }
30
+ if (name === 'AbortError' || code === '57014' || code === '25P02') return true
31
+ current = cause
32
+ }
33
+ return false
34
+ }
@@ -3,5 +3,5 @@ import { detectMediaType, resolveMediaType, SNIFF_BYTES } from './sniff.js'
3
3
 
4
4
  /** HTTP namespace: `http.file()` builds a file response; `http.detectMediaType()` names bytes the way uploads do; the server itself is managed by manifold.start().
5
5
  *
6
- * A client that disconnects before its response is finished aborts the request: the in-flight statement is cancelled, the transaction rolled back and the connection released. The context's `signal` (`flow.require().signal`) aborts with a `RequestAbortedError` (499, `REQUEST_ABORTED`); pass it to the handler's own outbound calls (`fetch(url, { signal })`, a `quota.call` send). The aborted request is not an internal error: `onInternalError` is not called and nothing is sent. A route opts out with `.route(method, path, { cancelOnDisconnect: false })`, e.g. a webhook receiver whose sender abandons slow deliveries and does not redeliver: its signal never aborts and the transaction commits after the socket closes. */
6
+ * A client that disconnects before its response is finished aborts the request: the in-flight statement is cancelled, the transaction rolled back and the connection released. The context's `signal` (`flow.require().signal`) aborts with a `RequestAbortedError` (499, `REQUEST_ABORTED`); pass it to the handler's own outbound calls (`fetch(url, { signal })`, a `quota.call` send). Nothing is sent, whether the handler then throws or completes (an injected call rejects with `AbortError`). What the abort caused (its reason, a cancelled statement) is not an internal error and `onInternalError` is not called; any other error thrown after the abort still reaches it. A route opts out with `.route(method, path, { cancelOnDisconnect: false })`, e.g. a webhook receiver whose sender abandons slow deliveries and does not redeliver: its signal never aborts and the transaction commits after the socket closes. */
7
7
  export const http = { file, detectMediaType, resolveMediaType, SNIFF_BYTES } as const
@@ -13,7 +13,7 @@ import { createRequestContext } from '../context/index.js'
13
13
  import { executeInTransaction } from '../context/run-in-transaction.js'
14
14
  import { resolveAndExecute, parseRouteInputs, resolveHandlerDatabases, buildCheckpoint, type ResolveOptions } from '../di/resolve.js'
15
15
  import { createRateLimitClasses } from './rate-limit-classes.js'
16
- import { RequestAbortedError } from './aborted.js'
16
+ import { RequestAbortedError, isAbortCaused } from './aborted.js'
17
17
  import { buildContext, type ContextOptions } from './middleware.js'
18
18
  import { closeTrace } from '../../trace/entry/close-trace.js'
19
19
  import { recordErrorStep } from './error-step.js'
@@ -39,6 +39,9 @@ import { withTenantSetting } from '../../auth/tenant/in-tenant.js'
39
39
  import type { Resource } from '../fixture/types.js'
40
40
  import { resourceToHandlers } from '../fixture/to-handlers.js'
41
41
 
42
+ /** The errors an aborted, injected request's raw response was destroyed with. */
43
+ const settledAborts = new WeakSet<object>()
44
+
42
45
  /** Fastify server wrapper with route registration, handler auto-wiring, and inject() for testing. */
43
46
  export interface PipeworkServer {
44
47
  route(method: HttpMethod, path: string, handler: Handler<Record<string, unknown>, unknown>): void
@@ -169,6 +172,8 @@ export function createServer(instance: Manifold, config: ServerConfig = {}): Pip
169
172
  }
170
173
 
171
174
  app.setErrorHandler(async (error, req, reply) => {
175
+ // The error an aborted request's raw response was destroyed with: not a fault, nothing to send.
176
+ if (typeof error === 'object' && error !== null && settledAborts.has(error)) return reply
172
177
  const status = (error as { statusCode?: unknown }).statusCode
173
178
  const open = requestFlows.get(req)
174
179
  const routeOf = (): string => (req.routeOptions as { url?: string } | undefined)?.url ?? req.url.split('?')[0]!
@@ -458,6 +463,20 @@ export function createServer(instance: Manifold, config: ServerConfig = {}): Pip
458
463
  }
459
464
  }
460
465
  }
466
+ // An aborted request is never answered: the raw response is destroyed, so an
467
+ // injected caller's promise rejects with AbortError and a real socket stays closed.
468
+ const settleAborted = (): FastifyReply => {
469
+ const injected = (req.raw as { _lightMyRequest?: unknown })._lightMyRequest !== undefined
470
+ if (reply.raw.destroyed) return reply
471
+ if (!injected) {
472
+ reply.raw.destroy()
473
+ return reply
474
+ }
475
+ const abortError = new DOMException('The request was aborted', 'AbortError')
476
+ settledAborts.add(abortError)
477
+ reply.raw.destroy(abortError)
478
+ return reply
479
+ }
461
480
  // Ends the upload stream and closes the connection if the body was left unread.
462
481
  const finishUpload = (failed: boolean): void => {
463
482
  if (settleUpload(uploaded?.stream) || (failed && upload !== null)) void reply.header('connection', 'close')
@@ -536,20 +555,29 @@ export function createServer(instance: Manifold, config: ServerConfig = {}): Pip
536
555
  result = await runInContext(ctx, () => resolveAndExecute(handler, body, req.query, req.params, httpOptions))
537
556
  }
538
557
 
558
+ if (abort.signal.aborted) {
559
+ finishUpload(true)
560
+ recordErrorStep(ctx, { method, route: path, status: 499, code: 'REQUEST_ABORTED', error: abort.signal.reason })
561
+ void closeTrace(instance, ctx.trace, 'error')
562
+ req.log.info({ route: `${method} ${path}`, requestId: String(req.id) }, 'request aborted by client')
563
+ return settleAborted()
564
+ }
539
565
  finishUpload(false)
540
566
  void closeTrace(instance, ctx.trace, 'closed')
541
567
  return await sendResult(reply, req, result, handler.meta.file ?? null, `${method} ${path}`)
542
568
  } catch (error) {
543
569
  finishUpload(true)
544
- // The client is gone, whatever the error was (a cancelled statement, the abort itself):
545
- // not a fault, nothing to send.
546
- if (abort.signal.aborted) {
570
+ // The client is gone, so nothing is sent. What the abort caused (the abort itself, a
571
+ // cancelled statement) is not a fault; any other error is classified and reported as usual.
572
+ const aborted = abort.signal.aborted
573
+ if (aborted && isAbortCaused(error, abort.signal)) {
547
574
  const reason: unknown = abort.signal.reason
548
575
  recordErrorStep(ctx, { method, route: path, status: 499, code: 'REQUEST_ABORTED', error: reason })
549
576
  if (ctx !== undefined) void closeTrace(instance, ctx.trace, 'error')
550
577
  req.log.info({ route: `${method} ${path}`, requestId: String(req.id) }, 'request aborted by client')
551
- return reply
578
+ return settleAborted()
552
579
  }
580
+ const send = (status: number, body: unknown): FastifyReply => (aborted ? settleAborted() : sendError(reply, status, body))
553
581
  // Records the error step, runs `refused` (the route's onRefused hook) while the
554
582
  // trace is still open, then closes the trace.
555
583
  const failWith = async (status: number, code: string, refused?: () => Promise<void>): Promise<void> => {
@@ -565,7 +593,7 @@ export function createServer(instance: Manifold, config: ServerConfig = {}): Pip
565
593
  await failWith(500, 'FILE_RESPONSE_INVALID')
566
594
  req.log.error({ route: `${method} ${path}`, requestId: String(req.id), err: error }, 'File response refused')
567
595
  await reportInternalError(req, error, handler)
568
- return sendError(reply, 500, { error: { code: 'FILE_RESPONSE_INVALID', message: error.message } })
596
+ return send(500, { error: { code: 'FILE_RESPONSE_INVALID', message: error.message } })
569
597
  }
570
598
 
571
599
  if (isPipeworkError(error)) {
@@ -581,7 +609,7 @@ export function createServer(instance: Manifold, config: ServerConfig = {}): Pip
581
609
  const retryAfter = response.error.retryAfterSeconds
582
610
  if (retryAfter !== undefined) void reply.header('Retry-After', String(retryAfter))
583
611
  if (error.httpStatus >= 500) await reportInternalError(req, error, handler)
584
- return sendError(reply, error.httpStatus, response)
612
+ return send(error.httpStatus, response)
585
613
  }
586
614
 
587
615
  // A malformed multipart body surfaces as a Fastify client error (4xx).
@@ -589,13 +617,13 @@ export function createServer(instance: Manifold, config: ServerConfig = {}): Pip
589
617
  if (typeof clientStatus === 'number' && clientStatus >= 400 && clientStatus < 500) {
590
618
  const response = buildClientErrorResponse(clientStatus, error)
591
619
  await failWith(clientStatus, response.error.code, () => runRefusedHook(req, handler.meta, ctx, clientStatus, response))
592
- return sendError(reply, clientStatus, response)
620
+ return send(clientStatus, response)
593
621
  }
594
622
 
595
623
  await failWith(500, 'INTERNAL_ERROR')
596
624
  req.log.error(error, 'Unhandled error in route handler')
597
625
  await reportInternalError(req, error, handler)
598
- return sendError(reply, 500, buildInternalErrorResponse(error, config.exposeErrorDetails))
626
+ return send(500, buildInternalErrorResponse(error, config.exposeErrorDetails))
599
627
  }
600
628
  }
601
629
 
@@ -73,6 +73,7 @@ export async function beginTestIsolation(instance: Manifold, task?: WatchedTask)
73
73
  ' Fix: call connectionIds() on a pool opened with instance.pool.getOrCreate() or tap(), outside test isolation.',
74
74
  ))
75
75
  },
76
+ async cancelBackend() { /* the one pinned test connection is never cancelled */ },
76
77
  async close() { /* test harness manages lifecycle */ },
77
78
  })
78
79
  }