Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/main/goxfTimeout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { describe, expect, it } from 'vitest'
import { withTimeout } from './goxfTimeout'

describe('withTimeout', () => {
it('returns the value when it settles in time', async () => {
expect(await withTimeout(Promise.resolve(5), 50, 0)).toEqual({ value: 5, timedOut: false })
})
it('returns the fallback when the promise never settles', async () => {
expect(await withTimeout(new Promise<number>(() => undefined), 20, 0)).toEqual({ value: 0, timedOut: true })
})
it('returns the fallback when the promise rejects', async () => {
expect(await withTimeout(Promise.reject(new Error('x')), 50, null)).toEqual({ value: null, timedOut: false })
})
})
26 changes: 26 additions & 0 deletions src/main/goxfTimeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/** GOXF: settle a promise within ms; on timeout resolve to `fallback` (the original keeps running, unobserved). */
export function withTimeout<T>(promise: Promise<T>, ms: number, fallback: T): Promise<{ value: T; timedOut: boolean }> {
return new Promise((resolve) => {
let done = false
const timer = setTimeout(() => {
if (done) return
done = true
resolve({ value: fallback, timedOut: true })
}, ms)
;(timer as { unref?: () => void }).unref?.()
promise.then(
(value) => {
if (done) return
done = true
clearTimeout(timer)
resolve({ value, timedOut: false })
},
() => {
if (done) return
done = true
clearTimeout(timer)
resolve({ value: fallback, timedOut: false })
}
)
})
}
38 changes: 30 additions & 8 deletions src/main/goxfUpdater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
type GoxfUpstreamPrompt
} from '@shared/goxfUpdate'
import { checkFailedMessage } from './updateCheck'
import { withTimeout } from './goxfTimeout'
import {
buildReplaceScript,
decideResume,
Expand Down Expand Up @@ -192,8 +193,18 @@ let updaterRules: string | undefined
* tested entry) when it has one; a network failure there, or an empty pool,
* falls back to the system network (which follows the system proxy).
*/
async function updaterFetch(url: string, init: RequestInit): Promise<Response> {
const pick = await updaterPoolProxy().catch(() => null)
/** GOXF: picking a pool proxy can hang (keychain decrypt, Mihomo start); past this, go direct. */
const POOL_PICK_TIMEOUT_MS = 4_000
/** Update checks: each route (pool, then direct) gets its own budget, so a dead pool never eats the direct try. */
const CHECK_ROUTE_TIMEOUT_MS = 12_000

/** routeTimeoutMs: per-route deadline when the caller has no signal of its own (downloads keep theirs). */
async function updaterFetch(url: string, init: RequestInit, routeTimeoutMs?: number): Promise<Response> {
const routeInit = (): RequestInit => (init.signal || !routeTimeoutMs ? init : { ...init, signal: AbortSignal.timeout(routeTimeoutMs) })
const name = basename(new URL(url).pathname)
const picked = await withTimeout(updaterPoolProxy(), POOL_PICK_TIMEOUT_MS, null)
if (picked.timedOut) logUpdate(`${name}: proxy pool did not answer in ${POOL_PICK_TIMEOUT_MS / 1000}s; using system network`)
const pick = picked.value
if (pick) {
try {
const ses = session.fromPartition(UPDATER_PARTITION)
Expand All @@ -202,25 +213,32 @@ async function updaterFetch(url: string, init: RequestInit): Promise<Response> {
await ses.closeAllConnections().catch(() => undefined)
updaterRules = pick.rules
}
const res = await ses.fetch(url, init)
logUpdate(`${basename(new URL(url).pathname)} via proxy pool ${pick.label}`)
const res = await ses.fetch(url, routeInit())
logUpdate(`${name} via proxy pool ${pick.label}: HTTP ${res.status}`)
return res
} catch (error) {
// A user pause/cancel (or the caller's own deadline) is not a reason to retry direct.
if (init.signal?.aborted) throw error
logUpdate(`proxy pool ${pick.label} failed (${error instanceof Error ? error.message : String(error)}); using system network`)
}
}
return net.fetch(url, init)
try {
const res = await net.fetch(url, routeInit())
logUpdate(`${name} via system network: HTTP ${res.status}`)
return res
} catch (error) {
logUpdate(`${name} via system network failed (${error instanceof Error ? error.message : String(error)})`)
throw error
}
}

type Fetched<T> = { ok: true; data: T | null } | { ok: false; message: string }

async function getJson<T>(url: string): Promise<Fetched<T>> {
try {
const res = await updaterFetch(url, {
headers: { Accept: 'application/vnd.github+json', 'User-Agent': `BotArk/${currentVersion()}` },
signal: AbortSignal.timeout(12_000)
})
headers: { Accept: 'application/vnd.github+json', 'User-Agent': `BotArk/${currentVersion()}` }
}, CHECK_ROUTE_TIMEOUT_MS)
// 404 = repo has no (latest) release yet: not an error.
if (res.status === 404) return { ok: true, data: null }
if (!res.ok) {
Expand Down Expand Up @@ -255,6 +273,10 @@ async function check(manual: boolean): Promise<boolean> {
})
upstreamPrompt = decision.upstream
portablePrompt = decision.portable
logUpdate(
`check (${manual ? 'manual' : 'auto'}, ${currentChannel()} channel): fork ${fork.ok ? 'ok' : `failed: ${fork.message}`}, ` +
`upstream ${up.ok ? 'ok' : 'failed'}; offer ${decision.portable?.version ?? 'none'}`
)
if (decision.upstream) broadcastGoxf({ type: 'upstream-available', prompt: decision.upstream })
if (decision.portable && !installing && !paused) {
const { asset: _asset, delta: _delta, fallback: _fallback, ...prompt } = decision.portable
Expand Down