@module-federation/retry-plugin 0.0.0-chore-bump-node-22-20260710161714
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/LICENSE +21 -0
- package/README.md +331 -0
- package/dist/CHANGELOG.md +598 -0
- package/dist/README.md +331 -0
- package/dist/esm/index.js +307 -0
- package/dist/index.d.ts +113 -0
- package/dist/index.js +312 -0
- package/package.json +51 -0
package/dist/README.md
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
# @module-federation/retry-plugin
|
|
2
|
+
|
|
3
|
+
> A robust retry plugin for Module Federation that provides automatic retry mechanisms for failed module requests with domain rotation, cache-busting, and comprehensive error handling.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🔄 **Automatic Retry**: Automatically retries failed fetch and script requests
|
|
8
|
+
- 🌐 **Domain Rotation**: Rotate through multiple domains for better reliability
|
|
9
|
+
- ⚡ **Cache Busting**: Add query parameters to bypass cache issues
|
|
10
|
+
- 📊 **Lifecycle Callbacks**: Comprehensive callbacks for retry events
|
|
11
|
+
- 🎯 **Flexible Configuration**: Highly configurable retry strategies
|
|
12
|
+
- 🔧 **TypeScript Support**: Full TypeScript support with type definitions
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npm install @module-federation/retry-plugin
|
|
18
|
+
# or
|
|
19
|
+
yarn add @module-federation/retry-plugin
|
|
20
|
+
# or
|
|
21
|
+
pnpm add @module-federation/retry-plugin
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Basic Usage
|
|
25
|
+
|
|
26
|
+
### Runtime Plugin Registration
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { createInstance } from '@module-federation/enhanced/runtime';
|
|
30
|
+
import { RetryPlugin } from '@module-federation/retry-plugin';
|
|
31
|
+
|
|
32
|
+
const mf = createInstance({
|
|
33
|
+
name: 'host',
|
|
34
|
+
remotes: [
|
|
35
|
+
{
|
|
36
|
+
name: 'remote1',
|
|
37
|
+
entry: 'http://localhost:2001/mf-manifest.json',
|
|
38
|
+
},
|
|
39
|
+
],
|
|
40
|
+
plugins: [
|
|
41
|
+
RetryPlugin({
|
|
42
|
+
retryTimes: 3,
|
|
43
|
+
retryDelay: 1000,
|
|
44
|
+
domains: ['https://cdn1.example.com', 'https://cdn2.example.com'],
|
|
45
|
+
manifestDomains: ['https://domain1.example.com', 'https://domain2.example.com'],
|
|
46
|
+
addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`,
|
|
47
|
+
onRetry: ({ times, url }) => console.log('Retrying...', times, url),
|
|
48
|
+
onSuccess: ({ url }) => console.log('Success!', url),
|
|
49
|
+
onError: ({ url }) => console.log('Failed!', url),
|
|
50
|
+
}),
|
|
51
|
+
],
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Build Plugin Registration
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
// webpack.config.js
|
|
59
|
+
import { ModuleFederationPlugin } from '@module-federation/webpack';
|
|
60
|
+
import { RetryPlugin } from '@module-federation/retry-plugin';
|
|
61
|
+
|
|
62
|
+
export default {
|
|
63
|
+
plugins: [
|
|
64
|
+
new ModuleFederationPlugin({
|
|
65
|
+
name: 'host',
|
|
66
|
+
remotes: {
|
|
67
|
+
remote1: 'remote1@http://localhost:2001/mf-manifest.json',
|
|
68
|
+
},
|
|
69
|
+
runtimePlugins: [path.join(__dirname, './src/runtime-plugin/retry.ts')],
|
|
70
|
+
}),
|
|
71
|
+
],
|
|
72
|
+
};
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
// src/runtime-plugin/retry.ts
|
|
77
|
+
import { RetryPlugin } from '@module-federation/retry-plugin';
|
|
78
|
+
|
|
79
|
+
export default () =>
|
|
80
|
+
RetryPlugin({
|
|
81
|
+
retryTimes: 3,
|
|
82
|
+
retryDelay: 1000,
|
|
83
|
+
domains: ['https://cdn1.example.com', 'https://cdn2.example.com'],
|
|
84
|
+
manifestDomains: ['https://domain1.example.com', 'https://domain2.example.com'],
|
|
85
|
+
addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`,
|
|
86
|
+
onRetry: ({ times, url }) => console.log('Retrying...', times, url),
|
|
87
|
+
onSuccess: ({ url }) => console.log('Success!', url),
|
|
88
|
+
onError: ({ url }) => console.log('Failed!', url),
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Configuration Options
|
|
93
|
+
|
|
94
|
+
### CommonRetryOptions
|
|
95
|
+
|
|
96
|
+
| Option | Type | Default | Description |
|
|
97
|
+
| ----------------- | --------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------ |
|
|
98
|
+
| `retryTimes` | `number` | `3` | Number of retry attempts |
|
|
99
|
+
| `retryDelay` | `number \| (attempt: number) => number` | `1000` | Delay between retries in milliseconds, or a function returning delay per 1-indexed retry attempt |
|
|
100
|
+
| `successTimes` | `number` | `0` | Number of successful requests required |
|
|
101
|
+
| `domains` | `string[]` | `[]` | Alternative domains for script resources |
|
|
102
|
+
| `manifestDomains` | `string[]` | `[]` | Alternative domains for manifest files |
|
|
103
|
+
| `addQuery` | `boolean \| function` | `false` | Add query parameters for cache busting |
|
|
104
|
+
| `fetchOptions` | `RequestInit` | `{}` | Additional fetch options |
|
|
105
|
+
| `onRetry` | `function` | `undefined` | Callback when retry occurs |
|
|
106
|
+
| `onSuccess` | `function` | `undefined` | Callback when request succeeds |
|
|
107
|
+
| `onError` | `function` | `undefined` | Callback when all retries fail |
|
|
108
|
+
|
|
109
|
+
### addQuery Function
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
addQuery: ({ times, originalQuery }) => {
|
|
113
|
+
// Add retry count and timestamp for cache busting
|
|
114
|
+
const separator = originalQuery ? '&' : '?';
|
|
115
|
+
return `${originalQuery}${separator}retry=${times}&t=${Date.now()}`;
|
|
116
|
+
};
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Callback Functions
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
onRetry: ({ times, domains, url, tagName }) => {
|
|
123
|
+
console.log(`Retry attempt ${times} for ${url}`);
|
|
124
|
+
console.log(`Available domains: ${domains?.join(', ')}`);
|
|
125
|
+
},
|
|
126
|
+
|
|
127
|
+
onSuccess: ({ domains, url, tagName }) => {
|
|
128
|
+
console.log(`Successfully loaded ${url}`);
|
|
129
|
+
console.log(`Used domain: ${domains?.[0]}`);
|
|
130
|
+
},
|
|
131
|
+
|
|
132
|
+
onError: ({ domains, url, tagName }) => {
|
|
133
|
+
console.error(`Failed to load ${url} after all retries`);
|
|
134
|
+
console.error(`Tried domains: ${domains?.join(', ')}`);
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
## Advanced Examples
|
|
139
|
+
|
|
140
|
+
### Custom Retry Strategy
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
RetryPlugin({
|
|
144
|
+
retryTimes: 5,
|
|
145
|
+
retryDelay: (attempt) => 1000 * 2 ** (attempt - 1), // Exponential backoff: 1s, 2s, 4s, ...
|
|
146
|
+
domains: ['https://cdn1.example.com', 'https://cdn2.example.com', 'https://cdn3.example.com'],
|
|
147
|
+
manifestDomains: ['https://api1.example.com', 'https://api2.example.com'],
|
|
148
|
+
addQuery: ({ times, originalQuery }) => {
|
|
149
|
+
const params = new URLSearchParams(originalQuery);
|
|
150
|
+
params.set('retry', times.toString());
|
|
151
|
+
params.set('cache_bust', Date.now().toString());
|
|
152
|
+
return params.toString();
|
|
153
|
+
},
|
|
154
|
+
onRetry: ({ times, url, domains }) => {
|
|
155
|
+
console.log(`Retry ${times}/5 for ${url}`);
|
|
156
|
+
console.log(`Trying domain: ${domains?.[times % domains.length]}`);
|
|
157
|
+
},
|
|
158
|
+
onSuccess: ({ url, domains }) => {
|
|
159
|
+
console.log(`✅ Successfully loaded ${url}`);
|
|
160
|
+
console.log(`✅ Used domain: ${domains?.[0]}`);
|
|
161
|
+
},
|
|
162
|
+
onError: ({ url, domains }) => {
|
|
163
|
+
console.error(`❌ Failed to load ${url} after all retries`);
|
|
164
|
+
console.error(`❌ Tried all domains: ${domains?.join(', ')}`);
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### Error Handling with Fallback
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
RetryPlugin({
|
|
173
|
+
retryTimes: 3,
|
|
174
|
+
retryDelay: 1000,
|
|
175
|
+
domains: ['https://cdn1.example.com', 'https://cdn2.example.com'],
|
|
176
|
+
onError: ({ url, domains }) => {
|
|
177
|
+
// Log error for monitoring
|
|
178
|
+
console.error('Module loading failed:', { url, domains });
|
|
179
|
+
|
|
180
|
+
// Send error to monitoring service
|
|
181
|
+
if (window.gtag) {
|
|
182
|
+
window.gtag('event', 'module_load_error', {
|
|
183
|
+
event_category: 'module_federation',
|
|
184
|
+
event_label: url,
|
|
185
|
+
value: domains?.length || 0,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Show user-friendly error message
|
|
190
|
+
const errorElement = document.createElement('div');
|
|
191
|
+
errorElement.className = 'module-load-error';
|
|
192
|
+
errorElement.innerHTML = `
|
|
193
|
+
<div style="padding: 16px; border: 1px solid #ffa39e; border-radius: 4px; background: #fff1f0; color: #cf1322;">
|
|
194
|
+
<h4>Module Loading Failed</h4>
|
|
195
|
+
<p>Unable to load module: ${url}</p>
|
|
196
|
+
<p>Please refresh the page to try again.</p>
|
|
197
|
+
</div>
|
|
198
|
+
`;
|
|
199
|
+
document.body.appendChild(errorElement);
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
### Production Configuration
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
RetryPlugin({
|
|
208
|
+
retryTimes: 3,
|
|
209
|
+
retryDelay: 1000,
|
|
210
|
+
domains: ['https://cdn1.prod.example.com', 'https://cdn2.prod.example.com', 'https://cdn3.prod.example.com'],
|
|
211
|
+
manifestDomains: ['https://api1.prod.example.com', 'https://api2.prod.example.com'],
|
|
212
|
+
addQuery: ({ times, originalQuery }) => {
|
|
213
|
+
const params = new URLSearchParams(originalQuery);
|
|
214
|
+
params.set('retry', times.toString());
|
|
215
|
+
params.set('v', process.env.BUILD_VERSION || '1.0.0');
|
|
216
|
+
return params.toString();
|
|
217
|
+
},
|
|
218
|
+
fetchOptions: {
|
|
219
|
+
cache: 'no-cache',
|
|
220
|
+
headers: {
|
|
221
|
+
'X-Requested-With': 'ModuleFederation',
|
|
222
|
+
},
|
|
223
|
+
},
|
|
224
|
+
onRetry: ({ times, url }) => {
|
|
225
|
+
// Only log in development
|
|
226
|
+
if (process.env.NODE_ENV === 'development') {
|
|
227
|
+
console.log(`Retry ${times} for ${url}`);
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
onSuccess: ({ url }) => {
|
|
231
|
+
// Track successful loads
|
|
232
|
+
if (window.analytics) {
|
|
233
|
+
window.analytics.track('module_loaded', { url });
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
onError: ({ url, domains }) => {
|
|
237
|
+
// Send error to monitoring service
|
|
238
|
+
if (window.errorReporting) {
|
|
239
|
+
window.errorReporting.captureException(new Error(`Module loading failed: ${url}`), { extra: { domains, url } });
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
## How It Works
|
|
246
|
+
|
|
247
|
+
1. **Fetch Retry**: Intercepts failed fetch requests for manifest files and retries with domain rotation
|
|
248
|
+
2. **Script Retry**: Intercepts failed script loading and retries with alternative domains
|
|
249
|
+
3. **Domain Rotation**: Cycles through provided domains to find working alternatives
|
|
250
|
+
4. **Cache Busting**: Adds query parameters to prevent cache-related issues
|
|
251
|
+
5. **Lifecycle Hooks**: Provides callbacks for monitoring and debugging
|
|
252
|
+
|
|
253
|
+
## Error Scenarios Handled
|
|
254
|
+
|
|
255
|
+
- Network timeouts and connection errors
|
|
256
|
+
- DNS resolution failures
|
|
257
|
+
- Server errors (5xx status codes)
|
|
258
|
+
- CDN failures and regional issues
|
|
259
|
+
- Cache-related loading problems
|
|
260
|
+
- CORS and security policy violations
|
|
261
|
+
|
|
262
|
+
## Browser Support
|
|
263
|
+
|
|
264
|
+
- Chrome 60+
|
|
265
|
+
- Firefox 55+
|
|
266
|
+
- Safari 12+
|
|
267
|
+
- Edge 79+
|
|
268
|
+
|
|
269
|
+
## TypeScript Support
|
|
270
|
+
|
|
271
|
+
The plugin includes full TypeScript definitions:
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import { RetryPlugin, type CommonRetryOptions } from '@module-federation/retry-plugin';
|
|
275
|
+
|
|
276
|
+
const options: CommonRetryOptions = {
|
|
277
|
+
retryTimes: 3,
|
|
278
|
+
retryDelay: 1000,
|
|
279
|
+
domains: ['https://cdn1.example.com'],
|
|
280
|
+
onRetry: ({ times, url }) => {
|
|
281
|
+
console.log(`Retry ${times} for ${url}`);
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
const plugin = RetryPlugin(options);
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
## Migration Guide
|
|
289
|
+
|
|
290
|
+
### From v0.18.x to v0.19.x
|
|
291
|
+
|
|
292
|
+
The plugin configuration has been simplified. The old `fetch` and `script` configuration objects are deprecated:
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
// ❌ Old way (deprecated)
|
|
296
|
+
RetryPlugin({
|
|
297
|
+
fetch: {
|
|
298
|
+
url: 'http://localhost:2008/not-exist-mf-manifest.json',
|
|
299
|
+
fallback: () => 'http://localhost:2001/mf-manifest.json',
|
|
300
|
+
},
|
|
301
|
+
script: {
|
|
302
|
+
url: 'http://localhost:2001/static/js/async/src_App_tsx.js',
|
|
303
|
+
customCreateScript: (url, attrs) => {
|
|
304
|
+
/* ... */
|
|
305
|
+
},
|
|
306
|
+
},
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
// ✅ New way
|
|
310
|
+
RetryPlugin({
|
|
311
|
+
retryTimes: 3,
|
|
312
|
+
retryDelay: 1000,
|
|
313
|
+
domains: ['http://localhost:2001'],
|
|
314
|
+
manifestDomains: ['http://localhost:2001'],
|
|
315
|
+
addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`,
|
|
316
|
+
});
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
## Contributing
|
|
320
|
+
|
|
321
|
+
Contributions are welcome! Please read our [contributing guidelines](https://github.com/module-federation/core/blob/main/CONTRIBUTING.md) and submit pull requests to our [GitHub repository](https://github.com/module-federation/core).
|
|
322
|
+
|
|
323
|
+
## License
|
|
324
|
+
|
|
325
|
+
`@module-federation/retry-plugin` is [MIT licensed](https://github.com/module-federation/core/blob/main/packages/retry-plugin/LICENSE).
|
|
326
|
+
|
|
327
|
+
## Related
|
|
328
|
+
|
|
329
|
+
- [Module Federation Documentation](https://module-federation.io/)
|
|
330
|
+
- [Module Federation Runtime](https://www.npmjs.com/package/@module-federation/runtime)
|
|
331
|
+
- [Module Federation Enhanced](https://www.npmjs.com/package/@module-federation/enhanced)
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import { createLogger } from "@module-federation/sdk";
|
|
2
|
+
|
|
3
|
+
//#region src/constant.ts
|
|
4
|
+
const defaultRetries = 3;
|
|
5
|
+
const defaultRetryDelay = 1e3;
|
|
6
|
+
const PLUGIN_IDENTIFIER = "[ Module Federation RetryPlugin ]";
|
|
7
|
+
const ERROR_ABANDONED = "The request failed and has now been abandoned";
|
|
8
|
+
const RUNTIME_008 = "RUNTIME-008";
|
|
9
|
+
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region src/logger.ts
|
|
12
|
+
const logger = createLogger(PLUGIN_IDENTIFIER);
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/utils.ts
|
|
16
|
+
function rewriteWithNextDomain(currentUrl, domains) {
|
|
17
|
+
if (!domains || domains.length === 0) return null;
|
|
18
|
+
try {
|
|
19
|
+
const u = new URL(currentUrl);
|
|
20
|
+
const currentHostname = u.hostname;
|
|
21
|
+
const currentPort = u.port;
|
|
22
|
+
const currentHost = `${currentHostname}${currentPort ? `:${currentPort}` : ""}`;
|
|
23
|
+
const normalized = domains.map((d) => {
|
|
24
|
+
try {
|
|
25
|
+
const du = new URL(d.startsWith("http") ? d : `https://${d}`);
|
|
26
|
+
return {
|
|
27
|
+
hostname: du.hostname,
|
|
28
|
+
port: du.port,
|
|
29
|
+
protocol: du.protocol
|
|
30
|
+
};
|
|
31
|
+
} catch {
|
|
32
|
+
return {
|
|
33
|
+
hostname: d,
|
|
34
|
+
port: "",
|
|
35
|
+
protocol: u.protocol
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
}).filter((d) => !!d.hostname);
|
|
39
|
+
if (normalized.length === 0) return null;
|
|
40
|
+
let idx = -1;
|
|
41
|
+
for (let i = normalized.length - 1; i >= 0; i--) if (`${normalized[i].hostname}${normalized[i].port ? `:${normalized[i].port}` : ""}` === currentHost) {
|
|
42
|
+
idx = i;
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
const total = normalized.length;
|
|
46
|
+
for (let step = 1; step <= total; step++) {
|
|
47
|
+
const candidate = normalized[((idx >= 0 ? idx : -1) + step) % total];
|
|
48
|
+
if (`${candidate.hostname}${candidate.port ? `:${candidate.port}` : ""}` !== currentHost) {
|
|
49
|
+
u.hostname = candidate.hostname;
|
|
50
|
+
if (candidate.port !== void 0 && candidate.port !== null && candidate.port !== "") u.port = candidate.port;
|
|
51
|
+
else u.port = "";
|
|
52
|
+
u.protocol = candidate.protocol || u.protocol;
|
|
53
|
+
return u.toString();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function appendRetryCountQuery(url, retryIndex, key = "retryCount") {
|
|
62
|
+
try {
|
|
63
|
+
const u = new URL(url);
|
|
64
|
+
u.searchParams.delete(key);
|
|
65
|
+
u.searchParams.set(key, String(retryIndex));
|
|
66
|
+
return u.toString();
|
|
67
|
+
} catch {
|
|
68
|
+
return url;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function getRetryUrl(baseUrl, opts = {}) {
|
|
72
|
+
const { domains, addQuery, retryIndex = 0, queryKey = "retryCount" } = opts;
|
|
73
|
+
let cleanBaseUrl = baseUrl;
|
|
74
|
+
try {
|
|
75
|
+
const urlObj = new URL(baseUrl);
|
|
76
|
+
urlObj.searchParams.delete(queryKey);
|
|
77
|
+
cleanBaseUrl = urlObj.toString();
|
|
78
|
+
} catch {}
|
|
79
|
+
let nextUrl = rewriteWithNextDomain(cleanBaseUrl, domains) ?? cleanBaseUrl;
|
|
80
|
+
if (retryIndex > 0 && addQuery) try {
|
|
81
|
+
const u = new URL(nextUrl);
|
|
82
|
+
const originalUrl = new URL(baseUrl);
|
|
83
|
+
originalUrl.searchParams.delete(queryKey);
|
|
84
|
+
const originalQuery = originalUrl.search.startsWith("?") ? originalUrl.search.slice(1) : originalUrl.search;
|
|
85
|
+
if (typeof addQuery === "function") {
|
|
86
|
+
const newQuery = addQuery({
|
|
87
|
+
times: retryIndex,
|
|
88
|
+
originalQuery
|
|
89
|
+
});
|
|
90
|
+
u.search = newQuery ? `?${newQuery.replace(/^\?/, "")}` : "";
|
|
91
|
+
nextUrl = u.toString();
|
|
92
|
+
} else if (addQuery === true) {
|
|
93
|
+
u.searchParams.delete(queryKey);
|
|
94
|
+
u.searchParams.set(queryKey, String(retryIndex));
|
|
95
|
+
nextUrl = u.toString();
|
|
96
|
+
}
|
|
97
|
+
} catch {
|
|
98
|
+
if (addQuery === true) nextUrl = appendRetryCountQuery(nextUrl, retryIndex, queryKey);
|
|
99
|
+
}
|
|
100
|
+
return nextUrl;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Extract domain/host info from a URL and combine it with path/query from another URL
|
|
104
|
+
* This is useful for domain rotation while preserving original path and query parameters
|
|
105
|
+
* @param domainUrl - URL containing the target domain/host
|
|
106
|
+
* @param pathQueryUrl - URL containing the target path and query parameters
|
|
107
|
+
* @returns Combined URL with domain from domainUrl and path/query from pathQueryUrl
|
|
108
|
+
*/
|
|
109
|
+
function combineUrlDomainWithPathQuery(domainUrl, pathQueryUrl) {
|
|
110
|
+
try {
|
|
111
|
+
const domainUrlObj = new URL(domainUrl);
|
|
112
|
+
const pathQueryUrlObj = new URL(pathQueryUrl);
|
|
113
|
+
domainUrlObj.pathname = pathQueryUrlObj.pathname;
|
|
114
|
+
domainUrlObj.search = pathQueryUrlObj.search;
|
|
115
|
+
return domainUrlObj.toString();
|
|
116
|
+
} catch {
|
|
117
|
+
return pathQueryUrl;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/fetch-retry.ts
|
|
123
|
+
function autoParseResponse(url, response) {
|
|
124
|
+
try {
|
|
125
|
+
const parsed = new URL(url);
|
|
126
|
+
if (parsed.pathname.endsWith(".js") || parsed.pathname.endsWith(".cjs") || parsed.pathname.endsWith(".mjs")) return response.text();
|
|
127
|
+
return response.json();
|
|
128
|
+
} catch (error) {
|
|
129
|
+
return response.json();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async function fetchRetry(params, lastRequestUrl, originalTotal) {
|
|
133
|
+
const { url, fetchOptions = {}, retryTimes = defaultRetries, retryDelay = defaultRetryDelay, domains, addQuery, onRetry, onSuccess, onError } = params;
|
|
134
|
+
if (!url) throw new Error(`${PLUGIN_IDENTIFIER}: url is required in fetchWithRetry`);
|
|
135
|
+
const total = originalTotal ?? params.retryTimes ?? defaultRetries;
|
|
136
|
+
const isFirstAttempt = !lastRequestUrl;
|
|
137
|
+
let baseUrl = url;
|
|
138
|
+
if (!isFirstAttempt && lastRequestUrl) baseUrl = combineUrlDomainWithPathQuery(lastRequestUrl, url);
|
|
139
|
+
let requestUrl = baseUrl;
|
|
140
|
+
if (!isFirstAttempt) requestUrl = getRetryUrl(baseUrl, {
|
|
141
|
+
domains,
|
|
142
|
+
addQuery,
|
|
143
|
+
retryIndex: total - retryTimes,
|
|
144
|
+
queryKey: "retryCount"
|
|
145
|
+
});
|
|
146
|
+
try {
|
|
147
|
+
if (!isFirstAttempt) {
|
|
148
|
+
const attemptIndex = total - retryTimes;
|
|
149
|
+
const delay = typeof retryDelay === "function" ? retryDelay(attemptIndex) : retryDelay;
|
|
150
|
+
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
|
|
151
|
+
}
|
|
152
|
+
const response = await fetch(requestUrl, fetchOptions);
|
|
153
|
+
const responseClone = response.clone();
|
|
154
|
+
if (!response.ok) throw new Error(`${PLUGIN_IDENTIFIER}: Request failed: ${response.status} ${response.statusText || ""} | url: ${requestUrl}`);
|
|
155
|
+
await autoParseResponse(requestUrl, responseClone).catch((error) => {
|
|
156
|
+
throw new Error(`${PLUGIN_IDENTIFIER}: JSON parse failed: ${error?.message || String(error)} | url: ${requestUrl}`);
|
|
157
|
+
});
|
|
158
|
+
if (!isFirstAttempt) onSuccess && requestUrl && onSuccess({
|
|
159
|
+
domains,
|
|
160
|
+
url: requestUrl,
|
|
161
|
+
tagName: "fetch"
|
|
162
|
+
});
|
|
163
|
+
return response;
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (retryTimes <= 0) {
|
|
166
|
+
const attemptedRetries = total - retryTimes;
|
|
167
|
+
if (!isFirstAttempt && attemptedRetries > 0) {
|
|
168
|
+
onError && onError({
|
|
169
|
+
domains,
|
|
170
|
+
url: requestUrl,
|
|
171
|
+
tagName: "fetch"
|
|
172
|
+
});
|
|
173
|
+
logger.log(`${PLUGIN_IDENTIFIER}: retry failed, no retries left for url: ${requestUrl}`);
|
|
174
|
+
}
|
|
175
|
+
throw new Error(`${RUNTIME_008}: ${PLUGIN_IDENTIFIER}: ${ERROR_ABANDONED} | url: ${requestUrl}`);
|
|
176
|
+
} else {
|
|
177
|
+
const nextIndex = total - retryTimes + 1;
|
|
178
|
+
const predictedNextUrl = getRetryUrl(combineUrlDomainWithPathQuery(requestUrl, url), {
|
|
179
|
+
domains,
|
|
180
|
+
addQuery,
|
|
181
|
+
retryIndex: nextIndex,
|
|
182
|
+
queryKey: "retryCount"
|
|
183
|
+
});
|
|
184
|
+
onRetry && onRetry({
|
|
185
|
+
times: nextIndex,
|
|
186
|
+
domains,
|
|
187
|
+
url: predictedNextUrl,
|
|
188
|
+
tagName: "fetch"
|
|
189
|
+
});
|
|
190
|
+
logger.log(`${PLUGIN_IDENTIFIER}: Trying again. Number of retries left: ${retryTimes - 1}`);
|
|
191
|
+
return await fetchRetry({
|
|
192
|
+
...params,
|
|
193
|
+
retryTimes: retryTimes - 1
|
|
194
|
+
}, requestUrl, total);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/script-retry.ts
|
|
201
|
+
function scriptRetry({ retryOptions, retryFn, beforeExecuteRetry = () => {} }) {
|
|
202
|
+
return async function(params) {
|
|
203
|
+
let retryWrapper;
|
|
204
|
+
let lastRequestUrl;
|
|
205
|
+
let originalUrl;
|
|
206
|
+
const { retryTimes = defaultRetries, retryDelay = defaultRetryDelay, domains, addQuery, onRetry, onSuccess, onError } = retryOptions || {};
|
|
207
|
+
let attempts = 0;
|
|
208
|
+
const maxAttempts = retryTimes;
|
|
209
|
+
while (attempts < maxAttempts) try {
|
|
210
|
+
beforeExecuteRetry();
|
|
211
|
+
const delay = typeof retryDelay === "function" ? retryDelay(attempts + 1) : retryDelay;
|
|
212
|
+
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
|
|
213
|
+
const retryIndex = attempts + 1;
|
|
214
|
+
retryWrapper = await retryFn({
|
|
215
|
+
...params,
|
|
216
|
+
getEntryUrl: (url) => {
|
|
217
|
+
if (!originalUrl) originalUrl = url;
|
|
218
|
+
let baseUrl = originalUrl;
|
|
219
|
+
if (lastRequestUrl) baseUrl = combineUrlDomainWithPathQuery(lastRequestUrl, originalUrl);
|
|
220
|
+
const next = getRetryUrl(baseUrl, {
|
|
221
|
+
domains,
|
|
222
|
+
addQuery,
|
|
223
|
+
retryIndex,
|
|
224
|
+
queryKey: "retryCount"
|
|
225
|
+
});
|
|
226
|
+
onRetry && onRetry({
|
|
227
|
+
times: retryIndex,
|
|
228
|
+
domains,
|
|
229
|
+
url: next,
|
|
230
|
+
tagName: "script"
|
|
231
|
+
});
|
|
232
|
+
lastRequestUrl = next;
|
|
233
|
+
return next;
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
onSuccess && lastRequestUrl && onSuccess({
|
|
237
|
+
domains,
|
|
238
|
+
url: lastRequestUrl,
|
|
239
|
+
tagName: "script"
|
|
240
|
+
});
|
|
241
|
+
break;
|
|
242
|
+
} catch (error) {
|
|
243
|
+
attempts++;
|
|
244
|
+
if (attempts >= maxAttempts) {
|
|
245
|
+
onError && lastRequestUrl && onError({
|
|
246
|
+
domains,
|
|
247
|
+
url: lastRequestUrl,
|
|
248
|
+
tagName: "script"
|
|
249
|
+
});
|
|
250
|
+
throw new Error(`${PLUGIN_IDENTIFIER}: ${ERROR_ABANDONED} | url: ${lastRequestUrl || "unknown"}`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return retryWrapper;
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
//#endregion
|
|
258
|
+
//#region src/index.ts
|
|
259
|
+
const RetryPlugin = (params) => {
|
|
260
|
+
if (params?.fetch || params?.script) logger.warn(`${PLUGIN_IDENTIFIER}: params is ${params}, fetch or script config is deprecated, please use the new config style. See docs: https://module-federation.io/plugin/plugins/retry-plugin.html`);
|
|
261
|
+
const { fetchOptions = {}, retryTimes = defaultRetries, successTimes = 0, retryDelay = defaultRetryDelay, domains = [], manifestDomains = [], addQuery, onRetry, onSuccess, onError } = params || {};
|
|
262
|
+
return {
|
|
263
|
+
name: "retry-plugin",
|
|
264
|
+
async fetch(manifestUrl, options) {
|
|
265
|
+
return fetchRetry({
|
|
266
|
+
url: manifestUrl,
|
|
267
|
+
fetchOptions: {
|
|
268
|
+
...options,
|
|
269
|
+
...fetchOptions
|
|
270
|
+
},
|
|
271
|
+
domains: manifestDomains || domains,
|
|
272
|
+
addQuery,
|
|
273
|
+
onRetry,
|
|
274
|
+
onSuccess,
|
|
275
|
+
onError,
|
|
276
|
+
retryTimes,
|
|
277
|
+
successTimes,
|
|
278
|
+
retryDelay
|
|
279
|
+
});
|
|
280
|
+
},
|
|
281
|
+
async loadEntryError({ getRemoteEntry, origin, remoteInfo, remoteEntryExports, globalLoading, uniqueKey }) {
|
|
282
|
+
const beforeExecuteRetry = () => {
|
|
283
|
+
delete globalLoading[uniqueKey];
|
|
284
|
+
};
|
|
285
|
+
return await scriptRetry({
|
|
286
|
+
retryOptions: {
|
|
287
|
+
retryTimes,
|
|
288
|
+
retryDelay,
|
|
289
|
+
domains,
|
|
290
|
+
addQuery,
|
|
291
|
+
onRetry,
|
|
292
|
+
onSuccess,
|
|
293
|
+
onError
|
|
294
|
+
},
|
|
295
|
+
retryFn: getRemoteEntry,
|
|
296
|
+
beforeExecuteRetry
|
|
297
|
+
})({
|
|
298
|
+
origin,
|
|
299
|
+
remoteInfo,
|
|
300
|
+
remoteEntryExports
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
//#endregion
|
|
307
|
+
export { RetryPlugin, appendRetryCountQuery, combineUrlDomainWithPathQuery, getRetryUrl, rewriteWithNextDomain };
|