@ohmyapi/relay 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/body.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ import { type ApiProtocol, type Data } from '@ohmyapi/protocols';
2
+ /** 读取有大小和超时限制的 JSON 对象,并保留解压后的原始字节。 */
3
+ export declare function readJsonBody(req: Request, signal: AbortSignal, stats: {
4
+ bytes: number;
5
+ }, progress: () => void, maxBodyBytes: number): Promise<{
6
+ parsed: Record<string, unknown>;
7
+ bytes: NonSharedBuffer;
8
+ }>;
9
+ /** 协议声明支持上传时接受 multipart,同时保留原始字节和对应的 boundary。 */
10
+ export declare function readProtocolBody(protocol: ApiProtocol, ...args: Parameters<typeof readJsonBody>): Promise<{
11
+ parsed: Data;
12
+ bytes: NonSharedBuffer;
13
+ form?: FormData;
14
+ contentType?: string;
15
+ }>;
package/dist/body.js ADDED
@@ -0,0 +1,117 @@
1
+ import { GatewayError } from '@ohmyapi/protocols';
2
+ import { promisify } from 'node:util';
3
+ import { brotliDecompress, gunzip, inflate, zstdDecompress } from 'node:zlib';
4
+ /** 请求体支持的 Content-Encoding。 */
5
+ const decoders = new Map([
6
+ ['gzip', promisify(gunzip)],
7
+ ['x-gzip', promisify(gunzip)],
8
+ ['deflate', promisify(inflate)],
9
+ ['br', promisify(brotliDecompress)],
10
+ ['zstd', promisify(zstdDecompress)],
11
+ ]);
12
+ /** 按 Content-Encoding 取得解压步骤,编码不受支持时在读取请求体之前拒绝。 */
13
+ function contentDecoders(req) {
14
+ return (req.headers.get('content-encoding') ?? '')
15
+ .split(',')
16
+ .map((encoding) => encoding.trim().toLowerCase())
17
+ .filter((encoding) => encoding && encoding !== 'identity')
18
+ .map((encoding) => {
19
+ const decode = decoders.get(encoding);
20
+ if (!decode)
21
+ throw new GatewayError(415, 'unsupported_content_encoding', `Content-Encoding ${encoding} is not supported`);
22
+ return { encoding, decode };
23
+ });
24
+ }
25
+ /** Content-Encoding 按编码顺序列出,逆序解压;解压后的大小同样受 `maxBodyBytes` 限制。 */
26
+ async function decodeBody(raw, steps, maxBodyBytes) {
27
+ let bytes = raw;
28
+ for (const { encoding, decode } of steps.toReversed()) {
29
+ try {
30
+ bytes = await decode(bytes, { maxOutputLength: maxBodyBytes });
31
+ }
32
+ catch (error) {
33
+ if (error.code === 'ERR_BUFFER_TOO_LARGE')
34
+ throw new GatewayError(413, 'request_too_large', 'Request body exceeds the gateway limit');
35
+ throw new GatewayError(400, 'invalid_content_encoding', `Request body is not valid ${encoding} data`);
36
+ }
37
+ }
38
+ return bytes;
39
+ }
40
+ async function readBodyBytes(req, signal, stats, progress, maxBodyBytes) {
41
+ const steps = contentDecoders(req);
42
+ const reader = req.body?.getReader();
43
+ if (!reader)
44
+ throw new GatewayError(400, 'invalid_request', 'A request body is required');
45
+ const cancel = () => {
46
+ void reader.cancel().catch(() => { });
47
+ };
48
+ signal.addEventListener('abort', cancel, { once: true });
49
+ if (signal.aborted)
50
+ cancel();
51
+ const chunks = [];
52
+ let size = 0;
53
+ try {
54
+ for (;;) {
55
+ const { done, value } = await reader.read();
56
+ if (done)
57
+ break;
58
+ if (value.byteLength)
59
+ progress();
60
+ size += value.byteLength;
61
+ stats.bytes = size;
62
+ if (size > maxBodyBytes) {
63
+ await reader.cancel();
64
+ throw new GatewayError(413, 'request_too_large', 'Request body exceeds the gateway limit');
65
+ }
66
+ chunks.push(value);
67
+ }
68
+ }
69
+ finally {
70
+ signal.removeEventListener('abort', cancel);
71
+ reader.releaseLock();
72
+ }
73
+ if (signal.aborted) {
74
+ const message = 'Request body was not completed before admission';
75
+ if (signal.reason === 'body_idle_timeout')
76
+ throw new GatewayError(408, 'body_idle_timeout', 'Request body upload stalled');
77
+ if (signal.reason === 'body_timeout')
78
+ throw new GatewayError(408, 'body_timeout', message);
79
+ throw new GatewayError(400, 'request_cancelled', message);
80
+ }
81
+ return decodeBody(Buffer.concat(chunks), steps, maxBodyBytes);
82
+ }
83
+ /** 读取有大小和超时限制的 JSON 对象,并保留解压后的原始字节。 */
84
+ export async function readJsonBody(req, signal, stats, progress, maxBodyBytes) {
85
+ if (!req.headers.get('content-type')?.toLowerCase().startsWith('application/json'))
86
+ throw new GatewayError(415, 'unsupported_media_type', 'Content-Type must be application/json');
87
+ const bytes = await readBodyBytes(req, signal, stats, progress, maxBodyBytes);
88
+ let parsed;
89
+ try {
90
+ parsed = JSON.parse(bytes.toString('utf8'));
91
+ }
92
+ catch {
93
+ throw new GatewayError(400, 'invalid_json', 'Invalid JSON body');
94
+ }
95
+ // 模型和流式选项由端点协议解析,请求体至少是一个对象。
96
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
97
+ throw new GatewayError(400, 'invalid_request', 'A model name and a boolean stream option are required');
98
+ return { parsed, bytes };
99
+ }
100
+ /** 协议声明支持上传时接受 multipart,同时保留原始字节和对应的 boundary。 */
101
+ export async function readProtocolBody(protocol, ...args) {
102
+ const [req] = args;
103
+ const contentType = req.headers.get('content-type') ?? '';
104
+ if (contentType.split(';', 1)[0].trim().toLowerCase() !== 'multipart/form-data')
105
+ return readJsonBody(...args);
106
+ if (!protocol.multipart || !new URL(req.url).pathname.endsWith(protocol.multipart.path))
107
+ throw new GatewayError(415, 'unsupported_media_type', 'This route does not accept multipart/form-data');
108
+ const bytes = await readBodyBytes(...args);
109
+ let form;
110
+ try {
111
+ form = await new Response(bytes, { headers: { 'content-type': contentType } }).formData();
112
+ }
113
+ catch {
114
+ throw new GatewayError(400, 'invalid_request', 'Invalid multipart form data');
115
+ }
116
+ return { parsed: protocol.multipart.parse(form), bytes, form, contentType };
117
+ }
@@ -0,0 +1,2 @@
1
+ /** 沿 cause 链判断上游请求是否在送达前失败。 */
2
+ export declare function requestNotSent(error: unknown): boolean;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * 这些错误发生在请求送达上游之前:解析地址、建立连接、TLS 握手、代理隧道或出站配置失败,上游不会执行请求。
3
+ * 连接重置、套接字关闭等可能发生在发送之后的错误不在此列。
4
+ */
5
+ const notSentCodes = new Set([
6
+ 'ECONNREFUSED',
7
+ 'ENOTFOUND',
8
+ 'EAI_AGAIN',
9
+ 'EAI_FAIL',
10
+ 'EAI_NONAME',
11
+ 'EHOSTUNREACH',
12
+ 'EHOSTDOWN',
13
+ 'ENETUNREACH',
14
+ 'ENETDOWN',
15
+ 'EADDRNOTAVAIL',
16
+ 'UND_ERR_CONNECT_TIMEOUT',
17
+ 'ERR_INVALID_URL',
18
+ 'ERR_OUTBOUND_SETUP',
19
+ 'CERT_HAS_EXPIRED',
20
+ 'CERT_NOT_YET_VALID',
21
+ 'CERT_REVOKED',
22
+ 'CERT_UNTRUSTED',
23
+ 'DEPTH_ZERO_SELF_SIGNED_CERT',
24
+ 'SELF_SIGNED_CERT_IN_CHAIN',
25
+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
26
+ 'UNABLE_TO_GET_ISSUER_CERT',
27
+ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
28
+ ]);
29
+ /** 代理拒绝建立隧道时 undici 报告的错误,CONNECT 之后才会发送请求。 */
30
+ const proxyTunnelRejected = /^Proxy response \(\d+\) !== 200 when HTTP Tunneling$/;
31
+ /** 沿 cause 链判断上游请求是否在送达前失败。 */
32
+ export function requestNotSent(error) {
33
+ let current = error;
34
+ for (let depth = 0; depth < 5 && current && typeof current === 'object'; depth++) {
35
+ const { code, message, cause } = current;
36
+ if (typeof code === 'string') {
37
+ if (notSentCodes.has(code) || code.startsWith('ERR_TLS_') || code.startsWith('ERR_SSL_'))
38
+ return true;
39
+ if (code === 'UND_ERR_ABORTED' && typeof message === 'string' && proxyTunnelRejected.test(message))
40
+ return true;
41
+ }
42
+ current = cause;
43
+ }
44
+ return false;
45
+ }
@@ -0,0 +1,3 @@
1
+ import { type Endpoint, modelListPath } from '@ohmyapi/protocols';
2
+ /** 按端点协议格式化错误;模型列表使用 OpenAI 格式。 */
3
+ export declare function errorResponse(endpoint: Endpoint | typeof modelListPath, status: number, code: string, message: string, id: string): Response;
package/dist/errors.js ADDED
@@ -0,0 +1,22 @@
1
+ import { modelListPath, openAIErrorBody, protocolFor } from '@ohmyapi/protocols';
2
+ /** 按端点协议格式化错误;模型列表使用 OpenAI 格式。 */
3
+ export function errorResponse(endpoint, status, code, message, id) {
4
+ const type = status === 401
5
+ ? 'authentication_error'
6
+ : status === 403
7
+ ? 'permission_error'
8
+ : status === 429
9
+ ? 'rate_limit_error'
10
+ : status >= 500
11
+ ? 'api_error'
12
+ : 'invalid_request_error';
13
+ const details = { status, type, code, message, id };
14
+ return Response.json(endpoint === modelListPath ? openAIErrorBody(details) : protocolFor(endpoint).errorBody(details), {
15
+ status,
16
+ headers: {
17
+ 'x-request-id': id,
18
+ 'cache-control': 'no-store',
19
+ ...(status === 429 ? { 'retry-after': '60' } : {}),
20
+ },
21
+ });
22
+ }
@@ -0,0 +1,2 @@
1
+ /** 转发给客户端的上游响应头:内容类型、Codex 会话状态和限流提示,其余不转发。 */
2
+ export declare function responseHeaders(upstream: Headers, requestId: string): Headers;
@@ -0,0 +1,18 @@
1
+ /** 转发给客户端的上游响应头:内容类型、Codex 会话状态和限流提示,其余不转发。 */
2
+ export function responseHeaders(upstream, requestId) {
3
+ const headers = new Headers({ 'x-request-id': requestId, 'cache-control': 'no-store' });
4
+ for (const name of [
5
+ 'content-type',
6
+ 'x-codex-turn-state',
7
+ 'x-reasoning-included',
8
+ 'retry-after',
9
+ 'x-ratelimit-limit-requests',
10
+ 'x-ratelimit-remaining-requests',
11
+ 'x-ratelimit-reset-requests',
12
+ ]) {
13
+ const value = upstream.get(name);
14
+ if (value)
15
+ headers.set(name, value);
16
+ }
17
+ return headers;
18
+ }
@@ -0,0 +1,8 @@
1
+ export { readJsonBody, readProtocolBody } from './body.ts';
2
+ export { requestNotSent } from './dispatch.ts';
3
+ export { errorResponse } from './errors.ts';
4
+ export { responseHeaders } from './headers.ts';
5
+ export { RequestLifecycle } from './lifecycle.ts';
6
+ export { type RelayResponseOptions, relayResponse } from './response.ts';
7
+ export { SseObserver } from './sse.ts';
8
+ export type * from './types.ts';
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { readJsonBody, readProtocolBody } from './body.js';
2
+ export { requestNotSent } from './dispatch.js';
3
+ export { errorResponse } from './errors.js';
4
+ export { responseHeaders } from './headers.js';
5
+ export { RequestLifecycle } from './lifecycle.js';
6
+ export { relayResponse } from './response.js';
7
+ export { SseObserver } from './sse.js';
@@ -0,0 +1,30 @@
1
+ export declare class RequestLifecycle {
2
+ readonly id: `${string}-${string}-${string}-${string}-${string}`;
3
+ readonly receivedAt: Date;
4
+ readonly abort: AbortController;
5
+ readonly done: Promise<void>;
6
+ releaseCapacity?: () => void;
7
+ releaseUpstream?: () => void;
8
+ private completeRequest;
9
+ private timer?;
10
+ private drainTimer?;
11
+ private drainTimeoutMs?;
12
+ private onDisconnect?;
13
+ clientDisconnected: boolean;
14
+ private finalization?;
15
+ private stopResponse?;
16
+ private readonly req;
17
+ private readonly onComplete;
18
+ private readonly disconnect;
19
+ private readonly onAbort;
20
+ constructor(req: Request, onComplete: () => void);
21
+ syncClientAbort(): void;
22
+ retainUpstreamOnDisconnect(timeoutMs: number): void;
23
+ disconnectClient(): void;
24
+ private releaseUserCapacity;
25
+ watchClientDisconnect(handler: () => void): void;
26
+ withBodyTimeout<T>(timeoutMs: number, idleTimeoutMs: number, read: (progress: () => void) => Promise<T>): Promise<T>;
27
+ setTimeout(reason: 'upstream_timeout' | 'upstream_idle_timeout', timeoutMs: number): void;
28
+ watchResponse(stop: () => Promise<void>): void;
29
+ finish(settle: () => Promise<void>, log: () => void): Promise<void>;
30
+ }
@@ -0,0 +1,110 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ export class RequestLifecycle {
3
+ id = randomUUID();
4
+ receivedAt = new Date();
5
+ abort = new AbortController();
6
+ done;
7
+ releaseCapacity;
8
+ releaseUpstream;
9
+ completeRequest = () => { };
10
+ timer;
11
+ drainTimer;
12
+ drainTimeoutMs;
13
+ onDisconnect;
14
+ clientDisconnected = false;
15
+ finalization;
16
+ stopResponse;
17
+ req;
18
+ onComplete;
19
+ disconnect = () => this.disconnectClient();
20
+ onAbort = () => {
21
+ void this.stopResponse?.();
22
+ };
23
+ constructor(req, onComplete) {
24
+ this.req = req;
25
+ this.onComplete = onComplete;
26
+ this.done = new Promise((resolve) => {
27
+ this.completeRequest = resolve;
28
+ });
29
+ req.signal.addEventListener('abort', this.disconnect, { once: true });
30
+ }
31
+ syncClientAbort() {
32
+ if (this.req.signal.aborted)
33
+ this.disconnect();
34
+ }
35
+ retainUpstreamOnDisconnect(timeoutMs) {
36
+ this.drainTimeoutMs = timeoutMs;
37
+ }
38
+ disconnectClient() {
39
+ if (this.finalization || this.clientDisconnected)
40
+ return;
41
+ this.clientDisconnected = true;
42
+ if (!this.drainTimeoutMs) {
43
+ this.abort.abort('client_disconnected');
44
+ return;
45
+ }
46
+ // 独立于空闲计时器,持续输出也不能无限延长断连后的收尾。
47
+ this.drainTimer = setTimeout(() => this.abort.abort('client_disconnected'), this.drainTimeoutMs);
48
+ // 后台读取只占用上游资源,客户端重试时不再计入用户并发。
49
+ this.releaseUserCapacity();
50
+ this.onDisconnect?.();
51
+ }
52
+ releaseUserCapacity() {
53
+ const release = this.releaseCapacity;
54
+ this.releaseCapacity = undefined;
55
+ release?.();
56
+ }
57
+ watchClientDisconnect(handler) {
58
+ this.onDisconnect = handler;
59
+ if (this.clientDisconnected)
60
+ handler();
61
+ }
62
+ // 总超时限制整体读取时长;停滞超时在每次收到数据时重置,尽早释放卡住的连接。
63
+ async withBodyTimeout(timeoutMs, idleTimeoutMs, read) {
64
+ const timer = setTimeout(() => this.abort.abort('body_timeout'), timeoutMs);
65
+ const idleTimer = setTimeout(() => this.abort.abort('body_idle_timeout'), idleTimeoutMs);
66
+ try {
67
+ return await read(() => idleTimer.refresh());
68
+ }
69
+ finally {
70
+ clearTimeout(timer);
71
+ clearTimeout(idleTimer);
72
+ }
73
+ }
74
+ setTimeout(reason, timeoutMs) {
75
+ if (this.timer)
76
+ clearTimeout(this.timer);
77
+ this.timer = setTimeout(() => this.abort.abort(reason), timeoutMs);
78
+ }
79
+ watchResponse(stop) {
80
+ this.stopResponse = stop;
81
+ this.abort.signal.addEventListener('abort', this.onAbort, { once: true });
82
+ if (this.abort.signal.aborted)
83
+ this.onAbort();
84
+ }
85
+ // 返回 Response 后仍保留资源,直到响应读取和计费收尾完成。
86
+ finish(settle, log) {
87
+ if (this.finalization)
88
+ return this.finalization;
89
+ if (this.timer)
90
+ clearTimeout(this.timer);
91
+ if (this.drainTimer)
92
+ clearTimeout(this.drainTimer);
93
+ this.onDisconnect = undefined;
94
+ this.req.signal.removeEventListener('abort', this.disconnect);
95
+ this.abort.signal.removeEventListener('abort', this.onAbort);
96
+ this.finalization = (async () => {
97
+ try {
98
+ await settle();
99
+ }
100
+ finally {
101
+ this.releaseUserCapacity();
102
+ this.releaseUpstream?.();
103
+ this.onComplete();
104
+ this.completeRequest();
105
+ log();
106
+ }
107
+ })();
108
+ return this.finalization;
109
+ }
110
+ }
@@ -0,0 +1,24 @@
1
+ import type { RequestLifecycle } from './lifecycle.ts';
2
+ import type { RelayLimits, RelayOutcome, ResponseObserver } from './types.ts';
3
+ export type RelayResponseOptions = {
4
+ upstream: Response;
5
+ /** 客户端是否请求流式响应;与实际响应类型不一致时以 unexpected_response_type 结束。 */
6
+ streaming: boolean;
7
+ lifecycle: RequestLifecycle;
8
+ limits: RelayLimits;
9
+ observer?: ResponseObserver;
10
+ /** 每收到一块数据,观察者处理之后、转发给客户端之前调用。 */
11
+ onChunk?: () => Promise<void>;
12
+ /** 每块数据转发后检查上游是否已到终止事件;返回值非空时停止读取并结束响应。 */
13
+ terminal?: () => 'completed' | 'failed' | undefined;
14
+ /** 响应结束时调用一次;完成之后客户端的响应才关闭。 */
15
+ onFinish: (outcome: RelayOutcome) => Promise<void>;
16
+ /** 读取上游时出错,随后按上游中断处理。 */
17
+ onError: (error: unknown) => void;
18
+ };
19
+ /**
20
+ * 把上游响应转发给客户端,转发的字节保持原样,同时交给观察者解析。
21
+ * 客户端断开后,如果 lifecycle 设置了 retainUpstreamOnDisconnect,继续在后台读完上游响应,直到超时;
22
+ * 否则中止读取。重定向不转发,以 GatewayError 拒绝。
23
+ */
24
+ export declare function relayResponse(options: RelayResponseOptions): Promise<Response>;
@@ -0,0 +1,169 @@
1
+ import { GatewayError } from '@ohmyapi/protocols';
2
+ import { responseHeaders } from './headers.js';
3
+ import { SseObserver } from './sse.js';
4
+ /**
5
+ * 把上游响应转发给客户端,转发的字节保持原样,同时交给观察者解析。
6
+ * 客户端断开后,如果 lifecycle 设置了 retainUpstreamOnDisconnect,继续在后台读完上游响应,直到超时;
7
+ * 否则中止读取。重定向不转发,以 GatewayError 拒绝。
8
+ */
9
+ export async function relayResponse(options) {
10
+ const { upstream, streaming, lifecycle, limits, observer, onChunk, terminal, onFinish, onError } = options;
11
+ const { id, abort } = lifecycle;
12
+ const contentType = upstream.headers.get('content-type')?.toLowerCase() ?? '';
13
+ if (upstream.status >= 300 && upstream.status < 400) {
14
+ await upstream.body?.cancel();
15
+ await onFinish({ kind: 'redirect', ended: false, errorCode: 'upstream_redirect', contentType });
16
+ throw new GatewayError(502, 'upstream_redirect', 'Upstream redirects are not supported');
17
+ }
18
+ const headers = responseHeaders(upstream.headers, id);
19
+ if (!upstream.body) {
20
+ await onFinish({ kind: 'empty', ended: true, errorCode: 'empty_response', contentType });
21
+ return new Response(null, { status: upstream.status, headers });
22
+ }
23
+ // 根据实际响应类型解析内容,转发字节保持原样。
24
+ const isSse = contentType.includes('text/event-stream');
25
+ const kind = isSse ? 'sse' : 'json';
26
+ const resetIdleTimeout = () => {
27
+ if (!isSse || abort.signal.aborted)
28
+ return;
29
+ lifecycle.setTimeout('upstream_idle_timeout', limits.streamIdleTimeoutMs);
30
+ };
31
+ resetIdleTimeout();
32
+ if (isSse)
33
+ headers.set('x-accel-buffering', 'no');
34
+ const sse = isSse && observer ? new SseObserver(observer, limits.maxEventBytes) : undefined;
35
+ const jsonChunks = [];
36
+ let jsonSize = 0;
37
+ let jsonTruncated = false;
38
+ const reader = upstream.body.getReader();
39
+ let pullTask;
40
+ let responseFinalization;
41
+ let stoppingResponse;
42
+ let drainTask;
43
+ let clientClosed = false;
44
+ let responseController;
45
+ const abortReason = () => (typeof abort.signal.reason === 'string' ? abort.signal.reason : 'upstream_disconnected');
46
+ // 读取任务停止后解析已收到的数据,再执行一次性收尾。ended 表示上游响应正常读到结尾。
47
+ const finalizeResponse = (errorCode, ended = false) => {
48
+ responseFinalization ??= (async () => {
49
+ sse?.finish(errorCode === 'client_disconnected' && !ended);
50
+ if (observer && !isSse && !jsonTruncated) {
51
+ try {
52
+ observer.event(JSON.parse(Buffer.concat(jsonChunks).toString('utf8')));
53
+ observer.done();
54
+ }
55
+ catch (error) {
56
+ observer.malformed(error);
57
+ }
58
+ }
59
+ reader.releaseLock();
60
+ await onFinish({ kind, ended, errorCode, contentType });
61
+ })();
62
+ return responseFinalization;
63
+ };
64
+ const failClient = () => {
65
+ if (clientClosed)
66
+ return;
67
+ clientClosed = true;
68
+ responseController.error(new Error('Upstream stream interrupted'));
69
+ };
70
+ const closeClient = () => {
71
+ if (clientClosed)
72
+ return;
73
+ clientClosed = true;
74
+ responseController.close();
75
+ };
76
+ const stopResponse = () => {
77
+ stoppingResponse ??= (async () => {
78
+ await reader.cancel().catch(() => { });
79
+ await pullTask;
80
+ await finalizeResponse(abortReason());
81
+ failClient();
82
+ })();
83
+ return stoppingResponse;
84
+ };
85
+ const readNext = async () => {
86
+ try {
87
+ const { value, done } = await reader.read();
88
+ if (done) {
89
+ const ended = !abort.signal.aborted;
90
+ await finalizeResponse(!ended
91
+ ? abortReason()
92
+ : !upstream.ok
93
+ ? 'upstream_http_error'
94
+ : streaming !== isSse
95
+ ? 'unexpected_response_type'
96
+ : lifecycle.clientDisconnected
97
+ ? 'client_disconnected'
98
+ : undefined, ended);
99
+ if (abort.signal.aborted)
100
+ failClient();
101
+ else
102
+ closeClient();
103
+ return;
104
+ }
105
+ resetIdleTimeout();
106
+ sse?.push(value);
107
+ await onChunk?.();
108
+ // 观察容量独立于转发:超出后继续转发,并报告这部分内容没有解析。
109
+ if (observer && !isSse && !jsonTruncated) {
110
+ jsonSize += value.byteLength;
111
+ if (jsonSize <= limits.maxBodyBytes)
112
+ jsonChunks.push(value);
113
+ else {
114
+ jsonChunks.length = 0;
115
+ jsonTruncated = true;
116
+ observer.truncated();
117
+ }
118
+ }
119
+ if (!abort.signal.aborted && !clientClosed && !lifecycle.clientDisconnected)
120
+ responseController.enqueue(value);
121
+ const state = terminal?.();
122
+ if (state) {
123
+ await reader.cancel().catch(() => { });
124
+ await finalizeResponse(state === 'failed' ? 'upstream_error' : lifecycle.clientDisconnected ? 'client_disconnected' : undefined);
125
+ if (!abort.signal.aborted)
126
+ closeClient();
127
+ }
128
+ }
129
+ catch (error) {
130
+ onError(error);
131
+ abort.abort(abort.signal.reason ?? 'upstream_disconnected');
132
+ failClient();
133
+ }
134
+ };
135
+ const drain = () => {
136
+ if (drainTask || responseFinalization || stoppingResponse)
137
+ return;
138
+ failClient();
139
+ drainTask = (async () => {
140
+ // 复用正在进行的读取,避免下游 pull 与后台收尾同时消费上游。
141
+ await pullTask;
142
+ while (!responseFinalization && !stoppingResponse && !abort.signal.aborted) {
143
+ pullTask = readNext();
144
+ await pullTask;
145
+ }
146
+ })().catch(onError);
147
+ };
148
+ const stream = new ReadableStream({
149
+ start: (controller) => {
150
+ responseController = controller;
151
+ },
152
+ pull: () => {
153
+ if (responseFinalization || stoppingResponse || drainTask)
154
+ return drainTask;
155
+ pullTask = readNext();
156
+ return pullTask;
157
+ },
158
+ cancel: () => {
159
+ clientClosed = true;
160
+ lifecycle.disconnectClient();
161
+ if (abort.signal.aborted)
162
+ return stopResponse();
163
+ drain();
164
+ },
165
+ });
166
+ lifecycle.watchResponse(stopResponse);
167
+ lifecycle.watchClientDisconnect(drain);
168
+ return new Response(stream, { status: upstream.status, headers });
169
+ }
package/dist/sse.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import type { ResponseObserver } from './types.ts';
2
+ /**
3
+ * 有界的增量 SSE 解析:按事件把 data 交给观察者,`[DONE]` 表示完成,其余按 JSON 解析。
4
+ * 单个事件超过 maxEventBytes 时跳过该事件并报告 truncated。只读取字节,不改动转发给客户端的内容。
5
+ */
6
+ export declare class SseObserver {
7
+ private decoder;
8
+ private line;
9
+ private lineLength;
10
+ private data;
11
+ private size;
12
+ private skip;
13
+ private previousCR;
14
+ private readonly observer;
15
+ private readonly maxEventBytes;
16
+ private readonly onEvent?;
17
+ constructor(observer: ResponseObserver, maxEventBytes: number, onEvent?: (value: unknown) => void);
18
+ push(chunk: Uint8Array): void;
19
+ finish(interrupted?: boolean): void;
20
+ private consume;
21
+ private endLine;
22
+ private event;
23
+ }
package/dist/sse.js ADDED
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 有界的增量 SSE 解析:按事件把 data 交给观察者,`[DONE]` 表示完成,其余按 JSON 解析。
3
+ * 单个事件超过 maxEventBytes 时跳过该事件并报告 truncated。只读取字节,不改动转发给客户端的内容。
4
+ */
5
+ export class SseObserver {
6
+ decoder = new TextDecoder();
7
+ line = '';
8
+ lineLength = 0;
9
+ data = [];
10
+ size = 0;
11
+ skip = false;
12
+ previousCR = false;
13
+ observer;
14
+ maxEventBytes;
15
+ onEvent;
16
+ constructor(observer, maxEventBytes, onEvent) {
17
+ this.onEvent = onEvent;
18
+ this.observer = observer;
19
+ this.maxEventBytes = maxEventBytes;
20
+ }
21
+ push(chunk) {
22
+ this.consume(this.decoder.decode(chunk, { stream: true }));
23
+ }
24
+ finish(interrupted = false) {
25
+ // 断连时末尾可能只有半个事件,只用此前已完整解析的事件。
26
+ if (interrupted) {
27
+ this.line = '';
28
+ this.data = [];
29
+ return;
30
+ }
31
+ this.consume(this.decoder.decode());
32
+ if (this.line)
33
+ this.endLine();
34
+ this.event();
35
+ }
36
+ consume(text) {
37
+ let offset = 0;
38
+ const breaks = /[\r\n]/g;
39
+ while (offset < text.length) {
40
+ if (this.previousCR) {
41
+ this.previousCR = false;
42
+ if (text[offset] === '\n') {
43
+ offset++;
44
+ continue;
45
+ }
46
+ }
47
+ breaks.lastIndex = offset;
48
+ const end = breaks.exec(text)?.index ?? text.length;
49
+ const fragment = text.slice(offset, end);
50
+ this.lineLength += fragment.length;
51
+ if (!this.skip) {
52
+ this.size += Buffer.byteLength(fragment, 'utf8');
53
+ if (this.size > this.maxEventBytes) {
54
+ this.skip = true;
55
+ this.line = '';
56
+ this.data = [];
57
+ this.observer.truncated();
58
+ }
59
+ else
60
+ this.line += fragment;
61
+ }
62
+ if (end === text.length)
63
+ break;
64
+ this.previousCR = text[end] === '\r';
65
+ this.endLine();
66
+ offset = end + 1;
67
+ }
68
+ }
69
+ endLine() {
70
+ if (!this.lineLength)
71
+ this.event();
72
+ else if (this.line.startsWith('data:'))
73
+ this.data.push(this.line.slice(5).replace(/^ /, ''));
74
+ this.line = '';
75
+ this.lineLength = 0;
76
+ }
77
+ event() {
78
+ if (!this.skip && this.data.length) {
79
+ const raw = this.data.join('\n');
80
+ if (raw === '[DONE]')
81
+ this.observer.done();
82
+ else {
83
+ try {
84
+ const value = JSON.parse(raw);
85
+ this.observer.event(value);
86
+ this.onEvent?.(value);
87
+ }
88
+ catch (error) {
89
+ this.observer.malformed(error);
90
+ }
91
+ }
92
+ }
93
+ this.data = [];
94
+ this.size = 0;
95
+ this.skip = false;
96
+ }
97
+ }
@@ -0,0 +1,46 @@
1
+ /** 转发上游响应时的超时和观察容量。 */
2
+ export type RelayLimits = {
3
+ /** 流式响应两次收到数据之间的最长间隔。 */
4
+ streamIdleTimeoutMs: number;
5
+ /** 解析单个 SSE 事件的字节上限;超出的事件照常转发,但不解析。 */
6
+ maxEventBytes: number;
7
+ /** 解析非流式响应体的字节上限;超出时照常转发,但不解析。 */
8
+ maxBodyBytes: number;
9
+ };
10
+ /** 接收从上游响应中解析出的内容。转发给客户端的字节保持原样。 */
11
+ export interface ResponseObserver {
12
+ /** SSE 事件的 data,或非流式响应体,按 JSON 解析后的值。 */
13
+ event(value: unknown): void;
14
+ /** 收到 SSE 的 `[DONE]`,或非流式响应体解析完成。 */
15
+ done(): void;
16
+ /** SSE 事件或响应体不是合法的 JSON,或 event 抛出了错误。 */
17
+ malformed(error: unknown): void;
18
+ /** SSE 事件或响应体超出观察容量,这部分内容没有解析。 */
19
+ truncated(): void;
20
+ }
21
+ /**
22
+ * 上游响应的形态:
23
+ * - redirect:重定向,响应体已丢弃。
24
+ * - empty:没有响应体。
25
+ * - sse:Content-Type 为 text/event-stream。
26
+ * - json:其余响应,按 JSON 解析。
27
+ */
28
+ export type ResponseKind = 'redirect' | 'empty' | 'sse' | 'json';
29
+ /** 响应结束时的情况,供调用方决定计费、记录等收尾。 */
30
+ export type RelayOutcome = {
31
+ kind: ResponseKind;
32
+ /** 上游响应体正常读到结尾,没有被取消或中断。 */
33
+ ended: boolean;
34
+ /**
35
+ * 响应没有正常完成的原因:
36
+ * - upstream_redirect、empty_response:见 kind。
37
+ * - upstream_http_error:上游返回失败的 HTTP 状态。
38
+ * - unexpected_response_type:流式设置与响应类型不一致。
39
+ * - upstream_error:terminal 报告上游以失败结束。
40
+ * - client_disconnected:客户端断开后,响应在后台读完。
41
+ * - 其余为 RequestLifecycle 中止请求的原因,例如 upstream_idle_timeout。
42
+ */
43
+ errorCode?: string;
44
+ /** 上游响应的 Content-Type,小写;没有时为空字符串。 */
45
+ contentType: string;
46
+ };
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,25 @@
1
1
  {
2
2
  "name": "@ohmyapi/relay",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Request lifecycle and response relaying for LLM API gateways",
5
+ "type": "module",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "engines": {
16
+ "node": ">=24.13.0"
17
+ },
18
+ "dependencies": {
19
+ "@ohmyapi/protocols": "^0.2.0"
20
+ },
21
+ "scripts": {
22
+ "build": "tsc -p tsconfig.json",
23
+ "typecheck": "tsc --noEmit -p tsconfig.json"
24
+ }
6
25
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.