Skip to content

Commit 64c2b7f

Browse files
committed
fix: stabilize sequential claims and simplify browser orchestration
Serialize manual and scheduled claims, reuse prewarmed account routes, and reconcile uncertain submissions before retrying. Remove obsolete worker plumbing and duplicate frontend request queues.
1 parent c453483 commit 64c2b7f

16 files changed

Lines changed: 451 additions & 288 deletions

‎internal/server/app.go‎

Lines changed: 57 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -51,63 +51,63 @@ type profileEntry struct {
5151
}
5252

5353
type App struct {
54-
db *sql.DB
55-
data, secret string
56-
root string
57-
version string
58-
log *log.Logger
59-
logfile *os.File
60-
web fs.FS
61-
configMu sync.RWMutex
62-
cfg shared.M
63-
mu sync.Mutex
64-
states map[string]*accountState
65-
upstreamCooldowns map[string]*upstreamCooldown
66-
cooldownEpochs map[string]uint64
67-
cooldownGeneration uint64
68-
available chan struct{}
69-
scheduleMu sync.Mutex
70-
waiters []*accountWaiter
71-
sticky map[string]stickyEntry
72-
responses map[string]responseEntry
73-
responseOrder []string
74-
responseBytes int
75-
clients map[string]*http.Client
76-
jars map[string]*diskJar
77-
claimLocks map[string]bool
78-
claimBatchMu sync.Mutex
79-
claimCandidatesMu sync.Mutex
80-
claimWorkerSlots chan int
81-
claimPreviewSlots chan struct{}
82-
claimReschedule chan struct{}
83-
claimScheduleCancel context.CancelFunc
84-
flowLocks map[string]bool
85-
localImportMu sync.Mutex
86-
credentialMu sync.Mutex
87-
businessRefreshes map[string]*businessTokenFlight
88-
reauth map[string]int64
89-
pollDue map[string]int64
90-
polling map[string]bool
91-
pollWake chan struct{}
92-
usageLogCleanupWake chan struct{}
93-
balances balanceManager
94-
profiles map[string]*profileEntry
95-
ctx context.Context
96-
cancel context.CancelFunc
97-
wg sync.WaitGroup
98-
webPort, gatewayPort int
99-
webUpdateHost string
100-
gatewayUpdateHost string
101-
origin string
102-
captcha captchaManager
103-
claimBrowser claimBrowserManager
104-
manualClaimBrowsers [manualClaimConcurrency]claimBrowserManager
105-
scheduledClaimBrowsers [dailyClaimConcurrency]claimBrowserManager
106-
proxies outboundProxyManager
107-
proxyHealthOnce sync.Once
108-
proxyHealthReschedule chan struct{}
109-
mihomoInstallMu sync.Mutex
110-
updates updateManager
54+
db *sql.DB
55+
data, secret string
56+
root string
57+
version string
58+
log *log.Logger
59+
logfile *os.File
60+
web fs.FS
61+
configMu sync.RWMutex
62+
cfg shared.M
63+
mu sync.Mutex
64+
states map[string]*accountState
65+
upstreamCooldowns map[string]*upstreamCooldown
66+
cooldownEpochs map[string]uint64
67+
cooldownGeneration uint64
68+
available chan struct{}
69+
scheduleMu sync.Mutex
70+
waiters []*accountWaiter
71+
sticky map[string]stickyEntry
72+
responses map[string]responseEntry
73+
responseOrder []string
74+
responseBytes int
75+
clients map[string]*http.Client
76+
jars map[string]*diskJar
77+
claimLocks map[string]bool
78+
claimBatchMu sync.Mutex
79+
claimCandidatesMu sync.Mutex
80+
claimSlot chan struct{}
81+
claimPreviewSlots chan struct{}
82+
claimReschedule chan struct{}
83+
claimScheduleCancel context.CancelFunc
84+
flowLocks map[string]bool
85+
localImportMu sync.Mutex
86+
credentialMu sync.Mutex
87+
businessRefreshes map[string]*businessTokenFlight
88+
reauth map[string]int64
89+
pollDue map[string]int64
90+
polling map[string]bool
91+
pollWake chan struct{}
92+
usageLogCleanupWake chan struct{}
93+
balances balanceManager
94+
profiles map[string]*profileEntry
95+
ctx context.Context
96+
cancel context.CancelFunc
97+
wg sync.WaitGroup
98+
webPort, gatewayPort int
99+
webUpdateHost string
100+
gatewayUpdateHost string
101+
origin string
102+
captcha captchaManager
103+
claimBrowser claimBrowserManager
104+
manualClaimBrowser claimBrowserManager
105+
scheduledClaimBrowser claimBrowserManager
106+
proxies outboundProxyManager
107+
proxyHealthOnce sync.Once
108+
proxyHealthReschedule chan struct{}
109+
mihomoInstallMu sync.Mutex
110+
updates updateManager
111111
}
112112

113113
func New(root, data string, web fs.FS, buildVersion string) (*App, error) {

‎internal/server/captcha.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ func (a *App) captchaHeaders(parent context.Context, account shared.M, purpose s
7777
return verification, routing.AsProxyFailure(err)
7878
}
7979
defer release()
80-
ctx, cancel := a.operationContext(parent, shared.Ms(shared.Fallback(options["timeout_ms"], 30000))+3*time.Second)
80+
ctx, cancel := a.operationContext(parent, captchaOperationTimeout(options, purpose))
8181
defer cancel()
8282
if ctx.Err() != nil {
8383
return verification, &fault.Failure{Kind: "server", Code: "captcha_timeout", Message: "上游安全验证已取消或超时"}

‎internal/server/captcha/captcha.cjs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ const path = require('node:path');
55

66
const SDK_URL = 'https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js';
77

8+
function browserLaunchTimeout(config) {
9+
return Math.max(5000, Math.min(60000, Number(config.browser_launch_timeout_ms) || 60000));
10+
}
11+
812
// Synthetic rendering interfaces for jsdom; no host GPU is queried.
913
function installCanvasWebGL(window) {
1014
const noop = () => {};
@@ -353,4 +357,4 @@ if (require.main === module) {
353357
});
354358
}
355359

356-
module.exports = { captchaExpression, captchaOutcome, installCanvasWebGL, run };
360+
module.exports = { browserLaunchTimeout, captchaExpression, captchaOutcome, installCanvasWebGL, run };

‎internal/server/captcha/captcha_browser.cjs‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ function browserLaunchFailure(error) {
1919
const reason = /sandbox|zygote_host_impl/i.test(message) ? 'sandbox'
2020
: /DISPLAY|X server|X11|ozone_platform_x11/i.test(message) ? 'display'
2121
: /shared librar|cannot open shared object/i.test(message) ? 'system_library'
22-
: error?.code === 'ENOENT' ? 'executable_missing' : 'browser_launch';
22+
: error?.code === 'ENOENT' ? 'executable_missing' : error?.name === 'TimeoutError' ? 'timeout' : 'browser_launch';
2323
return { ok: false, code: error?.code === 'captcha_display_unavailable' ? error.code : 'captcha_browser_launch_failed', stage: 'browser_launch', browser_launch_reason: reason };
2424
}
2525

@@ -111,7 +111,7 @@ function playwright(config) {
111111
return null;
112112
}
113113

114-
function browserPath(config, driver, headed = false) {
114+
function browserPath(config, driver, headed = false, preferHeadlessShell = false) {
115115
const windows = process.platform === 'win32';
116116
const names = windows ? ['msedge.exe', 'chrome.exe', 'chromium.exe'] : ['chromium', 'chromium-browser', 'google-chrome', 'google-chrome-stable', 'microsoft-edge'];
117117
if (config.browser_path) {
@@ -151,6 +151,10 @@ function browserPath(config, driver, headed = false) {
151151
}
152152
}
153153
}
154+
if (preferHeadlessShell) {
155+
const shell = candidates.find(file => headlessShell(file) && executable(file));
156+
if (shell) return shell;
157+
}
154158
return candidates.find(file => executable(file) && (!headed || !headlessShell(file))) || '';
155159
}
156160

@@ -164,8 +168,10 @@ function browserPlan(config, nativeUnavailable = '') {
164168
: !fullBrowser ? 'captcha_browser_missing'
165169
: proxy && (!['http:', 'https:'].includes(proxy.protocol) || proxy.username || proxy.password) ? 'captcha_proxy_unsupported'
166170
: !display.available ? 'captcha_display_unavailable' : '');
167-
const backend = requested === 'native' || (requested === 'auto' && !nativeCode) ? 'native' : 'playwright';
168-
const file = backend === 'native' || !headless ? fullBrowser : browserPath(config, driver);
171+
// Linux services avoid one X server and full desktop browser per worker when a headless driver is available.
172+
const preferNative = process.platform !== 'linux' || !driver || !headless;
173+
const backend = requested === 'native' || (requested === 'auto' && !nativeCode && preferNative) ? 'native' : 'playwright';
174+
const file = backend === 'native' || !headless ? fullBrowser : browserPath(config, driver, false, true);
169175
const code = backend === 'native' ? nativeCode : !driver ? 'captcha_playwright_missing' : !file ? 'captcha_browser_missing' : !headless && !display.available ? 'captcha_display_unavailable' : '';
170176
return { requested, backend, headless: backend === 'playwright' && headless, driver, display, file, code, nativeCode, fallback_code: requested === 'auto' && backend === 'playwright' ? nativeCode : '' };
171177
}
@@ -284,6 +290,7 @@ async function verify(browser, sessions, config) {
284290
}
285291

286292
async function worker() {
293+
const { browserLaunchTimeout } = require('./captcha.cjs');
287294
let browser, native, nativeUnavailable = '', stopping = false, chain = Promise.resolve();
288295
const display = new BrowserDisplay();
289296
const sessions = new Map();
@@ -321,11 +328,16 @@ async function worker() {
321328
}
322329
// Never switch runtimes after an SDK refusal, timeout or interaction request.
323330
if (!stopping && !result.ok && ['captcha_browser_launch_failed', 'captcha_display_unavailable'].includes(result.code) && !result.sdk_executed && plan.requested === 'auto') {
324-
nativeUnavailable = result.code;
325331
await native.close();
326-
result = null;
327-
plan = browserPlan(config, nativeUnavailable);
328-
if (plan.code) result = { ok: false, code: plan.code, stage: 'browser_selection' };
332+
const fallback = browserPlan(config, result.code);
333+
if (fallback.code) {
334+
// A missing fallback must not hide a transient native startup failure.
335+
plan = { ...plan, fallback_code: fallback.code };
336+
} else {
337+
nativeUnavailable = result.code;
338+
result = null;
339+
plan = fallback;
340+
}
329341
}
330342
}
331343
if (!stopping && !result && plan.backend === 'playwright') {
@@ -335,7 +347,7 @@ async function worker() {
335347
sessions.clear();
336348
const env = plan.headless ? process.env : await display.environment(config);
337349
if (stopping) return;
338-
browser = await plan.driver.library.chromium.launch({ executablePath: plan.file, headless: plan.headless, env, timeout: 20000 });
350+
browser = await plan.driver.library.chromium.launch({ executablePath: plan.file, headless: plan.headless, env, timeout: browserLaunchTimeout(config) });
339351
if (stopping) { await browser.close(); return; }
340352
}
341353
result = config.action === 'warm' ? { ok: true } : await verify(browser, sessions, config);

‎internal/server/captcha/captcha_native.cjs‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ const http = require('node:http');
55
const path = require('node:path');
66
const crypto = require('node:crypto');
77
const { spawn, execFile } = require('node:child_process');
8-
const { captchaExpression } = require('./captcha.cjs');
8+
const { browserLaunchTimeout, captchaExpression } = require('./captcha.cjs');
99

1010
function processInfo(pid) {
1111
try {
@@ -58,7 +58,7 @@ class NativeClaimBrowser {
5858
async open(config) {
5959
const proxy = config.proxy_url || '';
6060
const identity = config.action === 'warm' ? '' : config.session_key || crypto.randomBytes(32).toString('hex');
61-
if (this.child && this.child.exitCode === null && this.child.signalCode === null && this.proxy === proxy && (config.action === 'warm' || !this.identity || this.identity === identity)) {
61+
if (this.child && this.child.exitCode === null && this.child.signalCode === null && (config.action === 'warm' || (this.proxy === proxy && (!this.identity || this.identity === identity)))) {
6262
if (identity) this.identity = identity;
6363
return;
6464
}
@@ -79,6 +79,9 @@ class NativeClaimBrowser {
7979
const profile = this.profile = fs.mkdtempSync(path.join(config.browser_profiles, 'browser-'));
8080
const args = ['--user-data-dir=' + profile, '--no-first-run', '--no-default-browser-check'];
8181
if (process.platform === 'win32') args.push('--start-minimized');
82+
if (process.platform === 'linux') {
83+
args.push('--disable-dev-shm-usage', '--disable-background-networking', '--disable-component-update', '--password-store=basic');
84+
}
8285
// Match Playwright's root-service compatibility without changing non-root sandboxing.
8386
if (process.platform === 'linux' && process.getuid() === 0) args.push('--no-sandbox');
8487
args.push(proxy ? '--proxy-server=' + new URL(proxy).origin : '--no-proxy-server');
@@ -188,12 +191,12 @@ class NativeClaimBrowser {
188191
if (!job) return;
189192
this.job = null;
190193
clearTimeout(job.timer);
194+
if (job.warm) this.ready = !!result.ok;
191195
job.resolve({ ...result, session_reused: false });
192196
}
193197

194198
async run(config) {
195-
// Native claims need a fresh SDK instance; only the browser process is warmed.
196-
if (config.action === 'prepare') return { ok: true, preparation_skipped: true, runtime: 'native_browser' };
199+
// Preparation binds the account and proxy, without creating a verification ticket.
197200
this.opening = this.open(config);
198201
try {
199202
await this.opening;
@@ -203,8 +206,16 @@ class NativeClaimBrowser {
203206
if (this.stopping) return { ok: false, code: 'captcha_canceled' };
204207
if (!this.child || this.child.exitCode !== null || this.child.signalCode !== null) return { ok: false, code: 'captcha_browser_launch_failed', sdk_executed: false };
205208
if (this.job) return { ok: false, code: 'captcha_capacity_exceeded' };
206-
const warm = config.action === 'warm';
207-
const timeout = warm ? 20000 : Math.max(5000, Math.min(120000, Number(config.timeout_ms) || 30000));
209+
const warm = config.action === 'warm' || config.action === 'prepare';
210+
if (!warm && !this.ready) {
211+
const ready = await this.execute(config, true);
212+
if (!ready.ok || this.stopping) return ready;
213+
}
214+
return this.execute(config, warm);
215+
}
216+
217+
execute(config, warm) {
218+
const timeout = warm ? browserLaunchTimeout(config) : Math.max(5000, Math.min(120000, Number(config.timeout_ms) || 30000));
208219
return new Promise(resolve => {
209220
const job = this.job = {
210221
id: crypto.randomBytes(16).toString('hex'), resolve, sent: false,
@@ -215,7 +226,7 @@ class NativeClaimBrowser {
215226
this.job = null;
216227
// Cancel late SDK callbacks before accepting another job on this profile.
217228
await this.close();
218-
resolve({ ok: false, code: job.warm ? 'captcha_browser_launch_failed' : 'captcha_timeout', stage: job.warm ? 'browser_launch' : 'sdk_verify', runtime: 'native_browser', session_reused: false });
229+
resolve({ ok: false, code: job.warm ? 'captcha_browser_launch_failed' : 'captcha_timeout', stage: job.warm ? 'browser_launch' : 'sdk_verify', browser_launch_reason: job.warm ? 'timeout' : undefined, sdk_executed: job.sent && !job.warm, runtime: 'native_browser', session_reused: false });
219230
}, timeout);
220231
this.dispatch();
221232
});
@@ -241,6 +252,7 @@ class NativeClaimBrowser {
241252
const child = this.child; this.child = null;
242253
const profile = this.profile; this.profile = null;
243254
this.identity = '';
255+
this.ready = false;
244256
await stopBrowser(child);
245257
if (child?.pid && child.exitCode === null && child.signalCode === null) return;
246258
if (profile) {

0 commit comments

Comments
 (0)