fix: unify stream cleanup and configuration response handling
This commit is contained in:
1 parent
38a7c3da63
commit
1faa6c58fa
13 files changed
+463
-247
No files matched your search
@@ -22,6 +22,9 @@ status, OneBot configuration, logs, storage, and server settings.
|
||||
result; do not convert failed responses into successful feedback.
|
||||
- JSON endpoints must return an object. Malformed or non-object responses are
|
||||
reported as errors rather than displayed as empty lists or default settings.
|
||||
- Configuration responses include `config`; saves also report `saved`, `applied`,
|
||||
`online`, `errors`, and `message`. The UI uses these fields without legacy aliases
|
||||
or a second request after saving.
|
||||
- Password change flows use floating labels and inline validation consistently.
|
||||
- Password strength details appear only while the new-password field has focus
|
||||
and leave with the same motion language when focus moves away.
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
ApiError,
|
||||
type ApiClient,
|
||||
type ChangePasswordResult,
|
||||
type ConfigSaveResult,
|
||||
type CreateApiClientOptions,
|
||||
type LoginResult,
|
||||
type LogsStreamOptions,
|
||||
@@ -128,61 +129,13 @@ class HttpApiClient implements ApiClient {
|
||||
this.config = {
|
||||
get: async (uin) => {
|
||||
const url = `/api/config/${encodeURIComponent(uin)}`;
|
||||
const data = await this.getJson<{ config?: unknown } | unknown>(url);
|
||||
const raw =
|
||||
typeof data === 'object' &&
|
||||
data != null &&
|
||||
'config' in (data as Record<string, unknown>)
|
||||
? (data as { config: unknown }).config
|
||||
: data;
|
||||
return normalizeOneBotConfig(raw);
|
||||
const data = await this.getJson<{ config: unknown }>(url);
|
||||
return normalizeOneBotConfig(data.config);
|
||||
},
|
||||
save: async (uin, config) => {
|
||||
const url = `/api/config/${encodeURIComponent(uin)}`;
|
||||
const result = await this.fetchJson<{
|
||||
success?: boolean;
|
||||
saved?: boolean;
|
||||
applied?: boolean;
|
||||
online?: boolean;
|
||||
reloaded?: boolean;
|
||||
errors?: Array<{
|
||||
name: string;
|
||||
kind?: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient';
|
||||
phase: string;
|
||||
message: string;
|
||||
at: number;
|
||||
restored?: boolean;
|
||||
}>;
|
||||
config?: unknown;
|
||||
message?: string;
|
||||
}>(url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(config),
|
||||
});
|
||||
// Refetch the canonical persisted view after the save. Runtime apply
|
||||
// is a separate fact and is preserved alongside that config.
|
||||
let canonical =
|
||||
result.config === undefined ? null : normalizeOneBotConfig(result.config);
|
||||
|
||||
if (canonical === null) {
|
||||
try {
|
||||
canonical = await this.config.get(uin);
|
||||
} catch (error) {
|
||||
// Legacy servers omit `config`. Their POST still confirmed the
|
||||
// save, so a follow-up GET failure must not become "保存失败".
|
||||
console.warn('config saved but canonical refetch failed', error);
|
||||
canonical = config;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
config: canonical,
|
||||
saved: result.saved ?? result.success === true,
|
||||
applied: result.applied ?? result.reloaded === true,
|
||||
online: result.online ?? result.reloaded === true,
|
||||
errors: Array.isArray(result.errors) ? result.errors : [],
|
||||
message: result.message ?? '配置保存成功',
|
||||
};
|
||||
const result = await this.postJson<ConfigSaveResult>(url, config);
|
||||
return { ...result, config: normalizeOneBotConfig(result.config) };
|
||||
},
|
||||
};
|
||||
|
||||
@@ -747,14 +700,7 @@ class HttpApiClient implements ApiClient {
|
||||
|
||||
// ---------- SSE ----------
|
||||
|
||||
/**
|
||||
* Open a token-authed SSE channel to `path`, dispatching each parsed frame to
|
||||
* `onMessage` and surfacing transport state ('open' / 'reconnecting' /
|
||||
* 'closed') via `onStatus`. The fetch stream reconnects after transport loss
|
||||
* so it retains EventSource's user-visible behaviour while keeping the token
|
||||
* in the WebUI session header. A malformed frame (or a throw from
|
||||
* `onMessage`) is skipped. The returned disposer aborts the active request.
|
||||
*/
|
||||
/** Fetch-based SSE keeps the session token in a header and reconnects after transport loss. */
|
||||
private openSseChannel<T>(
|
||||
path: string,
|
||||
onMessage: (data: T) => void,
|
||||
@@ -770,28 +716,47 @@ class HttpApiClient implements ApiClient {
|
||||
let active: AbortController | null = null;
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const clearReconnect = () => {
|
||||
if (reconnectTimer !== null) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const disconnect = () => {
|
||||
clearReconnect();
|
||||
active?.abort();
|
||||
active = null;
|
||||
};
|
||||
|
||||
const scheduleReconnect = () => {
|
||||
if (disposed || reconnectTimer !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
onStatus?.('reconnecting');
|
||||
reconnectTimer = setTimeout(() => {
|
||||
reconnectTimer = null;
|
||||
void connect();
|
||||
}, 1_000);
|
||||
onStatus?.('reconnecting');
|
||||
};
|
||||
|
||||
const connect = async () => {
|
||||
if (disposed || active) {
|
||||
return;
|
||||
}
|
||||
|
||||
const token = this.currentToken;
|
||||
|
||||
if (disposed || !token) {
|
||||
onStatus?.('closed');
|
||||
if (!token) {
|
||||
dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
active = controller;
|
||||
const isCurrent = () =>
|
||||
!disposed && active === controller && !controller.signal.aborted;
|
||||
|
||||
try {
|
||||
const response = await fetch(path, {
|
||||
@@ -803,12 +768,15 @@ class HttpApiClient implements ApiClient {
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
if (!isCurrent()) {
|
||||
await response.body?.cancel();
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.status === 401) {
|
||||
disposed = true;
|
||||
active = null;
|
||||
dispose();
|
||||
this.setToken(null);
|
||||
this.onUnauthorized?.();
|
||||
onStatus?.('closed');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -822,9 +790,13 @@ class HttpApiClient implements ApiClient {
|
||||
let buffer = '';
|
||||
|
||||
try {
|
||||
while (!disposed) {
|
||||
while (isCurrent()) {
|
||||
const { done, value } = await reader.read();
|
||||
|
||||
if (!isCurrent()) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (done) {
|
||||
buffer += decoder.decode();
|
||||
break;
|
||||
@@ -836,7 +808,7 @@ class HttpApiClient implements ApiClient {
|
||||
throw new Error('SSE frame buffer exceeded 1 MiB');
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
while (isCurrent()) {
|
||||
const lf = buffer.indexOf('\n\n');
|
||||
const crlf = buffer.indexOf('\r\n\r\n');
|
||||
let separator = -1;
|
||||
@@ -880,18 +852,14 @@ class HttpApiClient implements ApiClient {
|
||||
/* already closed */
|
||||
}
|
||||
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch {
|
||||
/* already released */
|
||||
}
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
if (!disposed) {
|
||||
if (isCurrent()) {
|
||||
scheduleReconnect();
|
||||
}
|
||||
} catch {
|
||||
if (!disposed && !controller.signal.aborted) {
|
||||
if (isCurrent()) {
|
||||
scheduleReconnect();
|
||||
}
|
||||
} finally {
|
||||
@@ -901,28 +869,18 @@ class HttpApiClient implements ApiClient {
|
||||
}
|
||||
};
|
||||
|
||||
const onPageHide = () => {
|
||||
active?.abort();
|
||||
};
|
||||
const onPageHide = disconnect;
|
||||
|
||||
const onPageShow = (event: PageTransitionEvent) => {
|
||||
if (event.persisted && !disposed) {
|
||||
if (reconnectTimer !== null) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
|
||||
clearReconnect();
|
||||
void connect();
|
||||
}
|
||||
};
|
||||
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === 'visible' && !disposed && !active) {
|
||||
if (reconnectTimer !== null) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
|
||||
clearReconnect();
|
||||
void connect();
|
||||
}
|
||||
};
|
||||
@@ -936,9 +894,7 @@ class HttpApiClient implements ApiClient {
|
||||
document.addEventListener('freeze', onPageHide);
|
||||
}
|
||||
|
||||
void connect();
|
||||
|
||||
return () => {
|
||||
const dispose = () => {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
@@ -952,15 +908,12 @@ class HttpApiClient implements ApiClient {
|
||||
document.removeEventListener('freeze', onPageHide);
|
||||
}
|
||||
|
||||
if (reconnectTimer !== null) {
|
||||
clearTimeout(reconnectTimer);
|
||||
}
|
||||
|
||||
reconnectTimer = null;
|
||||
active?.abort();
|
||||
active = null;
|
||||
disconnect();
|
||||
onStatus?.('closed');
|
||||
};
|
||||
|
||||
void connect();
|
||||
return dispose;
|
||||
}
|
||||
|
||||
private openLogStream(options: LogsStreamOptions): () => void {
|
||||
@@ -985,12 +938,7 @@ class HttpApiClient implements ApiClient {
|
||||
};
|
||||
}
|
||||
|
||||
/** Open the single shared /api/logs/stream connection; every frame and status
|
||||
* change fans out to all subscribers, each isolated so one throwing handler
|
||||
* can't drop the frame for the others (and a subscriber unsubscribed mid-frame
|
||||
* is skipped). A no-token attempt does NOT cache a dead disposer — it reports
|
||||
* 'closed' and returns so a later subscribe / setToken can open for real,
|
||||
* avoiding poisoning the shared cache. */
|
||||
/** Isolate subscribers and leave unauthenticated attempts free to reconnect after login. */
|
||||
private openSharedLogStream(): void {
|
||||
if (!this.currentToken) {
|
||||
this.lastLogStatus = 'closed';
|
||||
@@ -1042,10 +990,7 @@ class HttpApiClient implements ApiClient {
|
||||
);
|
||||
}
|
||||
|
||||
/** Token changed (login / re-login / logout): the shared stream baked the old
|
||||
* token into its URL, so tear it down and reopen with the new one if anyone is
|
||||
* still listening. Without this a re-login would leave the feed retrying a
|
||||
* stale-token URL forever. */
|
||||
/** A new request must pick up the changed session token. */
|
||||
private reopenSharedLogStream(): void {
|
||||
if (this.logStreamDispose) {
|
||||
this.logStreamDispose();
|
||||
|
||||
@@ -45,7 +45,11 @@ function normalizeNotifications(raw: unknown): { channelIds: string[] } {
|
||||
* into the canonical {@link OneBotConfig} the editor expects.
|
||||
*/
|
||||
export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
|
||||
const cfg = (raw ?? {}) as Record<string, unknown>;
|
||||
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
throw new Error('服务端返回了无效的配置');
|
||||
}
|
||||
|
||||
const cfg = raw as Record<string, unknown>;
|
||||
const nets = (cfg.networks as Record<string, unknown> | undefined) ?? {};
|
||||
const legacyFormat: MessageFormat = cfg.messageFormat === 'string' ? 'string' : 'array';
|
||||
const legacyReport = !!cfg.reportSelfMessage;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createApiClient } from '../src/lib/api/client';
|
||||
import { normalizeOneBotConfig } from '../src/lib/onebot-config';
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe('API client configuration', () => {
|
||||
const config = normalizeOneBotConfig({});
|
||||
const tokenStore = { load: () => 'token', save: vi.fn() };
|
||||
|
||||
it('keeps persisted configuration separate from failed runtime application', async () => {
|
||||
const result = {
|
||||
config,
|
||||
saved: true,
|
||||
applied: false,
|
||||
online: true,
|
||||
errors: [{ name: 'http', phase: 'start', message: 'port in use', at: 1 }],
|
||||
message: '配置已保存,应用失败',
|
||||
};
|
||||
const fetchMock = vi.fn().mockResolvedValue(Response.json(result));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const client = createApiClient({ tokenStore });
|
||||
|
||||
await expect(client.config.save('12345', config)).resolves.toEqual(result);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('rejects a save response without configuration instead of refetching or returning the form', async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(Response.json({ success: true, reloaded: true }))
|
||||
.mockRejectedValue(new Error('refetch failed'));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const client = createApiClient({ tokenStore });
|
||||
|
||||
await expect(client.config.save('12345', config)).rejects.toThrow('无效的配置');
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('reads the configuration from the server envelope', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json({ config })));
|
||||
const client = createApiClient({ tokenStore });
|
||||
|
||||
await expect(client.config.get('12345')).resolves.toEqual(config);
|
||||
});
|
||||
|
||||
it('rejects a response without the configuration envelope', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(Response.json(config)));
|
||||
const client = createApiClient({ tokenStore });
|
||||
|
||||
await expect(client.config.get('12345')).rejects.toThrow('无效的配置');
|
||||
});
|
||||
});
|
||||
@@ -3,8 +3,10 @@ import { createApiClient } from '../src/lib/api/client';
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
describe('API client SSE authentication', () => {
|
||||
describe('API client SSE lifecycle', () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
@@ -47,6 +49,12 @@ describe('API client SSE authentication', () => {
|
||||
});
|
||||
|
||||
it('clears the session and stops reconnecting after an unauthorized response', async () => {
|
||||
const page = new EventTarget();
|
||||
const document = new EventTarget();
|
||||
const removePageListener = vi.spyOn(page, 'removeEventListener');
|
||||
const removeDocumentListener = vi.spyOn(document, 'removeEventListener');
|
||||
vi.stubGlobal('window', page);
|
||||
vi.stubGlobal('document', document);
|
||||
const save = vi.fn();
|
||||
const onUnauthorized = vi.fn();
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 401 }));
|
||||
@@ -63,6 +71,99 @@ describe('API client SSE authentication', () => {
|
||||
expect(save).toHaveBeenCalledWith(null);
|
||||
expect(statuses.at(-1)).toBe('closed');
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(removePageListener).toHaveBeenCalledWith('pagehide', expect.any(Function));
|
||||
expect(removePageListener).toHaveBeenCalledWith('pageshow', expect.any(Function));
|
||||
expect(removeDocumentListener).toHaveBeenCalledWith(
|
||||
'visibilitychange',
|
||||
expect.any(Function),
|
||||
);
|
||||
expect(removeDocumentListener).toHaveBeenCalledWith('freeze', expect.any(Function));
|
||||
});
|
||||
|
||||
it('stops delivering the current frame batch after disposal', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(
|
||||
'data: {"kind":"ready"}\n\ndata: {"kind":"invalidate","resource":"qq-list"}\n\n',
|
||||
),
|
||||
),
|
||||
);
|
||||
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
|
||||
const onEvent = vi.fn(() => dispose());
|
||||
const dispose = client.stateStream({ onEvent });
|
||||
await vi.waitFor(() => expect(onEvent).toHaveBeenCalled());
|
||||
expect(onEvent).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('ignores a delayed unauthorized response from a disposed connection', async () => {
|
||||
vi.useFakeTimers();
|
||||
const response = Promise.withResolvers<Response>();
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(() => response.promise),
|
||||
);
|
||||
const save = vi.fn();
|
||||
const onUnauthorized = vi.fn();
|
||||
const client = createApiClient({
|
||||
tokenStore: { load: () => 'token', save },
|
||||
onUnauthorized,
|
||||
});
|
||||
const dispose = client.stateStream({ onEvent: vi.fn() });
|
||||
dispose();
|
||||
response.resolve(new Response(null, { status: 401 }));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(onUnauthorized).not.toHaveBeenCalled();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears the reconnect timer when disposed by the status callback', async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('')));
|
||||
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
|
||||
const dispose = client.stateStream({
|
||||
onEvent: vi.fn(),
|
||||
onStatus: (status) => {
|
||||
if (status === 'reconnecting') {
|
||||
dispose();
|
||||
}
|
||||
},
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('suspends reconnects until the page returns and keeps one active request', async () => {
|
||||
vi.useFakeTimers();
|
||||
const page = new EventTarget();
|
||||
vi.stubGlobal('window', page);
|
||||
vi.stubGlobal('document', Object.assign(new EventTarget(), { visibilityState: 'visible' }));
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(new Response(''))
|
||||
.mockImplementation(
|
||||
(_url: string, init: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
init.signal!.addEventListener('abort', () => reject(init.signal!.reason), {
|
||||
once: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
const client = createApiClient({ tokenStore: { load: () => 'token', save: vi.fn() } });
|
||||
const onStatus = vi.fn();
|
||||
const dispose = client.stateStream({ onEvent: vi.fn(), onStatus });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(onStatus).toHaveBeenCalledWith('reconnecting');
|
||||
page.dispatchEvent(new Event('pagehide'));
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
page.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: true }));
|
||||
page.dispatchEvent(Object.assign(new Event('pageshow'), { persisted: true }));
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
dispose();
|
||||
});
|
||||
|
||||
it('reconnects after a completed stream without leaking the token', async () => {
|
||||
|
||||
Reference in new issue
Block a user