fix(webui): recover stalled requests
This commit is contained in:
5 files changed
+146
-13
No files matched your search
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Eye, Loader2, User, UserX } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
@@ -37,31 +37,48 @@ export function ProcessProbeDialog({ pid, processName, open, onOpenChange, onLoa
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [info, setInfo] = useState<QqPortLoginInfo | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const activeProbe = useRef<AbortController | null>(null);
|
||||
|
||||
const probe = useCallback(async () => {
|
||||
activeProbe.current?.abort();
|
||||
const controller = new AbortController();
|
||||
activeProbe.current = controller;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setInfo(null);
|
||||
try {
|
||||
const result = await api.processes.probeLoginInfo(pid);
|
||||
const result = await api.processes.probeLoginInfo(pid, controller.signal);
|
||||
if (activeProbe.current !== controller) return;
|
||||
setInfo(result as QqPortLoginInfo | null);
|
||||
if (!result) {
|
||||
setError('未检测到登录信息(端口 9210-9219 无响应)');
|
||||
}
|
||||
} catch (err) {
|
||||
if (activeProbe.current !== controller || controller.signal.aborted) return;
|
||||
setError(err instanceof Error ? err.message : '探测失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (activeProbe.current === controller) {
|
||||
activeProbe.current = null;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, [api.processes, pid]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
probe();
|
||||
void probe();
|
||||
} else {
|
||||
activeProbe.current?.abort();
|
||||
activeProbe.current = null;
|
||||
setLoading(false);
|
||||
setInfo(null);
|
||||
setError(null);
|
||||
}
|
||||
|
||||
return () => {
|
||||
activeProbe.current?.abort();
|
||||
activeProbe.current = null;
|
||||
};
|
||||
}, [open, probe]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
import { localStorageTokenStore } from './token-store';
|
||||
|
||||
const DEFAULT_TOKEN_KEY = 'snowluma_token';
|
||||
const REQUEST_TIMEOUT_MS = 30_000;
|
||||
|
||||
interface ErrorPayload {
|
||||
message?: string;
|
||||
@@ -72,7 +73,10 @@ class HttpApiClient implements ApiClient {
|
||||
load: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/load`),
|
||||
unload: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/unload`),
|
||||
refresh: (pid) => this.postJson<ProcessActionResult>(`/api/processes/${pid}/refresh`),
|
||||
probeLoginInfo: (pid) => this.getJson<{ info: unknown }>(`/api/processes/${pid}/probe-login`).then((d) => d.info ?? null),
|
||||
probeLoginInfo: (pid, signal) => this.fetchJson<{ info: unknown }>(
|
||||
`/api/processes/${pid}/probe-login`,
|
||||
{ signal },
|
||||
).then((d) => d.info ?? null),
|
||||
};
|
||||
|
||||
this.config = {
|
||||
@@ -211,7 +215,7 @@ class HttpApiClient implements ApiClient {
|
||||
getPublic: async () => {
|
||||
// Pre-auth path: a plain fetch with no bearer. Used by the login page
|
||||
// to theme itself before the operator has signed in.
|
||||
const res = await fetch('/api/ui/public');
|
||||
const res = await this.fetchWithDeadline('/api/ui/public');
|
||||
if (!res.ok) throw new ApiError(res.status, '无法获取外观配置');
|
||||
const data = await readJson<{ appearance: UiAppearance }>(res);
|
||||
return data.appearance;
|
||||
@@ -303,7 +307,8 @@ class HttpApiClient implements ApiClient {
|
||||
};
|
||||
if (this.currentToken) headers['Authorization'] = `Bearer ${this.currentToken}`;
|
||||
if (init.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
|
||||
const res = await fetch(url, { ...init, headers });
|
||||
|
||||
const res = await this.fetchWithDeadline(url, { ...init, headers });
|
||||
if (res.status === 401) {
|
||||
this.setToken(null);
|
||||
this.onUnauthorized?.();
|
||||
@@ -311,6 +316,29 @@ class HttpApiClient implements ApiClient {
|
||||
return res;
|
||||
}
|
||||
|
||||
private async fetchWithDeadline(
|
||||
url: string,
|
||||
init: RequestInit = {},
|
||||
): Promise<Response> {
|
||||
const deadline = new AbortController();
|
||||
const onCallerAbort = () => deadline.abort(init.signal?.reason);
|
||||
if (init.signal?.aborted) onCallerAbort();
|
||||
else init.signal?.addEventListener('abort', onCallerAbort, { once: true });
|
||||
const timer = setTimeout(() => deadline.abort(), REQUEST_TIMEOUT_MS);
|
||||
try {
|
||||
const res = await fetch(url, { ...init, signal: deadline.signal });
|
||||
return res;
|
||||
} catch (error) {
|
||||
if (deadline.signal.aborted && !init.signal?.aborted) {
|
||||
throw new ApiError(408, '请求超时,请重试', 'REQUEST_TIMEOUT');
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
init.signal?.removeEventListener('abort', onCallerAbort);
|
||||
}
|
||||
}
|
||||
|
||||
/** Like request(), but throws ApiError on non-2xx and parses JSON. */
|
||||
private async fetchJson<T>(url: string, init: RequestInit = {}): Promise<T> {
|
||||
const res = await this.request(url, init);
|
||||
@@ -349,7 +377,7 @@ class HttpApiClient implements ApiClient {
|
||||
// Login deliberately bypasses fetchJson/onUnauthorized so a bad password
|
||||
// doesn't trigger a global sign-out side effect.
|
||||
try {
|
||||
const res = await fetch('/api/login', {
|
||||
const res = await this.fetchWithDeadline('/api/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
|
||||
@@ -151,7 +151,7 @@ export interface ApiClient {
|
||||
load(pid: number): Promise<ProcessActionResult>;
|
||||
unload(pid: number): Promise<ProcessActionResult>;
|
||||
refresh(pid: number): Promise<ProcessActionResult>;
|
||||
probeLoginInfo(pid: number): Promise<unknown>;
|
||||
probeLoginInfo(pid: number, signal?: AbortSignal): Promise<unknown>;
|
||||
};
|
||||
|
||||
// ---- OneBotInstance per-UIN config ----
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createApiClient } from '../src/lib/api/client';
|
||||
|
||||
const tokenStore = {
|
||||
load: () => 'test-token',
|
||||
save: () => undefined,
|
||||
};
|
||||
|
||||
describe('API client request deadline', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('aborts a pending request and reports a retryable timeout', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn((_url: string, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () => {
|
||||
reject(new DOMException('Aborted', 'AbortError'));
|
||||
}, { once: true });
|
||||
})));
|
||||
const client = createApiClient({ tokenStore });
|
||||
|
||||
const request = client.request('/api/processes');
|
||||
const rejection = expect(request).rejects.toMatchObject({
|
||||
message: '请求超时,请重试',
|
||||
code: 'REQUEST_TIMEOUT',
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
|
||||
await rejection;
|
||||
});
|
||||
|
||||
it('cancels a login probe without preventing a later retry', async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockImplementationOnce((_url: string, init?: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () => {
|
||||
reject(new DOMException('Aborted', 'AbortError'));
|
||||
}, { once: true });
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({
|
||||
info: { port: 0, uin: '', loggedIn: false },
|
||||
}), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const client = createApiClient({ tokenStore });
|
||||
const controller = new AbortController();
|
||||
|
||||
const cancelled = client.processes.probeLoginInfo(4242, controller.signal);
|
||||
controller.abort();
|
||||
|
||||
await expect(cancelled).rejects.toMatchObject({ name: 'AbortError' });
|
||||
await expect(client.processes.probeLoginInfo(4242)).resolves.toEqual({
|
||||
port: 0,
|
||||
uin: '',
|
||||
loggedIn: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('settles a pending login with a retryable timeout message', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn((_url: string, init?: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init?.signal?.addEventListener('abort', () => {
|
||||
reject(new DOMException('Aborted', 'AbortError'));
|
||||
}, { once: true });
|
||||
}),
|
||||
));
|
||||
const client = createApiClient({ tokenStore });
|
||||
|
||||
const login = client.login('password');
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
|
||||
await expect(login).resolves.toEqual({
|
||||
ok: false,
|
||||
message: '请求超时,请重试',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -43,9 +43,10 @@ describe('storage API client', () => {
|
||||
|
||||
const client = createApiClient({ tokenStore });
|
||||
await expect(client.storage.get()).resolves.toEqual(payload);
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/system/storage', {
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/system/storage', expect.objectContaining({
|
||||
headers: { Authorization: 'Bearer test-token' },
|
||||
});
|
||||
signal: expect.any(AbortSignal),
|
||||
}));
|
||||
});
|
||||
|
||||
it('posts a partial log-settings patch', async () => {
|
||||
@@ -64,14 +65,15 @@ describe('storage API client', () => {
|
||||
const client = createApiClient({ tokenStore });
|
||||
await client.storage.saveSettings({ logRetainDays: 0 });
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/system/storage/settings', {
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/system/storage/settings', expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ logRetainDays: 0 }),
|
||||
headers: {
|
||||
Authorization: 'Bearer test-token',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
signal: expect.any(AbortSignal),
|
||||
}));
|
||||
});
|
||||
|
||||
it('returns a structured partial cleanup result from an HTTP 500 response', async () => {
|
||||
|
||||
Reference in new issue
Block a user