@restatedev/restate-sdk-clients 1.16.6 → 1.16.8

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.
@@ -1 +1 @@
1
- {"version":3,"file":"ingress.js","names":["status: number","responseText: string","message: string","parameter: unknown","opts: Opts<unknown, unknown> | SendOpts<unknown> | undefined","response: Response","errorBody: string","url: string","opts: ConnectionOpts","res: Send","opts","body","serde"],"sources":["../src/ingress.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport {\n type Service,\n type ServiceDefinitionFrom,\n type VirtualObject,\n type WorkflowDefinitionFrom,\n type Workflow,\n type VirtualObjectDefinitionFrom,\n type Serde,\n serde,\n type JournalValueCodec,\n} from \"@restatedev/restate-sdk-core\";\nimport {\n ConnectionOpts,\n Ingress,\n IngressClient,\n IngressSendClient,\n IngressWorkflowClient,\n Output,\n Send,\n ScopedIngress,\n WorkflowSubmission,\n} from \"./api.js\";\n\nimport { Opts, SendOpts } from \"./api.js\";\nimport {\n abortableSleep,\n backoffDelay,\n defaultShouldRetry,\n parseRetryAfter,\n type ResolvedRetryPolicy,\n resolveRetryPolicy,\n} from \"./retry.js\";\n\n/**\n * Connect to the restate Ingress\n *\n * @param opts connection options\n * @returns a connection the the restate ingress\n */\nexport function connect(opts: ConnectionOpts): Ingress {\n return new HttpIngress(opts);\n}\n\nexport class HttpCallError extends Error {\n constructor(\n public readonly status: number,\n public readonly responseText: string,\n public override readonly message: string\n ) {\n super(message);\n }\n}\n\ntype InvocationParameters<I> = {\n component: string;\n handler: string;\n key?: string;\n send?: boolean;\n opts?: Opts<I, unknown> | SendOpts<I>;\n parameter?: I;\n method?: string;\n scope?: string;\n};\n\nfunction optsFromArgs(args: unknown[]): {\n parameter?: unknown;\n opts?: Opts<unknown, unknown> | SendOpts<unknown>;\n} {\n let parameter: unknown;\n let opts: Opts<unknown, unknown> | SendOpts<unknown> | undefined;\n switch (args.length) {\n case 0: {\n break;\n }\n case 1: {\n if (args[0] instanceof Opts) {\n opts = args[0];\n } else if (args[0] instanceof SendOpts) {\n opts = args[0];\n } else {\n parameter = args[0];\n }\n break;\n }\n case 2: {\n parameter = args[0];\n if (args[1] instanceof Opts) {\n opts = args[1];\n } else if (args[1] instanceof SendOpts) {\n opts = args[1];\n } else {\n throw new TypeError(\n \"The second argument must be either Opts or SendOpts\"\n );\n }\n break;\n }\n default: {\n throw new TypeError(\"unexpected number of arguments\");\n }\n }\n return {\n parameter,\n opts,\n };\n}\n\nconst IDEMPOTENCY_KEY_HEADER = \"idempotency-key\";\nconst LIMIT_KEY_HEADER = \"x-restate-limit-key\";\n\nconst getFetch = (opts: ConnectionOpts): NonNullable<ConnectionOpts[\"fetch\"]> =>\n opts.fetch ?? globalThis.fetch;\n\nconst fetchWithRetries = async (\n opts: ConnectionOpts,\n url: string,\n init: RequestInit,\n callOpts: Opts<unknown, unknown> | SendOpts<unknown> | undefined,\n retryPolicy: ResolvedRetryPolicy | undefined\n): Promise<Uint8Array> => {\n const userSignal = callOpts?.opts.signal;\n const timeout = callOpts?.opts.timeout;\n if (userSignal !== undefined && timeout !== undefined) {\n // The caller configured two mutually exclusive ways to abort each attempt.\n throw new Error(\n \"You can't specify both signal and timeout options at the same time\"\n );\n }\n // A fresh timeout signal is minted per attempt below — a single\n // AbortSignal.timeout() would already be aborted on the second attempt.\n const attemptSignal = (): AbortSignal | undefined =>\n userSignal ??\n (timeout !== undefined ? AbortSignal.timeout(timeout) : undefined);\n const shouldRetry = retryPolicy?.shouldRetry ?? defaultShouldRetry;\n\n for (let attempt = 0; ; attempt++) {\n let response: Response;\n let errorBody: string;\n try {\n response = await getFetch(opts)(url, {\n ...init,\n signal: attemptSignal(),\n });\n if (response.ok) {\n // A 2xx response was received. Keep the body read inside this try so a\n // connection failure while streaming the body is retried as ambiguous.\n return new Uint8Array(await response.arrayBuffer());\n }\n // fetch resolves normally for non-2xx statuses. Read the body here both\n // for RetryFailure inspection and the final HttpCallError.\n errorBody = await response.text();\n } catch (e) {\n // fetch rejected, or the response body failed while streaming. Both are\n // ambiguous because the server may already have processed the request.\n if (\n retryPolicy &&\n attempt < retryPolicy.maxAttempts - 1 &&\n !userSignal?.aborted &&\n shouldRetry({ kind: \"network\", error: e }, attempt)\n ) {\n // Retries are enabled, attempts remain, the caller did not abort, and\n // the policy accepted this network failure.\n await abortableSleep(backoffDelay(retryPolicy, attempt), userSignal);\n continue;\n }\n // Retries are disabled or exhausted, the caller aborted, or the policy\n // rejected this failure.\n throw e;\n }\n if (\n retryPolicy &&\n attempt < retryPolicy.maxAttempts - 1 &&\n !userSignal?.aborted &&\n shouldRetry(\n {\n kind: \"response\",\n status: response.status,\n headers: response.headers,\n body: errorBody || undefined,\n },\n attempt\n )\n ) {\n // A non-2xx response was received, attempts remain, and the policy chose\n // to retry it (by default, HTTP 429 and 5xx).\n const retryAfter = parseRetryAfter(response.headers);\n await abortableSleep(\n backoffDelay(retryPolicy, attempt, retryAfter),\n userSignal\n );\n continue;\n }\n // The response is not retryable, retries are disabled or exhausted, the\n // caller aborted, or the policy rejected this response.\n throw new HttpCallError(\n response.status,\n errorBody,\n `Request failed: ${response.status}\\n${errorBody}`\n );\n }\n};\n\nconst doComponentInvocation = async <I, O>(\n opts: ConnectionOpts,\n params: InvocationParameters<I>,\n canBeRetried = Boolean(params.opts?.opts.idempotencyKey)\n): Promise<O> => {\n let attachable = false;\n //\n // ingress URL\n //\n let url: string;\n if (params.scope) {\n // Scoped path: /restate/scope/{scope}/{call|send}/{service}/{key?}/{handler}\n const pathType = params.send ? \"send\" : \"call\";\n const parts = [\n opts.url,\n \"restate/scope\",\n encodeURIComponent(params.scope),\n pathType,\n params.component,\n ];\n if (params.key) {\n parts.push(encodeURIComponent(params.key));\n }\n parts.push(params.handler);\n url = parts.join(\"/\");\n if (params.send && params.opts instanceof SendOpts) {\n const delay = params.opts.delay();\n if (delay) url += `?delay=${delay}ms`;\n }\n } else {\n const fragments = [opts.url, params.component];\n if (params.key) {\n fragments.push(encodeURIComponent(params.key));\n }\n fragments.push(params.handler);\n if (params.send ?? false) {\n if (params.opts instanceof SendOpts) {\n fragments.push(computeDelayAsIso(params.opts));\n } else {\n fragments.push(\"send\");\n }\n }\n url = fragments.join(\"/\");\n }\n //\n // request body\n //\n const inputSerde = params.opts?.opts.input ?? opts.serde ?? serde.json;\n\n const { body, contentType } = serializeBodyWithContentType(\n params.parameter,\n inputSerde,\n opts.journalValueCodec\n );\n //\n // headers\n //\n const headers = {\n ...(opts.headers ?? {}),\n ...(params.opts?.opts?.headers ?? {}),\n };\n if (contentType) {\n headers[\"Content-Type\"] = contentType;\n }\n //\n // idempotency\n //\n const idempotencyKey = params.opts?.opts.idempotencyKey;\n if (idempotencyKey) {\n headers[IDEMPOTENCY_KEY_HEADER] = idempotencyKey;\n attachable = true;\n }\n //\n // limit key\n //\n const limitKey = params.opts?.opts.limitKey;\n if (limitKey) {\n headers[LIMIT_KEY_HEADER] = limitKey;\n }\n\n //\n // retries\n //\n // Regular invocations default eligibility from the idempotency key, while\n // workflow submissions opt in because the workflow ID identifies the run.\n const retryPolicy = canBeRetried ? resolveRetryPolicy(opts.retry) : undefined;\n\n //\n // make the call\n //\n const responseBuf = await fetchWithRetries(\n opts,\n url,\n {\n method: params.method ?? \"POST\",\n headers,\n body,\n },\n params.opts,\n retryPolicy\n );\n if (!params.send) {\n const decodedBuf = opts.journalValueCodec\n ? await opts.journalValueCodec.decode(responseBuf)\n : responseBuf;\n const outputSerde = params.opts?.opts.output ?? opts.serde ?? serde.json;\n return outputSerde.deserialize(decodedBuf) as O;\n }\n const json = serde.json.deserialize(responseBuf) as O;\n return { ...json, attachable };\n};\n\nconst doWorkflowHandleCall = async <O>(\n opts: ConnectionOpts,\n wfName: string,\n wfKey: string,\n op: \"output\" | \"attach\",\n callOpts?: Opts<unknown, O> | SendOpts<unknown>\n): Promise<O> => {\n const outputSerde = callOpts?.opts.output ?? opts.serde ?? serde.json;\n //\n // headers\n //\n const headers = {\n ...(opts.headers ?? {}),\n };\n //\n // make the call\n //\n const url = `${opts.url}/restate/workflow/${wfName}/${encodeURIComponent(\n wfKey\n )}/${op}`;\n // Attach and output only observe the existing workflow, so both are eligible\n // when the connection has a retry policy.\n const retryPolicy = resolveRetryPolicy(opts.retry);\n\n const responseBuf = await fetchWithRetries(\n opts,\n url,\n { method: \"GET\", headers },\n callOpts,\n retryPolicy\n );\n const decodedBuf = opts.journalValueCodec\n ? await opts.journalValueCodec.decode(responseBuf)\n : responseBuf;\n return outputSerde.deserialize(decodedBuf) as O;\n};\n\nclass HttpIngress implements Ingress {\n constructor(private readonly opts: ConnectionOpts) {}\n\n private proxy(component: string, key?: string, send?: boolean) {\n return new Proxy(\n {},\n {\n get: (_target, prop) => {\n const handler = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n return doComponentInvocation<unknown, unknown>(this.opts, {\n component,\n handler,\n key,\n parameter,\n opts,\n send,\n });\n };\n },\n }\n );\n }\n\n serviceClient<D>(opts: ServiceDefinitionFrom<D>): IngressClient<Service<D>> {\n return this.proxy(opts.name) as IngressClient<Service<D>>;\n }\n\n objectClient<D>(\n opts: VirtualObjectDefinitionFrom<D>,\n key: string\n ): IngressClient<VirtualObject<D>> {\n return this.proxy(opts.name, key) as IngressClient<VirtualObject<D>>;\n }\n\n workflowClient<D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): IngressWorkflowClient<Workflow<D>> {\n const component = opts.name;\n const conn = this.opts;\n\n const workflowSubmit = async (\n ...args: unknown[]\n ): Promise<WorkflowSubmission<unknown>> => {\n const { parameter, opts } = optsFromArgs(args);\n const res: Send = await doComponentInvocation(\n conn,\n {\n component,\n handler: \"run\",\n key,\n send: true,\n parameter,\n opts,\n },\n true\n );\n\n return {\n invocationId: res.invocationId,\n status: res.status,\n attachable: true,\n };\n };\n\n const workflowAttach = (opts?: Opts<void, unknown>) =>\n doWorkflowHandleCall(conn, component, key, \"attach\", opts);\n\n const workflowOutput = async (\n opts?: Opts<void, unknown>\n ): Promise<Output<unknown>> => {\n try {\n const result = await doWorkflowHandleCall(\n conn,\n component,\n key,\n \"output\",\n opts\n );\n\n return {\n ready: true,\n result,\n };\n } catch (e) {\n if (!(e instanceof HttpCallError) || e.status !== 470) {\n throw e;\n }\n return {\n ready: false,\n get result() {\n throw new Error(\"Calling result() on a non ready workflow\");\n },\n };\n }\n };\n\n return new Proxy(\n {},\n {\n get: (_target, prop) => {\n const handler = prop as string;\n if (handler === \"workflowSubmit\") {\n return workflowSubmit;\n } else if (handler === \"workflowAttach\") {\n return workflowAttach;\n } else if (handler === \"workflowOutput\") {\n return workflowOutput;\n }\n // shared handlers pass trough via the ingress's normal invocation form\n // i.e. POST /<svc>/<key>/<handler>\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n return doComponentInvocation(conn, {\n component,\n handler,\n key,\n parameter,\n opts,\n });\n };\n },\n }\n ) as IngressWorkflowClient<Workflow<D>>;\n }\n\n objectSendClient<D>(\n opts: VirtualObjectDefinitionFrom<D>,\n key: string\n ): IngressSendClient<VirtualObject<D>> {\n return this.proxy(opts.name, key, true) as IngressSendClient<\n VirtualObject<D>\n >;\n }\n\n serviceSendClient<D>(\n opts: ServiceDefinitionFrom<D>\n ): IngressSendClient<Service<D>> {\n return this.proxy(opts.name, undefined, true) as IngressSendClient<\n Service<D>\n >;\n }\n\n scope(scopeKey: string): ScopedIngress {\n const conn = this.opts;\n const scopedProxy = (component: string, key?: string, send?: boolean) =>\n new Proxy(\n {},\n {\n get: (_target, prop) => {\n const handler = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n return doComponentInvocation<unknown, unknown>(conn, {\n component,\n handler,\n key,\n parameter,\n opts,\n send,\n scope: scopeKey,\n });\n };\n },\n }\n );\n\n return {\n serviceClient: <D>(opts: ServiceDefinitionFrom<D>) =>\n scopedProxy(opts.name) as IngressClient<Service<D>>,\n serviceSendClient: <D>(opts: ServiceDefinitionFrom<D>) =>\n scopedProxy(opts.name, undefined, true) as IngressSendClient<\n Service<D>\n >,\n objectClient: <D>(opts: VirtualObjectDefinitionFrom<D>, key: string) =>\n scopedProxy(opts.name, key) as IngressClient<VirtualObject<D>>,\n objectSendClient: <D>(\n opts: VirtualObjectDefinitionFrom<D>,\n key: string\n ) =>\n scopedProxy(opts.name, key, true) as IngressSendClient<\n VirtualObject<D>\n >,\n workflowClient: <D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): IngressWorkflowClient<Workflow<D>> => {\n const component = opts.name;\n\n const workflowSubmit = async (\n ...args: unknown[]\n ): Promise<WorkflowSubmission<unknown>> => {\n const { parameter, opts } = optsFromArgs(args);\n const res: Send = await doComponentInvocation(\n conn,\n {\n component,\n handler: \"run\",\n key,\n send: true,\n parameter,\n opts,\n scope: scopeKey,\n },\n true\n );\n return {\n invocationId: res.invocationId,\n status: res.status,\n attachable: true,\n };\n };\n\n const workflowAttach = (opts?: Opts<void, unknown>) =>\n doWorkflowHandleCall(conn, component, key, \"attach\", opts);\n\n const workflowOutput = async (\n opts?: Opts<void, unknown>\n ): Promise<Output<unknown>> => {\n try {\n const result = await doWorkflowHandleCall(\n conn,\n component,\n key,\n \"output\",\n opts\n );\n return { ready: true, result };\n } catch (e) {\n if (!(e instanceof HttpCallError) || e.status !== 470) {\n throw e;\n }\n return {\n ready: false,\n get result() {\n throw new Error(\"Calling result() on a non ready workflow\");\n },\n };\n }\n };\n\n return new Proxy(\n {},\n {\n get: (_target, prop) => {\n const handler = prop as string;\n if (handler === \"workflowSubmit\") {\n return workflowSubmit;\n } else if (handler === \"workflowAttach\") {\n return workflowAttach;\n } else if (handler === \"workflowOutput\") {\n return workflowOutput;\n }\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n return doComponentInvocation(conn, {\n component,\n handler,\n key,\n parameter,\n opts,\n scope: scopeKey,\n });\n };\n },\n }\n ) as IngressWorkflowClient<Workflow<D>>;\n },\n };\n }\n\n async call<I, O>(opts: {\n service: string;\n handler: string;\n parameter: I;\n key?: string;\n scope?: string;\n opts?: Opts<I, O>;\n }): Promise<O> {\n return doComponentInvocation<I, O>(this.opts, {\n component: opts.service,\n handler: opts.handler,\n key: opts.key,\n scope: opts.scope,\n parameter: opts.parameter,\n send: false,\n opts: opts.opts,\n });\n }\n\n async send<I>(opts: {\n service: string;\n handler: string;\n parameter: I;\n key?: string;\n scope?: string;\n opts?: SendOpts<I>;\n }): Promise<Send> {\n return doComponentInvocation<I, Send>(this.opts, {\n component: opts.service,\n handler: opts.handler,\n key: opts.key,\n scope: opts.scope,\n parameter: opts.parameter,\n send: true,\n opts: opts.opts,\n });\n }\n\n async resolveAwakeable<T>(\n id: string,\n payload?: T,\n payloadSerde?: Serde<T>\n ): Promise<void> {\n const url = `${this.opts.url}/restate/a/${id}/resolve`;\n const { body, contentType } = serializeBodyWithContentType(\n payload,\n payloadSerde ?? this.opts.serde ?? serde.json,\n this.opts.journalValueCodec\n );\n const headers = {\n ...(this.opts.headers ?? {}),\n };\n if (contentType) {\n headers[\"Content-Type\"] = contentType;\n }\n const httpResponse = await getFetch(this.opts)(url, {\n method: \"POST\",\n headers,\n body,\n });\n if (!httpResponse.ok) {\n const body = await httpResponse.text();\n throw new HttpCallError(\n httpResponse.status,\n body,\n `Request failed: ${httpResponse.status}\\n${body}`\n );\n }\n }\n\n async rejectAwakeable(id: string, reason: string): Promise<void> {\n const url = `${this.opts.url}/restate/a/${id}/reject`;\n const headers = {\n \"Content-Type\": \"text/plain\",\n ...(this.opts.headers ?? {}),\n };\n const httpResponse = await getFetch(this.opts)(url, {\n method: \"POST\",\n headers,\n body: reason,\n });\n if (!httpResponse.ok) {\n const body = await httpResponse.text();\n throw new HttpCallError(\n httpResponse.status,\n body,\n `Request failed: ${httpResponse.status}\\n${body}`\n );\n }\n }\n\n async result<T>(\n send: Send<T> | WorkflowSubmission<T>,\n resultSerde?: Serde<T>\n ): Promise<T> {\n if (!send.attachable) {\n throw new Error(\n `Unable to fetch the result for ${send.invocationId}.\n A service's result is stored only with an idempotencyKey is supplied when invocating the service.`\n );\n }\n //\n // headers\n //\n const headers = {\n ...(this.opts.headers ?? {}),\n };\n //\n // make the call\n const url = `${this.opts.url}/restate/invocation/${send.invocationId}/attach`;\n\n const httpResponse = await getFetch(this.opts)(url, {\n method: \"GET\",\n headers,\n });\n if (httpResponse.ok) {\n const responseBuf = new Uint8Array(await httpResponse.arrayBuffer());\n const decodedBuf = this.opts.journalValueCodec\n ? await this.opts.journalValueCodec.decode(responseBuf)\n : responseBuf;\n return (resultSerde ?? this.opts.serde ?? serde.json).deserialize(\n decodedBuf\n ) as T;\n }\n const body = await httpResponse.text();\n throw new HttpCallError(\n httpResponse.status,\n body,\n `Request failed: ${httpResponse.status}\\n${body}`\n );\n }\n}\n\nfunction computeDelayAsIso(opts: SendOpts): string {\n const delay = opts.delay();\n if (!delay) {\n return \"send\";\n }\n return `send?delay=${delay}ms`;\n}\n\nfunction serializeBodyWithContentType(\n body: unknown,\n serde: Serde<unknown>,\n journalValueCodec?: JournalValueCodec\n): {\n body?: Uint8Array;\n contentType?: string;\n} {\n let buffer = serde.serialize(body);\n if (journalValueCodec) {\n buffer = journalValueCodec.encode(buffer);\n }\n return {\n body: buffer,\n contentType: serde.contentType,\n };\n}\n"],"mappings":";;;;;;;;;;;AAkDA,SAAgB,QAAQ,MAA+B;AACrD,QAAO,IAAI,YAAY,KAAK;;AAG9B,IAAa,gBAAb,cAAmC,MAAM;CACvC,YACE,AAAgBA,QAChB,AAAgBC,cAChB,AAAyBC,SACzB;AACA,QAAM,QAAQ;EAJE;EACA;EACS;;;AAiB7B,SAAS,aAAa,MAGpB;CACA,IAAIC;CACJ,IAAIC;AACJ,SAAQ,KA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B,SAAS,6BACP,MACA,SACA,mBAIA;CACA,IAAI,SAASC,QAAM,UAAU,KAAK;AAClC,KAAI,kBACF,UAAS,kBAAkB,OAAO,OAAO;AAE3C,QAAO;EACL,MAAM;EACN,aAAaA,QAAM;EACpB"}
1
+ {"version":3,"file":"ingress.js","names":["status: number","responseText: string","message: string","parameter: unknown","opts: Opts<unknown, unknown> | SendOpts<unknown> | undefined","response: Response","errorBody: string","url: string","opts: ConnectionOpts","res: Send","opts","body","serde"],"sources":["../src/ingress.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport {\n type Service,\n type ServiceDefinitionFrom,\n type VirtualObject,\n type WorkflowDefinitionFrom,\n type Workflow,\n type VirtualObjectDefinitionFrom,\n type Serde,\n serde,\n type JournalValueCodec,\n} from \"@restatedev/restate-sdk-core\";\nimport {\n ConnectionOpts,\n Ingress,\n IngressClient,\n IngressSendClient,\n IngressWorkflowClient,\n Output,\n Send,\n ScopedIngress,\n WorkflowSubmission,\n} from \"./api.js\";\n\nimport { Opts, SendOpts } from \"./api.js\";\nimport {\n abortableSleep,\n backoffDelay,\n defaultShouldRetry,\n parseRetryAfter,\n type ResolvedRetryPolicy,\n resolveRetryPolicy,\n} from \"./retry.js\";\n\n/**\n * Connect to the restate Ingress\n *\n * @param opts connection options\n * @returns a connection the the restate ingress\n */\nexport function connect(opts: ConnectionOpts): Ingress {\n return new HttpIngress(opts);\n}\n\nexport class HttpCallError extends Error {\n constructor(\n public readonly status: number,\n public readonly responseText: string,\n public override readonly message: string\n ) {\n super(message);\n }\n}\n\ntype InvocationParameters<I> = {\n component: string;\n handler: string;\n key?: string;\n send?: boolean;\n opts?: Opts<I, unknown> | SendOpts<I>;\n parameter?: I;\n method?: string;\n scope?: string;\n};\n\nfunction optsFromArgs(args: unknown[]): {\n parameter?: unknown;\n opts?: Opts<unknown, unknown> | SendOpts<unknown>;\n} {\n let parameter: unknown;\n let opts: Opts<unknown, unknown> | SendOpts<unknown> | undefined;\n switch (args.length) {\n case 0: {\n break;\n }\n case 1: {\n if (args[0] instanceof Opts) {\n opts = args[0];\n } else if (args[0] instanceof SendOpts) {\n opts = args[0];\n } else {\n parameter = args[0];\n }\n break;\n }\n case 2: {\n parameter = args[0];\n if (args[1] instanceof Opts) {\n opts = args[1];\n } else if (args[1] instanceof SendOpts) {\n opts = args[1];\n } else {\n throw new TypeError(\n \"The second argument must be either Opts or SendOpts\"\n );\n }\n break;\n }\n default: {\n throw new TypeError(\"unexpected number of arguments\");\n }\n }\n return {\n parameter,\n opts,\n };\n}\n\nconst IDEMPOTENCY_KEY_HEADER = \"idempotency-key\";\nconst LIMIT_KEY_HEADER = \"x-restate-limit-key\";\n// Carries the 1-based attempt number on every request so the server can observe\n// how many times the client has (re)issued it.\nconst ATTEMPT_HEADER = \"x-restateclient-retry-attempt\";\n\nconst getFetch = (opts: ConnectionOpts): NonNullable<ConnectionOpts[\"fetch\"]> =>\n opts.fetch ?? globalThis.fetch;\n\nconst fetchWithRetries = async (\n opts: ConnectionOpts,\n url: string,\n init: RequestInit,\n callOpts: Opts<unknown, unknown> | SendOpts<unknown> | undefined,\n retryPolicy: ResolvedRetryPolicy | undefined\n): Promise<Uint8Array> => {\n const userSignal = callOpts?.opts.signal;\n const timeout = callOpts?.opts.timeout;\n if (userSignal !== undefined && timeout !== undefined) {\n // The caller configured two mutually exclusive ways to abort each attempt.\n throw new Error(\n \"You can't specify both signal and timeout options at the same time\"\n );\n }\n // A fresh timeout signal is minted per attempt below — a single\n // AbortSignal.timeout() would already be aborted on the second attempt.\n const attemptSignal = (): AbortSignal | undefined =>\n userSignal ??\n (timeout !== undefined ? AbortSignal.timeout(timeout) : undefined);\n const shouldRetry = retryPolicy?.shouldRetry ?? defaultShouldRetry;\n\n // Whether waiting `delay` and then starting the next attempt would still fall\n // within the maxDuration budget (measured from the first attempt; a non-finite\n // maxDuration disables the bound). Checked *after* the delay is known so we\n // never sleep out a backoff — or a long Retry-After — only to give up on the\n // attempt it precedes. This is a decision-time gate only: it never aborts an\n // in-flight request. The maxAttempts count is gated separately, before the\n // delay is computed.\n const startTime = Date.now();\n const nextAttemptFitsBudget = (\n policy: ResolvedRetryPolicy,\n delay: number\n ): boolean => Date.now() - startTime + delay < policy.maxDuration;\n\n // Headers are always a plain record in this codebase; carry them forward and\n // stamp the attempt number afresh on each try.\n const baseHeaders = (init.headers ?? {}) as Record<string, string>;\n\n for (let attempt = 0; ; attempt++) {\n let response: Response;\n let errorBody: string;\n try {\n response = await getFetch(opts)(url, {\n ...init,\n headers: { ...baseHeaders, [ATTEMPT_HEADER]: String(attempt + 1) },\n signal: attemptSignal(),\n });\n if (response.ok) {\n // A 2xx response was received. Keep the body read inside this try so a\n // connection failure while streaming the body is retried as ambiguous.\n return new Uint8Array(await response.arrayBuffer());\n }\n // fetch resolves normally for non-2xx statuses. Read the body here both\n // for RetryFailure inspection and the final HttpCallError.\n errorBody = await response.text();\n } catch (e) {\n // fetch rejected, or the response body failed while streaming. Both are\n // ambiguous because the server may already have processed the request.\n if (\n retryPolicy &&\n attempt < retryPolicy.maxAttempts - 1 &&\n !userSignal?.aborted &&\n shouldRetry({ kind: \"network\", error: e }, attempt)\n ) {\n // Retries are enabled, attempts remain, the caller did not abort, and\n // the policy accepted this failure. Retry only if the backoff still\n // leaves us within the duration budget.\n const delay = backoffDelay(retryPolicy, attempt);\n if (nextAttemptFitsBudget(retryPolicy, delay)) {\n await abortableSleep(delay, userSignal);\n continue;\n }\n }\n // Retries are disabled or exhausted, the caller aborted, the policy\n // rejected this failure, or the duration budget is spent.\n throw e;\n }\n if (\n retryPolicy &&\n attempt < retryPolicy.maxAttempts - 1 &&\n !userSignal?.aborted &&\n shouldRetry(\n {\n kind: \"response\",\n status: response.status,\n headers: response.headers,\n body: errorBody || undefined,\n },\n attempt\n )\n ) {\n // A non-2xx response was received, attempts remain, and the policy chose\n // to retry it (by default, transient statuses 408/425/429/5xx, unless the\n // error is attributed to the invocation via x-restate-error-source). The\n // delay is the server's Retry-After when present, else the computed\n // backoff; either way we only retry if it still fits the duration budget.\n const retryAfter = retryPolicy.respectRetryAfter\n ? parseRetryAfter(response.headers)\n : undefined;\n const delay = retryAfter ?? backoffDelay(retryPolicy, attempt);\n if (nextAttemptFitsBudget(retryPolicy, delay)) {\n await abortableSleep(delay, userSignal);\n continue;\n }\n }\n // The response is not retryable, retries are disabled or exhausted, the\n // caller aborted, or the policy rejected this response.\n throw new HttpCallError(\n response.status,\n errorBody,\n `Request failed: ${response.status}\\n${errorBody}`\n );\n }\n};\n\nconst doComponentInvocation = async <I, O>(\n opts: ConnectionOpts,\n params: InvocationParameters<I>,\n canBeRetried = Boolean(params.opts?.opts.idempotencyKey)\n): Promise<O> => {\n let attachable = false;\n //\n // ingress URL\n //\n let url: string;\n if (params.scope) {\n // Scoped path: /restate/scope/{scope}/{call|send}/{service}/{key?}/{handler}\n const pathType = params.send ? \"send\" : \"call\";\n const parts = [\n opts.url,\n \"restate/scope\",\n encodeURIComponent(params.scope),\n pathType,\n params.component,\n ];\n if (params.key) {\n parts.push(encodeURIComponent(params.key));\n }\n parts.push(params.handler);\n url = parts.join(\"/\");\n if (params.send && params.opts instanceof SendOpts) {\n const delay = params.opts.delay();\n if (delay) url += `?delay=${delay}ms`;\n }\n } else {\n const fragments = [opts.url, params.component];\n if (params.key) {\n fragments.push(encodeURIComponent(params.key));\n }\n fragments.push(params.handler);\n if (params.send ?? false) {\n if (params.opts instanceof SendOpts) {\n fragments.push(computeDelayAsIso(params.opts));\n } else {\n fragments.push(\"send\");\n }\n }\n url = fragments.join(\"/\");\n }\n //\n // request body\n //\n const inputSerde = params.opts?.opts.input ?? opts.serde ?? serde.json;\n\n const { body, contentType } = serializeBodyWithContentType(\n params.parameter,\n inputSerde,\n opts.journalValueCodec\n );\n //\n // headers\n //\n const headers = {\n ...(opts.headers ?? {}),\n ...(params.opts?.opts?.headers ?? {}),\n };\n if (contentType) {\n headers[\"Content-Type\"] = contentType;\n }\n //\n // idempotency\n //\n const idempotencyKey = params.opts?.opts.idempotencyKey;\n if (idempotencyKey) {\n headers[IDEMPOTENCY_KEY_HEADER] = idempotencyKey;\n attachable = true;\n }\n //\n // limit key\n //\n const limitKey = params.opts?.opts.limitKey;\n if (limitKey) {\n headers[LIMIT_KEY_HEADER] = limitKey;\n }\n\n //\n // retries\n //\n // Regular invocations default eligibility from the idempotency key, while\n // workflow submissions opt in because the workflow ID identifies the run.\n const retryPolicy = canBeRetried ? resolveRetryPolicy(opts.retry) : undefined;\n\n //\n // make the call\n //\n const responseBuf = await fetchWithRetries(\n opts,\n url,\n {\n method: params.method ?? \"POST\",\n headers,\n body,\n },\n params.opts,\n retryPolicy\n );\n if (!params.send) {\n const decodedBuf = opts.journalValueCodec\n ? await opts.journalValueCodec.decode(responseBuf)\n : responseBuf;\n const outputSerde = params.opts?.opts.output ?? opts.serde ?? serde.json;\n return outputSerde.deserialize(decodedBuf) as O;\n }\n const json = serde.json.deserialize(responseBuf) as O;\n return { ...json, attachable };\n};\n\nconst doWorkflowHandleCall = async <O>(\n opts: ConnectionOpts,\n wfName: string,\n wfKey: string,\n op: \"output\" | \"attach\",\n callOpts?: Opts<unknown, O> | SendOpts<unknown>\n): Promise<O> => {\n const outputSerde = callOpts?.opts.output ?? opts.serde ?? serde.json;\n //\n // headers\n //\n const headers = {\n ...(opts.headers ?? {}),\n };\n //\n // make the call\n //\n const url = `${opts.url}/restate/workflow/${wfName}/${encodeURIComponent(\n wfKey\n )}/${op}`;\n // Attach and output only observe the existing workflow, so both are eligible\n // when the connection has a retry policy.\n const retryPolicy = resolveRetryPolicy(opts.retry);\n\n const responseBuf = await fetchWithRetries(\n opts,\n url,\n { method: \"GET\", headers },\n callOpts,\n retryPolicy\n );\n const decodedBuf = opts.journalValueCodec\n ? await opts.journalValueCodec.decode(responseBuf)\n : responseBuf;\n return outputSerde.deserialize(decodedBuf) as O;\n};\n\nclass HttpIngress implements Ingress {\n constructor(private readonly opts: ConnectionOpts) {}\n\n private proxy(component: string, key?: string, send?: boolean) {\n return new Proxy(\n {},\n {\n get: (_target, prop) => {\n const handler = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n return doComponentInvocation<unknown, unknown>(this.opts, {\n component,\n handler,\n key,\n parameter,\n opts,\n send,\n });\n };\n },\n }\n );\n }\n\n serviceClient<D>(opts: ServiceDefinitionFrom<D>): IngressClient<Service<D>> {\n return this.proxy(opts.name) as IngressClient<Service<D>>;\n }\n\n objectClient<D>(\n opts: VirtualObjectDefinitionFrom<D>,\n key: string\n ): IngressClient<VirtualObject<D>> {\n return this.proxy(opts.name, key) as IngressClient<VirtualObject<D>>;\n }\n\n workflowClient<D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): IngressWorkflowClient<Workflow<D>> {\n const component = opts.name;\n const conn = this.opts;\n\n const workflowSubmit = async (\n ...args: unknown[]\n ): Promise<WorkflowSubmission<unknown>> => {\n const { parameter, opts } = optsFromArgs(args);\n const res: Send = await doComponentInvocation(\n conn,\n {\n component,\n handler: \"run\",\n key,\n send: true,\n parameter,\n opts,\n },\n true\n );\n\n return {\n invocationId: res.invocationId,\n status: res.status,\n attachable: true,\n };\n };\n\n const workflowAttach = (opts?: Opts<void, unknown>) =>\n doWorkflowHandleCall(conn, component, key, \"attach\", opts);\n\n const workflowOutput = async (\n opts?: Opts<void, unknown>\n ): Promise<Output<unknown>> => {\n try {\n const result = await doWorkflowHandleCall(\n conn,\n component,\n key,\n \"output\",\n opts\n );\n\n return {\n ready: true,\n result,\n };\n } catch (e) {\n if (!(e instanceof HttpCallError) || e.status !== 470) {\n throw e;\n }\n return {\n ready: false,\n get result() {\n throw new Error(\"Calling result() on a non ready workflow\");\n },\n };\n }\n };\n\n return new Proxy(\n {},\n {\n get: (_target, prop) => {\n const handler = prop as string;\n if (handler === \"workflowSubmit\") {\n return workflowSubmit;\n } else if (handler === \"workflowAttach\") {\n return workflowAttach;\n } else if (handler === \"workflowOutput\") {\n return workflowOutput;\n }\n // shared handlers pass trough via the ingress's normal invocation form\n // i.e. POST /<svc>/<key>/<handler>\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n return doComponentInvocation(conn, {\n component,\n handler,\n key,\n parameter,\n opts,\n });\n };\n },\n }\n ) as IngressWorkflowClient<Workflow<D>>;\n }\n\n objectSendClient<D>(\n opts: VirtualObjectDefinitionFrom<D>,\n key: string\n ): IngressSendClient<VirtualObject<D>> {\n return this.proxy(opts.name, key, true) as IngressSendClient<\n VirtualObject<D>\n >;\n }\n\n serviceSendClient<D>(\n opts: ServiceDefinitionFrom<D>\n ): IngressSendClient<Service<D>> {\n return this.proxy(opts.name, undefined, true) as IngressSendClient<\n Service<D>\n >;\n }\n\n scope(scopeKey: string): ScopedIngress {\n const conn = this.opts;\n const scopedProxy = (component: string, key?: string, send?: boolean) =>\n new Proxy(\n {},\n {\n get: (_target, prop) => {\n const handler = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n return doComponentInvocation<unknown, unknown>(conn, {\n component,\n handler,\n key,\n parameter,\n opts,\n send,\n scope: scopeKey,\n });\n };\n },\n }\n );\n\n return {\n serviceClient: <D>(opts: ServiceDefinitionFrom<D>) =>\n scopedProxy(opts.name) as IngressClient<Service<D>>,\n serviceSendClient: <D>(opts: ServiceDefinitionFrom<D>) =>\n scopedProxy(opts.name, undefined, true) as IngressSendClient<\n Service<D>\n >,\n objectClient: <D>(opts: VirtualObjectDefinitionFrom<D>, key: string) =>\n scopedProxy(opts.name, key) as IngressClient<VirtualObject<D>>,\n objectSendClient: <D>(\n opts: VirtualObjectDefinitionFrom<D>,\n key: string\n ) =>\n scopedProxy(opts.name, key, true) as IngressSendClient<\n VirtualObject<D>\n >,\n workflowClient: <D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): IngressWorkflowClient<Workflow<D>> => {\n const component = opts.name;\n\n const workflowSubmit = async (\n ...args: unknown[]\n ): Promise<WorkflowSubmission<unknown>> => {\n const { parameter, opts } = optsFromArgs(args);\n const res: Send = await doComponentInvocation(\n conn,\n {\n component,\n handler: \"run\",\n key,\n send: true,\n parameter,\n opts,\n scope: scopeKey,\n },\n true\n );\n return {\n invocationId: res.invocationId,\n status: res.status,\n attachable: true,\n };\n };\n\n const workflowAttach = (opts?: Opts<void, unknown>) =>\n doWorkflowHandleCall(conn, component, key, \"attach\", opts);\n\n const workflowOutput = async (\n opts?: Opts<void, unknown>\n ): Promise<Output<unknown>> => {\n try {\n const result = await doWorkflowHandleCall(\n conn,\n component,\n key,\n \"output\",\n opts\n );\n return { ready: true, result };\n } catch (e) {\n if (!(e instanceof HttpCallError) || e.status !== 470) {\n throw e;\n }\n return {\n ready: false,\n get result() {\n throw new Error(\"Calling result() on a non ready workflow\");\n },\n };\n }\n };\n\n return new Proxy(\n {},\n {\n get: (_target, prop) => {\n const handler = prop as string;\n if (handler === \"workflowSubmit\") {\n return workflowSubmit;\n } else if (handler === \"workflowAttach\") {\n return workflowAttach;\n } else if (handler === \"workflowOutput\") {\n return workflowOutput;\n }\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n return doComponentInvocation(conn, {\n component,\n handler,\n key,\n parameter,\n opts,\n scope: scopeKey,\n });\n };\n },\n }\n ) as IngressWorkflowClient<Workflow<D>>;\n },\n };\n }\n\n async call<I, O>(opts: {\n service: string;\n handler: string;\n parameter: I;\n key?: string;\n scope?: string;\n opts?: Opts<I, O>;\n }): Promise<O> {\n return doComponentInvocation<I, O>(this.opts, {\n component: opts.service,\n handler: opts.handler,\n key: opts.key,\n scope: opts.scope,\n parameter: opts.parameter,\n send: false,\n opts: opts.opts,\n });\n }\n\n async send<I>(opts: {\n service: string;\n handler: string;\n parameter: I;\n key?: string;\n scope?: string;\n opts?: SendOpts<I>;\n }): Promise<Send> {\n return doComponentInvocation<I, Send>(this.opts, {\n component: opts.service,\n handler: opts.handler,\n key: opts.key,\n scope: opts.scope,\n parameter: opts.parameter,\n send: true,\n opts: opts.opts,\n });\n }\n\n async resolveAwakeable<T>(\n id: string,\n payload?: T,\n payloadSerde?: Serde<T>\n ): Promise<void> {\n const url = `${this.opts.url}/restate/a/${id}/resolve`;\n const { body, contentType } = serializeBodyWithContentType(\n payload,\n payloadSerde ?? this.opts.serde ?? serde.json,\n this.opts.journalValueCodec\n );\n const headers = {\n ...(this.opts.headers ?? {}),\n };\n if (contentType) {\n headers[\"Content-Type\"] = contentType;\n }\n const httpResponse = await getFetch(this.opts)(url, {\n method: \"POST\",\n headers,\n body,\n });\n if (!httpResponse.ok) {\n const body = await httpResponse.text();\n throw new HttpCallError(\n httpResponse.status,\n body,\n `Request failed: ${httpResponse.status}\\n${body}`\n );\n }\n }\n\n async rejectAwakeable(id: string, reason: string): Promise<void> {\n const url = `${this.opts.url}/restate/a/${id}/reject`;\n const headers = {\n \"Content-Type\": \"text/plain\",\n ...(this.opts.headers ?? {}),\n };\n const httpResponse = await getFetch(this.opts)(url, {\n method: \"POST\",\n headers,\n body: reason,\n });\n if (!httpResponse.ok) {\n const body = await httpResponse.text();\n throw new HttpCallError(\n httpResponse.status,\n body,\n `Request failed: ${httpResponse.status}\\n${body}`\n );\n }\n }\n\n async result<T>(\n send: Send<T> | WorkflowSubmission<T>,\n resultSerde?: Serde<T>\n ): Promise<T> {\n if (!send.attachable) {\n throw new Error(\n `Unable to fetch the result for ${send.invocationId}.\n A service's result is stored only with an idempotencyKey is supplied when invocating the service.`\n );\n }\n //\n // headers\n //\n const headers = {\n ...(this.opts.headers ?? {}),\n };\n //\n // make the call\n //\n const url = `${this.opts.url}/restate/invocation/${send.invocationId}/attach`;\n // Attaching only observes the existing invocation, so it is safe to retry\n // when the connection has a retry policy.\n const retryPolicy = resolveRetryPolicy(this.opts.retry);\n\n const responseBuf = await fetchWithRetries(\n this.opts,\n url,\n { method: \"GET\", headers },\n undefined,\n retryPolicy\n );\n const decodedBuf = this.opts.journalValueCodec\n ? await this.opts.journalValueCodec.decode(responseBuf)\n : responseBuf;\n return (resultSerde ?? this.opts.serde ?? serde.json).deserialize(\n decodedBuf\n ) as T;\n }\n}\n\nfunction computeDelayAsIso(opts: SendOpts): string {\n const delay = opts.delay();\n if (!delay) {\n return \"send\";\n }\n return `send?delay=${delay}ms`;\n}\n\nfunction serializeBodyWithContentType(\n body: unknown,\n serde: Serde<unknown>,\n journalValueCodec?: JournalValueCodec\n): {\n body?: Uint8Array;\n contentType?: string;\n} {\n let buffer = serde.serialize(body);\n if (journalValueCodec) {\n buffer = journalValueCodec.encode(buffer);\n }\n return {\n body: buffer,\n contentType: serde.contentType,\n };\n}\n"],"mappings":";;;;;;;;;;;AAkDA,SAAgB,QAAQ,MAA+B;AACrD,QAAO,IAAI,YAAY,KAAK;;AAG9B,IAAa,gBAAb,cAAmC,MAAM;CACvC,YACE,AAAgBA,QAChB,AAAgBC,cAChB,AAAyBC,SACzB;AACA,QAAM,QAAQ;EAJE;EACA;EACS;;;AAiB7B,SAAS,aAAa,MAGpB;CACA,IAAIC;CACJ,IAAIC;AACJ,SAAQ,KAAK,QAAb;EACE,KAAK,EACH;EAEF,KAAK;AACH,OAAI,KAAK,cAAc,KACrB,QAAO,KAAK;YACH,KAAK,cAAc,SAC5B,QAAO,KAAK;OAEZ,aAAY,KAAK;AAEnB;EAEF,KAAK;AACH,eAAY,KAAK;AACjB,OAAI,KAAK,cAAc,KACrB,QAAO,KAAK;YACH,KAAK,cAAc,SAC5B,QAAO,KAAK;OAEZ,OAAM,IAAI,UACR,sDACD;AAEH;EAEF,QACE,OAAM,IAAI,UAAU,iCAAiC;;AAGzD,QAAO;EACL;EACA;EACD;;AAGH,MAAM,yBAAyB;AAC/B,MAAM,mBAAmB;AAGzB,MAAM,iBAAiB;AAEvB,MAAM,YAAY,SAChB,KAAK,SA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atedev_re
5
5
  //#region src/retry.ts
6
6
  const DEFAULT_RETRY_POLICY = {
7
7
  maxAttempts: 6,
8
- initialInterval: 100,
9
- maxInterval: 2e3,
10
- exponentiationFactor: 2
8
+ initialInterval: 250,
9
+ maxInterval: 3e3,
10
+ exponentiationFactor: 2,
11
+ respectRetryAfter: true,
12
+ maxDuration: 6e4
11
13
  };
12
14
  /**
13
15
  * Resolve a user supplied retry policy into a fully populated one.
@@ -20,37 +22,50 @@ function resolveRetryPolicy(retry) {
20
22
  if (retry === void 0 || retry === false) return;
21
23
  if (retry === true) return DEFAULT_RETRY_POLICY;
22
24
  return {
23
- maxAttempts: retry.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,
25
+ maxAttempts: retry.maxAttempts === false ? Infinity : retry.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,
24
26
  initialInterval: retry.initialInterval !== void 0 ? (0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(retry.initialInterval) : DEFAULT_RETRY_POLICY.initialInterval,
25
27
  maxInterval: retry.maxInterval !== void 0 ? (0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(retry.maxInterval) : DEFAULT_RETRY_POLICY.maxInterval,
26
28
  exponentiationFactor: retry.exponentiationFactor ?? DEFAULT_RETRY_POLICY.exponentiationFactor,
29
+ respectRetryAfter: retry.respectRetryAfter ?? DEFAULT_RETRY_POLICY.respectRetryAfter,
30
+ maxDuration: retry.maxDuration === false ? Infinity : retry.maxDuration !== void 0 ? (0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(retry.maxDuration) : DEFAULT_RETRY_POLICY.maxDuration,
27
31
  shouldRetry: retry.shouldRetry
28
32
  };
29
33
  }
30
- /** Whether an HTTP response status warrants a retry. */
34
+ /**
35
+ * Whether an HTTP response status is a transient ingress condition that
36
+ * warrants a retry: `408`, `425`, `429`, or any `5xx`.
37
+ */
31
38
  function isRetryableStatus(status) {
32
- return status === 429 || status >= 500 && status <= 599;
39
+ return status === 408 || status === 425 || status === 429 || status >= 500 && status <= 599;
33
40
  }
34
41
  /**
35
- * The built-in retry decision: retry network errors, HTTP `429`, and HTTP
36
- * `5xx`. Exported so a custom {@link RetryPolicy.shouldRetry} can compose with
37
- * it rather than reimplement it.
42
+ * The built-in retry decision. Retries network errors and responses with a
43
+ * transient status (`408`, `425`, `429`, or `5xx`) except errors restate
44
+ * attributes to the invocation itself, which are terminal outcomes of the
45
+ * durable execution and are never retried whatever their status code.
46
+ *
47
+ * restate-server discloses the origin via the `x-restate-error-source` header
48
+ * (`"invocation"` or `"ingress"`); when it is absent — a proxy stripped it, or
49
+ * an older server — the status alone drives the decision. See
50
+ * https://github.com/restatedev/restate/pull/5173.
51
+ *
52
+ * Exported so a custom {@link RetryPolicy.shouldRetry} can compose with it
53
+ * rather than reimplement it.
38
54
  */
39
55
  function defaultShouldRetry(failure) {
40
- return failure.kind === "network" || isRetryableStatus(failure.status);
56
+ if (failure.kind === "network") return true;
57
+ if (failure.headers.get("x-restate-error-source") === "invocation") return false;
58
+ return isRetryableStatus(failure.status);
41
59
  }
42
60
  /**
43
61
  * Compute the backoff for the given (zero based) attempt index using
44
- * exponential backoff with full jitter, capped at `maxInterval`.
45
- *
46
- * When the server provided an explicit `Retry-After` we honor it instead,
47
- * capped at `maxInterval` to avoid pathologically long waits.
62
+ * exponential backoff with ±20% jitter. The exponential base is capped at
63
+ * `maxInterval`; jitter is then applied on top, so the returned delay can sit
64
+ * up to 20% above `maxInterval`.
48
65
  */
49
- function backoffDelay(policy, attempt, retryAfterMs) {
50
- if (retryAfterMs !== void 0) return Math.min(retryAfterMs, policy.maxInterval);
66
+ function backoffDelay(policy, attempt) {
51
67
  const exp = policy.initialInterval * Math.pow(policy.exponentiationFactor, attempt);
52
- const ceiling = Math.min(exp, policy.maxInterval);
53
- return Math.random() * ceiling;
68
+ return Math.min(exp, policy.maxInterval) * (.8 + Math.random() * .4);
54
69
  }
55
70
  /**
56
71
  * Parse a `Retry-After` header value into milliseconds.
package/dist/retry.d.cts CHANGED
@@ -3,9 +3,18 @@ import { RetryFailure } from "./api.cjs";
3
3
  //#region src/retry.d.ts
4
4
 
5
5
  /**
6
- * The built-in retry decision: retry network errors, HTTP `429`, and HTTP
7
- * `5xx`. Exported so a custom {@link RetryPolicy.shouldRetry} can compose with
8
- * it rather than reimplement it.
6
+ * The built-in retry decision. Retries network errors and responses with a
7
+ * transient status (`408`, `425`, `429`, or `5xx`) except errors restate
8
+ * attributes to the invocation itself, which are terminal outcomes of the
9
+ * durable execution and are never retried whatever their status code.
10
+ *
11
+ * restate-server discloses the origin via the `x-restate-error-source` header
12
+ * (`"invocation"` or `"ingress"`); when it is absent — a proxy stripped it, or
13
+ * an older server — the status alone drives the decision. See
14
+ * https://github.com/restatedev/restate/pull/5173.
15
+ *
16
+ * Exported so a custom {@link RetryPolicy.shouldRetry} can compose with it
17
+ * rather than reimplement it.
9
18
  */
10
19
  declare function defaultShouldRetry(failure: RetryFailure): boolean;
11
20
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"retry.d.cts","names":[],"sources":["../src/retry.ts"],"sourcesContent":[],"mappings":";;;;;;;;;iBAwEgB,kBAAA,UAA4B"}
1
+ {"version":3,"file":"retry.d.cts","names":[],"sources":["../src/retry.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;iBAmHgB,kBAAA,UAA4B"}
package/dist/retry.d.ts CHANGED
@@ -3,9 +3,18 @@ import { RetryFailure } from "./api.js";
3
3
  //#region src/retry.d.ts
4
4
 
5
5
  /**
6
- * The built-in retry decision: retry network errors, HTTP `429`, and HTTP
7
- * `5xx`. Exported so a custom {@link RetryPolicy.shouldRetry} can compose with
8
- * it rather than reimplement it.
6
+ * The built-in retry decision. Retries network errors and responses with a
7
+ * transient status (`408`, `425`, `429`, or `5xx`) except errors restate
8
+ * attributes to the invocation itself, which are terminal outcomes of the
9
+ * durable execution and are never retried whatever their status code.
10
+ *
11
+ * restate-server discloses the origin via the `x-restate-error-source` header
12
+ * (`"invocation"` or `"ingress"`); when it is absent — a proxy stripped it, or
13
+ * an older server — the status alone drives the decision. See
14
+ * https://github.com/restatedev/restate/pull/5173.
15
+ *
16
+ * Exported so a custom {@link RetryPolicy.shouldRetry} can compose with it
17
+ * rather than reimplement it.
9
18
  */
10
19
  declare function defaultShouldRetry(failure: RetryFailure): boolean;
11
20
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"retry.d.ts","names":[],"sources":["../src/retry.ts"],"sourcesContent":[],"mappings":";;;;;;;;;iBAwEgB,kBAAA,UAA4B"}
1
+ {"version":3,"file":"retry.d.ts","names":[],"sources":["../src/retry.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;iBAmHgB,kBAAA,UAA4B"}
package/dist/retry.js CHANGED
@@ -3,9 +3,11 @@ import { millisOrDurationToMillis } from "@restatedev/restate-sdk-core";
3
3
  //#region src/retry.ts
4
4
  const DEFAULT_RETRY_POLICY = {
5
5
  maxAttempts: 6,
6
- initialInterval: 100,
7
- maxInterval: 2e3,
8
- exponentiationFactor: 2
6
+ initialInterval: 250,
7
+ maxInterval: 3e3,
8
+ exponentiationFactor: 2,
9
+ respectRetryAfter: true,
10
+ maxDuration: 6e4
9
11
  };
10
12
  /**
11
13
  * Resolve a user supplied retry policy into a fully populated one.
@@ -18,37 +20,50 @@ function resolveRetryPolicy(retry) {
18
20
  if (retry === void 0 || retry === false) return;
19
21
  if (retry === true) return DEFAULT_RETRY_POLICY;
20
22
  return {
21
- maxAttempts: retry.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,
23
+ maxAttempts: retry.maxAttempts === false ? Infinity : retry.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,
22
24
  initialInterval: retry.initialInterval !== void 0 ? millisOrDurationToMillis(retry.initialInterval) : DEFAULT_RETRY_POLICY.initialInterval,
23
25
  maxInterval: retry.maxInterval !== void 0 ? millisOrDurationToMillis(retry.maxInterval) : DEFAULT_RETRY_POLICY.maxInterval,
24
26
  exponentiationFactor: retry.exponentiationFactor ?? DEFAULT_RETRY_POLICY.exponentiationFactor,
27
+ respectRetryAfter: retry.respectRetryAfter ?? DEFAULT_RETRY_POLICY.respectRetryAfter,
28
+ maxDuration: retry.maxDuration === false ? Infinity : retry.maxDuration !== void 0 ? millisOrDurationToMillis(retry.maxDuration) : DEFAULT_RETRY_POLICY.maxDuration,
25
29
  shouldRetry: retry.shouldRetry
26
30
  };
27
31
  }
28
- /** Whether an HTTP response status warrants a retry. */
32
+ /**
33
+ * Whether an HTTP response status is a transient ingress condition that
34
+ * warrants a retry: `408`, `425`, `429`, or any `5xx`.
35
+ */
29
36
  function isRetryableStatus(status) {
30
- return status === 429 || status >= 500 && status <= 599;
37
+ return status === 408 || status === 425 || status === 429 || status >= 500 && status <= 599;
31
38
  }
32
39
  /**
33
- * The built-in retry decision: retry network errors, HTTP `429`, and HTTP
34
- * `5xx`. Exported so a custom {@link RetryPolicy.shouldRetry} can compose with
35
- * it rather than reimplement it.
40
+ * The built-in retry decision. Retries network errors and responses with a
41
+ * transient status (`408`, `425`, `429`, or `5xx`) except errors restate
42
+ * attributes to the invocation itself, which are terminal outcomes of the
43
+ * durable execution and are never retried whatever their status code.
44
+ *
45
+ * restate-server discloses the origin via the `x-restate-error-source` header
46
+ * (`"invocation"` or `"ingress"`); when it is absent — a proxy stripped it, or
47
+ * an older server — the status alone drives the decision. See
48
+ * https://github.com/restatedev/restate/pull/5173.
49
+ *
50
+ * Exported so a custom {@link RetryPolicy.shouldRetry} can compose with it
51
+ * rather than reimplement it.
36
52
  */
37
53
  function defaultShouldRetry(failure) {
38
- return failure.kind === "network" || isRetryableStatus(failure.status);
54
+ if (failure.kind === "network") return true;
55
+ if (failure.headers.get("x-restate-error-source") === "invocation") return false;
56
+ return isRetryableStatus(failure.status);
39
57
  }
40
58
  /**
41
59
  * Compute the backoff for the given (zero based) attempt index using
42
- * exponential backoff with full jitter, capped at `maxInterval`.
43
- *
44
- * When the server provided an explicit `Retry-After` we honor it instead,
45
- * capped at `maxInterval` to avoid pathologically long waits.
60
+ * exponential backoff with ±20% jitter. The exponential base is capped at
61
+ * `maxInterval`; jitter is then applied on top, so the returned delay can sit
62
+ * up to 20% above `maxInterval`.
46
63
  */
47
- function backoffDelay(policy, attempt, retryAfterMs) {
48
- if (retryAfterMs !== void 0) return Math.min(retryAfterMs, policy.maxInterval);
64
+ function backoffDelay(policy, attempt) {
49
65
  const exp = policy.initialInterval * Math.pow(policy.exponentiationFactor, attempt);
50
- const ceiling = Math.min(exp, policy.maxInterval);
51
- return Math.random() * ceiling;
66
+ return Math.min(exp, policy.maxInterval) * (.8 + Math.random() * .4);
52
67
  }
53
68
  /**
54
69
  * Parse a `Retry-After` header value into milliseconds.
package/dist/retry.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"retry.js","names":["DEFAULT_RETRY_POLICY: ResolvedRetryPolicy","reason: unknown"],"sources":["../src/retry.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport { millisOrDurationToMillis } from \"@restatedev/restate-sdk-core\";\nimport type { RetryFailure, RetryPolicy } from \"./api.js\";\n\n/** Fully resolved retry policy, with all defaults applied. */\nexport interface ResolvedRetryPolicy {\n maxAttempts: number;\n initialInterval: number;\n maxInterval: number;\n exponentiationFactor: number;\n shouldRetry?: (failure: RetryFailure, attempt: number) => boolean;\n}\n\nconst DEFAULT_RETRY_POLICY: ResolvedRetryPolicy = {\n maxAttempts: 6,\n initialInterval: 100,\n maxInterval: 2000,\n exponentiationFactor: 2,\n};\n\n/**\n * Resolve a user supplied retry policy into a fully populated one.\n *\n * Retries are opt-in: returns `undefined` (disabled) when `retry` is omitted or\n * `false`. `true` enables the built-in policy; an object enables it with the\n * provided overrides.\n */\nexport function resolveRetryPolicy(\n retry: RetryPolicy | boolean | undefined\n): ResolvedRetryPolicy | undefined {\n if (retry === undefined || retry === false) {\n return undefined;\n }\n if (retry === true) {\n return DEFAULT_RETRY_POLICY;\n }\n return {\n maxAttempts: retry.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,\n initialInterval:\n retry.initialInterval !== undefined\n ? millisOrDurationToMillis(retry.initialInterval)\n : DEFAULT_RETRY_POLICY.initialInterval,\n maxInterval:\n retry.maxInterval !== undefined\n ? millisOrDurationToMillis(retry.maxInterval)\n : DEFAULT_RETRY_POLICY.maxInterval,\n exponentiationFactor:\n retry.exponentiationFactor ?? DEFAULT_RETRY_POLICY.exponentiationFactor,\n shouldRetry: retry.shouldRetry,\n };\n}\n\n/** Whether an HTTP response status warrants a retry. */\nexport function isRetryableStatus(status: number): boolean {\n return status === 429 || (status >= 500 && status <= 599);\n}\n\n/**\n * The built-in retry decision: retry network errors, HTTP `429`, and HTTP\n * `5xx`. Exported so a custom {@link RetryPolicy.shouldRetry} can compose with\n * it rather than reimplement it.\n */\nexport function defaultShouldRetry(failure: RetryFailure): boolean {\n return failure.kind === \"network\" || isRetryableStatus(failure.status);\n}\n\n/**\n * Compute the backoff for the given (zero based) attempt index using\n * exponential backoff with full jitter, capped at `maxInterval`.\n *\n * When the server provided an explicit `Retry-After` we honor it instead,\n * capped at `maxInterval` to avoid pathologically long waits.\n */\nexport function backoffDelay(\n policy: ResolvedRetryPolicy,\n attempt: number,\n retryAfterMs?: number\n): number {\n if (retryAfterMs !== undefined) {\n return Math.min(retryAfterMs, policy.maxInterval);\n }\n const exp =\n policy.initialInterval * Math.pow(policy.exponentiationFactor, attempt);\n const ceiling = Math.min(exp, policy.maxInterval);\n // full jitter: random in [0, ceiling]\n return Math.random() * ceiling;\n}\n\n/**\n * Parse a `Retry-After` header value into milliseconds.\n *\n * Supports both the delay-seconds form (`\"120\"`) and the HTTP-date form\n * (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`). Returns `undefined` when absent or\n * unparseable.\n */\nexport function parseRetryAfter(\n headers: Headers,\n now: number = Date.now()\n): number | undefined {\n const value = headers.get(\"retry-after\");\n if (!value) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * 1000);\n }\n const dateMs = Date.parse(value);\n if (Number.isNaN(dateMs)) {\n return undefined;\n }\n return Math.max(0, dateMs - now);\n}\n\n/**\n * Sleep for `ms`, rejecting early if `signal` aborts in the meantime.\n */\nexport function abortableSleep(\n ms: number,\n signal?: AbortSignal\n): Promise<void> {\n const abortError = (): Error => {\n const reason: unknown = signal?.reason;\n return reason instanceof Error\n ? reason\n : new Error(\"The operation was aborted\");\n };\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError());\n return;\n }\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortError());\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"],"mappings":";;;AAuBA,MAAMA,uBAA4C;CAChD,aAAa;CACb,iBAAiB;CACjB,aAAa;CACb,sBAAsB;CACvB;;;;;;;;AASD,SAAgB,mBACd,OACiC;AACjC,KAAI,UAAU,UAAa,UAAU,MACnC;AAEF,KAAI,UAAU,KACZ,QAAO;AAET,QAAO;EACL,aAAa,MAAM,eAAe,qBAAqB;EACvD,iBACE,MAAM,oBAAoB,SACtB,yBAAyB,MAAM,gBAAgB,GAC/C,qBAAqB;EAC3B,aACE,MAAM,gBAAgB,SAClB,yBAAyB,MAAM,YAAY,GAC3C,qBAAqB;EAC3B,sBACE,MAAM,wBAAwB,qBAAqB;EACrD,aAAa,MAAM;EACpB;;;AAIH,SAAgB,kBAAkB,QAAyB;AACzD,QAAO,WAAW,OAAQ,UAAU,OAAO,UAAU;;;;;;;AAQvD,SAAgB,mBAAmB,SAAgC;AACjE,QAAO,QAAQ,SAAS,aAAa,kBAAkB,QAAQ,OAAO;;;;;;;;;AAUxE,SAAgB,aACd,QACA,SACA,cACQ;AACR,KAAI,iBAAiB,OACnB,QAAO,KAAK,IAAI,cAAc,OAAO,YAAY;CAEnD,MAAM,MACJ,OAAO,kBAAkB,KAAK,IAAI,OAAO,sBAAsB,QAAQ;CACzE,MAAM,UAAU,KAAK,IAAI,KAAK,OAAO,YAAY;AAEjD,QAAO,KAAK,QAAQ,GAAG;;;;;;;;;AAUzB,SAAgB,gBACd,SACA,MAAc,KAAK,KAAK,EACJ;CACpB,MAAM,QAAQ,QAAQ,IAAI,cAAc;AACxC,KAAI,CAAC,MACH;CAEF,MAAM,UAAU,OAAO,MAAM;AAC7B,KAAI,OAAO,SAAS,QAAQ,CAC1B,QAAO,KAAK,IAAI,GAAG,UAAU,IAAK;CAEpC,MAAM,SAAS,KAAK,MAAM,MAAM;AAChC,KAAI,OAAO,MAAM,OAAO,CACtB;AAEF,QAAO,KAAK,IAAI,GAAG,SAAS,IAAI;;;;;AAMlC,SAAgB,eACd,IACA,QACe;CACf,MAAM,mBAA0B;EAC9B,MAAMC,SAAkB,QAAQ;AAChC,SAAO,kBAAkB,QACrB,yBACA,IAAI,MAAM,4BAA4B;;AAE5C,QAAO,IAAI,SAAS,SAAS,WAAW;AACtC,MAAI,QAAQ,SAAS;AACnB,UAAO,YAAY,CAAC;AACpB;;EAEF,MAAM,gBAAgB;AACpB,gBAAa,MAAM;AACnB,UAAO,YAAY,CAAC;;EAEtB,MAAM,QAAQ,iBAAiB;AAC7B,WAAQ,oBAAoB,SAAS,QAAQ;AAC7C,YAAS;KACR,GAAG;AACN,UAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,MAAM,CAAC;GAC1D"}
1
+ {"version":3,"file":"retry.js","names":["DEFAULT_RETRY_POLICY: ResolvedRetryPolicy","reason: unknown"],"sources":["../src/retry.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport { millisOrDurationToMillis } from \"@restatedev/restate-sdk-core\";\nimport type { RetryFailure, RetryPolicy } from \"./api.js\";\n\n/** Fully resolved retry policy, with all defaults applied. */\nexport interface ResolvedRetryPolicy {\n /**\n * `Infinity` means retries are not bounded by attempt count (the user passed\n * `maxAttempts: false`).\n */\n maxAttempts: number;\n initialInterval: number;\n maxInterval: number;\n exponentiationFactor: number;\n respectRetryAfter: boolean;\n /**\n * In milliseconds. `Infinity` means retries are not bounded by duration (the\n * user passed `maxDuration: false`).\n */\n maxDuration: number;\n shouldRetry?: (failure: RetryFailure, attempt: number) => boolean;\n}\n\nconst DEFAULT_RETRY_POLICY: ResolvedRetryPolicy = {\n maxAttempts: 6,\n initialInterval: 250,\n maxInterval: 3000,\n exponentiationFactor: 2,\n respectRetryAfter: true,\n maxDuration: 60_000,\n};\n\n/**\n * Resolve a user supplied retry policy into a fully populated one.\n *\n * Retries are opt-in: returns `undefined` (disabled) when `retry` is omitted or\n * `false`. `true` enables the built-in policy; an object enables it with the\n * provided overrides.\n */\nexport function resolveRetryPolicy(\n retry: RetryPolicy | boolean | undefined\n): ResolvedRetryPolicy | undefined {\n if (retry === undefined || retry === false) {\n return undefined;\n }\n if (retry === true) {\n return DEFAULT_RETRY_POLICY;\n }\n return {\n // `false` disables the bound (Infinity); otherwise the override or default.\n maxAttempts:\n retry.maxAttempts === false\n ? Infinity\n : (retry.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts),\n initialInterval:\n retry.initialInterval !== undefined\n ? millisOrDurationToMillis(retry.initialInterval)\n : DEFAULT_RETRY_POLICY.initialInterval,\n maxInterval:\n retry.maxInterval !== undefined\n ? millisOrDurationToMillis(retry.maxInterval)\n : DEFAULT_RETRY_POLICY.maxInterval,\n exponentiationFactor:\n retry.exponentiationFactor ?? DEFAULT_RETRY_POLICY.exponentiationFactor,\n respectRetryAfter:\n retry.respectRetryAfter ?? DEFAULT_RETRY_POLICY.respectRetryAfter,\n // Defaults to 60s; `false` disables the duration bound (Infinity), relying\n // on maxAttempts alone.\n maxDuration:\n retry.maxDuration === false\n ? Infinity\n : retry.maxDuration !== undefined\n ? millisOrDurationToMillis(retry.maxDuration)\n : DEFAULT_RETRY_POLICY.maxDuration,\n shouldRetry: retry.shouldRetry,\n };\n}\n\n/**\n * Whether an HTTP response status is a transient ingress condition that\n * warrants a retry: `408`, `425`, `429`, or any `5xx`.\n */\nexport function isRetryableStatus(status: number): boolean {\n return (\n status === 408 ||\n status === 425 ||\n status === 429 ||\n (status >= 500 && status <= 599)\n );\n}\n\n/**\n * The built-in retry decision. Retries network errors and responses with a\n * transient status (`408`, `425`, `429`, or `5xx`) — except errors restate\n * attributes to the invocation itself, which are terminal outcomes of the\n * durable execution and are never retried whatever their status code.\n *\n * restate-server discloses the origin via the `x-restate-error-source` header\n * (`\"invocation\"` or `\"ingress\"`); when it is absent — a proxy stripped it, or\n * an older server — the status alone drives the decision. See\n * https://github.com/restatedev/restate/pull/5173.\n *\n * Exported so a custom {@link RetryPolicy.shouldRetry} can compose with it\n * rather than reimplement it.\n */\nexport function defaultShouldRetry(failure: RetryFailure): boolean {\n if (failure.kind === \"network\") {\n return true;\n }\n // An invocation-sourced error is the terminal result of the durable\n // execution; retrying it re-runs nothing and never changes the outcome.\n if (failure.headers.get(\"x-restate-error-source\") === \"invocation\") {\n return false;\n }\n return isRetryableStatus(failure.status);\n}\n\n/**\n * Compute the backoff for the given (zero based) attempt index using\n * exponential backoff with ±20% jitter. The exponential base is capped at\n * `maxInterval`; jitter is then applied on top, so the returned delay can sit\n * up to 20% above `maxInterval`.\n */\nexport function backoffDelay(\n policy: ResolvedRetryPolicy,\n attempt: number\n): number {\n const exp =\n policy.initialInterval * Math.pow(policy.exponentiationFactor, attempt);\n const base = Math.min(exp, policy.maxInterval);\n // ±20% jitter keeps clients from retrying in lockstep after a shared blip.\n return base * (0.8 + Math.random() * 0.4);\n}\n\n/**\n * Parse a `Retry-After` header value into milliseconds.\n *\n * Supports both the delay-seconds form (`\"120\"`) and the HTTP-date form\n * (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`). Returns `undefined` when absent or\n * unparseable.\n */\nexport function parseRetryAfter(\n headers: Headers,\n now: number = Date.now()\n): number | undefined {\n const value = headers.get(\"retry-after\");\n if (!value) {\n return undefined;\n }\n const seconds = Number(value);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * 1000);\n }\n const dateMs = Date.parse(value);\n if (Number.isNaN(dateMs)) {\n return undefined;\n }\n return Math.max(0, dateMs - now);\n}\n\n/**\n * Sleep for `ms`, rejecting early if `signal` aborts in the meantime.\n */\nexport function abortableSleep(\n ms: number,\n signal?: AbortSignal\n): Promise<void> {\n const abortError = (): Error => {\n const reason: unknown = signal?.reason;\n return reason instanceof Error\n ? reason\n : new Error(\"The operation was aborted\");\n };\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError());\n return;\n }\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortError());\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n"],"mappings":";;;AAiCA,MAAMA,uBAA4C;CAChD,aAAa;CACb,iBAAiB;CACjB,aAAa;CACb,sBAAsB;CACtB,mBAAmB;CACnB,aAAa;CACd;;;;;;;;AASD,SAAgB,mBACd,OACiC;AACjC,KAAI,UAAU,UAAa,UAAU,MACnC;AAEF,KAAI,UAAU,KACZ,QAAO;AAET,QAAO;EAEL,aACE,MAAM,gBAAgB,QAClB,WACC,MAAM,eAAe,qBAAqB;EACjD,iBACE,MAAM,oBAAoB,SACtB,yBAAyB,MAAM,gBAAgB,GAC/C,qBAAqB;EAC3B,aACE,MAAM,gBAAgB,SAClB,yBAAyB,MAAM,YAAY,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