All files / apps / api/src / lib outbound.ts

100% Statements 16/16
100% Branches 10/10
100% Functions 10/10
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                                                15x   13x               88x       12x             83x   83x 90x 1x     1x     76x 76x 1x         83x            
import { HTTP_STATUS, type Decoder } from '@chattra/shared'
import { Data, Effect, Schedule } from 'effect'
 
// The reference use of Effect in the Worker (design #25, K17): typed errors and retries
// at the I/O edge. Conventions: .claude/docs/effect.md.
 
export class OutboundNetworkError extends Data.TaggedError('OutboundNetworkError')<{
  readonly cause: unknown
}> {}
 
export class OutboundStatusError extends Data.TaggedError('OutboundStatusError')<{
  readonly status: number
}> {}
 
export class OutboundDecodeError extends Data.TaggedError('OutboundDecodeError')<{
  readonly cause: unknown
}> {}
 
export type OutboundError = OutboundNetworkError | OutboundStatusError | OutboundDecodeError
 
export interface OutboundRequest<T> {
  url: string
  init?: RequestInit
  decoder: Decoder<T>
  /** Time limit for one attempt. */
  timeoutMs?: number
  /** Extra attempts after the first. Pass 0 inside a queue consumer: the queue redelivers (design 4.15). */
  retries?: number
  baseDelayMs?: number
}
 
function isRetryable(error: OutboundError): boolean {
  if (error._tag === 'OutboundNetworkError') return true
 
  return (
    error._tag === 'OutboundStatusError' &&
    (error.status === HTTP_STATUS.tooManyRequests ||
      error.status >= HTTP_STATUS.internalServerError)
  )
}
 
function refuseStatus(res: Response): Effect.Effect<Response, OutboundStatusError> {
  if (res.ok) return Effect.succeed(res)
 
  // Cloudflare: cancelling a body nobody reads "is still good practice to free memory"
  // (developers.cloudflare.com/workers/platform/limits).
  return Effect.promise(async () => res.body?.cancel()).pipe(
    Effect.andThen(Effect.fail(new OutboundStatusError({ status: res.status }))),
  )
}
 
// One JSON call to another service. Retries only what a retry can fix: no answer, 429 or 5xx.
export function fetchJson<T>(request: OutboundRequest<T>): Effect.Effect<T, OutboundError> {
  const { url, init, decoder, timeoutMs = 10_000, retries = 3, baseDelayMs = 200 } = request
 
  const attempt = Effect.tryPromise({
    try: (signal) => fetch(url, { ...init, signal }),
    catch: (cause) => new OutboundNetworkError({ cause }),
  }).pipe(
    Effect.timeout(timeoutMs),
    Effect.catchTag('TimeoutError', (cause) => Effect.fail(new OutboundNetworkError({ cause }))),
    Effect.flatMap(refuseStatus),
    Effect.flatMap((res) =>
      Effect.tryPromise({
        try: async () => decoder.parse(await res.json()),
        catch: (cause) => new OutboundDecodeError({ cause }),
      }),
    ),
  )
 
  return Effect.retry(attempt, {
    while: isRetryable,
    times: retries,
    schedule: Schedule.jittered(Schedule.exponential(baseDelayMs)),
  })
}