req-race 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -2
- package/bin/req-race.js +87 -0
- package/package.json +51 -4
- package/src/index.d.ts +54 -0
- package/src/index.js +322 -0
- package/src/playwright.d.ts +22 -0
- package/src/playwright.js +79 -0
package/README.md
CHANGED
|
@@ -1,3 +1,107 @@
|
|
|
1
|
-
#
|
|
1
|
+
# req-race
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Automated stale-fetch race condition, out-of-order response chaos, and double-submit mutation tester** for browsers, Playwright, and CI.
|
|
4
|
+
|
|
5
|
+
Zero runtime dependencies for the core engine. Optional `playwright` peer dependency for E2E assertions and CLI scanning.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Why `req-race`?
|
|
10
|
+
|
|
11
|
+
Local APIs respond in ~5ms, hiding two of the most common production bugs:
|
|
12
|
+
|
|
13
|
+
1. **Stale-Fetch Race Conditions:** Typing `"react"` then `"rust"` fires two requests. If `"react"` returns after `"rust"`, the UI gets overwritten with stale `"react"` results.
|
|
14
|
+
2. **Double-Submit Mutations:** Double-clicking a submit/payment button fires duplicate `POST` requests.
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
npm install req-race
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
For Playwright assertions or CLI scanning:
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install -D playwright
|
|
28
|
+
npx playwright install chromium
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## Quick Start
|
|
34
|
+
|
|
35
|
+
### 1. Dev-Mode Chaos (`enableFetchRaceChaos`)
|
|
36
|
+
|
|
37
|
+
Drop into your app entry during development to reverse overlapping `fetch` responses and expose race conditions on `localhost`:
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
import { enableFetchRaceChaos, formatRaceReport } from "req-race";
|
|
41
|
+
|
|
42
|
+
const chaos = enableFetchRaceChaos({
|
|
43
|
+
mode: "reverse-order", // "reverse-order" | "jitter" | "throttle-mutations"
|
|
44
|
+
delayMs: 1000,
|
|
45
|
+
doubleSubmitWindowMs: 500,
|
|
46
|
+
onRaceDetected: (event) => console.warn("Race detected:", event),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// Later inspect telemetry:
|
|
50
|
+
console.log(formatRaceReport(chaos.getStats()));
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### 2. Race-Safe Fetch Wrapper (`createRaceSafeFetch`)
|
|
54
|
+
|
|
55
|
+
Automatically abort superseded in-flight `GET`/`HEAD` requests to the same endpoint:
|
|
56
|
+
|
|
57
|
+
```js
|
|
58
|
+
import { createRaceSafeFetch } from "req-race";
|
|
59
|
+
|
|
60
|
+
const safeFetch = createRaceSafeFetch();
|
|
61
|
+
const res = await safeFetch(`/api/search?q=${encodeURIComponent(query)}`);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### 3. Playwright CI Assertions (`req-race/playwright`)
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
import { test } from "@playwright/test";
|
|
68
|
+
import { assertNoStaleRace, assertNoDoubleSubmit } from "req-race/playwright";
|
|
69
|
+
|
|
70
|
+
test("search ignores stale out-of-order responses", async ({ page }) => {
|
|
71
|
+
await page.goto("http://localhost:5173/search");
|
|
72
|
+
|
|
73
|
+
await assertNoStaleRace(page, {
|
|
74
|
+
url: "**/api/search*",
|
|
75
|
+
trigger: async () => {
|
|
76
|
+
await page.fill("input[type=search]", "react");
|
|
77
|
+
await page.fill("input[type=search]", "rust");
|
|
78
|
+
},
|
|
79
|
+
selector: ".results-title",
|
|
80
|
+
expectedText: "rust",
|
|
81
|
+
delayMs: 800,
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("checkout button prevents double submit", async ({ page }) => {
|
|
86
|
+
await page.goto("http://localhost:5173/checkout");
|
|
87
|
+
|
|
88
|
+
await assertNoDoubleSubmit(page, {
|
|
89
|
+
button: 'button:has-text("Pay Now")',
|
|
90
|
+
url: "**/api/orders",
|
|
91
|
+
maxRequests: 1,
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### 4. CLI Usage
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
npx req-race http://localhost:5173 --mode reverse-order --delay 1000
|
|
100
|
+
npx req-race http://localhost:5173 --json
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
## License
|
|
106
|
+
|
|
107
|
+
MIT
|
package/bin/req-race.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { dirname, resolve } from "node:path";
|
|
6
|
+
import { formatRaceReport } from "../src/index.js";
|
|
7
|
+
|
|
8
|
+
const args = process.argv.slice(2);
|
|
9
|
+
|
|
10
|
+
if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
|
|
11
|
+
console.log(`
|
|
12
|
+
req-race — Automated stale-fetch race condition & double-submit tester
|
|
13
|
+
|
|
14
|
+
Usage:
|
|
15
|
+
npx req-race <url> [options]
|
|
16
|
+
|
|
17
|
+
Options:
|
|
18
|
+
--mode <mode> reverse-order | jitter | throttle-mutations (default: reverse-order)
|
|
19
|
+
--delay <ms> Delay ms for reordered requests (default: 1000)
|
|
20
|
+
--wait <ms> Wait ms after load to collect requests (default: 1500)
|
|
21
|
+
--json Output machine-readable JSON
|
|
22
|
+
-h, --help Show this help message
|
|
23
|
+
`);
|
|
24
|
+
process.exit(0);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const getArgValue = (flag) => {
|
|
28
|
+
const idx = args.indexOf(flag);
|
|
29
|
+
return idx !== -1 && args[idx + 1] ? args[idx + 1] : null;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const url = args.find((a) => !a.startsWith("-"));
|
|
33
|
+
const mode = getArgValue("--mode") || "reverse-order";
|
|
34
|
+
const delayMs = Number(getArgValue("--delay") ?? 1000);
|
|
35
|
+
const waitMs = Number(getArgValue("--wait") ?? 1500);
|
|
36
|
+
const jsonOutput = args.includes("--json");
|
|
37
|
+
|
|
38
|
+
if (!url) {
|
|
39
|
+
console.error("Error: Please provide a target URL, e.g. npx req-race http://localhost:5173");
|
|
40
|
+
process.exit(1);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let playwright;
|
|
44
|
+
try {
|
|
45
|
+
playwright = await import("playwright");
|
|
46
|
+
} catch {
|
|
47
|
+
console.error(
|
|
48
|
+
"Playwright is required for CLI URL testing.\nInstall it with: npm i -D playwright && npx playwright install chromium"
|
|
49
|
+
);
|
|
50
|
+
process.exit(1);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
54
|
+
const coreSource = readFileSync(resolve(__dirname, "../src/index.js"), "utf8").replace(
|
|
55
|
+
/\bexport\s+(?=function\b)/g,
|
|
56
|
+
""
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
const browser = await playwright.chromium.launch({ headless: true });
|
|
60
|
+
try {
|
|
61
|
+
const page = await browser.newPage();
|
|
62
|
+
await page.addInitScript(
|
|
63
|
+
({ source, opts }) => {
|
|
64
|
+
const factory = new Function(`${source}\nreturn enableFetchRaceChaos;`);
|
|
65
|
+
const enable = factory();
|
|
66
|
+
window.__reqRace = enable(opts);
|
|
67
|
+
},
|
|
68
|
+
{ source: coreSource, opts: { mode, delayMs } }
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
await page.goto(url, { waitUntil: "networkidle" });
|
|
72
|
+
if (waitMs > 0) await page.waitForTimeout(waitMs);
|
|
73
|
+
|
|
74
|
+
const stats = await page.evaluate(() => window.__reqRace?.getStats() ?? null);
|
|
75
|
+
const logs = await page.evaluate(() => window.__reqRace?.getLogs() ?? []);
|
|
76
|
+
|
|
77
|
+
if (jsonOutput) {
|
|
78
|
+
console.log(JSON.stringify({ stats, logs }, null, 2));
|
|
79
|
+
} else {
|
|
80
|
+
console.log(formatRaceReport(stats));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const hasIssues = stats && (stats.unabortedStaleCount > 0 || stats.duplicateMutations > 0);
|
|
84
|
+
process.exit(hasIssues ? 1 : 0);
|
|
85
|
+
} finally {
|
|
86
|
+
await browser.close();
|
|
87
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "req-race",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Automated stale-fetch race condition, out-of-order response chaos, and double-submit mutation tester for browsers, Playwright, and CI.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"types": "./src/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./src/index.d.ts",
|
|
11
|
+
"default": "./src/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./playwright": {
|
|
14
|
+
"types": "./src/playwright.d.ts",
|
|
15
|
+
"default": "./src/playwright.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"bin": {
|
|
19
|
+
"req-race": "bin/req-race.js"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"bin",
|
|
23
|
+
"src",
|
|
24
|
+
"README.md"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"test": "node --test test/*.test.js"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"fetch",
|
|
31
|
+
"race-condition",
|
|
32
|
+
"stale-fetch",
|
|
33
|
+
"abortcontroller",
|
|
34
|
+
"double-submit",
|
|
35
|
+
"chaos-testing",
|
|
36
|
+
"playwright",
|
|
37
|
+
"testing",
|
|
38
|
+
"cli"
|
|
39
|
+
],
|
|
40
|
+
"author": "Prince Bhut",
|
|
41
|
+
"license": "MIT",
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=18.0.0"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"playwright": ">=1.40.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"playwright": {
|
|
50
|
+
"optional": true
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export type ChaosMode = "reverse-order" | "jitter" | "throttle-mutations" | "timeout";
|
|
2
|
+
|
|
3
|
+
export interface RaceStats {
|
|
4
|
+
totalRequests: number;
|
|
5
|
+
reorderedResponses: number;
|
|
6
|
+
abortedCount: number;
|
|
7
|
+
unabortedStaleCount: number;
|
|
8
|
+
duplicateMutations: number;
|
|
9
|
+
timeouts: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RaceLogEntry {
|
|
13
|
+
id: number;
|
|
14
|
+
method: string;
|
|
15
|
+
key: string;
|
|
16
|
+
url: string;
|
|
17
|
+
startedAt: number;
|
|
18
|
+
finishedAt: number | null;
|
|
19
|
+
aborted: boolean;
|
|
20
|
+
delayedMs: number;
|
|
21
|
+
staleRisk: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface RaceChaosOptions {
|
|
25
|
+
target?: { fetch: typeof fetch };
|
|
26
|
+
mode?: ChaosMode;
|
|
27
|
+
delayMs?: number;
|
|
28
|
+
timeoutMs?: number;
|
|
29
|
+
minDelayMs?: number;
|
|
30
|
+
maxDelayMs?: number;
|
|
31
|
+
doubleSubmitWindowMs?: number;
|
|
32
|
+
urlPattern?: string | RegExp | null;
|
|
33
|
+
normalizeKey?: (url: string, method: string) => string;
|
|
34
|
+
onRaceDetected?: (event: Record<string, unknown>) => void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface RaceChaosController {
|
|
38
|
+
disable: () => void;
|
|
39
|
+
getStats: () => RaceStats;
|
|
40
|
+
getLogs: () => RaceLogEntry[];
|
|
41
|
+
resetStats: () => void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface RaceSafeFetchOptions {
|
|
45
|
+
normalizeKey?: (url: string, method: string) => string;
|
|
46
|
+
dedupeMutations?: boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function enableFetchRaceChaos(options?: RaceChaosOptions): RaceChaosController;
|
|
50
|
+
export function createRaceSafeFetch(
|
|
51
|
+
fetchImpl?: typeof fetch,
|
|
52
|
+
optionsOrNormalizeKey?: ((url: string, method: string) => string) | RaceSafeFetchOptions
|
|
53
|
+
): typeof fetch;
|
|
54
|
+
export function formatRaceReport(stats: RaceStats): string;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* req-race — Automated Stale-Fetch Race Condition & Double-Submit Tester.
|
|
3
|
+
* Zero-dependency browser & Node-compatible core.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const MUTATION_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
7
|
+
|
|
8
|
+
function sleep(ms, signal) {
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
if (signal?.aborted) {
|
|
11
|
+
reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
const timer = setTimeout(() => {
|
|
15
|
+
signal?.removeEventListener("abort", onAbort);
|
|
16
|
+
resolve();
|
|
17
|
+
}, ms);
|
|
18
|
+
function onAbort() {
|
|
19
|
+
clearTimeout(timer);
|
|
20
|
+
reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
21
|
+
}
|
|
22
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function defaultNormalizeKey(url, method) {
|
|
27
|
+
try {
|
|
28
|
+
const parsed = new URL(url, "http://localhost");
|
|
29
|
+
return `${method}:${parsed.pathname}`;
|
|
30
|
+
} catch {
|
|
31
|
+
return `${method}:${String(url).split("?")[0]}`;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function extractUrl(input) {
|
|
36
|
+
if (typeof input === "string") return input;
|
|
37
|
+
if (input && typeof input.url === "string") return input.url;
|
|
38
|
+
return String(input);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Enable fetch race-condition chaos and telemetry on a target (defaults to globalThis.fetch).
|
|
43
|
+
* @param {object} [options]
|
|
44
|
+
* @returns {{ disable: () => void, getStats: () => object, getLogs: () => Array, resetStats: () => void }}
|
|
45
|
+
*/
|
|
46
|
+
export function enableFetchRaceChaos(options = {}) {
|
|
47
|
+
const {
|
|
48
|
+
target = typeof globalThis !== "undefined" ? globalThis : null,
|
|
49
|
+
mode = "reverse-order",
|
|
50
|
+
delayMs = 1000,
|
|
51
|
+
timeoutMs = 1500,
|
|
52
|
+
minDelayMs = 100,
|
|
53
|
+
maxDelayMs = 900,
|
|
54
|
+
doubleSubmitWindowMs = 500,
|
|
55
|
+
urlPattern = null,
|
|
56
|
+
normalizeKey = defaultNormalizeKey,
|
|
57
|
+
onRaceDetected = null,
|
|
58
|
+
} = options;
|
|
59
|
+
|
|
60
|
+
if (!target || typeof target.fetch !== "function") {
|
|
61
|
+
throw new Error("enableFetchRaceChaos requires a target with a fetch() function.");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const rawOriginalFetch = target.fetch;
|
|
65
|
+
const originalFetch = rawOriginalFetch.bind(target);
|
|
66
|
+
const inFlightByKey = new Map();
|
|
67
|
+
const recentMutations = new Map();
|
|
68
|
+
const logs = [];
|
|
69
|
+
|
|
70
|
+
const stats = {
|
|
71
|
+
totalRequests: 0,
|
|
72
|
+
reorderedResponses: 0,
|
|
73
|
+
abortedCount: 0,
|
|
74
|
+
unabortedStaleCount: 0,
|
|
75
|
+
duplicateMutations: 0,
|
|
76
|
+
timeouts: 0,
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
let seq = 0;
|
|
80
|
+
|
|
81
|
+
const matchesPattern = (url) => {
|
|
82
|
+
if (!urlPattern) return true;
|
|
83
|
+
if (urlPattern instanceof RegExp) return urlPattern.test(url);
|
|
84
|
+
return url.includes(String(urlPattern));
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
target.fetch = async function reqRaceFetch(input, init = {}) {
|
|
88
|
+
const url = extractUrl(input);
|
|
89
|
+
const method = (init?.method || input?.method || "GET").toUpperCase();
|
|
90
|
+
|
|
91
|
+
if (!matchesPattern(url)) {
|
|
92
|
+
return originalFetch(input, init);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const id = ++seq;
|
|
96
|
+
const key = normalizeKey(url, method);
|
|
97
|
+
const startedAt = Date.now();
|
|
98
|
+
const signal = init?.signal || input?.signal;
|
|
99
|
+
stats.totalRequests++;
|
|
100
|
+
|
|
101
|
+
// Detect duplicate mutations within doubleSubmitWindowMs
|
|
102
|
+
if (MUTATION_METHODS.has(method)) {
|
|
103
|
+
const prevTs = recentMutations.get(key);
|
|
104
|
+
if (prevTs && startedAt - prevTs <= doubleSubmitWindowMs) {
|
|
105
|
+
stats.duplicateMutations++;
|
|
106
|
+
onRaceDetected?.({
|
|
107
|
+
type: "duplicate-mutation",
|
|
108
|
+
method,
|
|
109
|
+
key,
|
|
110
|
+
url,
|
|
111
|
+
deltaMs: startedAt - prevTs,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
recentMutations.set(key, startedAt);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const entry = {
|
|
118
|
+
id,
|
|
119
|
+
method,
|
|
120
|
+
key,
|
|
121
|
+
url,
|
|
122
|
+
startedAt,
|
|
123
|
+
finishedAt: null,
|
|
124
|
+
aborted: false,
|
|
125
|
+
delayedMs: 0,
|
|
126
|
+
staleRisk: false,
|
|
127
|
+
signal,
|
|
128
|
+
};
|
|
129
|
+
logs.push(entry);
|
|
130
|
+
|
|
131
|
+
const activeList = inFlightByKey.get(key) || [];
|
|
132
|
+
|
|
133
|
+
// If an earlier request for this key is still in flight, flag unaborted stale risk
|
|
134
|
+
for (const prev of activeList) {
|
|
135
|
+
if (!prev.signal?.aborted && !MUTATION_METHODS.has(method)) {
|
|
136
|
+
prev.staleRisk = true;
|
|
137
|
+
stats.unabortedStaleCount++;
|
|
138
|
+
onRaceDetected?.({
|
|
139
|
+
type: "unaborted-overlap",
|
|
140
|
+
method,
|
|
141
|
+
key,
|
|
142
|
+
earlierId: prev.id,
|
|
143
|
+
newerId: id,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
activeList.push(entry);
|
|
149
|
+
inFlightByKey.set(key, activeList);
|
|
150
|
+
|
|
151
|
+
let appliedDelay = 0;
|
|
152
|
+
if (mode === "jitter") {
|
|
153
|
+
appliedDelay = Math.floor(minDelayMs + Math.random() * Math.max(0, maxDelayMs - minDelayMs));
|
|
154
|
+
} else if (mode === "throttle-mutations" && MUTATION_METHODS.has(method)) {
|
|
155
|
+
appliedDelay = delayMs;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
try {
|
|
159
|
+
if (mode === "timeout") {
|
|
160
|
+
await sleep(timeoutMs, signal);
|
|
161
|
+
stats.timeouts++;
|
|
162
|
+
onRaceDetected?.({ type: "timeout", method, key, url, timeoutMs });
|
|
163
|
+
throw new DOMException(`Request timed out after ${timeoutMs}ms`, "TimeoutError");
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const response = await originalFetch(input, init);
|
|
167
|
+
|
|
168
|
+
// In reverse-order mode, if a newer request arrived while this one was in flight,
|
|
169
|
+
// hold this earlier response so the newer one resolves first!
|
|
170
|
+
const listNow = inFlightByKey.get(key) || [];
|
|
171
|
+
const hasNewer = listNow.some((item) => item.id > id);
|
|
172
|
+
if (mode === "reverse-order" && hasNewer && !signal?.aborted) {
|
|
173
|
+
appliedDelay = delayMs;
|
|
174
|
+
stats.reorderedResponses++;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (appliedDelay > 0) {
|
|
178
|
+
entry.delayedMs = appliedDelay;
|
|
179
|
+
await sleep(appliedDelay, signal);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
entry.finishedAt = Date.now();
|
|
183
|
+
return response;
|
|
184
|
+
} catch (err) {
|
|
185
|
+
if (err?.name === "AbortError" || signal?.aborted) {
|
|
186
|
+
entry.aborted = true;
|
|
187
|
+
stats.abortedCount++;
|
|
188
|
+
}
|
|
189
|
+
entry.finishedAt = Date.now();
|
|
190
|
+
throw err;
|
|
191
|
+
} finally {
|
|
192
|
+
const remaining = (inFlightByKey.get(key) || []).filter((item) => item.id !== id);
|
|
193
|
+
if (remaining.length > 0) {
|
|
194
|
+
inFlightByKey.set(key, remaining);
|
|
195
|
+
} else {
|
|
196
|
+
inFlightByKey.delete(key);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
disable() {
|
|
203
|
+
target.fetch = rawOriginalFetch;
|
|
204
|
+
},
|
|
205
|
+
getStats() {
|
|
206
|
+
return { ...stats };
|
|
207
|
+
},
|
|
208
|
+
getLogs() {
|
|
209
|
+
return logs.map((l) => ({
|
|
210
|
+
id: l.id,
|
|
211
|
+
method: l.method,
|
|
212
|
+
key: l.key,
|
|
213
|
+
url: l.url,
|
|
214
|
+
startedAt: l.startedAt,
|
|
215
|
+
finishedAt: l.finishedAt,
|
|
216
|
+
aborted: l.aborted,
|
|
217
|
+
delayedMs: l.delayedMs,
|
|
218
|
+
staleRisk: l.staleRisk,
|
|
219
|
+
}));
|
|
220
|
+
},
|
|
221
|
+
resetStats() {
|
|
222
|
+
stats.totalRequests = 0;
|
|
223
|
+
stats.reorderedResponses = 0;
|
|
224
|
+
stats.abortedCount = 0;
|
|
225
|
+
stats.unabortedStaleCount = 0;
|
|
226
|
+
stats.duplicateMutations = 0;
|
|
227
|
+
stats.timeouts = 0;
|
|
228
|
+
logs.length = 0;
|
|
229
|
+
recentMutations.clear();
|
|
230
|
+
},
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Create a race-safe fetch wrapper that automatically aborts previous in-flight
|
|
236
|
+
* GET/HEAD requests for the same normalized key, and optionally deduplicates
|
|
237
|
+
* concurrent identical mutations (POST/PUT/PATCH/DELETE).
|
|
238
|
+
* @param {typeof fetch} [fetchImpl]
|
|
239
|
+
* @param {((url: string, method: string) => string) | { normalizeKey?: (url: string, method: string) => string, dedupeMutations?: boolean }} [optionsOrNormalizeKey]
|
|
240
|
+
*/
|
|
241
|
+
export function createRaceSafeFetch(
|
|
242
|
+
fetchImpl = (...args) => globalThis.fetch(...args),
|
|
243
|
+
optionsOrNormalizeKey = {}
|
|
244
|
+
) {
|
|
245
|
+
const isFn = typeof optionsOrNormalizeKey === "function";
|
|
246
|
+
const normalizeKey = isFn
|
|
247
|
+
? optionsOrNormalizeKey
|
|
248
|
+
: optionsOrNormalizeKey.normalizeKey || defaultNormalizeKey;
|
|
249
|
+
const dedupeMutations = isFn ? false : Boolean(optionsOrNormalizeKey.dedupeMutations);
|
|
250
|
+
|
|
251
|
+
const controllers = new Map();
|
|
252
|
+
const inFlightMutations = new Map();
|
|
253
|
+
|
|
254
|
+
return async function raceSafeFetch(input, init = {}) {
|
|
255
|
+
const url = extractUrl(input);
|
|
256
|
+
const method = (init?.method || "GET").toUpperCase();
|
|
257
|
+
const key = normalizeKey(url, method);
|
|
258
|
+
|
|
259
|
+
if (method === "GET" || method === "HEAD") {
|
|
260
|
+
const prev = controllers.get(key);
|
|
261
|
+
if (prev) {
|
|
262
|
+
prev.abort(new DOMException("Superseded by newer request", "AbortError"));
|
|
263
|
+
}
|
|
264
|
+
const controller = new AbortController();
|
|
265
|
+
controllers.set(key, controller);
|
|
266
|
+
|
|
267
|
+
if (init?.signal) {
|
|
268
|
+
init.signal.addEventListener(
|
|
269
|
+
"abort",
|
|
270
|
+
() => controller.abort(init.signal.reason),
|
|
271
|
+
{ once: true }
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
try {
|
|
276
|
+
return await fetchImpl(input, { ...init, signal: controller.signal });
|
|
277
|
+
} finally {
|
|
278
|
+
if (controllers.get(key) === controller) {
|
|
279
|
+
controllers.delete(key);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if (dedupeMutations && MUTATION_METHODS.has(method)) {
|
|
285
|
+
const existing = inFlightMutations.get(key);
|
|
286
|
+
if (existing) return existing;
|
|
287
|
+
|
|
288
|
+
const promise = Promise.resolve(fetchImpl(input, init)).finally(() => {
|
|
289
|
+
if (inFlightMutations.get(key) === promise) {
|
|
290
|
+
inFlightMutations.delete(key);
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
inFlightMutations.set(key, promise);
|
|
294
|
+
return promise;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return fetchImpl(input, init);
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Format race-chaos statistics into a readable terminal report.
|
|
303
|
+
* @param {object} stats
|
|
304
|
+
* @returns {string}
|
|
305
|
+
*/
|
|
306
|
+
export function formatRaceReport(stats) {
|
|
307
|
+
if (!stats) return "No req-race telemetry recorded.";
|
|
308
|
+
|
|
309
|
+
const hasIssues = stats.unabortedStaleCount > 0 || stats.duplicateMutations > 0;
|
|
310
|
+
const lines = [
|
|
311
|
+
hasIssues
|
|
312
|
+
? `✖ req-race detected potential race conditions:`
|
|
313
|
+
: `✔ req-race passed (${stats.totalRequests} requests monitored):`,
|
|
314
|
+
` ├─ Total requests: ${stats.totalRequests}`,
|
|
315
|
+
` ├─ Reordered responses: ${stats.reorderedResponses}`,
|
|
316
|
+
` ├─ Properly aborted: ${stats.abortedCount}`,
|
|
317
|
+
` ├─ Unaborted stale risks: ${stats.unabortedStaleCount}`,
|
|
318
|
+
` └─ Duplicate mutations: ${stats.duplicateMutations}`,
|
|
319
|
+
];
|
|
320
|
+
|
|
321
|
+
return lines.join("\n");
|
|
322
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Page } from "playwright";
|
|
2
|
+
|
|
3
|
+
export interface StaleRaceOptions {
|
|
4
|
+
url: string | RegExp;
|
|
5
|
+
trigger: () => Promise<void>;
|
|
6
|
+
selector: string;
|
|
7
|
+
expectedText: string;
|
|
8
|
+
delayMs?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface DoubleSubmitOptions {
|
|
12
|
+
button: string;
|
|
13
|
+
url: string | RegExp;
|
|
14
|
+
maxRequests?: number;
|
|
15
|
+
windowMs?: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function assertNoStaleRace(page: Page, options: StaleRaceOptions): Promise<void>;
|
|
19
|
+
export function assertNoDoubleSubmit(
|
|
20
|
+
page: Page,
|
|
21
|
+
options: DoubleSubmitOptions
|
|
22
|
+
): Promise<{ mutationCount: number }>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Playwright helpers for req-race:
|
|
3
|
+
* - assertNoStaleRace: reverses response order of Request #1 behind Request #2
|
|
4
|
+
* - assertNoDoubleSubmit: rapid double-click mutation guard assertion
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Assert that rapid overlapping requests do not allow a delayed earlier response
|
|
9
|
+
* to overwrite the newer UI state.
|
|
10
|
+
* @param {import('playwright').Page} page
|
|
11
|
+
* @param {object} options
|
|
12
|
+
*/
|
|
13
|
+
export async function assertNoStaleRace(page, options) {
|
|
14
|
+
const { url, trigger, selector, expectedText, delayMs = 800 } = options;
|
|
15
|
+
|
|
16
|
+
let count = 0;
|
|
17
|
+
const handler = async (route) => {
|
|
18
|
+
count++;
|
|
19
|
+
const current = count;
|
|
20
|
+
const response = await route.fetch();
|
|
21
|
+
const body = await response.body();
|
|
22
|
+
|
|
23
|
+
if (current === 1) {
|
|
24
|
+
await new Promise((r) => setTimeout(r, delayMs));
|
|
25
|
+
}
|
|
26
|
+
await route.fulfill({ response, body });
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
await page.route(url, handler);
|
|
30
|
+
try {
|
|
31
|
+
await trigger();
|
|
32
|
+
await page.waitForTimeout(delayMs + 150);
|
|
33
|
+
const actual = await page.locator(selector).textContent();
|
|
34
|
+
if (!actual || !actual.includes(expectedText)) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
`Stale fetch race detected! Expected "${selector}" to include "${expectedText}", but got "${actual}".`
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
} finally {
|
|
40
|
+
await page.unroute(url, handler);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Rapidly double-click a button and assert that at most `maxRequests` mutation
|
|
46
|
+
* requests are fired.
|
|
47
|
+
* @param {import('playwright').Page} page
|
|
48
|
+
* @param {object} options
|
|
49
|
+
*/
|
|
50
|
+
export async function assertNoDoubleSubmit(page, options) {
|
|
51
|
+
const { button, url, maxRequests = 1, windowMs = 600 } = options;
|
|
52
|
+
|
|
53
|
+
let mutationCount = 0;
|
|
54
|
+
const onRequest = (req) => {
|
|
55
|
+
const method = req.method().toUpperCase();
|
|
56
|
+
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
|
|
57
|
+
const reqUrl = req.url();
|
|
58
|
+
const matches = typeof url === "string" ? reqUrl.includes(url.replace(/\*/g, "")) : url.test(reqUrl);
|
|
59
|
+
if (matches) mutationCount++;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
page.on("request", onRequest);
|
|
64
|
+
try {
|
|
65
|
+
const locator = page.locator(button).first();
|
|
66
|
+
await locator.click();
|
|
67
|
+
await locator.click({ force: true }).catch(() => {});
|
|
68
|
+
await page.waitForTimeout(windowMs);
|
|
69
|
+
|
|
70
|
+
if (mutationCount > maxRequests) {
|
|
71
|
+
throw new Error(
|
|
72
|
+
`Double-submit bug detected! Clicking "${button}" twice fired ${mutationCount} mutation requests (max allowed: ${maxRequests}).`
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
return { mutationCount };
|
|
76
|
+
} finally {
|
|
77
|
+
page.off("request", onRequest);
|
|
78
|
+
}
|
|
79
|
+
}
|