req-race 1.0.0 → 1.1.1
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/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +107 -107
- package/bin/req-race.js +143 -103
- package/config.schema.json +16 -0
- package/dist/browser/req-race.global.js +1 -0
- package/dist/cjs/browser.cjs +843 -0
- package/dist/cjs/cypress.cjs +618 -0
- package/dist/cjs/index.cjs +1064 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/playwright.cjs +257 -0
- package/dist/cjs/puppeteer.cjs +257 -0
- package/dist/esm/browser.js +813 -0
- package/dist/esm/cypress.js +591 -0
- package/dist/esm/index.js +1002 -0
- package/dist/esm/playwright.js +221 -0
- package/dist/esm/puppeteer.js +221 -0
- package/dist/types/browser.d.cts +9 -0
- package/dist/types/browser.d.ts +9 -0
- package/dist/types/chaos.d.cts +25 -0
- package/dist/types/chaos.d.ts +25 -0
- package/dist/types/config.d.cts +3 -0
- package/dist/types/config.d.ts +3 -0
- package/dist/types/cypress.d.cts +1 -0
- package/dist/types/cypress.d.ts +1 -0
- package/dist/types/index.d.cts +7 -0
- package/dist/types/index.d.ts +7 -0
- package/dist/types/playwright.d.cts +82 -0
- package/dist/types/playwright.d.ts +82 -0
- package/dist/types/prng.d.cts +1 -0
- package/dist/types/prng.d.ts +1 -0
- package/dist/types/puppeteer.d.cts +2 -0
- package/dist/types/puppeteer.d.ts +2 -0
- package/dist/types/reporters.d.cts +33 -0
- package/dist/types/reporters.d.ts +33 -0
- package/dist/types/safe-fetch.d.cts +24 -0
- package/dist/types/safe-fetch.d.ts +24 -0
- package/dist/types/types.d.cts +215 -0
- package/dist/types/types.d.ts +215 -0
- package/package.json +127 -53
- package/src/index.d.ts +0 -56
- package/src/index.js +0 -373
- package/src/playwright.d.ts +0 -30
- package/src/playwright.js +0 -113
|
@@ -0,0 +1,1002 @@
|
|
|
1
|
+
// src/prng.ts
|
|
2
|
+
function createSeededRandom(seed = Date.now()) {
|
|
3
|
+
let h = 2166136261;
|
|
4
|
+
const s = String(seed);
|
|
5
|
+
for (let i = 0; i < s.length; i++) {
|
|
6
|
+
h ^= s.charCodeAt(i);
|
|
7
|
+
h = Math.imul(h, 16777619);
|
|
8
|
+
}
|
|
9
|
+
let state = h >>> 0;
|
|
10
|
+
return function nextRandom() {
|
|
11
|
+
state = state + 1831565813 | 0;
|
|
12
|
+
let t = Math.imul(state ^ state >>> 15, 1 | state);
|
|
13
|
+
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
|
|
14
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// src/types.ts
|
|
19
|
+
var SupersededError = class extends Error {
|
|
20
|
+
code = "ERR_SUPERSEDED";
|
|
21
|
+
reason = "superseded";
|
|
22
|
+
constructor(message = "Superseded by newer request") {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = "AbortError";
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
var TimeoutError = class extends Error {
|
|
28
|
+
code = "ETIMEDOUT";
|
|
29
|
+
constructor(message = "Request timed out") {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = "TimeoutError";
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
var RaceAssertionError = class extends Error {
|
|
35
|
+
code = "ERR_RACE_ASSERTION";
|
|
36
|
+
constructor(message, options) {
|
|
37
|
+
super(message, options);
|
|
38
|
+
this.name = "RaceAssertionError";
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
var AlreadyEnabledError = class extends Error {
|
|
42
|
+
code = "ALREADY_ENABLED";
|
|
43
|
+
constructor(message = "req-race chaos is already enabled on this target. Call disable() first.") {
|
|
44
|
+
super(message);
|
|
45
|
+
this.name = "AlreadyEnabledError";
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
var ChaosCallbackError = class extends Error {
|
|
49
|
+
code = "ERR_CHAOS_CALLBACK";
|
|
50
|
+
constructor(message, options) {
|
|
51
|
+
super(message, options);
|
|
52
|
+
this.name = "ChaosCallbackError";
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var UnknownModeError = class extends Error {
|
|
56
|
+
code = "ERR_UNKNOWN_MODE";
|
|
57
|
+
constructor(mode) {
|
|
58
|
+
super(`Unknown req-race mode: "${mode}".`);
|
|
59
|
+
this.name = "UnknownModeError";
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
function isSupersededError(err) {
|
|
63
|
+
return Boolean(
|
|
64
|
+
err && typeof err === "object" && (err.code === "ERR_SUPERSEDED" || err.reason === "superseded")
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
function isTimeoutError(err) {
|
|
68
|
+
return Boolean(
|
|
69
|
+
err && typeof err === "object" && (err.name === "TimeoutError" || err.code === "ETIMEDOUT")
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/chaos.ts
|
|
74
|
+
var VERSION = "1.1.0";
|
|
75
|
+
var MODES = [
|
|
76
|
+
"reverse-order",
|
|
77
|
+
"jitter",
|
|
78
|
+
"throttle-mutations",
|
|
79
|
+
"timeout",
|
|
80
|
+
"slow",
|
|
81
|
+
"flaky",
|
|
82
|
+
"error-status",
|
|
83
|
+
"rate-limit",
|
|
84
|
+
"offline",
|
|
85
|
+
"hang",
|
|
86
|
+
"abort-mid-body",
|
|
87
|
+
"shuffle",
|
|
88
|
+
"custom"
|
|
89
|
+
];
|
|
90
|
+
var DEFAULT_OPTIONS = {
|
|
91
|
+
mode: "reverse-order",
|
|
92
|
+
delayMs: 1e3,
|
|
93
|
+
timeoutMs: 1500,
|
|
94
|
+
minDelayMs: 100,
|
|
95
|
+
maxDelayMs: 900,
|
|
96
|
+
doubleSubmitWindowMs: 500,
|
|
97
|
+
errorRate: 0.3,
|
|
98
|
+
status: 503,
|
|
99
|
+
statusText: "Service Unavailable",
|
|
100
|
+
body: "",
|
|
101
|
+
headers: {},
|
|
102
|
+
rateLimitAfter: 3,
|
|
103
|
+
rateLimitWindowMs: 1e3,
|
|
104
|
+
retryAfterSeconds: 1,
|
|
105
|
+
partialBytes: 16,
|
|
106
|
+
shuffleWindowMs: 300,
|
|
107
|
+
maxLogs: 1e3
|
|
108
|
+
};
|
|
109
|
+
var MUTATION_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
110
|
+
var ACTIVE_TARGETS = /* @__PURE__ */ new WeakSet();
|
|
111
|
+
var DEFAULT_CLOCK = {
|
|
112
|
+
now: () => Date.now(),
|
|
113
|
+
setTimeout: (fn, ms) => globalThis.setTimeout(fn, ms),
|
|
114
|
+
clearTimeout: (id) => globalThis.clearTimeout(id)
|
|
115
|
+
};
|
|
116
|
+
function sleepWithClock(ms, clock, signal) {
|
|
117
|
+
return new Promise((resolve, reject) => {
|
|
118
|
+
if (signal?.aborted) {
|
|
119
|
+
reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const timer = clock.setTimeout(() => {
|
|
123
|
+
signal?.removeEventListener("abort", onAbort);
|
|
124
|
+
resolve();
|
|
125
|
+
}, ms);
|
|
126
|
+
function onAbort() {
|
|
127
|
+
clock.clearTimeout(timer);
|
|
128
|
+
reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));
|
|
129
|
+
}
|
|
130
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
function hangUntilAbort(signal) {
|
|
134
|
+
return new Promise((_resolve, reject) => {
|
|
135
|
+
if (signal?.aborted) {
|
|
136
|
+
reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
signal?.addEventListener(
|
|
140
|
+
"abort",
|
|
141
|
+
() => reject(signal.reason ?? new DOMException("Aborted", "AbortError")),
|
|
142
|
+
{ once: true }
|
|
143
|
+
);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
function defaultNormalizeKey(url, method) {
|
|
147
|
+
try {
|
|
148
|
+
const parsed = new URL(url, "http://localhost");
|
|
149
|
+
return `${method}:${parsed.pathname}`;
|
|
150
|
+
} catch {
|
|
151
|
+
return `${method}:${String(url).split("#")[0]?.split("?")[0] ?? ""}`;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function extractUrl(input) {
|
|
155
|
+
if (typeof input === "string") return input;
|
|
156
|
+
if (input instanceof URL) return input.href;
|
|
157
|
+
if (input && typeof input.url === "string") return input.url;
|
|
158
|
+
return String(input);
|
|
159
|
+
}
|
|
160
|
+
function matchesUrl(url, pattern) {
|
|
161
|
+
if (!pattern) return true;
|
|
162
|
+
if (typeof pattern === "function") return pattern(url);
|
|
163
|
+
if (pattern instanceof RegExp) return pattern.test(url);
|
|
164
|
+
return url.includes(String(pattern));
|
|
165
|
+
}
|
|
166
|
+
function validateModes(modeInput) {
|
|
167
|
+
const list = Array.isArray(modeInput) ? modeInput : [modeInput];
|
|
168
|
+
for (const m of list) {
|
|
169
|
+
if (!MODES.includes(m)) {
|
|
170
|
+
throw new UnknownModeError(String(m));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return list;
|
|
174
|
+
}
|
|
175
|
+
function makePartialBodyResponse(original, partialBytes) {
|
|
176
|
+
const stream = new ReadableStream({
|
|
177
|
+
async start(controller) {
|
|
178
|
+
try {
|
|
179
|
+
const text = await original.text();
|
|
180
|
+
const encoded = new TextEncoder().encode(text);
|
|
181
|
+
controller.enqueue(encoded.slice(0, Math.max(0, partialBytes)));
|
|
182
|
+
controller.error(new TypeError("network error mid-body"));
|
|
183
|
+
} catch (err) {
|
|
184
|
+
controller.error(err);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
return new Response(stream, {
|
|
189
|
+
status: original.status,
|
|
190
|
+
statusText: original.statusText,
|
|
191
|
+
headers: original.headers
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
function enableFetchRaceChaos(options = {}) {
|
|
195
|
+
const target = options.target ?? (typeof globalThis !== "undefined" ? globalThis : null);
|
|
196
|
+
if (!target || typeof target.fetch !== "function") {
|
|
197
|
+
throw new Error("enableFetchRaceChaos requires a target with a fetch() function.");
|
|
198
|
+
}
|
|
199
|
+
if (ACTIVE_TARGETS.has(target)) {
|
|
200
|
+
throw new AlreadyEnabledError();
|
|
201
|
+
}
|
|
202
|
+
let activeModes = validateModes(options.mode ?? DEFAULT_OPTIONS.mode);
|
|
203
|
+
let offlineForced = false;
|
|
204
|
+
let enabled = true;
|
|
205
|
+
const seed = options.seed ?? Math.floor(Math.random() * 1e9);
|
|
206
|
+
const rand = createSeededRandom(seed);
|
|
207
|
+
const clock = options.clock ?? DEFAULT_CLOCK;
|
|
208
|
+
const delayMs = options.delayMs ?? DEFAULT_OPTIONS.delayMs;
|
|
209
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_OPTIONS.timeoutMs;
|
|
210
|
+
const minDelayMs = options.minDelayMs ?? DEFAULT_OPTIONS.minDelayMs;
|
|
211
|
+
const maxDelayMs = options.maxDelayMs ?? DEFAULT_OPTIONS.maxDelayMs;
|
|
212
|
+
const doubleSubmitWindowMs = options.doubleSubmitWindowMs ?? DEFAULT_OPTIONS.doubleSubmitWindowMs;
|
|
213
|
+
const errorRate = options.errorRate ?? DEFAULT_OPTIONS.errorRate;
|
|
214
|
+
const maxLogs = options.maxLogs ?? DEFAULT_OPTIONS.maxLogs;
|
|
215
|
+
const normalizeKey = options.normalizeKey ?? defaultNormalizeKey;
|
|
216
|
+
const rawOriginalFetch = target.fetch;
|
|
217
|
+
const originalFetch = rawOriginalFetch.bind(target);
|
|
218
|
+
const inFlightByKey = /* @__PURE__ */ new Map();
|
|
219
|
+
const recentMutations = /* @__PURE__ */ new Map();
|
|
220
|
+
const rateLimitWindows = /* @__PURE__ */ new Map();
|
|
221
|
+
const logs = [];
|
|
222
|
+
const stats = {
|
|
223
|
+
totalRequests: 0,
|
|
224
|
+
reorderedResponses: 0,
|
|
225
|
+
abortedCount: 0,
|
|
226
|
+
unabortedStaleCount: 0,
|
|
227
|
+
duplicateMutations: 0,
|
|
228
|
+
timeouts: 0,
|
|
229
|
+
failedRequests: 0,
|
|
230
|
+
injectedErrors: 0,
|
|
231
|
+
rateLimited: 0,
|
|
232
|
+
hungRequests: 0,
|
|
233
|
+
partialBodies: 0,
|
|
234
|
+
retriedCount: 0,
|
|
235
|
+
deduplicatedCount: 0,
|
|
236
|
+
maxConcurrentPerKey: {},
|
|
237
|
+
byKey: {},
|
|
238
|
+
seed
|
|
239
|
+
};
|
|
240
|
+
let seq = 0;
|
|
241
|
+
ACTIVE_TARGETS.add(target);
|
|
242
|
+
const pushLog = (entry) => {
|
|
243
|
+
logs.push(entry);
|
|
244
|
+
if (logs.length > maxLogs) {
|
|
245
|
+
logs.shift();
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
const nav = target.navigator;
|
|
249
|
+
const rawSendBeacon = nav?.sendBeacon;
|
|
250
|
+
if (options.patchBeacon && nav && typeof rawSendBeacon === "function") {
|
|
251
|
+
nav.sendBeacon = function patchedSendBeacon(url, data) {
|
|
252
|
+
const key = normalizeKey(url, "BEACON");
|
|
253
|
+
const now = clock.now();
|
|
254
|
+
stats.totalRequests++;
|
|
255
|
+
const prev = recentMutations.get(key);
|
|
256
|
+
if (prev && now - prev <= doubleSubmitWindowMs) {
|
|
257
|
+
stats.duplicateMutations++;
|
|
258
|
+
}
|
|
259
|
+
recentMutations.set(key, now);
|
|
260
|
+
return rawSendBeacon.call(nav, url, data);
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
target.fetch = async function reqRaceFetch(input, init = {}) {
|
|
264
|
+
const url = extractUrl(input);
|
|
265
|
+
const method = (init?.method || (typeof input === "object" && "method" in input ? input.method : void 0) || "GET").toUpperCase();
|
|
266
|
+
if (!matchesUrl(url, options.urlPattern)) {
|
|
267
|
+
return originalFetch(input, init);
|
|
268
|
+
}
|
|
269
|
+
if (options.methods && !options.methods.map((m) => m.toUpperCase()).includes(method)) {
|
|
270
|
+
return originalFetch(input, init);
|
|
271
|
+
}
|
|
272
|
+
const matchedRule = options.rules?.find(
|
|
273
|
+
(r) => matchesUrl(url, r.urlPattern) && (!r.methods || r.methods.map((m) => m.toUpperCase()).includes(method))
|
|
274
|
+
);
|
|
275
|
+
const modesToRun = matchedRule ? validateModes(matchedRule.mode) : activeModes;
|
|
276
|
+
const effDelay = matchedRule?.delayMs ?? delayMs;
|
|
277
|
+
const effTimeout = matchedRule?.timeoutMs ?? timeoutMs;
|
|
278
|
+
const effMinDelay = matchedRule?.minDelayMs ?? minDelayMs;
|
|
279
|
+
const effMaxDelay = matchedRule?.maxDelayMs ?? maxDelayMs;
|
|
280
|
+
const effErrorRate = matchedRule?.errorRate ?? errorRate;
|
|
281
|
+
const id = ++seq;
|
|
282
|
+
const key = normalizeKey(url, method);
|
|
283
|
+
const startedAt = clock.now();
|
|
284
|
+
const signal = init?.signal || (typeof input === "object" && "signal" in input ? input.signal : void 0);
|
|
285
|
+
stats.totalRequests++;
|
|
286
|
+
const keyStat = stats.byKey[key] ??= { requests: 0, reordered: 0, unabortedStale: 0 };
|
|
287
|
+
keyStat.requests++;
|
|
288
|
+
if (MUTATION_METHODS.has(method)) {
|
|
289
|
+
const prevTs = recentMutations.get(key);
|
|
290
|
+
if (prevTs !== void 0 && startedAt - prevTs <= doubleSubmitWindowMs) {
|
|
291
|
+
stats.duplicateMutations++;
|
|
292
|
+
options.onRaceDetected?.({
|
|
293
|
+
type: "duplicate-mutation",
|
|
294
|
+
method,
|
|
295
|
+
key,
|
|
296
|
+
url,
|
|
297
|
+
requestId: id,
|
|
298
|
+
detail: `Duplicate ${method} within ${startedAt - prevTs}ms`
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
recentMutations.set(key, startedAt);
|
|
302
|
+
}
|
|
303
|
+
const entry = {
|
|
304
|
+
id,
|
|
305
|
+
key,
|
|
306
|
+
method,
|
|
307
|
+
url,
|
|
308
|
+
startedAt,
|
|
309
|
+
endedAt: null,
|
|
310
|
+
delayApplied: 0,
|
|
311
|
+
action: "pass",
|
|
312
|
+
status: null,
|
|
313
|
+
aborted: false,
|
|
314
|
+
reordered: false,
|
|
315
|
+
staleRisk: false,
|
|
316
|
+
mode: modesToRun.join("+")
|
|
317
|
+
};
|
|
318
|
+
pushLog(entry);
|
|
319
|
+
options.onRequest?.(entry);
|
|
320
|
+
const activeList = inFlightByKey.get(key) ?? [];
|
|
321
|
+
for (const prev of activeList) {
|
|
322
|
+
if (!prev.signal?.aborted && !MUTATION_METHODS.has(method)) {
|
|
323
|
+
prev.staleRisk = true;
|
|
324
|
+
stats.unabortedStaleCount++;
|
|
325
|
+
keyStat.unabortedStale++;
|
|
326
|
+
options.onRaceDetected?.({
|
|
327
|
+
type: "unaborted-stale",
|
|
328
|
+
method,
|
|
329
|
+
key,
|
|
330
|
+
url,
|
|
331
|
+
requestId: prev.id,
|
|
332
|
+
supersededBy: id,
|
|
333
|
+
detail: `Request #${prev.id} not aborted when #${id} started`
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
const tracker = { id, signal, staleRisk: false };
|
|
338
|
+
activeList.push(tracker);
|
|
339
|
+
inFlightByKey.set(key, activeList);
|
|
340
|
+
stats.maxConcurrentPerKey[key] = Math.max(
|
|
341
|
+
stats.maxConcurrentPerKey[key] ?? 0,
|
|
342
|
+
activeList.length
|
|
343
|
+
);
|
|
344
|
+
try {
|
|
345
|
+
if (offlineForced || modesToRun.includes("offline")) {
|
|
346
|
+
stats.injectedErrors++;
|
|
347
|
+
stats.failedRequests++;
|
|
348
|
+
entry.action = "offline-error";
|
|
349
|
+
throw new TypeError("Failed to fetch (offline)");
|
|
350
|
+
}
|
|
351
|
+
if (modesToRun.includes("hang")) {
|
|
352
|
+
stats.hungRequests++;
|
|
353
|
+
entry.action = "hang";
|
|
354
|
+
options.onRaceDetected?.({
|
|
355
|
+
type: "hang",
|
|
356
|
+
key,
|
|
357
|
+
method,
|
|
358
|
+
url,
|
|
359
|
+
requestId: id,
|
|
360
|
+
detail: "Request hung indefinitely"
|
|
361
|
+
});
|
|
362
|
+
await hangUntilAbort(signal);
|
|
363
|
+
}
|
|
364
|
+
if (modesToRun.includes("custom") && options.chaos) {
|
|
365
|
+
let decision;
|
|
366
|
+
try {
|
|
367
|
+
decision = await options.chaos(
|
|
368
|
+
{
|
|
369
|
+
method,
|
|
370
|
+
url,
|
|
371
|
+
key,
|
|
372
|
+
headers: {},
|
|
373
|
+
attempt: 1,
|
|
374
|
+
index: id,
|
|
375
|
+
indexForKey: keyStat.requests,
|
|
376
|
+
...signal ? { signal } : {}
|
|
377
|
+
},
|
|
378
|
+
{ random: rand, now: clock.now }
|
|
379
|
+
);
|
|
380
|
+
} catch (cbErr) {
|
|
381
|
+
throw new ChaosCallbackError("Chaos callback threw an error.", { cause: cbErr });
|
|
382
|
+
}
|
|
383
|
+
if (decision && "hang" in decision && decision.hang) {
|
|
384
|
+
stats.hungRequests++;
|
|
385
|
+
entry.action = "custom-hang";
|
|
386
|
+
await hangUntilAbort(signal);
|
|
387
|
+
} else if (decision && "fail" in decision) {
|
|
388
|
+
stats.injectedErrors++;
|
|
389
|
+
stats.failedRequests++;
|
|
390
|
+
if (decision.fail === "timeout") {
|
|
391
|
+
stats.timeouts++;
|
|
392
|
+
throw new TimeoutError();
|
|
393
|
+
}
|
|
394
|
+
if (decision.fail === "abort") {
|
|
395
|
+
throw new DOMException("Aborted by chaos", "AbortError");
|
|
396
|
+
}
|
|
397
|
+
throw new TypeError("Failed to fetch (custom chaos)");
|
|
398
|
+
} else if (decision && "respond" in decision) {
|
|
399
|
+
stats.injectedErrors++;
|
|
400
|
+
entry.status = decision.respond.status;
|
|
401
|
+
entry.action = "custom-respond";
|
|
402
|
+
return new Response(decision.respond.body ?? "", {
|
|
403
|
+
status: decision.respond.status,
|
|
404
|
+
...decision.respond.headers ? { headers: decision.respond.headers } : {}
|
|
405
|
+
});
|
|
406
|
+
} else if (decision && "delayMs" in decision) {
|
|
407
|
+
entry.delayApplied += decision.delayMs;
|
|
408
|
+
await sleepWithClock(decision.delayMs, clock, signal);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
for (const m of modesToRun) {
|
|
412
|
+
if (m === "timeout") {
|
|
413
|
+
await sleepWithClock(effTimeout, clock, signal);
|
|
414
|
+
stats.timeouts++;
|
|
415
|
+
stats.failedRequests++;
|
|
416
|
+
entry.action = "timeout";
|
|
417
|
+
options.onRaceDetected?.({
|
|
418
|
+
type: "timeout",
|
|
419
|
+
key,
|
|
420
|
+
method,
|
|
421
|
+
url,
|
|
422
|
+
requestId: id,
|
|
423
|
+
detail: `Timed out after ${effTimeout}ms`
|
|
424
|
+
});
|
|
425
|
+
throw new TimeoutError(`Request timed out after ${effTimeout}ms`);
|
|
426
|
+
}
|
|
427
|
+
if (m === "rate-limit") {
|
|
428
|
+
const limit = options.rateLimitAfter ?? DEFAULT_OPTIONS.rateLimitAfter;
|
|
429
|
+
const winMs = options.rateLimitWindowMs ?? DEFAULT_OPTIONS.rateLimitWindowMs;
|
|
430
|
+
const now = clock.now();
|
|
431
|
+
const recent = (rateLimitWindows.get(key) ?? []).filter((t) => now - t <= winMs);
|
|
432
|
+
recent.push(now);
|
|
433
|
+
rateLimitWindows.set(key, recent);
|
|
434
|
+
if (recent.length > limit) {
|
|
435
|
+
stats.rateLimited++;
|
|
436
|
+
stats.injectedErrors++;
|
|
437
|
+
entry.status = 429;
|
|
438
|
+
entry.action = "rate-limited";
|
|
439
|
+
options.onRaceDetected?.({
|
|
440
|
+
type: "rate-limited",
|
|
441
|
+
key,
|
|
442
|
+
method,
|
|
443
|
+
url,
|
|
444
|
+
requestId: id,
|
|
445
|
+
detail: "429 Too Many Requests"
|
|
446
|
+
});
|
|
447
|
+
return new Response("Too Many Requests", {
|
|
448
|
+
status: 429,
|
|
449
|
+
headers: {
|
|
450
|
+
"Retry-After": String(options.retryAfterSeconds ?? DEFAULT_OPTIONS.retryAfterSeconds)
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
if (m === "flaky" && rand() < effErrorRate) {
|
|
456
|
+
stats.injectedErrors++;
|
|
457
|
+
stats.failedRequests++;
|
|
458
|
+
entry.action = "flaky-error";
|
|
459
|
+
throw new TypeError("Failed to fetch (flaky)");
|
|
460
|
+
}
|
|
461
|
+
if (m === "error-status" && rand() < effErrorRate) {
|
|
462
|
+
const status = matchedRule?.status ?? options.status ?? DEFAULT_OPTIONS.status;
|
|
463
|
+
stats.injectedErrors++;
|
|
464
|
+
entry.status = status;
|
|
465
|
+
entry.action = "error-status";
|
|
466
|
+
return new Response(matchedRule?.body ?? options.body ?? "", {
|
|
467
|
+
status,
|
|
468
|
+
statusText: matchedRule?.statusText ?? options.statusText ?? DEFAULT_OPTIONS.statusText,
|
|
469
|
+
headers: matchedRule?.headers ?? options.headers ?? {}
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
if (m === "slow") {
|
|
473
|
+
entry.delayApplied += effDelay;
|
|
474
|
+
await sleepWithClock(effDelay, clock, signal);
|
|
475
|
+
}
|
|
476
|
+
if (m === "jitter") {
|
|
477
|
+
const span = Math.max(0, effMaxDelay - effMinDelay);
|
|
478
|
+
const d = Math.floor(effMinDelay + rand() * span);
|
|
479
|
+
entry.delayApplied += d;
|
|
480
|
+
await sleepWithClock(d, clock, signal);
|
|
481
|
+
}
|
|
482
|
+
if (m === "shuffle") {
|
|
483
|
+
const d = Math.floor(rand() * (options.shuffleWindowMs ?? DEFAULT_OPTIONS.shuffleWindowMs));
|
|
484
|
+
entry.delayApplied += d;
|
|
485
|
+
await sleepWithClock(d, clock, signal);
|
|
486
|
+
}
|
|
487
|
+
if (m === "throttle-mutations" && MUTATION_METHODS.has(method)) {
|
|
488
|
+
entry.delayApplied += effDelay;
|
|
489
|
+
await sleepWithClock(effDelay, clock, signal);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
let response = await originalFetch(input, init);
|
|
493
|
+
if (modesToRun.includes("reverse-order")) {
|
|
494
|
+
const listNow = inFlightByKey.get(key) ?? [];
|
|
495
|
+
const hasNewer = listNow.some((item) => item.id > id);
|
|
496
|
+
if (hasNewer && !signal?.aborted) {
|
|
497
|
+
entry.delayApplied += effDelay;
|
|
498
|
+
entry.reordered = true;
|
|
499
|
+
entry.action = "reordered";
|
|
500
|
+
stats.reorderedResponses++;
|
|
501
|
+
keyStat.reordered++;
|
|
502
|
+
await sleepWithClock(effDelay, clock, signal);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
if (modesToRun.includes("abort-mid-body")) {
|
|
506
|
+
stats.partialBodies++;
|
|
507
|
+
entry.action = "abort-mid-body";
|
|
508
|
+
response = makePartialBodyResponse(
|
|
509
|
+
response,
|
|
510
|
+
options.partialBytes ?? DEFAULT_OPTIONS.partialBytes
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
entry.status = response.status ?? 200;
|
|
514
|
+
entry.endedAt = clock.now();
|
|
515
|
+
entry.staleRisk = tracker.staleRisk;
|
|
516
|
+
options.onResponse?.(entry);
|
|
517
|
+
return response;
|
|
518
|
+
} catch (err) {
|
|
519
|
+
if (err?.name === "AbortError" || signal?.aborted) {
|
|
520
|
+
entry.aborted = true;
|
|
521
|
+
stats.abortedCount++;
|
|
522
|
+
} else if (entry.action === "pass") {
|
|
523
|
+
stats.failedRequests++;
|
|
524
|
+
entry.error = err?.message ?? String(err);
|
|
525
|
+
}
|
|
526
|
+
entry.endedAt = clock.now();
|
|
527
|
+
entry.staleRisk = tracker.staleRisk;
|
|
528
|
+
throw err;
|
|
529
|
+
} finally {
|
|
530
|
+
const remaining = (inFlightByKey.get(key) ?? []).filter((item) => item.id !== id);
|
|
531
|
+
if (remaining.length > 0) {
|
|
532
|
+
inFlightByKey.set(key, remaining);
|
|
533
|
+
} else {
|
|
534
|
+
inFlightByKey.delete(key);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
return {
|
|
539
|
+
disable() {
|
|
540
|
+
if (!enabled) return;
|
|
541
|
+
enabled = false;
|
|
542
|
+
target.fetch = rawOriginalFetch;
|
|
543
|
+
if (options.patchBeacon && nav && rawSendBeacon) {
|
|
544
|
+
nav.sendBeacon = rawSendBeacon;
|
|
545
|
+
}
|
|
546
|
+
ACTIVE_TARGETS.delete(target);
|
|
547
|
+
},
|
|
548
|
+
getStats() {
|
|
549
|
+
return {
|
|
550
|
+
...stats,
|
|
551
|
+
maxConcurrentPerKey: { ...stats.maxConcurrentPerKey },
|
|
552
|
+
byKey: { ...stats.byKey }
|
|
553
|
+
};
|
|
554
|
+
},
|
|
555
|
+
getLogs() {
|
|
556
|
+
return logs.map((l) => ({ ...l }));
|
|
557
|
+
},
|
|
558
|
+
resetStats() {
|
|
559
|
+
stats.totalRequests = 0;
|
|
560
|
+
stats.reorderedResponses = 0;
|
|
561
|
+
stats.abortedCount = 0;
|
|
562
|
+
stats.unabortedStaleCount = 0;
|
|
563
|
+
stats.duplicateMutations = 0;
|
|
564
|
+
stats.timeouts = 0;
|
|
565
|
+
stats.failedRequests = 0;
|
|
566
|
+
stats.injectedErrors = 0;
|
|
567
|
+
stats.rateLimited = 0;
|
|
568
|
+
stats.hungRequests = 0;
|
|
569
|
+
stats.partialBodies = 0;
|
|
570
|
+
stats.retriedCount = 0;
|
|
571
|
+
stats.deduplicatedCount = 0;
|
|
572
|
+
stats.maxConcurrentPerKey = {};
|
|
573
|
+
stats.byKey = {};
|
|
574
|
+
logs.length = 0;
|
|
575
|
+
recentMutations.clear();
|
|
576
|
+
rateLimitWindows.clear();
|
|
577
|
+
},
|
|
578
|
+
setOffline(offline) {
|
|
579
|
+
offlineForced = offline;
|
|
580
|
+
},
|
|
581
|
+
setMode(mode) {
|
|
582
|
+
activeModes = validateModes(mode);
|
|
583
|
+
},
|
|
584
|
+
getSeed() {
|
|
585
|
+
return seed;
|
|
586
|
+
},
|
|
587
|
+
isEnabled() {
|
|
588
|
+
return enabled;
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
function enableXhrRaceChaos(options = {}) {
|
|
593
|
+
return enableFetchRaceChaos({ ...options, patchXhr: true });
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// src/safe-fetch.ts
|
|
597
|
+
var MUTATION_METHODS2 = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
598
|
+
var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 425, 429, 500, 502, 503, 504]);
|
|
599
|
+
function mergeSignals(signals) {
|
|
600
|
+
const valid = signals.filter((s) => Boolean(s));
|
|
601
|
+
const controller = new AbortController();
|
|
602
|
+
const listeners = [];
|
|
603
|
+
for (const sig of valid) {
|
|
604
|
+
if (sig.aborted) {
|
|
605
|
+
controller.abort(sig.reason);
|
|
606
|
+
return { signal: controller.signal, cleanup: () => {
|
|
607
|
+
} };
|
|
608
|
+
}
|
|
609
|
+
const fn = () => controller.abort(sig.reason);
|
|
610
|
+
sig.addEventListener("abort", fn, { once: true });
|
|
611
|
+
listeners.push({ sig, fn });
|
|
612
|
+
}
|
|
613
|
+
return {
|
|
614
|
+
signal: controller.signal,
|
|
615
|
+
cleanup: () => {
|
|
616
|
+
for (const { sig, fn } of listeners) {
|
|
617
|
+
sig.removeEventListener("abort", fn);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
function sleep(ms, signal) {
|
|
623
|
+
return new Promise((resolve, reject) => {
|
|
624
|
+
if (signal?.aborted) {
|
|
625
|
+
reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
const timer = setTimeout(() => {
|
|
629
|
+
signal?.removeEventListener("abort", onAbort);
|
|
630
|
+
resolve();
|
|
631
|
+
}, ms);
|
|
632
|
+
function onAbort() {
|
|
633
|
+
clearTimeout(timer);
|
|
634
|
+
reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));
|
|
635
|
+
}
|
|
636
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
function parseRetryAfterMs(headerVal) {
|
|
640
|
+
if (!headerVal) return null;
|
|
641
|
+
const secs = Number(headerVal);
|
|
642
|
+
if (!Number.isNaN(secs) && secs >= 0) return secs * 1e3;
|
|
643
|
+
const dateMs = Date.parse(headerVal);
|
|
644
|
+
if (!Number.isNaN(dateMs)) return Math.max(0, dateMs - Date.now());
|
|
645
|
+
return null;
|
|
646
|
+
}
|
|
647
|
+
function createRaceSafeFetch(fetchImpl = (...args) => globalThis.fetch(...args), optionsOrNormalizeKey = {}) {
|
|
648
|
+
const isFn = typeof optionsOrNormalizeKey === "function";
|
|
649
|
+
const opts = isFn ? { normalizeKey: optionsOrNormalizeKey } : optionsOrNormalizeKey;
|
|
650
|
+
const normalizeKey = opts.keyBy ?? opts.normalizeKey ?? defaultNormalizeKey;
|
|
651
|
+
const supersedeMethods = new Set(
|
|
652
|
+
(opts.supersedeMethods ?? ["GET", "HEAD"]).map((m) => m.toUpperCase())
|
|
653
|
+
);
|
|
654
|
+
const dedupeMutations = Boolean(opts.dedupeMutations);
|
|
655
|
+
const dedupeWindowMs = opts.dedupeWindowMs ?? 0;
|
|
656
|
+
const timeoutMs = opts.timeoutMs ?? 0;
|
|
657
|
+
const totalTimeoutMs = opts.totalTimeoutMs ?? 0;
|
|
658
|
+
const retries = opts.retries ?? 0;
|
|
659
|
+
const retryMethods = new Set(
|
|
660
|
+
(opts.retryMethods ?? ["GET", "HEAD", "OPTIONS"]).map((m) => m.toUpperCase())
|
|
661
|
+
);
|
|
662
|
+
const retryDelayMs = opts.retryDelayMs ?? 200;
|
|
663
|
+
const retryBackoff = opts.retryBackoff ?? 2;
|
|
664
|
+
const maxRetryDelayMs = opts.maxRetryDelayMs ?? 1e4;
|
|
665
|
+
const retryJitter = opts.retryJitter ?? true;
|
|
666
|
+
const respectRetryAfter = opts.respectRetryAfter ?? true;
|
|
667
|
+
const controllers = /* @__PURE__ */ new Map();
|
|
668
|
+
const inFlightMutations = /* @__PURE__ */ new Map();
|
|
669
|
+
const defaultRetryOn = (resOrErr) => {
|
|
670
|
+
if (resOrErr instanceof Error) {
|
|
671
|
+
if (isSupersededError(resOrErr) || resOrErr.name === "AbortError") return false;
|
|
672
|
+
return true;
|
|
673
|
+
}
|
|
674
|
+
return RETRY_STATUSES.has(resOrErr.status);
|
|
675
|
+
};
|
|
676
|
+
const shouldRetry = opts.retryOn ?? defaultRetryOn;
|
|
677
|
+
const runOnce = async (input, init, baseSignal, key) => {
|
|
678
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
679
|
+
return fetchImpl(input, { ...init, ...baseSignal ? { signal: baseSignal } : {} });
|
|
680
|
+
}
|
|
681
|
+
const timeoutController = new AbortController();
|
|
682
|
+
let timedOut = false;
|
|
683
|
+
const timer = setTimeout(() => {
|
|
684
|
+
timedOut = true;
|
|
685
|
+
const err = new TimeoutError(`Request timed out after ${timeoutMs}ms`);
|
|
686
|
+
timeoutController.abort(err);
|
|
687
|
+
if (key) opts.onTimeout?.({ key, timeoutMs });
|
|
688
|
+
}, timeoutMs);
|
|
689
|
+
const merged = mergeSignals([baseSignal, timeoutController.signal]);
|
|
690
|
+
try {
|
|
691
|
+
return await fetchImpl(input, { ...init, signal: merged.signal });
|
|
692
|
+
} catch (err) {
|
|
693
|
+
if (timedOut) {
|
|
694
|
+
throw new TimeoutError(`Request timed out after ${timeoutMs}ms`);
|
|
695
|
+
}
|
|
696
|
+
throw err;
|
|
697
|
+
} finally {
|
|
698
|
+
clearTimeout(timer);
|
|
699
|
+
merged.cleanup();
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
return async function raceSafeFetch(input, init = {}) {
|
|
703
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
704
|
+
const method = (init?.method || (typeof input === "object" && "method" in input ? input.method : void 0) || "GET").toUpperCase();
|
|
705
|
+
const key = normalizeKey(url, method);
|
|
706
|
+
const headers = new Headers(
|
|
707
|
+
init?.headers ?? (typeof input === "object" && "headers" in input ? input.headers : void 0)
|
|
708
|
+
);
|
|
709
|
+
if (opts.idempotencyKey && MUTATION_METHODS2.has(method) && !headers.has("Idempotency-Key")) {
|
|
710
|
+
const ikey = typeof opts.idempotencyKey === "function" ? opts.idempotencyKey(url, method) : `${key}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
711
|
+
headers.set("Idempotency-Key", ikey);
|
|
712
|
+
}
|
|
713
|
+
const nextInit = { ...init, headers };
|
|
714
|
+
if (supersedeMethods.has(method)) {
|
|
715
|
+
const prev = controllers.get(key);
|
|
716
|
+
if (prev) {
|
|
717
|
+
opts.onAbort?.({ key, url, method });
|
|
718
|
+
prev.abort(new SupersededError());
|
|
719
|
+
}
|
|
720
|
+
const controller = new AbortController();
|
|
721
|
+
controllers.set(key, controller);
|
|
722
|
+
const merged = mergeSignals([
|
|
723
|
+
init?.signal ?? (typeof input === "object" && "signal" in input ? input.signal : void 0),
|
|
724
|
+
controller.signal
|
|
725
|
+
]);
|
|
726
|
+
const totalDeadline = totalTimeoutMs > 0 ? Date.now() + totalTimeoutMs : Infinity;
|
|
727
|
+
try {
|
|
728
|
+
let attempt = 0;
|
|
729
|
+
while (true) {
|
|
730
|
+
try {
|
|
731
|
+
const res = await runOnce(input, nextInit, merged.signal, key);
|
|
732
|
+
if (attempt < retries && retryMethods.has(method) && shouldRetry(res, attempt + 1) && Date.now() < totalDeadline) {
|
|
733
|
+
attempt++;
|
|
734
|
+
const ra = respectRetryAfter ? parseRetryAfterMs(res.headers?.get?.("Retry-After") ?? null) : null;
|
|
735
|
+
const rawDelay = ra ?? Math.min(maxRetryDelayMs, retryDelayMs * retryBackoff ** (attempt - 1));
|
|
736
|
+
const d = retryJitter ? Math.floor(rawDelay * (0.5 + Math.random() * 0.5)) : rawDelay;
|
|
737
|
+
opts.onRetry?.({ key, attempt, delayMs: d });
|
|
738
|
+
await sleep(d, merged.signal);
|
|
739
|
+
continue;
|
|
740
|
+
}
|
|
741
|
+
return res;
|
|
742
|
+
} catch (err) {
|
|
743
|
+
const userAborted = isSupersededError(err) || err?.name === "AbortError" || merged.signal.aborted;
|
|
744
|
+
if (!userAborted && attempt < retries && retryMethods.has(method) && shouldRetry(err, attempt + 1) && Date.now() < totalDeadline) {
|
|
745
|
+
attempt++;
|
|
746
|
+
const rawDelay = Math.min(maxRetryDelayMs, retryDelayMs * retryBackoff ** (attempt - 1));
|
|
747
|
+
const d = retryJitter ? Math.floor(rawDelay * (0.5 + Math.random() * 0.5)) : rawDelay;
|
|
748
|
+
opts.onRetry?.({ key, attempt, delayMs: d });
|
|
749
|
+
await sleep(d, merged.signal);
|
|
750
|
+
continue;
|
|
751
|
+
}
|
|
752
|
+
throw err;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
} finally {
|
|
756
|
+
merged.cleanup();
|
|
757
|
+
if (controllers.get(key) === controller) {
|
|
758
|
+
controllers.delete(key);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
if (dedupeMutations && MUTATION_METHODS2.has(method)) {
|
|
763
|
+
const existing = inFlightMutations.get(key);
|
|
764
|
+
if (existing && (dedupeWindowMs === 0 || Date.now() - existing.startedAt <= dedupeWindowMs)) {
|
|
765
|
+
opts.onDedupe?.({ key, url });
|
|
766
|
+
const res2 = await existing.promise;
|
|
767
|
+
return typeof res2?.clone === "function" ? res2.clone() : res2;
|
|
768
|
+
}
|
|
769
|
+
const promise = Promise.resolve(runOnce(input, nextInit, init?.signal ?? void 0, key)).finally(() => {
|
|
770
|
+
if (inFlightMutations.get(key)?.promise === promise) {
|
|
771
|
+
inFlightMutations.delete(key);
|
|
772
|
+
}
|
|
773
|
+
});
|
|
774
|
+
inFlightMutations.set(key, { promise, startedAt: Date.now() });
|
|
775
|
+
const res = await promise;
|
|
776
|
+
return typeof res?.clone === "function" ? res.clone() : res;
|
|
777
|
+
}
|
|
778
|
+
return runOnce(input, nextInit, init?.signal ?? void 0, key);
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
function createLatestGuard() {
|
|
782
|
+
let currentId = 0;
|
|
783
|
+
let currentController = null;
|
|
784
|
+
return {
|
|
785
|
+
next() {
|
|
786
|
+
currentController?.abort(new SupersededError());
|
|
787
|
+
currentId++;
|
|
788
|
+
const id = currentId;
|
|
789
|
+
const controller = new AbortController();
|
|
790
|
+
currentController = controller;
|
|
791
|
+
return {
|
|
792
|
+
id,
|
|
793
|
+
signal: controller.signal,
|
|
794
|
+
isLatest: () => id === currentId
|
|
795
|
+
};
|
|
796
|
+
},
|
|
797
|
+
async run(fn) {
|
|
798
|
+
const ticket = this.next();
|
|
799
|
+
const value = await fn(ticket.signal);
|
|
800
|
+
if (!ticket.isLatest()) {
|
|
801
|
+
return { stale: true };
|
|
802
|
+
}
|
|
803
|
+
return { stale: false, value };
|
|
804
|
+
},
|
|
805
|
+
reset() {
|
|
806
|
+
currentController?.abort(new SupersededError());
|
|
807
|
+
currentController = null;
|
|
808
|
+
currentId++;
|
|
809
|
+
}
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
function createLatestOnly(fn, options = {}) {
|
|
813
|
+
const mode = options.onSuperseded ?? "reject";
|
|
814
|
+
let seq = 0;
|
|
815
|
+
const wrapped = async function(...args) {
|
|
816
|
+
const id = ++seq;
|
|
817
|
+
const res = await fn.apply(this, args);
|
|
818
|
+
if (id !== seq) {
|
|
819
|
+
if (mode === "resolve-undefined") return void 0;
|
|
820
|
+
throw new SupersededError();
|
|
821
|
+
}
|
|
822
|
+
return res;
|
|
823
|
+
};
|
|
824
|
+
wrapped.cancel = () => {
|
|
825
|
+
seq++;
|
|
826
|
+
};
|
|
827
|
+
return wrapped;
|
|
828
|
+
}
|
|
829
|
+
function createMutationLock(fn, options = {}) {
|
|
830
|
+
const mode = options.mode ?? "ignore";
|
|
831
|
+
let pending = null;
|
|
832
|
+
const wrapped = async function(...args) {
|
|
833
|
+
if (pending) {
|
|
834
|
+
if (mode === "ignore") return void 0;
|
|
835
|
+
if (mode === "share") return pending;
|
|
836
|
+
await pending.catch(() => {
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
const p = Promise.resolve(fn.apply(this, args)).finally(() => {
|
|
840
|
+
if (pending === p) pending = null;
|
|
841
|
+
});
|
|
842
|
+
pending = p;
|
|
843
|
+
return p;
|
|
844
|
+
};
|
|
845
|
+
wrapped.isPending = () => Boolean(pending);
|
|
846
|
+
return wrapped;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
// src/reporters.ts
|
|
850
|
+
function escapeXml(str) {
|
|
851
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
852
|
+
}
|
|
853
|
+
function formatRaceReport(stats, options = {}) {
|
|
854
|
+
if (!stats) return "No req-race telemetry recorded.";
|
|
855
|
+
const useColor = options.color ?? false;
|
|
856
|
+
const red = (s) => useColor ? `\x1B[31m${s}\x1B[0m` : s;
|
|
857
|
+
const green = (s) => useColor ? `\x1B[32m${s}\x1B[0m` : s;
|
|
858
|
+
const hasIssues = stats.unabortedStaleCount > 0 || stats.duplicateMutations > 0;
|
|
859
|
+
const lines = [
|
|
860
|
+
hasIssues ? red(`\u2716 req-race v${VERSION} detected potential race conditions (seed: ${stats.seed}):`) : green(`\u2714 req-race v${VERSION} passed (${stats.totalRequests} requests, seed: ${stats.seed}):`),
|
|
861
|
+
` \u251C\u2500 Total requests: ${stats.totalRequests}`,
|
|
862
|
+
` \u251C\u2500 Reordered responses: ${stats.reorderedResponses}`,
|
|
863
|
+
` \u251C\u2500 Properly aborted: ${stats.abortedCount}`,
|
|
864
|
+
` \u251C\u2500 Unaborted stale risks: ${stats.unabortedStaleCount}`,
|
|
865
|
+
` \u251C\u2500 Duplicate mutations: ${stats.duplicateMutations}`,
|
|
866
|
+
` \u2514\u2500 Timeouts / Failed: ${stats.timeouts} / ${stats.failedRequests}`
|
|
867
|
+
];
|
|
868
|
+
if (options.verbose && options.logs?.length) {
|
|
869
|
+
lines.push("", "Timeline:");
|
|
870
|
+
for (const l of options.logs) {
|
|
871
|
+
lines.push(` #${l.id} ${l.method} ${l.url} -> ${l.action} (delay: ${l.delayApplied}ms)`);
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
return lines.join("\n");
|
|
875
|
+
}
|
|
876
|
+
function toJson(stats, logs = []) {
|
|
877
|
+
return { version: VERSION, seed: stats.seed, stats, logs };
|
|
878
|
+
}
|
|
879
|
+
function toMarkdown(stats, logs = []) {
|
|
880
|
+
const status = stats.unabortedStaleCount > 0 || stats.duplicateMutations > 0 ? "\u2716 Issues Found" : "\u2714 Passed";
|
|
881
|
+
return [
|
|
882
|
+
`## req-race Report (${status})`,
|
|
883
|
+
"",
|
|
884
|
+
`- **Seed:** \`${stats.seed}\``,
|
|
885
|
+
`- **Total Requests:** ${stats.totalRequests}`,
|
|
886
|
+
`- **Reordered Responses:** ${stats.reorderedResponses}`,
|
|
887
|
+
`- **Unaborted Stale Risks:** ${stats.unabortedStaleCount}`,
|
|
888
|
+
`- **Duplicate Mutations:** ${stats.duplicateMutations}`,
|
|
889
|
+
`- **Logged Entries:** ${logs.length}`,
|
|
890
|
+
""
|
|
891
|
+
].join("\n");
|
|
892
|
+
}
|
|
893
|
+
function toJUnit(stats, _logs = []) {
|
|
894
|
+
const failures = [];
|
|
895
|
+
if (stats.unabortedStaleCount > 0) {
|
|
896
|
+
failures.push(
|
|
897
|
+
` <testcase name="unaborted-stale-race" classname="req-race">
|
|
898
|
+
<failure message="${escapeXml(`${stats.unabortedStaleCount} unaborted stale race(s) detected`)}" />
|
|
899
|
+
</testcase>`
|
|
900
|
+
);
|
|
901
|
+
}
|
|
902
|
+
if (stats.duplicateMutations > 0) {
|
|
903
|
+
failures.push(
|
|
904
|
+
` <testcase name="duplicate-mutation" classname="req-race">
|
|
905
|
+
<failure message="${escapeXml(`${stats.duplicateMutations} duplicate mutation(s) detected`)}" />
|
|
906
|
+
</testcase>`
|
|
907
|
+
);
|
|
908
|
+
}
|
|
909
|
+
const cases = failures.length === 0 ? ` <testcase name="req-race-chaos" classname="req-race" />` : failures.join("\n");
|
|
910
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
911
|
+
<testsuite name="req-race" tests="${Math.max(1, failures.length)}" failures="${failures.length}">
|
|
912
|
+
${cases}
|
|
913
|
+
</testsuite>
|
|
914
|
+
`;
|
|
915
|
+
}
|
|
916
|
+
function toSarif(stats, _logs = []) {
|
|
917
|
+
const results = [];
|
|
918
|
+
if (stats.unabortedStaleCount > 0) {
|
|
919
|
+
results.push({
|
|
920
|
+
ruleId: "unaborted-stale",
|
|
921
|
+
level: "error",
|
|
922
|
+
message: { text: `${stats.unabortedStaleCount} unaborted overlapping GET request(s) detected.` }
|
|
923
|
+
});
|
|
924
|
+
}
|
|
925
|
+
if (stats.duplicateMutations > 0) {
|
|
926
|
+
results.push({
|
|
927
|
+
ruleId: "duplicate-mutation",
|
|
928
|
+
level: "error",
|
|
929
|
+
message: { text: `${stats.duplicateMutations} duplicate mutation request(s) detected.` }
|
|
930
|
+
});
|
|
931
|
+
}
|
|
932
|
+
return {
|
|
933
|
+
$schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
|
|
934
|
+
version: "2.1.0",
|
|
935
|
+
runs: [{ tool: { driver: { name: "req-race", version: VERSION } }, results }]
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
// src/config.ts
|
|
940
|
+
var CONFIG_FILES = [
|
|
941
|
+
"req-race.config.json",
|
|
942
|
+
"req-race.config.js",
|
|
943
|
+
"req-race.config.mjs",
|
|
944
|
+
"req-race.config.cjs"
|
|
945
|
+
];
|
|
946
|
+
function defineConfig(config) {
|
|
947
|
+
return config;
|
|
948
|
+
}
|
|
949
|
+
async function loadConfig(cwd, explicitPath) {
|
|
950
|
+
const { existsSync, readFileSync } = await import("node:fs");
|
|
951
|
+
const { resolve } = await import("node:path");
|
|
952
|
+
const { pathToFileURL } = await import("node:url");
|
|
953
|
+
const readCfg = async (absPath) => {
|
|
954
|
+
if (absPath.endsWith(".json")) {
|
|
955
|
+
return JSON.parse(readFileSync(absPath, "utf8"));
|
|
956
|
+
}
|
|
957
|
+
const mod = await import(pathToFileURL(absPath).href);
|
|
958
|
+
return mod.default ?? mod;
|
|
959
|
+
};
|
|
960
|
+
if (explicitPath) {
|
|
961
|
+
const abs = resolve(cwd, explicitPath);
|
|
962
|
+
return readCfg(abs);
|
|
963
|
+
}
|
|
964
|
+
for (const name of CONFIG_FILES) {
|
|
965
|
+
const abs = resolve(cwd, name);
|
|
966
|
+
if (existsSync(abs)) return readCfg(abs);
|
|
967
|
+
}
|
|
968
|
+
const pkgPath = resolve(cwd, "package.json");
|
|
969
|
+
if (existsSync(pkgPath)) {
|
|
970
|
+
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
|
|
971
|
+
if (pkg["req-race"]) return pkg["req-race"];
|
|
972
|
+
}
|
|
973
|
+
return {};
|
|
974
|
+
}
|
|
975
|
+
export {
|
|
976
|
+
AlreadyEnabledError,
|
|
977
|
+
ChaosCallbackError,
|
|
978
|
+
DEFAULT_OPTIONS,
|
|
979
|
+
MODES,
|
|
980
|
+
RaceAssertionError,
|
|
981
|
+
SupersededError,
|
|
982
|
+
TimeoutError,
|
|
983
|
+
UnknownModeError,
|
|
984
|
+
VERSION,
|
|
985
|
+
createLatestGuard,
|
|
986
|
+
createLatestOnly,
|
|
987
|
+
createMutationLock,
|
|
988
|
+
createRaceSafeFetch,
|
|
989
|
+
createSeededRandom,
|
|
990
|
+
defaultNormalizeKey,
|
|
991
|
+
defineConfig,
|
|
992
|
+
enableFetchRaceChaos,
|
|
993
|
+
enableXhrRaceChaos,
|
|
994
|
+
formatRaceReport,
|
|
995
|
+
isSupersededError,
|
|
996
|
+
isTimeoutError,
|
|
997
|
+
loadConfig,
|
|
998
|
+
toJUnit,
|
|
999
|
+
toJson,
|
|
1000
|
+
toMarkdown,
|
|
1001
|
+
toSarif
|
|
1002
|
+
};
|