@orpc/client 2.0.0-beta.46 → 2.0.0-beta.48
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.
- package/README.md +6 -4
- package/dist/adapters/fetch/index.d.mts +2 -48
- package/dist/adapters/fetch/index.mjs +2 -77
- package/dist/adapters/fetch/rpc-link.d.mts +13 -0
- package/dist/adapters/fetch/rpc-link.mjs +10 -0
- package/dist/adapters/fetch/transport.d.mts +31 -0
- package/dist/adapters/fetch/transport.mjs +65 -0
- package/dist/adapters/message-port/index.d.mts +3 -80
- package/dist/adapters/message-port/index.mjs +3 -101
- package/dist/adapters/message-port/message-port.d.mts +29 -0
- package/dist/adapters/message-port/message-port.mjs +43 -0
- package/dist/adapters/message-port/rpc-link.d.mts +14 -0
- package/dist/adapters/message-port/rpc-link.mjs +10 -0
- package/dist/adapters/message-port/transport.d.mts +35 -0
- package/dist/adapters/message-port/transport.mjs +47 -0
- package/dist/adapters/standard/codec.d.mts +14 -0
- package/dist/adapters/standard/codec.mjs +1 -0
- package/dist/adapters/standard/index.d.mts +5 -60
- package/dist/adapters/standard/index.mjs +4 -6
- package/dist/adapters/standard/link.d.mts +40 -0
- package/dist/adapters/standard/link.mjs +79 -0
- package/dist/adapters/standard/plugin.d.mts +32 -0
- package/dist/adapters/standard/plugin.mjs +16 -0
- package/dist/adapters/standard/rpc-link-codec.d.mts +55 -0
- package/dist/adapters/standard/rpc-link-codec.mjs +104 -0
- package/dist/adapters/standard/transport.d.mts +14 -0
- package/dist/adapters/standard/transport.mjs +1 -0
- package/dist/adapters/websocket/index.d.mts +2 -136
- package/dist/adapters/websocket/index.mjs +2 -131
- package/dist/adapters/websocket/rpc-link.d.mts +13 -0
- package/dist/adapters/websocket/rpc-link.mjs +10 -0
- package/dist/adapters/websocket/transport.d.mts +119 -0
- package/dist/adapters/websocket/transport.mjs +123 -0
- package/dist/async-iterator-object.d.mts +7 -0
- package/dist/async-iterator-object.mjs +30 -0
- package/dist/client-safe.d.mts +16 -0
- package/dist/client-safe.mjs +23 -0
- package/dist/client.d.mts +51 -0
- package/dist/client.mjs +32 -0
- package/dist/consts.d.mts +10 -0
- package/dist/consts.mjs +10 -0
- package/dist/dynamic-link.d.mts +13 -0
- package/dist/dynamic-link.mjs +12 -0
- package/dist/error-utils.d.mts +24 -0
- package/dist/error-utils.mjs +44 -0
- package/dist/error.d.mts +138 -0
- package/dist/error.mjs +105 -0
- package/dist/index.d.mts +42 -137
- package/dist/index.mjs +18 -142
- package/dist/plugins/batch.d.mts +150 -0
- package/dist/plugins/batch.mjs +339 -0
- package/dist/plugins/cookie-jar.d.mts +82 -0
- package/dist/plugins/cookie-jar.mjs +229 -0
- package/dist/plugins/dedupe.d.mts +58 -0
- package/dist/plugins/dedupe.mjs +199 -0
- package/dist/plugins/index.d.mts +28 -420
- package/dist/plugins/index.mjs +17 -971
- package/dist/plugins/request-compression.d.mts +44 -0
- package/dist/plugins/request-compression.mjs +150 -0
- package/dist/plugins/response-compression.d.mts +28 -0
- package/dist/plugins/response-compression.mjs +78 -0
- package/dist/plugins/retry-after.d.mts +41 -0
- package/dist/plugins/retry-after.mjs +71 -0
- package/dist/plugins/retry.d.mts +82 -0
- package/dist/plugins/retry.mjs +127 -0
- package/dist/plugins/timeout.d.mts +25 -0
- package/dist/plugins/timeout.mjs +36 -0
- package/dist/rpc-json-serializer.d.mts +99 -0
- package/dist/rpc-json-serializer.mjs +365 -0
- package/dist/rpc-serializer.d.mts +32 -0
- package/dist/rpc-serializer.mjs +100 -0
- package/dist/types.d.mts +93 -0
- package/dist/types.mjs +1 -0
- package/dist/utils.d.mts +46 -0
- package/dist/utils.mjs +53 -0
- package/package.json +5 -5
- package/dist/adapters/fetch/index.d.ts +0 -48
- package/dist/adapters/message-port/index.d.ts +0 -80
- package/dist/adapters/standard/index.d.ts +0 -60
- package/dist/adapters/websocket/index.d.ts +0 -136
- package/dist/index.d.ts +0 -144
- package/dist/plugins/index.d.ts +0 -420
- package/dist/shared/client.BoHJeq15.d.mts +0 -233
- package/dist/shared/client.BoHJeq15.d.ts +0 -233
- package/dist/shared/client.CKQeJJ2U.mjs +0 -172
- package/dist/shared/client.DqIWeNhQ.d.mts +0 -131
- package/dist/shared/client.DqIWeNhQ.d.ts +0 -131
- package/dist/shared/client.JBJwBhR8.d.ts +0 -90
- package/dist/shared/client.LF04eOvL.mjs +0 -115
- package/dist/shared/client._wG5INmC.mjs +0 -505
- package/dist/shared/client.euYjjcFz.d.mts +0 -90
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from "../adapters/standard/index.mjs";
|
|
2
|
+
import type { ClientContext } from "../types.mjs";
|
|
3
|
+
export interface RequestCompressionLinkPluginOptions<T extends ClientContext> {
|
|
4
|
+
/**
|
|
5
|
+
* The compression scheme to use for request compression.
|
|
6
|
+
*
|
|
7
|
+
* @default 'gzip'
|
|
8
|
+
*/
|
|
9
|
+
encoding?: "gzip" | "deflate" | "deflate-raw" | undefined;
|
|
10
|
+
/**
|
|
11
|
+
* The minimum request size in bytes required to trigger compression.
|
|
12
|
+
* Requests smaller than this threshold will not be compressed to avoid overhead.
|
|
13
|
+
* If the request size cannot be determined, compression will still be applied.
|
|
14
|
+
*
|
|
15
|
+
* @default 1024 (1KB)
|
|
16
|
+
*/
|
|
17
|
+
threshold?: number | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* Determines whether a request with the given Content-Type should be compressed.
|
|
20
|
+
* Only consulted for binary transfers (streams, files, and file form-data parts).
|
|
21
|
+
* Also receives the transport interceptor options for per-request decisions.
|
|
22
|
+
*
|
|
23
|
+
* @default isCompressibleContentType (covers common text-based formats)
|
|
24
|
+
*/
|
|
25
|
+
isCompressibleContentType?: ((contentType: string | null | undefined, options: StandardLinkTransportInterceptorOptions<T>) => boolean) | undefined;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Compresses request bodies before sending them to the server,
|
|
29
|
+
* reducing bandwidth usage for large payloads.
|
|
30
|
+
*
|
|
31
|
+
* @see {@link https://orpc.dev/docs/plugins/request-compression | Request Compression Plugin}
|
|
32
|
+
*/
|
|
33
|
+
export declare class RequestCompressionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
34
|
+
name: string;
|
|
35
|
+
/**
|
|
36
|
+
* Compression should be done after batching, to compress the final request
|
|
37
|
+
*/
|
|
38
|
+
after: string[];
|
|
39
|
+
private readonly encoding;
|
|
40
|
+
private readonly threshold;
|
|
41
|
+
private readonly isCompressibleContentType;
|
|
42
|
+
constructor(options?: RequestCompressionLinkPluginOptions<T>);
|
|
43
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
44
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { isAsyncIteratorObject, isCompressibleContentType, toArray } from "@orpc/shared";
|
|
2
|
+
import { flattenStandardHeader, generateContentDisposition } from "@standard-server/core";
|
|
3
|
+
import { toFetchBody } from "@standard-server/fetch";
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
const AVG_BYTES_PER_CHAR = 1.2;
|
|
7
|
+
|
|
8
|
+
export class RequestCompressionLinkPlugin {
|
|
9
|
+
name = "~request-compression";
|
|
10
|
+
|
|
11
|
+
after = ["~batch"];
|
|
12
|
+
encoding;
|
|
13
|
+
threshold;
|
|
14
|
+
isCompressibleContentType;
|
|
15
|
+
constructor(options = {}) {
|
|
16
|
+
this.encoding = options.encoding ?? "gzip";
|
|
17
|
+
this.threshold = options.threshold ?? 1024;
|
|
18
|
+
this.isCompressibleContentType = options.isCompressibleContentType ?? isCompressibleContentType;
|
|
19
|
+
}
|
|
20
|
+
init(options) {
|
|
21
|
+
const transportInterceptor = async ({ next, ...interceptorOptions }) => {
|
|
22
|
+
const request = interceptorOptions.request;
|
|
23
|
+
const contentEncoding = flattenStandardHeader(request.headers["content-encoding"])?.trim()?.toLowerCase();
|
|
24
|
+
if (contentEncoding !== undefined) {
|
|
25
|
+
return next();
|
|
26
|
+
}
|
|
27
|
+
if (request.body instanceof ReadableStream) {
|
|
28
|
+
const contentLength = Number(flattenStandardHeader(request.headers["content-length"]));
|
|
29
|
+
if ((!Number.isFinite(contentLength) || contentLength >= this.threshold) && this.isCompressibleContentType(flattenStandardHeader(request.headers["content-type"]), interceptorOptions)) {
|
|
30
|
+
const compressedStream = request.body.pipeThrough(new CompressionStream(this.encoding));
|
|
31
|
+
return next({
|
|
32
|
+
...interceptorOptions,
|
|
33
|
+
request: {
|
|
34
|
+
...interceptorOptions.request,
|
|
35
|
+
body: compressedStream,
|
|
36
|
+
headers: {
|
|
37
|
+
...request.headers,
|
|
38
|
+
"content-length": [],
|
|
39
|
+
"content-encoding": this.encoding
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
} else if (request.body instanceof Blob) {
|
|
45
|
+
const contentType = request.headers["content-type"] ?? request.body.type;
|
|
46
|
+
if ((!Number.isFinite(request.body.size) || request.body.size >= this.threshold) && this.isCompressibleContentType(flattenStandardHeader(contentType), interceptorOptions)) {
|
|
47
|
+
const compressedStream = request.body.stream().pipeThrough(new CompressionStream(this.encoding));
|
|
48
|
+
const contentDisposition = request.headers["content-disposition"] ?? generateContentDisposition(request.body instanceof File ? request.body.name : "blob");
|
|
49
|
+
return next({
|
|
50
|
+
...interceptorOptions,
|
|
51
|
+
request: {
|
|
52
|
+
...interceptorOptions.request,
|
|
53
|
+
body: compressedStream,
|
|
54
|
+
headers: {
|
|
55
|
+
...request.headers,
|
|
56
|
+
"standard-server": request.headers["standard-server"] ?? "file",
|
|
57
|
+
"content-type": contentType,
|
|
58
|
+
"content-length": [],
|
|
59
|
+
"content-disposition": contentDisposition,
|
|
60
|
+
"content-encoding": this.encoding
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
} else if (request.body instanceof FormData) {
|
|
66
|
+
const PART_OVERHEAD = 64;
|
|
67
|
+
let contentLength = 0;
|
|
68
|
+
for (const [key, value] of request.body) {
|
|
69
|
+
contentLength += PART_OVERHEAD + key.length;
|
|
70
|
+
if (value instanceof Blob) {
|
|
71
|
+
if (!Number.isFinite(value.size)) {
|
|
72
|
+
if (!this.isCompressibleContentType(value.type, interceptorOptions)) {
|
|
73
|
+
|
|
74
|
+
contentLength = -Infinity;
|
|
75
|
+
break;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
contentLength = Infinity;
|
|
79
|
+
} else {
|
|
80
|
+
contentLength += this.isCompressibleContentType(value.type, interceptorOptions) ? value.size : -value.size;
|
|
81
|
+
}
|
|
82
|
+
} else {
|
|
83
|
+
contentLength += value.length * AVG_BYTES_PER_CHAR;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (contentLength >= this.threshold) {
|
|
87
|
+
const res = new Response(request.body);
|
|
88
|
+
const compressedStream = res.body.pipeThrough(new CompressionStream(this.encoding));
|
|
89
|
+
return next({
|
|
90
|
+
...interceptorOptions,
|
|
91
|
+
request: {
|
|
92
|
+
...interceptorOptions.request,
|
|
93
|
+
body: compressedStream,
|
|
94
|
+
headers: {
|
|
95
|
+
...request.headers,
|
|
96
|
+
"standard-server": [],
|
|
97
|
+
"content-type": res.headers.get("content-type"),
|
|
98
|
+
"content-length": [],
|
|
99
|
+
"content-encoding": this.encoding
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
} else if (request.body instanceof URLSearchParams) {
|
|
105
|
+
const string = request.body.toString();
|
|
106
|
+
if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
|
|
107
|
+
const compressedStream = new Blob([string]).stream().pipeThrough(new CompressionStream(this.encoding));
|
|
108
|
+
const [, bodyHeaders] = toFetchBody(request.body, request.headers);
|
|
109
|
+
return next({
|
|
110
|
+
...interceptorOptions,
|
|
111
|
+
request: {
|
|
112
|
+
...interceptorOptions.request,
|
|
113
|
+
body: compressedStream,
|
|
114
|
+
headers: {
|
|
115
|
+
...bodyHeaders,
|
|
116
|
+
|
|
117
|
+
"standard-server": bodyHeaders["standard-server"] ?? [],
|
|
118
|
+
"content-length": [],
|
|
119
|
+
"content-encoding": this.encoding
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
} else if (request.body !== undefined && !isAsyncIteratorObject(request.body)) {
|
|
125
|
+
const [string, bodyHeaders] = toFetchBody(request.body, request.headers);
|
|
126
|
+
if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
|
|
127
|
+
const compressedStream = new Blob([string]).stream().pipeThrough(new CompressionStream(this.encoding));
|
|
128
|
+
return next({
|
|
129
|
+
...interceptorOptions,
|
|
130
|
+
request: {
|
|
131
|
+
...interceptorOptions.request,
|
|
132
|
+
body: compressedStream,
|
|
133
|
+
headers: {
|
|
134
|
+
...bodyHeaders,
|
|
135
|
+
"standard-server": bodyHeaders["standard-server"] ?? [],
|
|
136
|
+
"content-length": [],
|
|
137
|
+
"content-encoding": this.encoding
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return next();
|
|
144
|
+
};
|
|
145
|
+
return {
|
|
146
|
+
...options,
|
|
147
|
+
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { StandardLinkOptions, StandardLinkPlugin } from "../adapters/standard/index.mjs";
|
|
2
|
+
import type { ClientContext } from "../types.mjs";
|
|
3
|
+
export interface ResponseCompressionLinkPluginOptions<_T extends ClientContext> {
|
|
4
|
+
/**
|
|
5
|
+
* Compression schemes to advertise via Accept-Encoding, in preference order.
|
|
6
|
+
* Only schemes that can be decompressed by this plugin should be listed.
|
|
7
|
+
*
|
|
8
|
+
* @default ['gzip', 'deflate']
|
|
9
|
+
*/
|
|
10
|
+
encodings?: readonly ("gzip" | "deflate" | "deflate-raw")[] | undefined;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Advertises Accept-Encoding on requests and decompresses response bodies
|
|
14
|
+
* based on the Content-Encoding header. Works at the standard link level,
|
|
15
|
+
* so it supports all adapters.
|
|
16
|
+
*
|
|
17
|
+
* @see {@link https://orpc.dev/docs/plugins/response-compression | Response Compression Plugin}
|
|
18
|
+
*/
|
|
19
|
+
export declare class ResponseCompressionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
20
|
+
name: string;
|
|
21
|
+
/**
|
|
22
|
+
* Decompression should wrap the final batch response instead of sub-responses.
|
|
23
|
+
*/
|
|
24
|
+
after: string[];
|
|
25
|
+
private readonly encodings;
|
|
26
|
+
constructor(options?: ResponseCompressionLinkPluginOptions<T>);
|
|
27
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
28
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { toArray } from "@orpc/shared";
|
|
2
|
+
import { flattenStandardHeader } from "@standard-server/core";
|
|
3
|
+
import { toFetchHeaders, toStandardBody } from "@standard-server/fetch";
|
|
4
|
+
|
|
5
|
+
const MAX_CONTENT_ENCODINGS = 5;
|
|
6
|
+
|
|
7
|
+
export class ResponseCompressionLinkPlugin {
|
|
8
|
+
name = "~response-compression";
|
|
9
|
+
|
|
10
|
+
after = ["~batch"];
|
|
11
|
+
encodings;
|
|
12
|
+
constructor(options = {}) {
|
|
13
|
+
this.encodings = options.encodings ?? ["gzip", "deflate"];
|
|
14
|
+
}
|
|
15
|
+
init(options) {
|
|
16
|
+
const acceptEncodingHeader = this.encodings.join(", ");
|
|
17
|
+
const transportInterceptor = async ({ next, ...interceptorOptions }) => {
|
|
18
|
+
const response = await next({
|
|
19
|
+
...interceptorOptions,
|
|
20
|
+
request: {
|
|
21
|
+
...interceptorOptions.request,
|
|
22
|
+
headers: {
|
|
23
|
+
...interceptorOptions.request.headers,
|
|
24
|
+
"accept-encoding": acceptEncodingHeader
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
const encodings = parseContentEncodings(flattenStandardHeader(response.headers["content-encoding"]));
|
|
29
|
+
if (encodings.length === 0 || !encodings.every(isSupportedEncoding)) {
|
|
30
|
+
return response;
|
|
31
|
+
}
|
|
32
|
+
const decompressedHeaders = {
|
|
33
|
+
...response.headers,
|
|
34
|
+
"content-length": undefined,
|
|
35
|
+
"content-encoding": undefined
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
...response,
|
|
39
|
+
headers: decompressedHeaders,
|
|
40
|
+
async resolveBody(hint) {
|
|
41
|
+
const stream = await response.resolveBody("octet-stream");
|
|
42
|
+
|
|
43
|
+
if (!(stream instanceof ReadableStream)) {
|
|
44
|
+
return stream;
|
|
45
|
+
}
|
|
46
|
+
if (encodings.length > MAX_CONTENT_ENCODINGS) {
|
|
47
|
+
throw new TypeError("Too many content encodings.");
|
|
48
|
+
}
|
|
49
|
+
let decompressedStream = stream;
|
|
50
|
+
for (let i = encodings.length - 1; i >= 0; i--) {
|
|
51
|
+
decompressedStream = decompressedStream.pipeThrough(new DecompressionStream(encodings[i]));
|
|
52
|
+
}
|
|
53
|
+
const fetchResponse = new Response(decompressedStream, { headers: toFetchHeaders(decompressedHeaders) });
|
|
54
|
+
return toStandardBody(fetchResponse, { hint });
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
return {
|
|
59
|
+
...options,
|
|
60
|
+
transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const SUPPORTED_ENCODINGS = [
|
|
65
|
+
"gzip",
|
|
66
|
+
"deflate",
|
|
67
|
+
"deflate-raw"
|
|
68
|
+
];
|
|
69
|
+
function isSupportedEncoding(encoding) {
|
|
70
|
+
return SUPPORTED_ENCODINGS.includes(encoding);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function parseContentEncodings(header) {
|
|
74
|
+
if (header === undefined) {
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
return header.split(",").map((part) => part.trim().toLowerCase());
|
|
78
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Value } from "@orpc/shared";
|
|
2
|
+
import type { StandardLazyResponse } from "@standard-server/core";
|
|
3
|
+
import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from "../adapters/standard/index.mjs";
|
|
4
|
+
import type { ClientContext } from "../types.mjs";
|
|
5
|
+
export interface RetryAfterLinkPluginOptions<T extends ClientContext> {
|
|
6
|
+
/**
|
|
7
|
+
* Override condition to determine whether to retry or not.
|
|
8
|
+
*
|
|
9
|
+
* @default ((response) => response.status === 429 || response.status === 503)
|
|
10
|
+
*/
|
|
11
|
+
condition?: Value<boolean, [response: StandardLazyResponse, options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* Maximum attempts before giving up retries.
|
|
14
|
+
*
|
|
15
|
+
* @default 3
|
|
16
|
+
*/
|
|
17
|
+
maxAttempts?: Value<number, [response: StandardLazyResponse, options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* Maximum timeout in milliseconds to wait before giving up retries.
|
|
20
|
+
*
|
|
21
|
+
* @default 5 * 60 * 1000 (5 minutes)
|
|
22
|
+
*/
|
|
23
|
+
timeout?: Value<number, [response: StandardLazyResponse, options: StandardLinkTransportInterceptorOptions<T>]> | undefined;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The Retry After Link Plugin automatically retries requests based on server `retry-after` header.
|
|
27
|
+
* This is particularly useful for handling rate limiting and temporary server unavailability.
|
|
28
|
+
*
|
|
29
|
+
* @remarks
|
|
30
|
+
* **Note**: Requests with a stream or async iterator body are never retried, since the body cannot be resent.
|
|
31
|
+
*
|
|
32
|
+
* @see {@link https://orpc.dev/docs/plugins/retry-after | Retry After Plugin}
|
|
33
|
+
*/
|
|
34
|
+
export declare class RetryAfterLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
35
|
+
private readonly condition;
|
|
36
|
+
private readonly maxAttempts;
|
|
37
|
+
private readonly timeout;
|
|
38
|
+
name: string;
|
|
39
|
+
constructor(options?: RetryAfterLinkPluginOptions<T>);
|
|
40
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
41
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { isAsyncIteratorObject, sleep, toArray, value } from "@orpc/shared";
|
|
2
|
+
import { flattenStandardHeader } from "@standard-server/core";
|
|
3
|
+
import { COMMON_ERROR_STATUS_MAP } from "../error.mjs";
|
|
4
|
+
|
|
5
|
+
export class RetryAfterLinkPlugin {
|
|
6
|
+
condition;
|
|
7
|
+
maxAttempts;
|
|
8
|
+
timeout;
|
|
9
|
+
name = "~retry-after";
|
|
10
|
+
constructor(options = {}) {
|
|
11
|
+
this.condition = options.condition ?? ((response) => response.status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS || response.status === COMMON_ERROR_STATUS_MAP.SERVICE_UNAVAILABLE);
|
|
12
|
+
this.maxAttempts = options.maxAttempts ?? 3;
|
|
13
|
+
this.timeout = options.timeout ?? 5 * 60 * 1e3;
|
|
14
|
+
}
|
|
15
|
+
init(options) {
|
|
16
|
+
const interceptor = async (interceptorOptions) => {
|
|
17
|
+
const { body } = interceptorOptions.request;
|
|
18
|
+
|
|
19
|
+
if (body instanceof ReadableStream || isAsyncIteratorObject(body)) {
|
|
20
|
+
return interceptorOptions.next();
|
|
21
|
+
}
|
|
22
|
+
const startTime = Date.now();
|
|
23
|
+
let attemptCount = 0;
|
|
24
|
+
while (true) {
|
|
25
|
+
attemptCount++;
|
|
26
|
+
const response = await interceptorOptions.next();
|
|
27
|
+
if (!value(this.condition, response, interceptorOptions)) {
|
|
28
|
+
return response;
|
|
29
|
+
}
|
|
30
|
+
const retryAfterHeader = flattenStandardHeader(response.headers["retry-after"]);
|
|
31
|
+
const retryAfterMs = parseRetryAfterHeader(retryAfterHeader);
|
|
32
|
+
if (retryAfterMs === undefined) {
|
|
33
|
+
return response;
|
|
34
|
+
}
|
|
35
|
+
if (attemptCount >= value(this.maxAttempts, response, interceptorOptions)) {
|
|
36
|
+
return response;
|
|
37
|
+
}
|
|
38
|
+
const timeoutMs = value(this.timeout, response, interceptorOptions);
|
|
39
|
+
const elapsedTime = Date.now() - startTime;
|
|
40
|
+
if (elapsedTime + retryAfterMs > timeoutMs) {
|
|
41
|
+
return response;
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
await sleep(retryAfterMs, { signal: interceptorOptions.signal });
|
|
45
|
+
} catch {}
|
|
46
|
+
if (interceptorOptions.signal?.aborted) {
|
|
47
|
+
return response;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
return {
|
|
52
|
+
...options,
|
|
53
|
+
transportInterceptors: [interceptor, ...toArray(options.transportInterceptors)]
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function parseRetryAfterHeader(value) {
|
|
58
|
+
value = value?.trim();
|
|
59
|
+
if (!value) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
const seconds = Number(value);
|
|
63
|
+
if (Number.isFinite(seconds)) {
|
|
64
|
+
return Math.max(0, seconds * 1e3);
|
|
65
|
+
}
|
|
66
|
+
const retryDate = Date.parse(value);
|
|
67
|
+
if (!Number.isNaN(retryDate)) {
|
|
68
|
+
return Math.max(0, retryDate - Date.now());
|
|
69
|
+
}
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { Promisable, Value } from "@orpc/shared";
|
|
2
|
+
import type { StandardLinkInterceptorOptions, StandardLinkOptions, StandardLinkPlugin } from "../adapters/standard/index.mjs";
|
|
3
|
+
import type { ClientContext } from "../types.mjs";
|
|
4
|
+
export interface RetryLinkPluginAttemptOptions<T extends RetryLinkPluginContext> extends StandardLinkInterceptorOptions<T> {
|
|
5
|
+
/**
|
|
6
|
+
* Latest retry delay advertised by the server via event metadata.
|
|
7
|
+
*/
|
|
8
|
+
lastEventRetry: number | undefined;
|
|
9
|
+
/**
|
|
10
|
+
* Current retry attempt number, starting at 1.
|
|
11
|
+
*/
|
|
12
|
+
attempt: number;
|
|
13
|
+
/**
|
|
14
|
+
* Error that triggered this retry attempt.
|
|
15
|
+
*/
|
|
16
|
+
error: unknown;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Client context options that control retry behavior per call
|
|
20
|
+
* when the `RetryLinkPlugin` is enabled.
|
|
21
|
+
*
|
|
22
|
+
* @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
|
|
23
|
+
*/
|
|
24
|
+
export interface RetryLinkPluginContext {
|
|
25
|
+
/**
|
|
26
|
+
* Maximum retry attempts before throwing.
|
|
27
|
+
* Use `Number.POSITIVE_INFINITY` for infinite retries (e.g. for AsyncIteratorObject).
|
|
28
|
+
*
|
|
29
|
+
* @default 0
|
|
30
|
+
*/
|
|
31
|
+
retry?: Value<Promisable<number>, [Omit<StandardLinkInterceptorOptions<RetryLinkPluginContext>, "next">]> | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Delay (in ms) before retrying.
|
|
34
|
+
*
|
|
35
|
+
* @remarks
|
|
36
|
+
* **Note**: Why 2000ms? The EventSource spec suggests a default retry delay of 2 seconds if it doesn't specify
|
|
37
|
+
*
|
|
38
|
+
* @default (o) => o.lastEventRetry ?? 2000
|
|
39
|
+
*/
|
|
40
|
+
retryDelay?: Value<Promisable<number>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Determine whether to retry.
|
|
43
|
+
*
|
|
44
|
+
* @default (o) => isRetryableError(o.error)
|
|
45
|
+
*/
|
|
46
|
+
shouldRetry?: Value<Promisable<boolean>, [RetryLinkPluginAttemptOptions<RetryLinkPluginContext>]> | undefined;
|
|
47
|
+
/**
|
|
48
|
+
* Hook called before each retry. Can return a cleanup callback.
|
|
49
|
+
*/
|
|
50
|
+
onRetry?: ((options: RetryLinkPluginAttemptOptions<RetryLinkPluginContext>) => void | ((isSuccess: boolean) => void)) | undefined;
|
|
51
|
+
}
|
|
52
|
+
export interface RetryLinkPluginOptions<_T extends RetryLinkPluginContext> {
|
|
53
|
+
/**
|
|
54
|
+
* Default retry options. Can be overridden by individual calls via the context.
|
|
55
|
+
*/
|
|
56
|
+
default?: RetryLinkPluginContext | undefined;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Default `shouldRetry` check of `RetryLinkPlugin`. Returns `false` only for errors
|
|
60
|
+
* from a 4xx response other than `408` and `429`.
|
|
61
|
+
*
|
|
62
|
+
* @see {@link https://orpc.dev/docs/plugins/retry#client-error-responses | Retry Plugin - Client Error Responses}
|
|
63
|
+
*/
|
|
64
|
+
export declare function isRetryableError(error: unknown): boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Automatically retries failed requests based on customizable retry strategies,
|
|
67
|
+
* improving the resilience of your application.
|
|
68
|
+
*
|
|
69
|
+
* @remarks
|
|
70
|
+
* **Note**: Retry behavior is configured through the client context on each call.
|
|
71
|
+
*
|
|
72
|
+
* @see {@link https://orpc.dev/docs/plugins/retry | Retry Plugin}
|
|
73
|
+
*/
|
|
74
|
+
export declare class RetryLinkPlugin<T extends RetryLinkPluginContext & ClientContext> implements StandardLinkPlugin<T> {
|
|
75
|
+
private readonly defaultRetry;
|
|
76
|
+
private readonly defaultRetryDelay;
|
|
77
|
+
private readonly defaultShouldRetry;
|
|
78
|
+
private readonly defaultOnRetry;
|
|
79
|
+
name: string;
|
|
80
|
+
constructor(options?: RetryLinkPluginOptions<T>);
|
|
81
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
82
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { AsyncIteratorClass, isAsyncIteratorObject, override, sleep, toArray, value } from "@orpc/shared";
|
|
2
|
+
import { getEventMeta } from "@standard-server/core";
|
|
3
|
+
import { COMMON_ERROR_STATUS_MAP, ORPCError, ResponseError } from "../error.mjs";
|
|
4
|
+
|
|
5
|
+
export function isRetryableError(error) {
|
|
6
|
+
const responseError = error instanceof ORPCError ? error.cause : error;
|
|
7
|
+
if (!(responseError instanceof ResponseError)) {
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
const { status } = responseError.response;
|
|
11
|
+
return status < 400 || status >= 500 || status === COMMON_ERROR_STATUS_MAP.TIMEOUT || status === COMMON_ERROR_STATUS_MAP.TOO_MANY_REQUESTS;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class RetryLinkPlugin {
|
|
15
|
+
defaultRetry;
|
|
16
|
+
defaultRetryDelay;
|
|
17
|
+
defaultShouldRetry;
|
|
18
|
+
defaultOnRetry;
|
|
19
|
+
name = "~retry";
|
|
20
|
+
constructor(options = {}) {
|
|
21
|
+
this.defaultRetry = options.default?.retry ?? 0;
|
|
22
|
+
this.defaultRetryDelay = options.default?.retryDelay ?? ((o) => o.lastEventRetry ?? 2e3);
|
|
23
|
+
this.defaultShouldRetry = options.default?.shouldRetry ?? ((o) => isRetryableError(o.error));
|
|
24
|
+
this.defaultOnRetry = options.default?.onRetry;
|
|
25
|
+
}
|
|
26
|
+
init(options) {
|
|
27
|
+
const interceptor = async (interceptorOptions) => {
|
|
28
|
+
const { next, ...callOptions } = interceptorOptions;
|
|
29
|
+
const maxAttempts = await value(callOptions.context.retry ?? this.defaultRetry, callOptions);
|
|
30
|
+
const retryDelay = callOptions.context.retryDelay ?? this.defaultRetryDelay;
|
|
31
|
+
const shouldRetry = callOptions.context.shouldRetry ?? this.defaultShouldRetry;
|
|
32
|
+
const onRetry = callOptions.context.onRetry ?? this.defaultOnRetry;
|
|
33
|
+
if (maxAttempts <= 0) {
|
|
34
|
+
return next(callOptions);
|
|
35
|
+
}
|
|
36
|
+
let lastEventId = callOptions.lastEventId;
|
|
37
|
+
let lastEventRetry;
|
|
38
|
+
let callback;
|
|
39
|
+
let attempt = 1;
|
|
40
|
+
let isIteratorAborted = false;
|
|
41
|
+
const callNext = async (initialError) => {
|
|
42
|
+
let currentError = initialError;
|
|
43
|
+
while (true) {
|
|
44
|
+
const updatedCallOptions = {
|
|
45
|
+
...callOptions,
|
|
46
|
+
lastEventId
|
|
47
|
+
};
|
|
48
|
+
let retryDelayMs = 0;
|
|
49
|
+
if (currentError) {
|
|
50
|
+
if (isIteratorAborted || attempt > maxAttempts) {
|
|
51
|
+
throw currentError.error;
|
|
52
|
+
}
|
|
53
|
+
const attemptOptions = {
|
|
54
|
+
...updatedCallOptions,
|
|
55
|
+
attempt,
|
|
56
|
+
error: currentError.error,
|
|
57
|
+
lastEventRetry
|
|
58
|
+
};
|
|
59
|
+
const shouldRetryBool = await value(shouldRetry, attemptOptions);
|
|
60
|
+
if (!shouldRetryBool) {
|
|
61
|
+
throw currentError.error;
|
|
62
|
+
}
|
|
63
|
+
retryDelayMs = await value(retryDelay, attemptOptions);
|
|
64
|
+
callback = onRetry?.(attemptOptions);
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
if (currentError) {
|
|
68
|
+
await sleep(retryDelayMs, { signal: updatedCallOptions.signal });
|
|
69
|
+
if (isIteratorAborted) {
|
|
70
|
+
throw currentError.error;
|
|
71
|
+
}
|
|
72
|
+
attempt++;
|
|
73
|
+
}
|
|
74
|
+
currentError = undefined;
|
|
75
|
+
return await next(updatedCallOptions);
|
|
76
|
+
} catch (error) {
|
|
77
|
+
currentError = { error };
|
|
78
|
+
if (updatedCallOptions.signal?.aborted) {
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
} finally {
|
|
82
|
+
callback?.(!currentError);
|
|
83
|
+
callback = undefined;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const output = await callNext();
|
|
88
|
+
if (!isAsyncIteratorObject(output)) {
|
|
89
|
+
return output;
|
|
90
|
+
}
|
|
91
|
+
let current = output;
|
|
92
|
+
return override(() => current, new AsyncIteratorClass(async () => {
|
|
93
|
+
while (true) {
|
|
94
|
+
try {
|
|
95
|
+
const item = await current.next();
|
|
96
|
+
const meta = getEventMeta(item.value);
|
|
97
|
+
lastEventId = meta?.id ?? lastEventId;
|
|
98
|
+
lastEventRetry = meta?.retry ?? lastEventRetry;
|
|
99
|
+
return item;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
const meta = getEventMeta(error);
|
|
102
|
+
lastEventId = meta?.id ?? lastEventId;
|
|
103
|
+
lastEventRetry = meta?.retry ?? lastEventRetry;
|
|
104
|
+
const asyncIteratorObject = await callNext({ error });
|
|
105
|
+
if (!isAsyncIteratorObject(asyncIteratorObject)) {
|
|
106
|
+
throw new TypeError("RetryLinkPlugin: Expected an AsyncIteratorObject, got a different type.");
|
|
107
|
+
}
|
|
108
|
+
current = asyncIteratorObject;
|
|
109
|
+
if (isIteratorAborted) {
|
|
110
|
+
await current.return?.();
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}, async ({ kind }) => {
|
|
116
|
+
isIteratorAborted = true;
|
|
117
|
+
if (kind === "cancelled") {
|
|
118
|
+
await current.return?.();
|
|
119
|
+
}
|
|
120
|
+
}));
|
|
121
|
+
};
|
|
122
|
+
return {
|
|
123
|
+
...options,
|
|
124
|
+
interceptors: [interceptor, ...toArray(options.interceptors)]
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Value } from "@orpc/shared";
|
|
2
|
+
import type { StandardLinkInterceptorOptions, StandardLinkOptions, StandardLinkPlugin } from "../adapters/standard/index.mjs";
|
|
3
|
+
import type { ClientContext } from "../types.mjs";
|
|
4
|
+
export interface TimeoutLinkPluginOptions<T extends ClientContext> {
|
|
5
|
+
/**
|
|
6
|
+
* Timeout in milliseconds before the request is aborted.
|
|
7
|
+
* Use `null` or `undefined` to disable the timeout.
|
|
8
|
+
*/
|
|
9
|
+
timeout: Value<number | null | undefined, [options: StandardLinkInterceptorOptions<T>]>;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The Timeout Link Plugin aborts requests that exceed a configured timeout with an `AbortError`.
|
|
13
|
+
*
|
|
14
|
+
* @see {@link https://orpc.dev/docs/plugins/timeout | Timeout Plugin}
|
|
15
|
+
*/
|
|
16
|
+
export declare class TimeoutLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
|
|
17
|
+
private readonly timeout;
|
|
18
|
+
name: string;
|
|
19
|
+
/**
|
|
20
|
+
* Should abort if the total retry time exceeds the configured timeout
|
|
21
|
+
*/
|
|
22
|
+
after: string[];
|
|
23
|
+
constructor(options: NoInfer<TimeoutLinkPluginOptions<T>>);
|
|
24
|
+
init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
|
|
25
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { AbortError, anyAbortSignal, toArray, value } from "@orpc/shared";
|
|
2
|
+
|
|
3
|
+
export class TimeoutLinkPlugin {
|
|
4
|
+
timeout;
|
|
5
|
+
name = "~timeout";
|
|
6
|
+
|
|
7
|
+
after = ["~retry"];
|
|
8
|
+
constructor(options) {
|
|
9
|
+
this.timeout = options.timeout;
|
|
10
|
+
}
|
|
11
|
+
init(options) {
|
|
12
|
+
const interceptor = async (interceptorOptions) => {
|
|
13
|
+
const timeoutMs = value(this.timeout, interceptorOptions);
|
|
14
|
+
if (timeoutMs === null || timeoutMs === undefined) {
|
|
15
|
+
return interceptorOptions.next();
|
|
16
|
+
}
|
|
17
|
+
const controller = new AbortController();
|
|
18
|
+
const timeoutId = setTimeout(() => {
|
|
19
|
+
controller.abort(new AbortError(`Request timed out after ${timeoutMs}ms`));
|
|
20
|
+
}, timeoutMs);
|
|
21
|
+
const signal = anyAbortSignal([interceptorOptions.signal, controller.signal]);
|
|
22
|
+
try {
|
|
23
|
+
return await interceptorOptions.next({
|
|
24
|
+
...interceptorOptions,
|
|
25
|
+
signal
|
|
26
|
+
});
|
|
27
|
+
} finally {
|
|
28
|
+
clearTimeout(timeoutId);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
...options,
|
|
33
|
+
interceptors: [interceptor, ...toArray(options.interceptors)]
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
}
|