@bleedingdev/modern-js-runtime-extensions 3.9.0-ultramodern.4 → 3.9.0-ultramodern.5
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/dist/cjs/contextExtensions.js +74 -0
- package/dist/cjs/headRuntime.js +91 -0
- package/dist/cjs/helmetContext.js +54 -0
- package/dist/cjs/index.js +18 -4
- package/dist/cjs/prefetchPolicy.js +52 -0
- package/dist/cjs/request-policy/browser.js +139 -0
- package/dist/cjs/request-policy/client.js +234 -0
- package/dist/cjs/request-policy/node.js +149 -0
- package/dist/cjs/request-policy/policyCore.js +266 -0
- package/dist/cjs/request-policy/requestContext.js +137 -0
- package/dist/cjs/request-policy/traceparent.js +56 -0
- package/dist/cjs/request-policy/transport.js +234 -0
- package/dist/cjs/request-policy/types.js +57 -0
- package/dist/cjs/routeHydration.js +127 -0
- package/dist/cjs/routerPrefetchPolicy.js +153 -0
- package/dist/cjs/routerProvider.js +170 -0
- package/dist/cjs/routerState.js +167 -0
- package/dist/cjs/routerStatePlugin.js +86 -0
- package/dist/cjs/routerStateTypes.js +18 -0
- package/dist/cjs/runtimeContextProjection.js +112 -0
- package/dist/cjs/server-config/bffRuntime.js +18 -0
- package/dist/cjs/server-config/index.js +18 -0
- package/dist/cjs/server-config/serverTelemetry.js +18 -0
- package/dist/cjs/shellStream.js +34 -2
- package/dist/cjs/workspaceEvents.js +159 -0
- package/dist/esm/contextExtensions.mjs +33 -0
- package/dist/esm/headRuntime.mjs +43 -0
- package/dist/esm/helmetContext.mjs +13 -0
- package/dist/esm/index.mjs +2 -0
- package/dist/esm/prefetchPolicy.mjs +11 -0
- package/dist/esm/request-policy/browser.mjs +11 -0
- package/dist/esm/request-policy/client.mjs +195 -0
- package/dist/esm/request-policy/policyCore.mjs +171 -0
- package/dist/esm/request-policy/requestContext.mjs +75 -0
- package/dist/esm/request-policy/traceparent.mjs +18 -0
- package/dist/esm/request-policy/transport.mjs +196 -0
- package/dist/esm/request-policy/types.mjs +10 -0
- package/dist/esm/routeHydration.mjs +77 -0
- package/dist/esm/routerPrefetchPolicy.mjs +115 -0
- package/dist/esm/routerProvider.mjs +117 -0
- package/dist/esm/routerState.mjs +105 -0
- package/dist/esm/routerStatePlugin.mjs +48 -0
- package/dist/esm/routerStateTypes.mjs +0 -0
- package/dist/esm/runtimeContextProjection.mjs +74 -0
- package/dist/esm/server-config/bffRuntime.mjs +0 -0
- package/dist/esm/server-config/index.mjs +0 -0
- package/dist/esm/server-config/serverTelemetry.mjs +0 -0
- package/dist/esm/shellStream.mjs +34 -2
- package/dist/esm/workspaceEvents.mjs +66 -0
- package/dist/esm-node/contextExtensions.mjs +34 -0
- package/dist/esm-node/headRuntime.mjs +44 -0
- package/dist/esm-node/helmetContext.mjs +14 -0
- package/dist/esm-node/index.mjs +2 -0
- package/dist/esm-node/prefetchPolicy.mjs +12 -0
- package/dist/esm-node/request-policy/browser.mjs +12 -0
- package/dist/esm-node/request-policy/client.mjs +196 -0
- package/dist/esm-node/request-policy/node.mjs +22 -0
- package/dist/esm-node/request-policy/policyCore.mjs +172 -0
- package/dist/esm-node/request-policy/requestContext.mjs +76 -0
- package/dist/esm-node/request-policy/traceparent.mjs +19 -0
- package/dist/esm-node/request-policy/transport.mjs +197 -0
- package/dist/esm-node/request-policy/types.mjs +11 -0
- package/dist/esm-node/routeHydration.mjs +78 -0
- package/dist/esm-node/routerPrefetchPolicy.mjs +116 -0
- package/dist/esm-node/routerProvider.mjs +118 -0
- package/dist/esm-node/routerState.mjs +106 -0
- package/dist/esm-node/routerStatePlugin.mjs +49 -0
- package/dist/esm-node/routerStateTypes.mjs +1 -0
- package/dist/esm-node/runtimeContextProjection.mjs +75 -0
- package/dist/esm-node/server-config/bffRuntime.mjs +1 -0
- package/dist/esm-node/server-config/index.mjs +1 -0
- package/dist/esm-node/server-config/serverTelemetry.mjs +1 -0
- package/dist/esm-node/shellStream.mjs +34 -2
- package/dist/esm-node/workspaceEvents.mjs +67 -0
- package/dist/types/contextExtensions.d.ts +34 -0
- package/dist/types/headRuntime.d.ts +12 -0
- package/dist/types/helmetContext.d.ts +10 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/prefetchPolicy.d.ts +4 -0
- package/dist/types/request-policy/browser.d.ts +10 -0
- package/dist/types/request-policy/client.d.ts +14 -0
- package/dist/types/request-policy/node.d.ts +10 -0
- package/dist/types/request-policy/policyCore.d.ts +107 -0
- package/dist/types/request-policy/requestContext.d.ts +22 -0
- package/dist/types/request-policy/traceparent.d.ts +10 -0
- package/dist/types/request-policy/transport.d.ts +12 -0
- package/dist/types/request-policy/types.d.ts +144 -0
- package/dist/types/routeHydration.d.ts +24 -0
- package/dist/types/routerPrefetchPolicy.d.ts +28 -0
- package/dist/types/routerProvider.d.ts +77 -0
- package/dist/types/routerState.d.ts +12 -0
- package/dist/types/routerStatePlugin.d.ts +19 -0
- package/dist/types/routerStateTypes.d.ts +40 -0
- package/dist/types/runtimeContextProjection.d.ts +30 -0
- package/dist/types/server-config/bffRuntime.d.ts +122 -0
- package/dist/types/server-config/index.d.ts +2 -0
- package/dist/types/server-config/serverTelemetry.d.ts +322 -0
- package/dist/types/workspaceEvents.d.ts +62 -0
- package/package.json +198 -13
- package/rslib.config.mts +17 -2
- package/rstest.config.mts +33 -2
- package/src/contextExtensions.ts +81 -0
- package/src/headRuntime.tsx +77 -0
- package/src/helmetContext.ts +31 -0
- package/src/index.ts +2 -0
- package/src/prefetchPolicy.ts +33 -0
- package/src/request-policy/browser.ts +22 -0
- package/src/request-policy/client.ts +404 -0
- package/src/request-policy/node.ts +41 -0
- package/src/request-policy/policyCore.ts +424 -0
- package/src/request-policy/requestContext.ts +149 -0
- package/src/request-policy/traceparent.ts +43 -0
- package/src/request-policy/transport.ts +349 -0
- package/src/request-policy/types.ts +229 -0
- package/src/routeHydration.ts +208 -0
- package/src/routerPrefetchPolicy.ts +195 -0
- package/src/routerProvider.ts +340 -0
- package/src/routerState.ts +208 -0
- package/src/routerStatePlugin.ts +86 -0
- package/src/routerStateTypes.ts +46 -0
- package/src/runtimeContextProjection.ts +105 -0
- package/src/server-config/bffRuntime.ts +136 -0
- package/src/server-config/index.ts +2 -0
- package/src/server-config/serverTelemetry.ts +337 -0
- package/src/shellStream.ts +55 -25
- package/src/workspaceEvents.ts +324 -0
- package/tests/buildIdentity.test.ts +2 -4
- package/tests/contextExtensions.test.ts +71 -0
- package/tests/headRuntime.test.tsx +369 -0
- package/tests/nativeSafeFailureCompatibility.test.ts +117 -0
- package/tests/prefetchPolicy.test.ts +51 -0
- package/tests/rendererHead.test.ts +1 -72
- package/tests/request-policy/browser-policy.test.ts +608 -0
- package/tests/request-policy/client-isolation.test.ts +149 -0
- package/tests/request-policy/identityBinding.test.ts +75 -0
- package/tests/request-policy/node-policy.test.ts +741 -0
- package/tests/request-policy/policyCore.test.ts +250 -0
- package/tests/request-policy/requestContext.test.ts +80 -0
- package/tests/request-policy/requestFactory.outbound-contract.test.ts +691 -0
- package/tests/request-policy/traceparent.test.ts +55 -0
- package/tests/request-policy/transport-retry.test.ts +370 -0
- package/tests/routeHydration.test.ts +180 -0
- package/tests/routerPrefetchPolicy.test.ts +102 -0
- package/tests/routerProvider.test.ts +38 -0
- package/tests/routerState.test.ts +157 -0
- package/tests/routerStatePlugin.test.ts +108 -0
- package/tests/runtimeContextProjection.test.ts +135 -0
- package/tests/shellStream.test.ts +37 -0
- package/tests/workspaceEvents.test.ts +391 -0
- package/dist/cjs/rscHtmlStream.js +0 -128
- package/dist/esm/rscHtmlStream.mjs +0 -86
- package/dist/esm-node/rscHtmlStream.mjs +0 -87
- package/dist/types/rscHtmlStream.d.ts +0 -4
- package/src/rscHtmlStream.ts +0 -142
- package/tests/rscHtmlStream.test.ts +0 -153
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { IdentityBindingViolationError, ProducerDomainNotConfiguredError, TRACEPARENT_HEADER, attachOperationContextHeaders, buildEnvelopeHeaderValue, deleteHeader, firstHeaderValue, isEmptyDomain, isSecuredRequestId, parseTraceparentValue, readHeader, resolveConfiguredRequest, toOrigin, writeHeader } from "./policyCore.mjs";
|
|
2
|
+
import { executeWithResilience } from "./transport.mjs";
|
|
3
|
+
import { BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS, BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER } from "./types.mjs";
|
|
4
|
+
const createPolicyClient = (nativeClient, environment)=>{
|
|
5
|
+
const isServerTarget = 'server' === environment.target;
|
|
6
|
+
const configuredRequests = new Map();
|
|
7
|
+
const realResolveHeaders = new Map();
|
|
8
|
+
const realRequireEnvelope = new Map();
|
|
9
|
+
const realAllowCrossOriginEnvelope = new Map();
|
|
10
|
+
const realTransportResilience = new Map();
|
|
11
|
+
const realIdentityBinding = new Map();
|
|
12
|
+
const realOperationContract = new Map();
|
|
13
|
+
const domainMap = new Map();
|
|
14
|
+
const attachEnvelopeHeaderIfRequired = (headers, requestId, url, incomingHeaders)=>{
|
|
15
|
+
const shouldRequireEnvelope = realRequireEnvelope.get(requestId) ?? isSecuredRequestId(requestId);
|
|
16
|
+
if (!shouldRequireEnvelope) return;
|
|
17
|
+
headers[BFF_ENVELOPE_HEADER] = buildEnvelopeHeaderValue({
|
|
18
|
+
requestId,
|
|
19
|
+
target: environment.target,
|
|
20
|
+
sourceOrigin: environment.resolveSourceOrigin(incomingHeaders),
|
|
21
|
+
targetOrigin: toOrigin(url),
|
|
22
|
+
traceContext: parseTraceparentValue(readHeader(headers, TRACEPARENT_HEADER)),
|
|
23
|
+
allowCrossOriginEnvelope: realAllowCrossOriginEnvelope.get(requestId)
|
|
24
|
+
});
|
|
25
|
+
};
|
|
26
|
+
const attachSecuredOperationHeaders = (headers, requestId, method, path, operationContext)=>{
|
|
27
|
+
if (!isSecuredRequestId(requestId)) return;
|
|
28
|
+
attachOperationContextHeaders({
|
|
29
|
+
headers,
|
|
30
|
+
requestId,
|
|
31
|
+
target: environment.target,
|
|
32
|
+
method,
|
|
33
|
+
path,
|
|
34
|
+
operationContext,
|
|
35
|
+
operationContract: realOperationContract.get(requestId),
|
|
36
|
+
operationContextHeader: BFF_OPERATION_CONTEXT_HEADER,
|
|
37
|
+
operationContextDetailHeader: BFF_OPERATION_CONTEXT_DETAIL_HEADER
|
|
38
|
+
});
|
|
39
|
+
};
|
|
40
|
+
const applyIdentityAndForwardedHeaders = ({ headers, requestId, incomingHeaders, forwardedHeaders, allowedHeaders: targetAllowedHeaders })=>{
|
|
41
|
+
const identityBinding = realIdentityBinding.get(requestId);
|
|
42
|
+
const identityBindingEnabled = identityBinding?.enabled ?? isSecuredRequestId(requestId);
|
|
43
|
+
const identityBindingStrict = identityBinding?.strict ?? isSecuredRequestId(requestId);
|
|
44
|
+
const protectedIdentityHeaders = (identityBinding?.protectedHeaders || BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS).map((header)=>header.toLowerCase());
|
|
45
|
+
if (identityBindingEnabled) {
|
|
46
|
+
const derivedIdentityHeaders = {};
|
|
47
|
+
if (isServerTarget) for (const header of protectedIdentityHeaders){
|
|
48
|
+
const incomingHeaderValue = readHeader(incomingHeaders, header);
|
|
49
|
+
if (void 0 !== incomingHeaderValue) writeHeader(derivedIdentityHeaders, header, incomingHeaderValue);
|
|
50
|
+
}
|
|
51
|
+
const customDerivedHeaders = identityBinding?.deriveHeaders?.({
|
|
52
|
+
requestId,
|
|
53
|
+
target: environment.target,
|
|
54
|
+
incomingHeaders: isServerTarget ? {
|
|
55
|
+
...incomingHeaders
|
|
56
|
+
} : {},
|
|
57
|
+
protectedHeaders: [
|
|
58
|
+
...protectedIdentityHeaders
|
|
59
|
+
]
|
|
60
|
+
});
|
|
61
|
+
if (customDerivedHeaders && 'object' == typeof customDerivedHeaders) for (const header of protectedIdentityHeaders){
|
|
62
|
+
const customValue = readHeader(customDerivedHeaders, header);
|
|
63
|
+
if (void 0 !== customValue) writeHeader(derivedIdentityHeaders, header, customValue);
|
|
64
|
+
}
|
|
65
|
+
for (const header of protectedIdentityHeaders){
|
|
66
|
+
const attemptedValue = readHeader(headers, header);
|
|
67
|
+
if (void 0 === attemptedValue) continue;
|
|
68
|
+
const violation = {
|
|
69
|
+
requestId,
|
|
70
|
+
target: environment.target,
|
|
71
|
+
header,
|
|
72
|
+
attemptedValue,
|
|
73
|
+
derivedValue: readHeader(derivedIdentityHeaders, header),
|
|
74
|
+
reason: 'client_override_blocked'
|
|
75
|
+
};
|
|
76
|
+
identityBinding?.onViolation?.(violation);
|
|
77
|
+
if (identityBindingStrict) throw new IdentityBindingViolationError(violation);
|
|
78
|
+
deleteHeader(headers, header);
|
|
79
|
+
}
|
|
80
|
+
Object.keys(derivedIdentityHeaders).forEach((header)=>{
|
|
81
|
+
isServerTarget ? writeHeader(forwardedHeaders, header, derivedIdentityHeaders[header]) : writeHeader(headers, header, derivedIdentityHeaders[header]);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
if (isServerTarget) {
|
|
85
|
+
const resolveHeaders = realResolveHeaders.get(requestId);
|
|
86
|
+
if (resolveHeaders) {
|
|
87
|
+
const resolvedHeaders = resolveHeaders({
|
|
88
|
+
requestId,
|
|
89
|
+
allowedHeaders: targetAllowedHeaders,
|
|
90
|
+
incomingHeaders: {
|
|
91
|
+
...forwardedHeaders
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
if (resolvedHeaders && 'object' == typeof resolvedHeaders) for (const key of targetAllowedHeaders){
|
|
95
|
+
const resolvedValue = readHeader(resolvedHeaders, key);
|
|
96
|
+
if (void 0 !== resolvedValue) {
|
|
97
|
+
if (identityBindingEnabled && protectedIdentityHeaders.includes(key.toLowerCase())) {
|
|
98
|
+
writeHeader(forwardedHeaders, key.toLowerCase(), resolvedValue);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
writeHeader(forwardedHeaders, key, resolvedValue);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return headers;
|
|
107
|
+
};
|
|
108
|
+
const configure = (options)=>{
|
|
109
|
+
const { request, interceptor, allowedHeaders, resolveHeaders, transport, requireEnvelope, allowCrossOriginEnvelope, identityBinding, operationContract, setDomain, requestId = 'default' } = options;
|
|
110
|
+
const hasExistingDomain = domainMap.has(requestId);
|
|
111
|
+
if ('default' !== requestId && !setDomain && !hasExistingDomain) throw new ProducerDomainNotConfiguredError(requestId);
|
|
112
|
+
let resolvedDomain;
|
|
113
|
+
nativeClient.configure({
|
|
114
|
+
request,
|
|
115
|
+
interceptor,
|
|
116
|
+
allowedHeaders,
|
|
117
|
+
requestId,
|
|
118
|
+
setDomain: setDomain ? (options)=>{
|
|
119
|
+
resolvedDomain = setDomain(options);
|
|
120
|
+
if ('default' !== requestId && isEmptyDomain(resolvedDomain)) throw new ProducerDomainNotConfiguredError(requestId);
|
|
121
|
+
return resolvedDomain;
|
|
122
|
+
} : void 0
|
|
123
|
+
});
|
|
124
|
+
realResolveHeaders.delete(requestId);
|
|
125
|
+
realTransportResilience.delete(requestId);
|
|
126
|
+
realIdentityBinding.delete(requestId);
|
|
127
|
+
realOperationContract.delete(requestId);
|
|
128
|
+
realRequireEnvelope.delete(requestId);
|
|
129
|
+
realAllowCrossOriginEnvelope.delete(requestId);
|
|
130
|
+
if (isServerTarget && 'function' == typeof resolveHeaders) realResolveHeaders.set(requestId, resolveHeaders);
|
|
131
|
+
if (transport && 'object' == typeof transport) realTransportResilience.set(requestId, transport);
|
|
132
|
+
if (identityBinding && 'object' == typeof identityBinding) realIdentityBinding.set(requestId, identityBinding);
|
|
133
|
+
if (operationContract && 'object' == typeof operationContract) realOperationContract.set(requestId, operationContract);
|
|
134
|
+
if ('boolean' == typeof requireEnvelope) realRequireEnvelope.set(requestId, requireEnvelope);
|
|
135
|
+
if ('boolean' == typeof allowCrossOriginEnvelope || 'function' == typeof allowCrossOriginEnvelope) realAllowCrossOriginEnvelope.set(requestId, allowCrossOriginEnvelope);
|
|
136
|
+
if ('string' == typeof resolvedDomain) domainMap.set(requestId, resolvedDomain);
|
|
137
|
+
configuredRequests.set(requestId, true);
|
|
138
|
+
};
|
|
139
|
+
const createHooks = (path, method, requestId, operationContext, upload = false)=>({
|
|
140
|
+
onStart: ({ configuredDomain })=>{
|
|
141
|
+
resolveConfiguredRequest(configuredRequests, requestId, false);
|
|
142
|
+
if (!upload && 'default' !== requestId && isEmptyDomain(configuredDomain)) throw new ProducerDomainNotConfiguredError(requestId);
|
|
143
|
+
},
|
|
144
|
+
prepareHeaders: applyIdentityAndForwardedHeaders,
|
|
145
|
+
dispatch: (context)=>{
|
|
146
|
+
const { incomingHeaders, url, init: { headers } } = context;
|
|
147
|
+
if (isServerTarget && !upload) {
|
|
148
|
+
if (void 0 === readHeader(headers, TRACEPARENT_HEADER)) {
|
|
149
|
+
const incomingTraceparent = firstHeaderValue(readHeader(incomingHeaders, TRACEPARENT_HEADER));
|
|
150
|
+
if ('string' == typeof incomingTraceparent) writeHeader(headers, TRACEPARENT_HEADER, incomingTraceparent);
|
|
151
|
+
}
|
|
152
|
+
if (void 0 === readHeader(headers, TRACEPARENT_HEADER) && operationContext?.traceparent) writeHeader(headers, TRACEPARENT_HEADER, operationContext.traceparent);
|
|
153
|
+
}
|
|
154
|
+
attachEnvelopeHeaderIfRequired(headers, requestId, url, incomingHeaders);
|
|
155
|
+
attachSecuredOperationHeaders(headers, requestId, method, path, operationContext);
|
|
156
|
+
return executeWithResilience({
|
|
157
|
+
requestId,
|
|
158
|
+
target: environment.target,
|
|
159
|
+
method,
|
|
160
|
+
url,
|
|
161
|
+
init: context.init,
|
|
162
|
+
fetcher: context.fetcher,
|
|
163
|
+
transport: realTransportResilience.get(requestId)
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
const createRequest = (...args)=>{
|
|
168
|
+
const options = 'object' == typeof args[0] && null !== args[0] ? args[0] : {
|
|
169
|
+
path: args[0],
|
|
170
|
+
method: args[1],
|
|
171
|
+
port: args[2],
|
|
172
|
+
httpMethodDecider: args[3],
|
|
173
|
+
fetch: args[4],
|
|
174
|
+
requestId: args[5],
|
|
175
|
+
operationContext: args[6]
|
|
176
|
+
};
|
|
177
|
+
const { operationContext, requestId = 'default', ...nativeOptions } = options;
|
|
178
|
+
return nativeClient.createRequest({
|
|
179
|
+
...nativeOptions,
|
|
180
|
+
requestId,
|
|
181
|
+
hooks: createHooks(options.path, options.method, requestId, operationContext)
|
|
182
|
+
});
|
|
183
|
+
};
|
|
184
|
+
const createUploader = ({ operationContext, requestId = 'default', ...options })=>nativeClient.createUploader({
|
|
185
|
+
...options,
|
|
186
|
+
requestId,
|
|
187
|
+
hooks: createHooks(options.path, 'POST', requestId, operationContext, true)
|
|
188
|
+
});
|
|
189
|
+
return {
|
|
190
|
+
configure,
|
|
191
|
+
createRequest,
|
|
192
|
+
createUploader
|
|
193
|
+
};
|
|
194
|
+
};
|
|
195
|
+
export { createPolicyClient };
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { parseTraceparent } from "./traceparent.mjs";
|
|
2
|
+
const TRACEPARENT_HEADER = 'traceparent';
|
|
3
|
+
const readProcessEnv = (key)=>{
|
|
4
|
+
if ("u" < typeof process || void 0 === process.env || 'string' != typeof process.env[key]) return;
|
|
5
|
+
return process.env[key];
|
|
6
|
+
};
|
|
7
|
+
const isStrictDefaultRequestIdEnabled = ()=>'true' === readProcessEnv('MODERN_BFF_STRICT_DEFAULT_REQUEST_ID');
|
|
8
|
+
const isSecuredRequestId = (requestId)=>'default' !== requestId || isStrictDefaultRequestIdEnabled();
|
|
9
|
+
const isEmptyDomain = (domain)=>'string' != typeof domain || '' === domain.trim();
|
|
10
|
+
const firstHeaderValue = (value)=>Array.isArray(value) ? value[0] : value;
|
|
11
|
+
const findHeaderKey = (headers, header)=>{
|
|
12
|
+
const normalized = header.toLowerCase();
|
|
13
|
+
return Object.keys(headers).find((key)=>key.toLowerCase() === normalized);
|
|
14
|
+
};
|
|
15
|
+
const readHeader = (headers, header)=>{
|
|
16
|
+
const key = findHeaderKey(headers, header);
|
|
17
|
+
return 'string' == typeof key ? headers[key] : void 0;
|
|
18
|
+
};
|
|
19
|
+
const writeHeader = (headers, header, value)=>{
|
|
20
|
+
if (void 0 === value) return;
|
|
21
|
+
const key = findHeaderKey(headers, header);
|
|
22
|
+
if ('string' == typeof key && key !== header) delete headers[key];
|
|
23
|
+
headers[header] = value;
|
|
24
|
+
};
|
|
25
|
+
const deleteHeader = (headers, header)=>{
|
|
26
|
+
const key = findHeaderKey(headers, header);
|
|
27
|
+
if ('string' == typeof key) delete headers[key];
|
|
28
|
+
};
|
|
29
|
+
const toOrigin = (value)=>{
|
|
30
|
+
if (!value) return;
|
|
31
|
+
try {
|
|
32
|
+
return new URL(value).origin;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const parseTraceparentValue = (value)=>parseTraceparent(firstHeaderValue(value));
|
|
38
|
+
const buildOperationContext = ({ requestId, method, path, operationContext, traceparent })=>{
|
|
39
|
+
const routePath = operationContext?.routePath || path;
|
|
40
|
+
const operationMethod = (operationContext?.method || method || 'GET').toUpperCase();
|
|
41
|
+
const rawOperationId = operationContext?.operationId || `${operationMethod}:${routePath}`;
|
|
42
|
+
const operationId = rawOperationId.startsWith(`${requestId}:`) ? rawOperationId : `${requestId}:${rawOperationId}`;
|
|
43
|
+
const traceparentValue = operationContext?.traceparent || ('string' == typeof firstHeaderValue(traceparent) ? String(firstHeaderValue(traceparent)) : void 0);
|
|
44
|
+
const parsedTraceContext = operationContext?.traceId && operationContext?.spanId ? {
|
|
45
|
+
traceId: operationContext.traceId,
|
|
46
|
+
spanId: operationContext.spanId
|
|
47
|
+
} : parseTraceparentValue(traceparentValue);
|
|
48
|
+
return {
|
|
49
|
+
requestId,
|
|
50
|
+
operationId,
|
|
51
|
+
routePath,
|
|
52
|
+
method: operationMethod,
|
|
53
|
+
...operationContext?.schemaHash ? {
|
|
54
|
+
schemaHash: operationContext.schemaHash
|
|
55
|
+
} : {},
|
|
56
|
+
...'number' == typeof operationContext?.operationVersion ? {
|
|
57
|
+
operationVersion: operationContext.operationVersion
|
|
58
|
+
} : {},
|
|
59
|
+
...traceparentValue ? {
|
|
60
|
+
traceparent: traceparentValue
|
|
61
|
+
} : {},
|
|
62
|
+
...parsedTraceContext ? {
|
|
63
|
+
traceId: parsedTraceContext.traceId,
|
|
64
|
+
spanId: parsedTraceContext.spanId
|
|
65
|
+
} : {}
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
class ProducerClientNotInitializedError extends Error {
|
|
69
|
+
constructor(requestId){
|
|
70
|
+
super(`Producer client "${requestId}" is not initialized. Call initProducerClient() (or configure()) before using generated APIs for this requestId.`), this.code = 'BFF_PRODUCER_CLIENT_NOT_INITIALIZED';
|
|
71
|
+
this.name = 'ProducerClientNotInitializedError';
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
class ProducerDomainNotConfiguredError extends Error {
|
|
75
|
+
constructor(requestId){
|
|
76
|
+
super(`Producer client "${requestId}" must provide setDomain() during configure().`), this.code = 'BFF_PRODUCER_DOMAIN_NOT_CONFIGURED';
|
|
77
|
+
this.name = 'ProducerDomainNotConfiguredError';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
class CrossOriginEnvelopePolicyError extends Error {
|
|
81
|
+
constructor(requestId, sourceOrigin, targetOrigin){
|
|
82
|
+
super(`Cross-origin envelope is not allowed for producer "${requestId}" (${sourceOrigin || 'unknown-origin'} -> ${targetOrigin || 'unknown-origin'}). Configure allowCrossOriginEnvelope to explicitly allow this flow.`), this.code = 'BFF_CROSS_ORIGIN_ENVELOPE_NOT_ALLOWED';
|
|
83
|
+
this.name = 'CrossOriginEnvelopePolicyError';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
class IdentityBindingViolationError extends Error {
|
|
87
|
+
constructor(violation){
|
|
88
|
+
super(`Identity header "${violation.header}" for producer "${violation.requestId}" was rejected by server-derived identity binding.`), this.code = 'BFF_IDENTITY_BINDING_VIOLATION';
|
|
89
|
+
this.name = 'IdentityBindingViolationError';
|
|
90
|
+
this.violation = violation;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
class OperationContractViolationError extends Error {
|
|
94
|
+
constructor(violation){
|
|
95
|
+
super(`Operation contract violation "${violation.reason}" for producer "${violation.requestId}" operation "${violation.operationId}".`), this.code = 'BFF_OPERATION_CONTRACT_VIOLATION';
|
|
96
|
+
this.name = 'OperationContractViolationError';
|
|
97
|
+
this.violation = violation;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const validateOperationContract = ({ requestId, target, contextPayload, operationContract })=>{
|
|
101
|
+
const operationContractEnabled = operationContract?.enabled ?? isSecuredRequestId(requestId);
|
|
102
|
+
if (!operationContractEnabled) return;
|
|
103
|
+
const strict = operationContract?.strict ?? true;
|
|
104
|
+
const requireSchemaHash = operationContract?.requireSchemaHash ?? true;
|
|
105
|
+
const requireOperationVersion = operationContract?.requireOperationVersion ?? true;
|
|
106
|
+
const maybeReportViolation = (reason)=>{
|
|
107
|
+
const violation = {
|
|
108
|
+
requestId,
|
|
109
|
+
target,
|
|
110
|
+
operationId: contextPayload.operationId,
|
|
111
|
+
routePath: contextPayload.routePath,
|
|
112
|
+
method: contextPayload.method,
|
|
113
|
+
schemaHash: 'string' == typeof contextPayload.schemaHash ? contextPayload.schemaHash : void 0,
|
|
114
|
+
operationVersion: 'number' == typeof contextPayload.operationVersion ? contextPayload.operationVersion : void 0,
|
|
115
|
+
reason
|
|
116
|
+
};
|
|
117
|
+
operationContract?.onViolation?.(violation);
|
|
118
|
+
if (strict) throw new OperationContractViolationError(violation);
|
|
119
|
+
};
|
|
120
|
+
if (requireSchemaHash && 'string' != typeof contextPayload.schemaHash) maybeReportViolation('missing_schema_hash');
|
|
121
|
+
if (requireOperationVersion && 'number' != typeof contextPayload.operationVersion) maybeReportViolation('missing_operation_version');
|
|
122
|
+
};
|
|
123
|
+
const resolveConfiguredRequest = (configuredRequests, requestId, fallback)=>{
|
|
124
|
+
const configuredRequest = configuredRequests.get(requestId);
|
|
125
|
+
if (configuredRequest) return configuredRequest;
|
|
126
|
+
if ('default' !== requestId) throw new ProducerClientNotInitializedError(requestId);
|
|
127
|
+
return fallback;
|
|
128
|
+
};
|
|
129
|
+
const buildEnvelopeHeaderValue = ({ requestId, target, sourceOrigin, targetOrigin, traceContext, allowCrossOriginEnvelope })=>{
|
|
130
|
+
const isCrossOrigin = Boolean(sourceOrigin) && Boolean(targetOrigin) && sourceOrigin !== targetOrigin;
|
|
131
|
+
if (isCrossOrigin) {
|
|
132
|
+
const isAllowed = 'function' == typeof allowCrossOriginEnvelope ? true === allowCrossOriginEnvelope({
|
|
133
|
+
requestId,
|
|
134
|
+
sourceOrigin,
|
|
135
|
+
targetOrigin,
|
|
136
|
+
target
|
|
137
|
+
}) : true === allowCrossOriginEnvelope;
|
|
138
|
+
if (!isAllowed) throw new CrossOriginEnvelopePolicyError(requestId, sourceOrigin, targetOrigin);
|
|
139
|
+
}
|
|
140
|
+
return JSON.stringify({
|
|
141
|
+
requestId,
|
|
142
|
+
target,
|
|
143
|
+
timestamp: Date.now(),
|
|
144
|
+
sourceOrigin,
|
|
145
|
+
targetOrigin,
|
|
146
|
+
...traceContext ? {
|
|
147
|
+
traceId: traceContext.traceId,
|
|
148
|
+
spanId: traceContext.spanId
|
|
149
|
+
} : {}
|
|
150
|
+
});
|
|
151
|
+
};
|
|
152
|
+
const attachOperationContextHeaders = ({ headers, requestId, target, method, path, operationContext, operationContract, operationContextHeader, operationContextDetailHeader })=>{
|
|
153
|
+
if (void 0 === readHeader(headers, TRACEPARENT_HEADER) && operationContext?.traceparent) writeHeader(headers, TRACEPARENT_HEADER, operationContext.traceparent);
|
|
154
|
+
const contextPayload = buildOperationContext({
|
|
155
|
+
requestId,
|
|
156
|
+
method,
|
|
157
|
+
path,
|
|
158
|
+
operationContext,
|
|
159
|
+
traceparent: readHeader(headers, TRACEPARENT_HEADER)
|
|
160
|
+
});
|
|
161
|
+
validateOperationContract({
|
|
162
|
+
requestId,
|
|
163
|
+
target,
|
|
164
|
+
contextPayload,
|
|
165
|
+
operationContract
|
|
166
|
+
});
|
|
167
|
+
if (void 0 === readHeader(headers, operationContextHeader)) writeHeader(headers, operationContextHeader, contextPayload.operationId);
|
|
168
|
+
writeHeader(headers, operationContextDetailHeader, JSON.stringify(contextPayload));
|
|
169
|
+
return contextPayload;
|
|
170
|
+
};
|
|
171
|
+
export { CrossOriginEnvelopePolicyError, IdentityBindingViolationError, OperationContractViolationError, ProducerClientNotInitializedError, ProducerDomainNotConfiguredError, TRACEPARENT_HEADER, attachOperationContextHeaders, buildEnvelopeHeaderValue, buildOperationContext, deleteHeader, findHeaderKey, firstHeaderValue, isEmptyDomain, isSecuredRequestId, parseTraceparentValue, readHeader, resolveConfiguredRequest, toOrigin, validateOperationContract, writeHeader };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { parseTraceparent } from "./traceparent.mjs";
|
|
2
|
+
const BFF_LOCALE_HEADER = 'accept-language';
|
|
3
|
+
const BFF_TRACEPARENT_HEADER = 'traceparent';
|
|
4
|
+
const readHeader = (headers, header)=>{
|
|
5
|
+
if (!headers) return;
|
|
6
|
+
const normalized = header.toLowerCase();
|
|
7
|
+
const key = Object.keys(headers).find((current)=>current.toLowerCase() === normalized);
|
|
8
|
+
if (!key) return;
|
|
9
|
+
const value = headers[key];
|
|
10
|
+
return Array.isArray(value) ? value[0] : value;
|
|
11
|
+
};
|
|
12
|
+
const readString = (value)=>'string' == typeof value && value.length > 0 ? value : void 0;
|
|
13
|
+
function createOperationContextSnapshot(operationContext, safeContext) {
|
|
14
|
+
if (!operationContext) return;
|
|
15
|
+
const snapshot = {
|
|
16
|
+
...operationContext,
|
|
17
|
+
...safeContext.locale || operationContext?.locale ? {
|
|
18
|
+
locale: safeContext.locale || operationContext?.locale
|
|
19
|
+
} : {},
|
|
20
|
+
...safeContext.traceparent || operationContext?.traceparent ? {
|
|
21
|
+
traceparent: safeContext.traceparent || operationContext?.traceparent
|
|
22
|
+
} : {},
|
|
23
|
+
...safeContext.traceId || operationContext?.traceId ? {
|
|
24
|
+
traceId: safeContext.traceId || operationContext?.traceId
|
|
25
|
+
} : {},
|
|
26
|
+
...safeContext.spanId || operationContext?.spanId ? {
|
|
27
|
+
spanId: safeContext.spanId || operationContext?.spanId
|
|
28
|
+
} : {}
|
|
29
|
+
};
|
|
30
|
+
return Object.keys(snapshot).some((key)=>void 0 !== snapshot[key]) ? snapshot : void 0;
|
|
31
|
+
}
|
|
32
|
+
function createRequestContextSnapshot(input = {}) {
|
|
33
|
+
const locale = readString(input.locale) || readString(readHeader(input.headers, BFF_LOCALE_HEADER));
|
|
34
|
+
const traceparent = readString(input.traceparent) || readString(input.operationContext?.traceparent) || readString(readHeader(input.headers, BFF_TRACEPARENT_HEADER));
|
|
35
|
+
const parsedTraceparent = input.operationContext?.traceId && input.operationContext?.spanId ? {
|
|
36
|
+
traceId: input.operationContext.traceId,
|
|
37
|
+
spanId: input.operationContext.spanId
|
|
38
|
+
} : parseTraceparent(traceparent);
|
|
39
|
+
const headers = {};
|
|
40
|
+
if (locale) headers[BFF_LOCALE_HEADER] = locale;
|
|
41
|
+
if (traceparent) headers[BFF_TRACEPARENT_HEADER] = traceparent;
|
|
42
|
+
const operationContext = createOperationContextSnapshot(input.operationContext, {
|
|
43
|
+
...locale ? {
|
|
44
|
+
locale
|
|
45
|
+
} : {},
|
|
46
|
+
...traceparent ? {
|
|
47
|
+
traceparent
|
|
48
|
+
} : {},
|
|
49
|
+
...parsedTraceparent ? {
|
|
50
|
+
traceId: parsedTraceparent.traceId,
|
|
51
|
+
spanId: parsedTraceparent.spanId
|
|
52
|
+
} : {}
|
|
53
|
+
});
|
|
54
|
+
return {
|
|
55
|
+
headers,
|
|
56
|
+
...locale ? {
|
|
57
|
+
locale
|
|
58
|
+
} : {},
|
|
59
|
+
...traceparent ? {
|
|
60
|
+
traceparent
|
|
61
|
+
} : {},
|
|
62
|
+
...parsedTraceparent ? {
|
|
63
|
+
traceId: parsedTraceparent.traceId,
|
|
64
|
+
spanId: parsedTraceparent.spanId
|
|
65
|
+
} : {},
|
|
66
|
+
...operationContext ? {
|
|
67
|
+
operationContext
|
|
68
|
+
} : {}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function createRequestContextHeaders(input = {}) {
|
|
72
|
+
return createRequestContextSnapshot(input).headers;
|
|
73
|
+
}
|
|
74
|
+
export { BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS, BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER } from "./types.mjs";
|
|
75
|
+
export { BFF_LOCALE_HEADER, BFF_TRACEPARENT_HEADER, createRequestContextHeaders, createRequestContextSnapshot, parseTraceparent };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const TRACEPARENT_REGEX = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i;
|
|
2
|
+
const isAllZeroHex = (value)=>/^0+$/.test(value);
|
|
3
|
+
function parseTraceparent(traceparent) {
|
|
4
|
+
if (!traceparent) return;
|
|
5
|
+
const match = traceparent.trim().match(TRACEPARENT_REGEX);
|
|
6
|
+
if (!match) return;
|
|
7
|
+
const [, rawTraceId, rawSpanId, rawFlags] = match;
|
|
8
|
+
if (!rawTraceId || !rawSpanId || !rawFlags) return;
|
|
9
|
+
const traceId = rawTraceId.toLowerCase();
|
|
10
|
+
const spanId = rawSpanId.toLowerCase();
|
|
11
|
+
if (isAllZeroHex(traceId) || isAllZeroHex(spanId)) return;
|
|
12
|
+
return {
|
|
13
|
+
traceId,
|
|
14
|
+
spanId,
|
|
15
|
+
sampled: (0x1 & Number.parseInt(rawFlags, 16)) === 1
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export { parseTraceparent };
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
const DEFAULT_RETRYABLE_STATUS_CODES = [
|
|
2
|
+
408,
|
|
3
|
+
425,
|
|
4
|
+
429,
|
|
5
|
+
500,
|
|
6
|
+
502,
|
|
7
|
+
503,
|
|
8
|
+
504
|
|
9
|
+
];
|
|
10
|
+
const DEFAULT_BASE_DELAY_MS = 100;
|
|
11
|
+
const DEFAULT_MAX_DELAY_MS = 1000;
|
|
12
|
+
const DEFAULT_JITTER_RATIO = 0.1;
|
|
13
|
+
const DEFAULT_RETRYABLE_METHODS = new Set([
|
|
14
|
+
'DELETE',
|
|
15
|
+
'GET',
|
|
16
|
+
'HEAD',
|
|
17
|
+
'OPTIONS',
|
|
18
|
+
'PUT',
|
|
19
|
+
'TRACE'
|
|
20
|
+
]);
|
|
21
|
+
const createTimeoutError = (timeoutMs)=>{
|
|
22
|
+
const error = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
23
|
+
error.name = 'TimeoutError';
|
|
24
|
+
return error;
|
|
25
|
+
};
|
|
26
|
+
const unrefTimer = (timer)=>{
|
|
27
|
+
if ('object' == typeof timer && null !== timer && 'unref' in timer && 'function' == typeof timer.unref) timer.unref();
|
|
28
|
+
};
|
|
29
|
+
const wait = (ms)=>new Promise((resolve)=>{
|
|
30
|
+
const timer = setTimeout(()=>resolve(), ms);
|
|
31
|
+
unrefTimer(timer);
|
|
32
|
+
});
|
|
33
|
+
const toStatusCode = (error)=>{
|
|
34
|
+
if (!error || 'object' != typeof error) return;
|
|
35
|
+
const status = error.status;
|
|
36
|
+
if ('number' == typeof status) return status;
|
|
37
|
+
const responseStatus = error.response?.status;
|
|
38
|
+
if ('number' == typeof responseStatus) return responseStatus;
|
|
39
|
+
};
|
|
40
|
+
const isRetryableNetworkError = (error)=>{
|
|
41
|
+
if (!error || 'object' != typeof error) return false;
|
|
42
|
+
const name = error.name;
|
|
43
|
+
if ('FetchError' === name || 'TimeoutError' === name || 'TypeError' === name) return true;
|
|
44
|
+
const code = error.code;
|
|
45
|
+
return 'ECONNRESET' === code || 'ETIMEDOUT' === code || 'ECONNREFUSED' === code || 'EPIPE' === code;
|
|
46
|
+
};
|
|
47
|
+
const normalizePositiveNumber = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
48
|
+
const normalizeNonNegativeInt = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
|
|
49
|
+
const normalizeJitterRatio = (value)=>{
|
|
50
|
+
if ('number' != typeof value || !Number.isFinite(value)) return DEFAULT_JITTER_RATIO;
|
|
51
|
+
return Math.max(0, Math.min(1, value));
|
|
52
|
+
};
|
|
53
|
+
const shouldRetryWithDefaults = (method, statusCode, error, retryableStatusCodes)=>{
|
|
54
|
+
if (!DEFAULT_RETRYABLE_METHODS.has(method.toUpperCase())) return false;
|
|
55
|
+
if ('number' == typeof statusCode) return retryableStatusCodes.includes(statusCode);
|
|
56
|
+
return isRetryableNetworkError(error);
|
|
57
|
+
};
|
|
58
|
+
const shouldRetry = (retryOptions, context, retryableStatusCodes)=>{
|
|
59
|
+
if ('function' == typeof retryOptions?.shouldRetry) try {
|
|
60
|
+
return retryOptions.shouldRetry(context);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
return shouldRetryWithDefaults(context.method, context.statusCode, context.error, retryableStatusCodes);
|
|
65
|
+
};
|
|
66
|
+
const getBackoffMs = (retryOptions, attempt)=>{
|
|
67
|
+
const baseDelayMs = normalizePositiveNumber(retryOptions?.baseDelayMs, DEFAULT_BASE_DELAY_MS);
|
|
68
|
+
const maxDelayMs = normalizePositiveNumber(retryOptions?.maxDelayMs, DEFAULT_MAX_DELAY_MS);
|
|
69
|
+
const jitterRatio = normalizeJitterRatio(retryOptions?.jitterRatio);
|
|
70
|
+
const exponentialDelay = Math.min(maxDelayMs, baseDelayMs * 2 ** Math.max(0, attempt - 1));
|
|
71
|
+
const jitterFactor = 0 === jitterRatio ? 1 : 1 + (2 * Math.random() - 1) * jitterRatio;
|
|
72
|
+
return Math.max(0, Math.floor(exponentialDelay * jitterFactor));
|
|
73
|
+
};
|
|
74
|
+
const emitDegradedEvent = (transport, event)=>{
|
|
75
|
+
if ('function' != typeof transport?.onDegraded) return;
|
|
76
|
+
try {
|
|
77
|
+
transport.onDegraded(event);
|
|
78
|
+
} catch (error) {}
|
|
79
|
+
};
|
|
80
|
+
const withTimeout = async (promise, timeoutMs, signalBuilder)=>{
|
|
81
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
82
|
+
const result = await promise;
|
|
83
|
+
return {
|
|
84
|
+
result
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
const controller = signalBuilder?.();
|
|
88
|
+
let timeoutTriggered = false;
|
|
89
|
+
let rejectTimeout;
|
|
90
|
+
const timeoutPromise = new Promise((_, reject)=>{
|
|
91
|
+
rejectTimeout = reject;
|
|
92
|
+
});
|
|
93
|
+
const timer = setTimeout(()=>{
|
|
94
|
+
timeoutTriggered = true;
|
|
95
|
+
if (controller) controller.abort();
|
|
96
|
+
rejectTimeout?.(createTimeoutError(timeoutMs));
|
|
97
|
+
}, timeoutMs);
|
|
98
|
+
unrefTimer(timer);
|
|
99
|
+
try {
|
|
100
|
+
const result = await Promise.race([
|
|
101
|
+
promise,
|
|
102
|
+
timeoutPromise
|
|
103
|
+
]);
|
|
104
|
+
return {
|
|
105
|
+
result,
|
|
106
|
+
timeoutTriggered
|
|
107
|
+
};
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (timeoutTriggered && error?.name === 'AbortError') throw createTimeoutError(timeoutMs);
|
|
110
|
+
throw error;
|
|
111
|
+
} finally{
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
const executeWithResilience = async ({ requestId, target, method, url, init, fetcher, transport })=>{
|
|
116
|
+
const retries = normalizeNonNegativeInt(transport?.retry?.retries, 0);
|
|
117
|
+
const timeoutMs = 'number' == typeof transport?.timeoutMs && transport.timeoutMs > 0 ? transport.timeoutMs : void 0;
|
|
118
|
+
const maxAttempts = retries + 1;
|
|
119
|
+
const retryableStatusCodes = transport?.retry?.retryableStatusCodes && transport.retry.retryableStatusCodes.length > 0 ? transport.retry.retryableStatusCodes : DEFAULT_RETRYABLE_STATUS_CODES;
|
|
120
|
+
let attempt = 0;
|
|
121
|
+
while(attempt < maxAttempts){
|
|
122
|
+
attempt += 1;
|
|
123
|
+
const canUseAbortController = "u" > typeof AbortController;
|
|
124
|
+
let controller;
|
|
125
|
+
if (timeoutMs && canUseAbortController) controller = new AbortController();
|
|
126
|
+
const callerSignal = init.signal;
|
|
127
|
+
const requestSignal = controller ? callerSignal && !callerSignal.aborted ? AbortSignal.any([
|
|
128
|
+
callerSignal,
|
|
129
|
+
controller.signal
|
|
130
|
+
]) : callerSignal || controller.signal : callerSignal;
|
|
131
|
+
const nextInit = requestSignal ? {
|
|
132
|
+
...init,
|
|
133
|
+
signal: requestSignal
|
|
134
|
+
} : init;
|
|
135
|
+
try {
|
|
136
|
+
const { result } = await withTimeout(fetcher(url, nextInit), timeoutMs, ()=>controller);
|
|
137
|
+
return result;
|
|
138
|
+
} catch (error) {
|
|
139
|
+
const statusCode = toStatusCode(error);
|
|
140
|
+
const decisionContext = {
|
|
141
|
+
requestId,
|
|
142
|
+
target,
|
|
143
|
+
method,
|
|
144
|
+
url,
|
|
145
|
+
attempt,
|
|
146
|
+
maxAttempts,
|
|
147
|
+
error,
|
|
148
|
+
statusCode
|
|
149
|
+
};
|
|
150
|
+
if (error?.name === 'TimeoutError') emitDegradedEvent(transport, {
|
|
151
|
+
requestId,
|
|
152
|
+
target,
|
|
153
|
+
method,
|
|
154
|
+
url,
|
|
155
|
+
reason: 'timeout',
|
|
156
|
+
attempt,
|
|
157
|
+
maxAttempts,
|
|
158
|
+
timeoutMs,
|
|
159
|
+
statusCode,
|
|
160
|
+
error
|
|
161
|
+
});
|
|
162
|
+
const canRetry = attempt < maxAttempts && shouldRetry(transport?.retry, decisionContext, retryableStatusCodes);
|
|
163
|
+
if (!canRetry) {
|
|
164
|
+
if (retries > 0 || error?.name === 'TimeoutError') emitDegradedEvent(transport, {
|
|
165
|
+
requestId,
|
|
166
|
+
target,
|
|
167
|
+
method,
|
|
168
|
+
url,
|
|
169
|
+
reason: 'retry_exhausted',
|
|
170
|
+
attempt,
|
|
171
|
+
maxAttempts,
|
|
172
|
+
timeoutMs,
|
|
173
|
+
statusCode,
|
|
174
|
+
error
|
|
175
|
+
});
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
const backoffMs = getBackoffMs(transport?.retry, attempt);
|
|
179
|
+
emitDegradedEvent(transport, {
|
|
180
|
+
requestId,
|
|
181
|
+
target,
|
|
182
|
+
method,
|
|
183
|
+
url,
|
|
184
|
+
reason: 'retry',
|
|
185
|
+
attempt,
|
|
186
|
+
maxAttempts,
|
|
187
|
+
timeoutMs,
|
|
188
|
+
backoffMs,
|
|
189
|
+
statusCode,
|
|
190
|
+
error
|
|
191
|
+
});
|
|
192
|
+
if (backoffMs > 0) await wait(backoffMs);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
export { executeWithResilience };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
|
|
2
|
+
const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
|
|
3
|
+
const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
|
|
4
|
+
const BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS = [
|
|
5
|
+
'x-tenant-id',
|
|
6
|
+
'x-subject-id',
|
|
7
|
+
'x-user-id',
|
|
8
|
+
BFF_OPERATION_CONTEXT_HEADER
|
|
9
|
+
];
|
|
10
|
+
export { BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS, BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER };
|