|
1 | 1 | /** |
2 | | - * Solver backend dispatch -- fork patch: out-of-thread solving. |
| 2 | + * Solver backend dispatch — fully in-process, self-contained. |
3 | 3 | * |
4 | | - * Backend (ZCODE_CAPTCHA_BACKEND): "happy" (default) -- the happy-dom solver |
5 | | - * in src/proxy/captcha-happy.ts. |
6 | | - * |
7 | | - * Fork change: the solver runs in a worker_threads Worker instead of on the |
8 | | - * main thread. In-process solving froze the proxy's event loop via |
9 | | - * Atomics.wait sync XHRs (each up to 30s), so a burst of parallel solves |
10 | | - * stalled EVERY connection -- the "thinking for minutes after idle" failure. |
11 | | - * Worker solving also isolates happy-dom's global browser-frame/cookie state |
12 | | - * per solve (one Worker per solve, terminated after), removing cross-solve |
13 | | - * races the in-process path suffered under parallel waves. |
14 | | - * |
15 | | - * Bundling: `bun build --compile` cannot resolve `new Worker(new URL(...))` |
16 | | - * at runtime (module paths don't exist in the single-file binary), so the |
17 | | - * worker entry is imported as a build-time FILE ASSET |
18 | | - * (`import entryPath from "./captcha-worker-entry.ts" with { type: "file" }`) |
19 | | - * and extracted to a temp path by the compiled runtime. Verified working in |
20 | | - * compiled exes on Bun 1.4; plain `bun run` resolves the same asset import. |
| 4 | + * Backend (ZCODE_CAPTCHA_BACKEND): "happy" (default) — the happy-dom solver |
| 5 | + * in src/proxy/captcha-happy.ts, executed per captcha-worker-dispatch.ts: |
| 6 | + * one worker thread per solve (keeps Atomics.wait sync XHRs off the proxy's |
| 7 | + * event loop — issue #54) with an in-process fallback where the worker asset |
| 8 | + * is unavailable (dev checkouts, Docker TS-source image, Android bundle). |
21 | 9 | */ |
22 | | -import { Worker } from "node:worker_threads"; |
23 | | -// Asset import: embeds the PRE-BUNDLED worker (plain JS, self-contained ESM -- |
24 | | -// built by scripts/build-fork-worker.ts before compilation; raw .ts assets |
25 | | -// are not parsed by the compiled runtime). If the bundle is missing, run |
26 | | -// scripts/build-fork-worker.ts to regenerate it (package.json wires it as |
27 | | -// the prebuild hook). @ts-expect-error -- Bun's `with { type: "file" }` |
28 | | -// asset import has no DOM-lib type declaration; the default export is the |
29 | | -// extracted file path at runtime. |
30 | | -// @ts-expect-error asset import |
31 | | -import captchaWorkerEntryPath from "./captcha-worker-entry.bundle.js" with { type: "file" }; |
| 10 | +import { solveViaWorkerOrInProcess } from "./captcha-worker-dispatch.js"; |
32 | 11 |
|
33 | 12 | const BACKEND = process.env.ZCODE_CAPTCHA_BACKEND?.trim().toLowerCase() || "happy"; |
34 | 13 |
|
35 | | -/** Per-solve timeout: overall deadline the worker gets before termination. */ |
36 | | -const SOLVE_WORKER_TIMEOUT_MS = Number(process.env.CAPTCHA_SOLVE_TIMEOUT_MS || 20_000); |
37 | | - |
38 | | -interface SolveRequest { |
39 | | - id: number; |
40 | | - scene: string; |
41 | | - region: string; |
42 | | - prefix: string; |
43 | | -} |
44 | | -type SolveResponse = { id: number; ok: true; param: string } | { id: number; ok: false; error: string }; |
45 | | - |
46 | | -let nextSolveId = 0; |
47 | | - |
48 | 14 | export async function runCaptchaSolve(scene: string, region: string, prefix: string): Promise<string> { |
49 | 15 | if (BACKEND !== "happy") { |
50 | 16 | throw new Error(`captcha backend "${BACKEND}" is not available; use ZCODE_CAPTCHA_BACKEND=happy`); |
51 | 17 | } |
52 | | - return solveInWorker({ scene, region, prefix }); |
53 | | -} |
54 | | - |
55 | | -/** |
56 | | - * One solve = one Worker. Startup cost is a few ms (happy-dom loads lazily |
57 | | - * inside the entry on first message); termination guarantees no state leaks |
58 | | - * between solves. A hung solve cannot wedge anything: the pool's takeToken |
59 | | - * race deadline (25s) fires first, and the worker is force-terminated here. |
60 | | - */ |
61 | | -function solveInWorker(req: { scene: string; region: string; prefix: string }): Promise<string> { |
62 | | - const id = ++nextSolveId; |
63 | | - return new Promise<string>((resolve, reject) => { |
64 | | - let settled = false; |
65 | | - let worker: Worker | null = null; |
66 | | - const settle = (fn: () => void) => { |
67 | | - if (settled) return; |
68 | | - settled = true; |
69 | | - clearTimeout(timer); |
70 | | - try { worker?.terminate(); } catch {} |
71 | | - fn(); |
72 | | - }; |
73 | | - const timer = setTimeout(() => { |
74 | | - settle(() => reject(new Error(`captcha worker timeout (${SOLVE_WORKER_TIMEOUT_MS}ms)`))); |
75 | | - }, SOLVE_WORKER_TIMEOUT_MS); |
76 | | - |
77 | | - try { |
78 | | - worker = new Worker(captchaWorkerEntryPath); |
79 | | - } catch (err) { |
80 | | - settle(() => reject(new Error(`captcha worker spawn failed: ${(err as Error).message}`))); |
81 | | - return; |
82 | | - } |
83 | | - const msg: SolveRequest = { id, ...req }; |
84 | | - worker.on("message", (m: SolveResponse) => { |
85 | | - if (!m || m.id !== id) return; |
86 | | - if (m.ok) settle(() => resolve(m.param)); |
87 | | - else settle(() => reject(new Error(m.error))); |
88 | | - }); |
89 | | - worker.on("error", (err: Error) => { |
90 | | - settle(() => reject(new Error(`captcha worker error: ${err.message}`))); |
91 | | - }); |
92 | | - worker.on("exit", (code) => { |
93 | | - if (code !== 0 && !settled) { |
94 | | - settle(() => reject(new Error(`captcha worker exited (code ${code}) before solving`))); |
95 | | - } else if (!settled) { |
96 | | - settle(() => reject(new Error("captcha worker exited before responding"))); |
97 | | - } |
98 | | - }); |
99 | | - worker.postMessage(msg); |
100 | | - }); |
| 18 | + return solveViaWorkerOrInProcess({ scene, region, prefix }); |
101 | 19 | } |
102 | 20 |
|
103 | | -/** Worker-per-solve needs no concurrency plumbing -- kept for the pool API. */ |
| 21 | +/** Worker-per-solve needs no concurrency plumbing — kept for the pool API. */ |
104 | 22 | export function setCaptchaSolverConcurrency(_n: number): void {} |
105 | 23 |
|
106 | 24 | /** Nothing long-lived to shut down: workers are terminated per solve. */ |
|
0 commit comments