The four NetworkAdapters each carried a byte-identical reload() state machine (sigChanged/wasEnabled -> Reopened/Closed/Opened/Normal). Lift it into IOneBotNetworkAdapter as a template method; per-adapter variation is now expressed via three hooks: bindingSignature(), willEnable() (default enabled!==false; clients add && !!url), and onConfigReplaced() (post-swap side effects). Also delete four redundant 'override get isActive()' (identical to the base getter), lift the duplicated uin-logger setup into the base ctor, and drop http-post's now-redundant signature_ cache. NetworkReloadType is a test-observability seam -- the sole production caller (instance.applyConfigDiff) discards it -- so a new base-level test exercises all transitions directly. Behaviour-preserving: +94/-157 in src, full workspace typecheck clean, 332 onebot tests pass.
219 lines
7.7 KiB
TypeScript
219 lines
7.7 KiB
TypeScript
import { createLogger } from '@snowluma/common/logger';
|
||
import {
|
||
createServer,
|
||
type IncomingMessage,
|
||
type Server,
|
||
type ServerResponse,
|
||
} from 'http';
|
||
import type { DispatchPayload } from '../event-filter';
|
||
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
|
||
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||
import { isAuthorized, normalizePath } from './utils';
|
||
|
||
const moduleLog = createLogger('OneBot.HTTP');
|
||
|
||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||
private server: Server | null = null;
|
||
private listening = false;
|
||
|
||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||
super(name, config, ctx, moduleLog);
|
||
}
|
||
|
||
open(): void {
|
||
if (this.isEnabled) return;
|
||
if (this.config.enabled === false) return;
|
||
this.startServer();
|
||
this.isEnabled = true;
|
||
}
|
||
|
||
close(): void {
|
||
if (!this.isEnabled && !this.server) return;
|
||
this.isEnabled = false;
|
||
this.listening = false;
|
||
this.server?.close();
|
||
this.server = null;
|
||
}
|
||
|
||
override describeStatus(): AdapterStatus {
|
||
if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' };
|
||
if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' };
|
||
return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' };
|
||
}
|
||
|
||
protected override bindingSignature(config: HttpServerNetwork): string {
|
||
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}`;
|
||
}
|
||
|
||
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
|
||
|
||
private startServer(): void {
|
||
const server = createServer((req, res) => {
|
||
void this.handleRequest(req, res);
|
||
});
|
||
this.server = server;
|
||
|
||
server.on('listening', () => {
|
||
this.listening = true;
|
||
this.log.success(
|
||
'[%s] listening %s:%d%s',
|
||
this.name,
|
||
this.config.host ?? '0.0.0.0',
|
||
this.config.port,
|
||
normalizePath(this.config.path ?? '/'),
|
||
);
|
||
});
|
||
server.on('error', (err) => {
|
||
this.listening = false;
|
||
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
|
||
});
|
||
|
||
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
|
||
}
|
||
|
||
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||
const expectedPath = normalizePath(this.config.path ?? '/');
|
||
const accessToken = this.config.accessToken ?? '';
|
||
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
|
||
const incomingPath = parsedUrl.pathname;
|
||
|
||
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
|
||
let action = '';
|
||
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
|
||
action = '';
|
||
} else if (incomingPath.startsWith(ep)) {
|
||
action = incomingPath.substring(ep.length);
|
||
} else {
|
||
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
|
||
return;
|
||
}
|
||
|
||
if (!isAuthorized(req, accessToken)) {
|
||
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
|
||
return;
|
||
}
|
||
|
||
if (req.method === 'GET' && !action) {
|
||
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
|
||
return;
|
||
}
|
||
|
||
try {
|
||
let params: Record<string, unknown> = {};
|
||
let echo: unknown;
|
||
|
||
if (req.method === 'GET') {
|
||
parsedUrl.searchParams.forEach((value, key) => {
|
||
try {
|
||
params[key] = JSON.parse(value);
|
||
} catch {
|
||
params[key] = value;
|
||
}
|
||
});
|
||
} else if (req.method === 'POST') {
|
||
const bodyContent = await readRequestBody(req);
|
||
if (bodyContent.trim()) {
|
||
const contentType = req.headers['content-type'] ?? '';
|
||
if (contentType.includes('application/x-www-form-urlencoded')) {
|
||
const parsed = new URLSearchParams(bodyContent);
|
||
parsed.forEach((value, key) => {
|
||
try {
|
||
params[key] = JSON.parse(value);
|
||
} catch {
|
||
params[key] = value;
|
||
}
|
||
});
|
||
if (params.action && !action) {
|
||
action = String(params.action);
|
||
delete params.action;
|
||
}
|
||
if (params.echo !== undefined) {
|
||
echo = params.echo;
|
||
delete params.echo;
|
||
}
|
||
} else if (contentType.includes('application/json') || !contentType) {
|
||
try {
|
||
const parsedBody = JSON.parse(bodyContent);
|
||
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
|
||
if (parsedBody.action && !action) action = String(parsedBody.action);
|
||
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
|
||
params = parsedBody.params as Record<string, unknown>;
|
||
} else {
|
||
params = parsedBody as Record<string, unknown>;
|
||
}
|
||
echo = parsedBody.echo;
|
||
}
|
||
} catch {
|
||
if (contentType.includes('application/json')) {
|
||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
|
||
return;
|
||
}
|
||
// 无 content-type,JSON 失败则 fallback 到 urlencoded
|
||
const parsed = new URLSearchParams(bodyContent);
|
||
parsed.forEach((value, key) => {
|
||
try {
|
||
params[key] = JSON.parse(value);
|
||
} catch {
|
||
params[key] = value;
|
||
}
|
||
});
|
||
if (params.action && !action) {
|
||
action = String(params.action);
|
||
delete params.action;
|
||
}
|
||
if (params.echo !== undefined) {
|
||
echo = params.echo;
|
||
delete params.echo;
|
||
}
|
||
}
|
||
} else {
|
||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` });
|
||
return;
|
||
}
|
||
}
|
||
} else {
|
||
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
|
||
return;
|
||
}
|
||
|
||
if (!action) {
|
||
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
|
||
return;
|
||
}
|
||
|
||
const response = await this.ctx.api.handle(action, params as JsonObject);
|
||
if (echo !== undefined) {
|
||
response.echo = echo as JsonValue;
|
||
}
|
||
writeJson(res, 200, response);
|
||
} catch (error) {
|
||
const wording = error instanceof Error ? error.message : 'internal error';
|
||
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
|
||
}
|
||
}
|
||
}
|
||
|
||
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
|
||
return new Promise((resolve, reject) => {
|
||
const chunks: Buffer[] = [];
|
||
let total = 0;
|
||
req.on('data', (chunk: Buffer) => {
|
||
total += chunk.length;
|
||
if (total > maxBytes) {
|
||
reject(new Error('request body too large'));
|
||
req.destroy();
|
||
return;
|
||
}
|
||
chunks.push(chunk);
|
||
});
|
||
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||
req.on('error', reject);
|
||
});
|
||
}
|
||
|
||
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
|
||
res.statusCode = statusCode;
|
||
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
||
res.end(JSON.stringify(data));
|
||
}
|