Skip to content

Commit 201994f

Browse files
author
hzq
committed
Preserve observed bytes in bounded gateway downloads
Detach transport views before the next read, release readers without waiting for cleanup, and distinguish size refusals from unfinished requests. Return only complete JSON, metadata and artifact responses. Improvement-Round: 3/10 after v0.0.74
1 parent 4cf7e21 commit 201994f

9 files changed

Lines changed: 719 additions & 75 deletions

File tree

‎docs/operations.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,8 @@ CLI equivalents are `oaa agents --limit 20`, `oaa agent AGENT --section routes -
154154

155155
Output text has lossless cursors; large results no longer hide response IDs or artifact references behind a truncated JSON preview. Artifact links are authenticated `oaa://files/{id}` resources. MCP resource reads are limited to 4 MiB to keep base64 frames bounded; larger files use authenticated HTTP or `oaa download` (up to the existing 8 MiB file limit). Access still requires file scope and the originating agent grant. There are no tokens in resource URLs.
156156

157+
The gateway client copies each response chunk when it reads it. Files, skill resources and JSON are returned only after the body ends and the actual bytes fit the limit. A smaller or missing `Content-Length` does not authorize a larger body. A confirmed overflow is `gateway_response_too_large`; an interrupted 2xx body is `invalid_gateway_response`, not a successful download. If an error body breaks, the client keeps the HTTP status but does not report details from a partial document or resend the request.
158+
157159
CLI callers can complete the same workflow without the console: `oaa upload SELECTED_FILE`, `oaa invoke ... --idempotency-key KEY`, `oaa wait RESPONSE_ID`, `oaa output RESPONSE_ID`, `oaa artifacts RESPONSE_ID`, and `oaa download FILE_ID --out NEW_FILE`. Use `--url` and `--token-file` or `OAA_GATEWAY_URL` / `OAA_TOKEN_FILE`. Downloads never overwrite an existing file.
158160

159161
Publishing a native agent requires an enabled worker adapter as well as the MCP entry. Merely reading an MCP server does not export the caller's process, private plugins, or desktop login state.

‎docs/zh-CN/operations.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ MCP 的任务工作流是 `oaa_upload_text`(可选)、`oaa_preview_route`、
161161

162162
输出文本有无损游标;大的结果不再把响应 ID 或产物引用藏在被截断的 JSON 预览后面。产物链接是带鉴权的 `oaa://files/{id}` 资源。MCP 资源读取限制在 4 MiB,以保证 base64 帧有界;更大的文件使用带鉴权的 HTTP 或 `oaa download`(上限仍是现有的 8 MiB 文件限制)。访问仍然需要文件权限和来源智能体的授权。资源 URL 里没有令牌。
163163

164+
网关客户端在每次读取时复制当前分片。文件、技能资源和 JSON 只有在正文结束、实际字节数通过限额检查后才会交付;较小或缺失的 `Content-Length` 不能放宽上限。已确认超限返回 `gateway_response_too_large`;2xx 正文中断返回 `invalid_gateway_response`,不算下载成功。错误正文中途断开时保留已收到的 HTTP 状态,不采信半份文档里的错误详情,也不重新发送请求。
165+
164166
CLI 调用方不用控制台也能完成同样的工作流:`oaa upload SELECTED_FILE`、`oaa invoke ... --idempotency-key KEY`、`oaa wait RESPONSE_ID`、`oaa output RESPONSE_ID`、`oaa artifacts RESPONSE_ID`、`oaa download FILE_ID --out NEW_FILE`。使用 `--url` 与 `--token-file`,或 `OAA_GATEWAY_URL` / `OAA_TOKEN_FILE`。下载从不覆盖已有文件。
165167

166168
发布一个原生智能体,除了 MCP 入口,还需要一个已启用的 worker 适配器。仅仅读取一个 MCP 服务器,并不会导出调用方的进程、私有插件或桌面登录状态。

‎src/client/client.ts‎

Lines changed: 65 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import { readFile } from 'node:fs/promises';
22
import { processLocale } from '../core/locale.js';
3-
import { Fault } from '../core/util.js';
3+
import { Fault, checkAbort, deadlineTimer } from '../core/util.js';
44
import { validateEndpoint } from '../config/config.js';
55
import { MAX_SKILL_EXPORT_FILE_BYTES } from '../core/skill-files.js';
6+
import { readGatewayBytes, type GatewayBody } from './response-bytes.js';
67
export type RequestOptions = {
78
signal?: AbortSignal;
89
timeoutMs?: number;
@@ -110,10 +111,32 @@ export class GatewayClient {
110111
'invalid_idempotency_key',
111112
'Use 1-200 printable ASCII characters without spaces.',
112113
);
113-
const deadline = AbortSignal.timeout(options.timeoutMs ?? 35_000);
114-
const signal = options.signal ? AbortSignal.any([options.signal, deadline]) : deadline;
114+
if (!Number.isSafeInteger(limit) || limit < 0)
115+
throw new Fault(
116+
'invalid_request',
117+
'Response byte limit must be a non-negative safe integer.',
118+
400,
119+
);
120+
const timeoutMs = options.timeoutMs ?? 35_000;
121+
if (!Number.isInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647)
122+
throw new Fault(
123+
'invalid_request',
124+
'Gateway timeout must be a non-negative integer within the timer range.',
125+
400,
126+
);
127+
const callerSignal = options.signal;
128+
const deadline = deadlineTimer(timeoutMs);
129+
let signal: AbortSignal;
130+
try {
131+
signal = callerSignal ? AbortSignal.any([callerSignal, deadline.signal]) : deadline.signal;
132+
} catch (error) {
133+
deadline.clear();
134+
throw error;
135+
}
136+
let response: Response, bytes: GatewayBody;
115137
try {
116-
const response = await fetch(target, {
138+
checkAbort(signal);
139+
response = await fetch(target, {
117140
method,
118141
redirect: 'error',
119142
signal,
@@ -126,63 +149,52 @@ export class GatewayClient {
126149
},
127150
body: body === undefined ? undefined : JSON.stringify(body),
128151
});
129-
const maximum = response.ok ? limit : 65536;
130-
if (Number(response.headers.get('content-length')) > maximum) {
131-
await response.body?.cancel();
132-
throw new Fault(
133-
'gateway_response_too_large',
134-
'Gateway response exceeds its bounded reader.',
135-
502,
136-
);
137-
}
138-
const chunks: Uint8Array[] = [];
139-
let size = 0;
140-
const reader = response.body?.getReader();
141-
try {
142-
if (reader)
143-
while (true) {
144-
const next = await reader.read();
145-
if (next.done) break;
146-
size += next.value.length;
147-
if (size > maximum)
148-
throw new Fault(
149-
'gateway_response_too_large',
150-
'Gateway response exceeds its bounded reader.',
151-
502,
152-
);
153-
chunks.push(next.value);
154-
}
155-
} finally {
156-
await reader?.cancel().catch(() => {});
157-
}
158-
const bytes = Buffer.concat(chunks);
159-
if (!response.ok) {
160-
let error: { code?: unknown; message?: unknown } | undefined;
161-
try {
162-
error = JSON.parse(bytes.toString('utf8'))?.error;
163-
} catch {
164-
// Non-JSON error body: report the HTTP status instead.
165-
}
166-
throw new Fault(
167-
typeof error?.code === 'string' ? error.code.slice(0, 100) : 'gateway_error',
168-
typeof error?.message === 'string'
169-
? error.message.slice(0, 2000)
170-
: `Gateway returned HTTP ${response.status}`,
171-
response.status,
172-
);
173-
}
174-
return { bytes };
152+
bytes = await readGatewayBytes(response, signal, response.ok ? limit : 65536);
175153
} catch (error) {
176-
if (signal.aborted)
154+
if (signal.aborted) {
155+
const timedOut = deadline.signal.aborted && signal.reason === deadline.signal.reason;
177156
throw new Fault(
178-
options.signal?.aborted ? 'request_cancelled' : 'gateway_timeout',
157+
timedOut ? 'gateway_timeout' : 'request_cancelled',
179158
'Gateway request ended before confirmation. An accepted task may still be running; retry submissions with the same idempotency key.',
180-
options.signal?.aborted ? 499 : 504,
159+
timedOut ? 504 : 499,
181160
);
161+
}
182162
// fetch 连不上(端口没人监听、地址写错)时只抛 TypeError('fetch failed'):换成能告诉新人下一步的码。
183163
if (error instanceof TypeError)
184164
throw new Fault('gateway_unreachable', `Cannot reach the gateway at ${this.url}.`, 503);
185165
throw error;
166+
} finally {
167+
deadline.clear();
186168
}
169+
// Disposal cannot revoke a limit or a complete response already observed.
170+
if (bytes === 'too_large')
171+
throw new Fault(
172+
'gateway_response_too_large',
173+
'Gateway response exceeds its bounded reader.',
174+
502,
175+
);
176+
if (!response.ok) {
177+
let error: { code?: unknown; message?: unknown } | undefined;
178+
if (bytes !== 'incomplete')
179+
try {
180+
error = JSON.parse(bytes.toString('utf8'))?.error;
181+
} catch {
182+
/* Only a complete JSON error supplies details. */
183+
}
184+
throw new Fault(
185+
typeof error?.code === 'string' ? error.code.slice(0, 100) : 'gateway_error',
186+
typeof error?.message === 'string'
187+
? error.message.slice(0, 2000)
188+
: `Gateway returned HTTP ${response.status}`,
189+
response.status,
190+
);
191+
}
192+
if (bytes === 'incomplete')
193+
throw new Fault(
194+
'invalid_gateway_response',
195+
'Gateway response ended before confirmation. An accepted task may still be running; retry submissions with the same idempotency key.',
196+
502,
197+
);
198+
return { bytes };
187199
}
188200
}

‎src/client/response-bytes.ts‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import { types } from 'node:util';
2+
import { acquireResponseReader, discardResponseBody } from '../core/response-reader.js';
3+
import { checkAbort } from '../core/util.js';
4+
5+
export type GatewayBody = Buffer | 'too_large' | 'incomplete';
6+
const MAX_BLOCK_GROWTH = 64 * 1024;
7+
8+
/** A transport may reuse a view on its next pull. Pack small reads into owned blocks rather
9+
* than retaining views, or repeatedly copying all previous bytes as the response grows. */
10+
class OwnedBytes {
11+
private blocks?: Buffer[];
12+
private tail?: Buffer;
13+
private filled = 0;
14+
private size = 0;
15+
constructor(
16+
private readonly maximum: number,
17+
private hint: number,
18+
) {}
19+
private copyInto(out: Buffer) {
20+
let off = 0;
21+
if (this.blocks) {
22+
for (const b of this.blocks) {
23+
out.set(b, off);
24+
off += b.length;
25+
}
26+
}
27+
if (this.tail && this.filled)
28+
out.set(
29+
this.filled === this.tail.length ? this.tail : this.tail.subarray(0, this.filled),
30+
off,
31+
);
32+
}
33+
append(view: Uint8Array): boolean {
34+
const n = view.byteLength;
35+
if (n > this.maximum - this.size) return false;
36+
if (!n) return true;
37+
const end = this.size + n;
38+
// Use a declared length only once it is supported by at least half that many observed bytes.
39+
const useHint = this.hint >= end && this.hint - end <= end;
40+
if (!this.tail) {
41+
this.tail = Buffer.allocUnsafeSlow(useHint ? this.hint : n);
42+
if (useHint) this.hint = 0;
43+
this.tail.set(view);
44+
this.size = this.filled = n;
45+
return true;
46+
}
47+
if (useHint) {
48+
const out = Buffer.allocUnsafeSlow(this.hint);
49+
this.copyInto(out);
50+
this.blocks = undefined;
51+
this.tail = out;
52+
this.filled = this.size;
53+
this.hint = 0;
54+
}
55+
const room = this.tail.length - this.filled;
56+
if (n <= room) {
57+
this.tail.set(view, this.filled);
58+
this.filled += n;
59+
} else {
60+
if (room) this.tail.set(view.subarray(0, room), this.filled);
61+
(this.blocks ??= []).push(this.tail);
62+
const rest = n - room,
63+
growth = Math.min(MAX_BLOCK_GROWTH, this.tail.length * 2);
64+
this.tail = Buffer.allocUnsafeSlow(
65+
Math.min(this.maximum - this.size - room, Math.max(rest, growth)),
66+
);
67+
this.tail.set(room ? view.subarray(room) : view);
68+
this.filled = rest;
69+
}
70+
this.size = end;
71+
return true;
72+
}
73+
finish(): Buffer {
74+
if (!this.tail) return Buffer.alloc(0);
75+
if (!this.blocks && this.filled === this.tail.length) return this.tail;
76+
// Spare capacity is never exposed through the returned Buffer's backing ArrayBuffer.
77+
const out = Buffer.allocUnsafeSlow(this.size);
78+
this.copyInto(out);
79+
return out;
80+
}
81+
}
82+
83+
/** Only EOF returns a buffer. The declared length is a refusal or allocation hint, never a receipt. */
84+
export async function readGatewayBytes(
85+
response: Response,
86+
signal: AbortSignal,
87+
maximum: number,
88+
): Promise<GatewayBody> {
89+
if (signal.aborted) {
90+
discardResponseBody(response);
91+
checkAbort(signal);
92+
}
93+
const declared = Number(response.headers.get('content-length'));
94+
if (declared > maximum) {
95+
discardResponseBody(response);
96+
return 'too_large';
97+
}
98+
if (response.bodyUsed || response.body?.locked) {
99+
discardResponseBody(response);
100+
return 'incomplete';
101+
}
102+
const owned = acquireResponseReader(response, signal);
103+
if (!owned) return Buffer.alloc(0);
104+
const bytes = new OwnedBytes(
105+
maximum,
106+
Number.isSafeInteger(declared) && declared > 0 ? declared : 0,
107+
);
108+
try {
109+
checkAbort(signal);
110+
while (true) {
111+
let part: ReadableStreamReadResult<Uint8Array>;
112+
try {
113+
part = await owned.reader.read();
114+
} catch {
115+
checkAbort(signal);
116+
return 'incomplete';
117+
}
118+
checkAbort(signal);
119+
if (part.done) break;
120+
const chunk = part.value;
121+
if (!types.isUint8Array(chunk)) return 'incomplete';
122+
if (!bytes.append(chunk)) return 'too_large';
123+
}
124+
return bytes.finish();
125+
} finally {
126+
owned.release();
127+
}
128+
}

‎src/core/errors-en.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ export const ERROR_EN: Readonly<Record<string, readonly [string, string?]>> = {
302302
gateway_response_too_large: ['The gateway response exceeds the client read limit.'],
303303
gateway_timeout: ['The gateway request ended before confirmation; an accepted task may still be running.', 'Submit again with the same Idempotency-Key.'],
304304
invalid_gateway_path: ['The request path leaves the configured gateway origin.'],
305-
invalid_gateway_response: ['The gateway returned invalid JSON.'],
305+
invalid_gateway_response: ['The gateway response is incomplete or contains invalid JSON.'],
306306
request_cancelled: ['The caller cancelled the gateway request.'],
307307
token_required: ['No API key file was given.', 'Add --token-file: admin commands use .oaa/admin.token from oaa init; calls use a key file from oaa key create.'],
308308
gateway_unreachable: ['Cannot reach the gateway.', 'Start it first (oaa serve --detach; from a source checkout, npm run oaa -- serve --detach), or point --url at a running gateway.'],

‎src/core/errors.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ const ROWS: Row[] = [
360360
['gateway_response_too_large', 502, 'client', _, '网关响应超过客户端读取上限'],
361361
['gateway_timeout', 504, 'client', R, '网关请求在确认前结束,已接受的任务可能仍在运行', '用同一个 Idempotency-Key 重新提交'],
362362
['invalid_gateway_path', 400, 'client', _, '请求路径离开了配置的网关源'],
363-
['invalid_gateway_response', 502, 'client', _, '网关返回了无效的 JSON'],
363+
['invalid_gateway_response', 502, 'client', _, '网关响应不完整或 JSON 格式无效'],
364364
['request_cancelled', 499, 'client', _, '调用方取消了网关请求'],
365365
['token_required', 400, 'client', _, '未提供 API 密钥文件', '加 --token-file:管理命令用 oaa init 生成的 .oaa/admin.token,调用用 oaa key create 生成的密钥文件'],
366366
['gateway_unreachable', 503, 'client', R, '连不上网关', '先启动网关(oaa serve --detach,源码目录里是 npm run oaa -- serve --detach),或用 --url 指向正在运行的网关'],

‎src/core/response-reader.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { checkAbort } from './util.js';
2+
3+
/** Cancelling an unused body must not wait for a transport acknowledgement or steal a reader. */
4+
export function discardResponseBody(response: Response | undefined): void {
5+
const body = response?.body;
6+
if (body && !body.locked) void body.cancel().catch(() => {});
7+
}
8+
9+
/** The owner reads directly, so it can consume the observed bytes before the next async handoff. */
10+
export function acquireResponseReader(response: Response, signal: AbortSignal) {
11+
if (signal.aborted) discardResponseBody(response);
12+
checkAbort(signal);
13+
if (!response.body) return;
14+
const reader = response.body.getReader();
15+
const cancel = () => {
16+
void reader.cancel().catch(() => {});
17+
};
18+
signal.addEventListener('abort', cancel, { once: true });
19+
return {
20+
reader,
21+
release() {
22+
signal.removeEventListener('abort', cancel);
23+
cancel();
24+
reader.releaseLock();
25+
},
26+
};
27+
}

‎src/providers/http-stream.ts‎

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,23 @@
11
import { Fault, checkAbort } from '../core/util.js';
2+
import { acquireResponseReader } from '../core/response-reader.js';
3+
export { discardResponseBody } from '../core/response-reader.js';
24

35
type ReadLimits = { maxBytes?: number; limitCode?: string };
46

5-
/** Release an unused body without waiting for the transport or disturbing another reader. */
6-
export function discardResponseBody(response: Response | undefined): void {
7-
const body = response?.body;
8-
if (body && !body.locked) void body.cancel().catch(() => {});
9-
}
10-
117
/** With allowInBudgetPrefix, a consumer may finish at the limit; reading past it still fails. */
128
export async function* responseChunks(
139
response: Response,
1410
signal: AbortSignal,
1511
{ maxBytes = 8 * 1024 * 1024, limitCode = 'upstream_output_limit' }: ReadLimits,
1612
allowInBudgetPrefix = false,
1713
): AsyncGenerator<Uint8Array> {
18-
if (signal.aborted) discardResponseBody(response);
19-
checkAbort(signal);
20-
if (!response.body) return;
21-
const reader = response.body.getReader();
14+
const owned = acquireResponseReader(response, signal);
15+
if (!owned) return;
2216
let remaining = maxBytes;
23-
const cancel = () => {
24-
void reader.cancel().catch(() => {});
25-
};
26-
signal.addEventListener('abort', cancel, { once: true });
2717
try {
2818
checkAbort(signal);
2919
while (true) {
30-
let next = await reader.read();
20+
let next = await owned.reader.read();
3121
checkAbort(signal);
3222
if (next.done) break;
3323
if (next.value.byteLength > remaining) {
@@ -50,11 +40,7 @@ export async function* responseChunks(
5040
yield next.value;
5141
}
5242
} finally {
53-
signal.removeEventListener('abort', cancel);
54-
// Cancellation closes this reader immediately. A transport (or another tee branch) can
55-
// acknowledge it much later; that acknowledgement is not part of the model's result.
56-
cancel();
57-
reader.releaseLock();
43+
owned.release();
5844
}
5945
}
6046

0 commit comments

Comments
 (0)