修复:自动回收失效隧道占用并限制首次连接等待时间
This commit is contained in:
@@ -45,6 +45,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
if (revisions.current && state.dataRevision !== revisions.current.dataRevision) setRefreshKey(value => value + 1);
|
||||
revisions.current = state;
|
||||
setError('');
|
||||
setReady(true);
|
||||
return true;
|
||||
} catch (value) {
|
||||
if (alive.current && generation.current === epoch && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '页面状态校验失败,请重试');
|
||||
@@ -84,7 +85,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
} }));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
void validate().then(ok => { if (ok) setReady(true); });
|
||||
void validate();
|
||||
const invalidate = () => setRefreshKey(value => value + 1);
|
||||
window.addEventListener(WORKSPACE_INVALIDATED, invalidate);
|
||||
return () => { alive.current = false; generation.current++; validation.current = null; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); };
|
||||
@@ -95,7 +96,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
const frame = requestAnimationFrame(() => window.scrollTo(0, entries.current.get(page)?.scroll || 0));
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [page, ready, activeEntryKey]);
|
||||
const connectionNotice = error && <Alert type="warning" showIcon message="页面状态暂未更新" description={error} action={<Button onClick={() => { void validate().then(ok => { if (ok) setReady(true); }); }}>重新连接</Button>} />;
|
||||
const connectionNotice = error && <Alert type="warning" showIcon message="页面状态暂未更新" description={error} action={<Button onClick={() => { void validate(); }}>重新连接</Button>} />;
|
||||
if (!ready) return connectionNotice || <div className="loading-panel"><Spin />正在打开工作台…</div>;
|
||||
return <>{connectionNotice}{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => {
|
||||
const active = name === page;
|
||||
|
||||
+15
-11
@@ -1,6 +1,7 @@
|
||||
import { WORKSPACE_INVALIDATED } from './pageCache';
|
||||
import { consumeEventStream, type StreamEvent } from './eventStream';
|
||||
import { publicErrorMessage } from './publicDataDisplay';
|
||||
import { RequestTimeoutError, withRequestDeadline } from './requestDeadline';
|
||||
import type {
|
||||
AuthUser,
|
||||
FilterField,
|
||||
@@ -65,16 +66,19 @@ async function readResponse<T>(response: Response): Promise<T> {
|
||||
return payload as T;
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
async function request<T>(path: string, init: RequestInit = {}, timeoutMs?: number): Promise<T> {
|
||||
const headers = new Headers(init.headers);
|
||||
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
|
||||
const response = await fetchApi(path, {
|
||||
...init,
|
||||
headers,
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
});
|
||||
return readResponse<T>(response);
|
||||
const send = async (signal = init.signal) => {
|
||||
const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' });
|
||||
return readResponse<T>(response);
|
||||
};
|
||||
if (!timeoutMs) return send();
|
||||
try { return await withRequestDeadline(signal => send(signal), timeoutMs); }
|
||||
catch (error) {
|
||||
if (error instanceof RequestTimeoutError) throw new ApiError(408, '连接质量数据服务超时,请点击重新连接;服务恢复后可继续使用。');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
|
||||
@@ -113,7 +117,7 @@ async function readEventStream(path: string, options: { signal?: AbortSignal; la
|
||||
}
|
||||
|
||||
export async function refreshCsrf(): Promise<string> {
|
||||
const result = await request<{ token: string }>('/api/auth/csrf');
|
||||
const result = await request<{ token: string }>('/api/auth/csrf', {}, 8000);
|
||||
csrfToken = result.token;
|
||||
return csrfToken;
|
||||
}
|
||||
@@ -143,14 +147,14 @@ async function mutateForm<T>(path: string, body: FormData): Promise<T> {
|
||||
}
|
||||
|
||||
export const api = {
|
||||
workspaceState() { return request<{ authRevision: string; dataRevision: string }>('/api/workspace/state'); },
|
||||
workspaceState() { return request<{ authRevision: string; dataRevision: string }>('/api/workspace/state', {}, 8000); },
|
||||
filterFields(manage = false) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`); },
|
||||
filterFieldOptions(key: string, search = '') { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`); },
|
||||
filterFieldColumns() { return request<{ black: string[]; bright: string[] }>('/api/filter-fields/columns'); },
|
||||
saveFilterFields(fields: FilterField[]) { return mutate<FilterField[]>('/api/filter-fields', fields, 'PUT'); },
|
||||
refreshCsrf,
|
||||
async me(): Promise<AuthUser> {
|
||||
const result = await request<{ user: AuthUser }>('/api/auth/me');
|
||||
const result = await request<{ user: AuthUser }>('/api/auth/me', {}, 8000);
|
||||
return result.user;
|
||||
},
|
||||
login(username: string, password: string) {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
export class RequestTimeoutError extends Error {
|
||||
constructor() { super('请求超时'); this.name = 'RequestTimeoutError'; }
|
||||
}
|
||||
|
||||
/** 限制整个请求(包括读取响应正文)的等待时间,并终止底层网络连接。 */
|
||||
export async function withRequestDeadline<T>(operation: (signal: AbortSignal) => Promise<T>, timeoutMs: number): Promise<T> {
|
||||
const controller = new AbortController();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const expired = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => { reject(new RequestTimeoutError()); controller.abort(); }, timeoutMs);
|
||||
});
|
||||
try { return await Promise.race([operation(controller.signal), expired]); }
|
||||
finally { clearTimeout(timer); }
|
||||
}
|
||||
Reference in New Issue
Block a user