projects/sdk/src/internal/rest/classify.ts

/**
 * REST failure classification: The internal RestFailure, response rejection and rate-limit classification, bounded
 * provider error-body reads and the conversion into public operation errors.
 * Invariant: Mutations retry only after a confirmed rate-limit rejection, a rejected response marks the outcome rejected
 * only for real operation requests, and provider error bodies keep only sanitized codes, messages and field paths.
 * Implements [SDK contracts: Results and failures](/docs/SDK-CONTRACTS.md#results-and-failures)
 */
import { ClientClosedError, ConnectionError, RateLimitError, type OperationErrorOptions } from "#sdk/errors"
import type { MessageOperationError } from "#sdk/message-errors"
import { apiErrorDetail, unrecognizedProviderCode, type ApiErrorDetail } from "#sdk/api-errors"
import {
    inputValidationFailure,
    type InputValidationConstraint,
    type InputValidationDetail,
} from "#sdk/input-validation"
import { record } from "../decode/primitives.js"
import { failures, TransportError } from "../effect-failures.js"
import { linkRejectionError } from "../rejection-scope.js"
import { readBoundedJson, type ReaderState } from "../response-json.js"

/** Whether an operation's request may have reached Fluxer */
export type Outcome = MessageOperationError["outcome"]

/** Fields of one internal REST failure. Omitted values are null or false */
export interface RestFailureOptions {
    readonly reason: MessageOperationError["reason"]
    readonly outcome: Outcome
    readonly status?: number | null
    readonly retryAfterMs?: number | null
    /** Whether a GET may be repeated after this failure under the bounded read-retry policy */
    readonly retryableRead?: boolean
    readonly apiError?: ApiErrorDetail | null
    readonly inputValidation?: InputValidationDetail | null
    /** Unrecognized Fluxer error code with a safe shape, when apiError is null */
    readonly providerCode?: string | null
    /** For reason response, the response field path or named check that failed */
    readonly responseField?: string | null
    /** Whether a rate-limited upload read an attachment from a caller's stream, so the same call cannot be repeated */
    readonly streamUsed?: boolean
    /** Whether this is Fluxer's busy upload slots answer, which applied nothing (see uploadSlotsBusy below) */
    readonly uploadSlotsBusy?: boolean
    /** Underlying transport failure, kept as the public error's cause */
    readonly cause?: unknown
}

/** One REST operation failure before it becomes a domain-specific public error */
export class RestFailure extends Error {
    readonly reason: MessageOperationError["reason"]
    readonly outcome: Outcome
    readonly status: number | null
    readonly retryAfterMs: number | null
    readonly retryableRead: boolean
    readonly apiError: ApiErrorDetail | null
    readonly inputValidation: InputValidationDetail | null
    readonly providerCode: string | null
    readonly responseField: string | null
    /** Whether a rate-limited operation read a caller's stream, set where the failure is made or once the operation ends */
    streamUsed: boolean
    /** Whether this is Fluxer's busy upload slots answer, which applied nothing */
    readonly uploadSlotsBusy: boolean
    override readonly cause?: unknown
    /** Whether the failed request was a GET, set once where the request method is known */
    read = false

    constructor(options: RestFailureOptions) {
        super("REST operation failed")
        this.reason = options.reason
        this.outcome = options.outcome
        this.status = options.status ?? null
        this.retryAfterMs = options.retryAfterMs ?? null
        this.retryableRead = options.retryableRead ?? false
        this.apiError = options.apiError ?? null
        this.inputValidation = options.inputValidation ?? null
        this.providerCode = options.providerCode ?? null
        this.responseField = options.responseField ?? null
        this.streamUsed = options.streamUsed ?? false
        this.uploadSlotsBusy = options.uploadSlotsBusy ?? false
        this.cause = options.cause
    }

    /** The same failure recorded under the operation's current outcome */
    withOutcome(outcome: Outcome): RestFailure {
        return linkRejectionError(
            new RestFailure({
                reason: this.reason,
                outcome,
                status: this.status,
                retryAfterMs: this.retryAfterMs,
                retryableRead: this.retryableRead,
                apiError: this.apiError,
                inputValidation: this.inputValidation,
                providerCode: this.providerCode,
                responseField: this.responseField,
                streamUsed: this.streamUsed,
                uploadSlotsBusy: this.uploadSlotsBusy,
                cause: this.cause,
            }),
            this,
        )
    }
}

/** The failures of REST work, matched by mapFailureCause so a RestFailure never reaches callers */
export const restFailures = failures(RestFailure, ClientClosedError)

/** The failures of instance discovery inside a REST admission slot */
export const discoveryFailures = failures(RestFailure, ClientClosedError, ConnectionError, RateLimitError)

/** A local validation failure before any request was sent */
export function inputFailure(detail: InputValidationDetail): RestFailure {
    return new RestFailure({ reason: "input", outcome: "notDispatched", inputValidation: detail })
}

export function localInputFailure(
    path: string,
    constraint: InputValidationConstraint,
    explanation: string,
): RestFailure {
    return inputFailure(inputValidationFailure(path, constraint, explanation).detail)
}

// Keep the named REST metadata at one constructor boundary, while domain tags and operation types stay distinct
export function operationFailure<Operation extends string, Failure>(
    error: RestFailure | ClientClosedError,
    ErrorType: new (options: OperationErrorOptions<Operation>) => Failure,
    operation: NoInfer<Operation>,
): Failure | ClientClosedError {
    if (!(error instanceof RestFailure)) return error
    return linkRejectionError(
        new ErrorType({
            operation,
            reason: error.reason,
            outcome: error.outcome,
            status: error.status,
            retryAfterMs: error.retryAfterMs,
            apiError: error.apiError,
            inputValidation: error.inputValidation,
            providerCode: error.providerCode,
            responseField: error.responseField,
            ...(error.read ? { read: true } : {}),
            ...(error.streamUsed ? { streamUsed: true } : {}),
            ...(error.uploadSlotsBusy ? { uploadSlotsBusy: true } : {}),
            ...(error.cause === undefined ? {} : { cause: error.cause }),
        }),
        error,
    )
}

/** Translate an instance-discovery failure into the operation's not-dispatched failure */
export function instanceFailure(error: unknown): RestFailure | ClientClosedError {
    if (error instanceof ClientClosedError) return error
    if (error instanceof RestFailure) return error
    if (error instanceof RateLimitError)
        return new RestFailure({ reason: "rateLimit", outcome: "notDispatched", retryAfterMs: error.retryAfterMs })
    if (error instanceof ConnectionError)
        return new RestFailure({
            reason: "network",
            outcome: "notDispatched",
            status: error.status,
            cause: new TransportError(error),
        })
    return new RestFailure({ reason: "network", outcome: "notDispatched", cause: new TransportError(error) })
}

const retryAfterSecondsPattern = /^\d+(?:\.\d+)?$/
const imfFixdatePattern =
    /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} (?:GMT|UTC)$/
const rfc850DatePattern =
    /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), \d{2}-(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2} \d{2}:\d{2}:\d{2} (?:GMT|UTC)$/
const asctimeDatePattern =
    /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (?: \d|\d{2}) \d{2}:\d{2}:\d{2} \d{4}$/

/**
 * Parse a Retry-After header as non-negative numeric seconds or an HTTP-date measured against now, returning whole
 * milliseconds rounded up, or null when missing, empty or malformed
 */
export function parseRetryAfterHeader(header: string | null, now = Date.now()): number | null {
    const value = header?.trim()
    if (!value) return null
    if (retryAfterSecondsPattern.test(value)) {
        const delay = Number(value) * 1_000
        return Number.isFinite(delay) ? Math.ceil(delay) : null
    }
    if (imfFixdatePattern.test(value) || rfc850DatePattern.test(value)) {
        const timestamp = Date.parse(value)
        return Number.isFinite(timestamp) ? Math.max(0, Math.ceil(timestamp - now)) : null
    }
    if (asctimeDatePattern.test(value)) {
        const timestamp = Date.parse(`${value} GMT`)
        return Number.isFinite(timestamp) ? Math.max(0, Math.ceil(timestamp - now)) : null
    }
    return null
}

function globalRateLimit(response: Response): boolean {
    // A positive scope assertion wins over conflicting local metadata. Do not
    // interpret malformed or combined header values as a global rejection
    return (
        response.headers.get("x-ratelimit-global")?.trim().toLowerCase() === "true" ||
        response.headers.get("x-ratelimit-scope")?.trim().toLowerCase() === "global"
    )
}

/**
 * What one HTTP 429 said about the limiter that answered it, for the ratelimit.wait and ratelimit.deadline records and
 * the rate-limit observation. Each member is present only when the response sent it in the expected form
 */
export interface RateLimitDetails {
    /** X-RateLimit-Scope header */
    readonly scope?: string
    /** X-RateLimit-Bucket header */
    readonly bucket?: string
    /** X-RateLimit-Limit header */
    readonly limit?: number
    /** X-RateLimit-Remaining header */
    readonly remaining?: number
    /** X-RateLimit-Reset-After header, in seconds */
    readonly resetAfterSeconds?: number
    /** Retry-After header in its delay-seconds form, not as an HTTP date */
    readonly retryAfterHeaderSeconds?: number
    /** The body's retry_after member, in seconds */
    readonly retryAfterSeconds?: number
    /** The body's global member */
    readonly bodyGlobal?: boolean
}

/** A short header token, such as a scope name or bucket hash, or undefined for anything else */
function headerToken(response: Response, name: string): string | undefined {
    const value = response.headers.get(name)?.trim()
    return value !== undefined && /^[\w.:-]{1,64}$/.test(value) ? value : undefined
}

/** A count of at most 15 digits, or seconds of at most 32 digits and one decimal point, otherwise undefined */
function headerNumber(response: Response, name: string, integer = false): number | undefined {
    const value = response.headers.get(name)?.trim()
    return value !== undefined && (integer ? /^\d{1,15}$/ : /^(?=.{1,32}$)\d+(?:\.\d+)?$/).test(value)
        ? Number(value)
        : undefined
}

function rateLimitHeaders(response: Response): RateLimitDetails {
    const details = {
        scope: headerToken(response, "x-ratelimit-scope"),
        bucket: headerToken(response, "x-ratelimit-bucket"),
        limit: headerNumber(response, "x-ratelimit-limit", true),
        remaining: headerNumber(response, "x-ratelimit-remaining", true),
        resetAfterSeconds: headerNumber(response, "x-ratelimit-reset-after"),
        retryAfterHeaderSeconds: headerNumber(response, "retry-after"),
    }
    return Object.fromEntries(Object.entries(details).filter(([, value]) => value !== undefined)) as RateLimitDetails
}

/** Largest provider error body read for its reviewed detail */
const errorBodyMaxBytes = 8_192
/** Time allowed for reading an error body before it is cancelled */
const errorBodyReadTimeoutMs = 100

type ApiErrorRead = {
    readonly detail: ApiErrorDetail | null
    /** Unrecognized Fluxer error code with a safe shape */
    readonly providerCode: string | null
    readonly retryAfterMs: number | null
    readonly global: boolean
    /** The body is a JSON object with a boolean global member, as Fluxer's own rate-limit rejections send */
    readonly fluxerLimit: boolean
    /** The retry_after and global members exactly as the body sent them, for rate-limit records */
    readonly sent: Pick<RateLimitDetails, "retryAfterSeconds" | "bodyGlobal">
    readonly cleanupDefect: unknown
}

class ApiErrorBodyCleanupError extends Error {
    constructor(cause?: unknown) {
        super("Failed to release an API error response body", cause === undefined ? undefined : { cause })
        this.name = "ApiErrorBodyCleanupError"
    }
}

async function readApiError(
    response: Response,
    signal: AbortSignal,
    source: "fluxer" | "upload" = "fluxer",
    requireJsonContentType = true,
): Promise<ApiErrorRead> {
    const body = response.body
    if (
        !body ||
        (requireJsonContentType && !/^application\/json(?:;|$)/i.test(response.headers.get("content-type") ?? ""))
    )
        return {
            detail: null,
            providerCode: null,
            retryAfterMs: null,
            global: false,
            fluxerLimit: false,
            sent: {},
            cleanupDefect: null,
        }
    const declared = response.headers.get("content-length")
    if (declared !== null && (!/^\d+$/.test(declared) || Number(declared) > errorBodyMaxBytes))
        return {
            detail: null,
            providerCode: null,
            retryAfterMs: null,
            global: false,
            fluxerLimit: false,
            sent: {},
            cleanupDefect: null,
        }
    const state: ReaderState = { reader: undefined, done: false }
    let result: ApiErrorDetail | null = null
    let providerCode: string | null = null
    let retryAfterMs: number | null = null
    let global = false
    let fluxerLimit = false
    let sent: ApiErrorRead["sent"] = {}
    let cleanupDefect: unknown = null
    const recordCleanupDefect = (cause: unknown) => {
        const defect = new ApiErrorBodyCleanupError(cause)
        cleanupDefect =
            cleanupDefect === null
                ? defect
                : new AggregateError([cleanupDefect, defect], "API error response cleanup failed")
    }
    try {
        const read = await readBoundedJson(response, {
            maxBytes: errorBodyMaxBytes,
            signal,
            timeoutMs: errorBodyReadTimeoutMs,
            fatal: false,
            state,
        })
        if (read.kind === "ok") {
            const data = read.value
            // Signed upload destinations can be external storage, not a Fluxer API error source
            result = source === "fluxer" ? apiErrorDetail(data) : null
            providerCode = source === "fluxer" ? unrecognizedProviderCode(data) : null
            if (record(data)) {
                if (typeof data.retry_after === "number" && data.retry_after >= 0) {
                    const milliseconds = data.retry_after * 1000
                    if (Number.isFinite(milliseconds)) retryAfterMs = milliseconds
                    if (Number.isFinite(data.retry_after)) sent = { retryAfterSeconds: data.retry_after }
                }
                global = data.global === true
                fluxerLimit = typeof data.global === "boolean"
                if (fluxerLimit) sent = { ...sent, bodyGlobal: data.global as boolean }
            }
        }
    } catch {
        // allow-silent: An unreadable error body only removes the optional reviewed detail from the returned failure
        result = null
        providerCode = null
    } finally {
        if (state.reader) {
            try {
                state.reader.releaseLock()
            } catch (error) {
                recordCleanupDefect(error)
            }
        }
    }
    if (!state.done) {
        try {
            await body.cancel()
        } catch (error) {
            // Re-cancelling a fetch body after its own request abort can reject with that exact reason
            if (!(signal.aborted && error === signal.reason)) recordCleanupDefect(error)
        }
    }
    return { detail: result, providerCode, retryAfterMs, global, fluxerLimit, sent, cleanupDefect }
}

/** What classification needs from the attempt that received the response */
export interface ClassifyContext {
    readonly method: string
    /** The request retries HTTP 500, 502, 503 and 504 answers, as a GET or a repeatable read POST does */
    readonly retriesAsRead: boolean
    /** A signed upload PUT, whose destination is external storage rather than the Fluxer API */
    readonly upload: boolean
    /** A multipart request to the Fluxer API that carries files */
    readonly multipart: boolean
    /** A preparation step, such as upload planning, that cannot change the operation's outcome */
    readonly preparation: boolean
    /** The request accepts Fluxer's temporarily-disabled-feature rejection as a successful fallback */
    readonly hasFeatureFallback: boolean
    /** The operation's shared outcome, updated when Fluxer confirms a rejection */
    readonly progress: { outcome: Outcome }
    readonly signal: AbortSignal
    /** Cleanup failures collected for the attempt's release step */
    readonly cleanupDefects: unknown[]
    readonly now: () => number
    /** Pause every route until the given logical time, for a global limit Fluxer declared */
    readonly pauseGlobal: (until: number) => void
    /**
     * Pause every route of this client from the given logical time on, for a limit that did not identify itself, and
     * return the time the pause ends, which repeated unidentified limits make later
     */
    readonly pauseClient: (until: number) => number
    /** Tell admission that a response other than an unidentified 429 arrived, which ends a probe of such a limit */
    readonly responded: () => void
    /** Pause the learned bucket until the given logical time */
    readonly pauseBucket: (until: number) => void
    /** Tell guarded caches that a GET found no resource */
    readonly notFound: () => void
}

/**
 * What a 429 pauses. A global limit Fluxer declared, and a 429 that names no limiter, such as one from a proxy in front
 * of the API, pause every API request of the client. A limit Fluxer identifies as a route limit pauses its bucket
 */
export type RateLimitPause = "client" | "bucket"

/**
 * Whether a 429 identifies itself as one of Fluxer's route limits: It sends an X-RateLimit-Bucket or a non-global
 * X-RateLimit-Scope header, or a JSON body with a boolean global member
 */
function identifiedRouteLimit(response: Response, apiRead: ApiErrorRead): boolean {
    return (
        headerToken(response, "x-ratelimit-bucket") !== undefined ||
        headerToken(response, "x-ratelimit-scope") !== undefined ||
        apiRead.fluxerLimit
    )
}

/**
 * Pause what a 429 with a usable wait holds: Every route for a global limit, the client for an unidentified limit, or
 * the bucket. Returns the wait the retry observes, which repeated unidentified limits make longer than asked
 */
function applyRateLimitPause(
    asked: number,
    global: boolean,
    identified: boolean,
    context: ClassifyContext,
): { readonly retry: number; readonly pause: RateLimitPause } {
    const now = context.now()
    const until = now + asked
    if (global) {
        context.pauseGlobal(until)
        context.responded()
        return { retry: asked, pause: "client" }
    }
    if (!identified) return { retry: Math.ceil(context.pauseClient(until) - now), pause: "client" }
    context.pauseBucket(until)
    context.responded()
    return { retry: asked, pause: "bucket" }
}

/** A response the attempt continues with, or a rate-limit wait before the same request is sent again */
export type ResponseClass =
    | { readonly kind: "accepted" }
    | { readonly kind: "featureDisabled" }
    | {
          readonly kind: "retry"
          readonly retry: number
          /** Whether Fluxer declared the limit global in its headers or body */
          readonly global: boolean
          /** What the SDK paused: Every API request of this client, or only the request's rate-limit bucket */
          readonly pause: RateLimitPause
          readonly apiError: ApiErrorDetail | null
          readonly providerCode: string | undefined
          readonly details: RateLimitDetails
      }

function collect(context: ClassifyContext, read: ApiErrorRead) {
    if (read.cleanupDefect !== null && !context.cleanupDefects.includes(read.cleanupDefect))
        context.cleanupDefects.push(read.cleanupDefect)
}

/** The longer of the waits a rejection asks for in its headers and in its body */
function rejectionRetryAfter(response: Response, apiRead: ApiErrorRead): number | null {
    const headerRetryAfterMs = parseRetryAfterHeader(response.headers.get("retry-after"))
    return headerRetryAfterMs === null
        ? apiRead.retryAfterMs
        : apiRead.retryAfterMs === null
          ? headerRetryAfterMs
          : Math.max(headerRetryAfterMs, apiRead.retryAfterMs)
}

/**
 * Fluxer's answer when every multipart upload slot of an API process stayed busy for 10 seconds: HTTP 503 with
 * SERVICE_UNAVAILABLE and Retry-After 5. It comes while Fluxer reads the request's files, before any message, edit or
 * thread is applied, and Fluxer then deletes the files it already stored, so the request changed nothing
 * (channel/services/FormUploadSlots.ts:7-22, channel/services/AttachmentUploadService.ts:141-162 and
 * channel/services/message/MessageRequestParser.ts:47-83 in fluxer_api/src/api at 0098958f). Fluxer's other 503
 * answers send Retry-After 1 or none and come from database and gateway calls at any step, so they keep an unknown
 * outcome
 */
function uploadSlotsBusy(response: Response, apiRead: ApiErrorRead, context: ClassifyContext): boolean {
    return (
        context.multipart &&
        !context.preparation &&
        response.status === 503 &&
        apiRead.detail?.providerCode === "SERVICE_UNAVAILABLE" &&
        response.headers.get("retry-after")?.trim() === "5"
    )
}

/** Classify a received response. Rejections throw a RestFailure with the outcome Fluxer established */
export async function classifyResponse(response: Response, context: ClassifyContext): Promise<ResponseClass> {
    const { progress } = context
    if (response.status === 429) {
        if (context.upload) {
            const apiRead = await readApiError(response, context.signal, "upload", false)
            collect(context, apiRead)
            // Storage, or a proxy in front of it, may answer with only the header. A signed PUT is never replayed here
            throw new RestFailure({
                reason: "rateLimit",
                outcome: progress.outcome,
                status: 429,
                retryAfterMs: rejectionRetryAfter(response, apiRead),
                apiError: apiRead.detail,
            })
        }
        let delay = parseRetryAfterHeader(response.headers.get("retry-after"))
        const headerGlobal = globalRateLimit(response)
        // Protect other routes before bounded body inspection, including
        // when the request is interrupted while waiting for that body
        if (headerGlobal && delay !== null && delay > 0) context.pauseGlobal(context.now() + delay)
        const apiRead = await readApiError(response, context.signal, "fluxer", false)
        collect(context, apiRead)
        // A body never shortens the header's wait. Fluxer rounds its header up from the body, and a proxy in front of
        // the API may hold requests for longer than a body it passes on
        if (apiRead.retryAfterMs !== null)
            delay = delay !== null ? Math.max(delay, apiRead.retryAfterMs) : apiRead.retryAfterMs
        // Mutation resends require a received rate-limit rejection
        if (!context.preparation) progress.outcome = "rejected"
        if (delay === null || delay <= 0)
            throw new RestFailure({
                reason: "rateLimit",
                outcome: progress.outcome,
                status: 429,
                apiError: apiRead.detail,
                providerCode: apiRead.providerCode,
            })
        const global = headerGlobal || apiRead.global
        const { retry, pause } = applyRateLimitPause(
            Math.ceil(delay),
            global,
            identifiedRouteLimit(response, apiRead),
            context,
        )
        return {
            kind: "retry",
            retry,
            global,
            pause,
            apiError: apiRead.detail,
            providerCode: apiRead.providerCode ?? undefined,
            details: { ...rateLimitHeaders(response), ...apiRead.sent },
        }
    }
    context.responded()
    if (response.ok) return { kind: "accepted" }
    let apiRead: ApiErrorRead | undefined
    if (response.status === 403 && context.hasFeatureFallback) {
        apiRead = await readApiError(response, context.signal)
        collect(context, apiRead)
        if (apiRead.detail?.providerCode === "FEATURE_TEMPORARILY_DISABLED") return { kind: "featureDisabled" }
    }
    if (response.status === 404 && context.method === "GET") context.notFound()
    const rejected = response.status >= 400 && response.status < 500
    if (rejected && !context.preparation) progress.outcome = "rejected"
    const retryableRead = context.retriesAsRead && [500, 502, 503, 504].includes(response.status)
    apiRead ??= await readApiError(response, context.signal, context.upload ? "upload" : "fluxer")
    collect(context, apiRead)
    const slotsBusy = uploadSlotsBusy(response, apiRead, context)
    if (slotsBusy) progress.outcome = "rejected"
    const retryAfterMs = rejectionRetryAfter(response, apiRead)
    throw new RestFailure({
        ...(slotsBusy ? { uploadSlotsBusy: true } : {}),
        reason: response.status === 404 && !context.preparation ? "notFound" : "rejected",
        outcome: progress.outcome,
        status: response.status,
        retryAfterMs,
        retryableRead,
        apiError: apiRead.detail,
        providerCode: apiRead.providerCode,
    })
}