@morgan9668/dsh-llm-gateway 1.1.0 → 1.1.1
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/README.md +16 -5
- package/docs/DETAIL.md +21 -8
- package/index.js +100 -28
- package/package.json +2 -2
- package/tests/body-limit.mjs +158 -0
package/README.md
CHANGED
|
@@ -112,6 +112,7 @@ bundle 自带 `cordis.patch.yml`,安装时自动插入插件行,不需要手
|
|
|
112
112
|
| `host` | `127.0.0.1` | 绑定地址。默认只绑回环,局域网内其它机器访问不到 |
|
|
113
113
|
| `port` | `8392` | 监听端口;非法值静默回退到默认值,不会报错 |
|
|
114
114
|
| `apiKey` | 空 | 为空表示不鉴权;非空时要求 `Authorization: Bearer <key>` 全串精确匹配 |
|
|
115
|
+
| `maxBodyBytes` | 256 MiB | 单个请求体上限。Codex 每轮重发整段历史,带图会话会很大;超过就回 413。缩小它是给暴露到公网的实例加一道闸 |
|
|
115
116
|
|
|
116
117
|
> 网关**不导出 Config schema**:所有值从插件行的 `config` 里读,缺字段就用默认值。
|
|
117
118
|
> 因此写错字段名不会报错,只会被忽略——改完记得看日志里的 `listening on http://…`。
|
|
@@ -303,15 +304,19 @@ wire_api = "responses"
|
|
|
303
304
|
| 余额不足 / 额度用尽 | 归为账号失败 | 402 `ACCOUNT_QUOTA` + 「充值或换模型组」 |
|
|
304
305
|
| 429 / 冷却中 | 归为限流 | 429 `RATE_LIMIT` + 「等冷却,立刻重发还是同一句」 |
|
|
305
306
|
| 只有思考没有正文 | 判为空回答,不当成功 | 502 `empty_reasoning_only`,让客户端按自己的策略重试 |
|
|
306
|
-
| 请求体过大 | `content-length`
|
|
307
|
+
| 请求体过大 | `content-length` 与实际字节各卡一次,边读边计不缓冲整个 body | 413 `request body too large (limit 268435456 bytes)` + `x-should-retry: false` |
|
|
307
308
|
| 请求体不是合法 JSON | 直接拒绝 | 400 `request body is not valid JSON` |
|
|
308
309
|
| 确定性失败被反复重试 | 响应头显式拒绝 | `x-should-retry: false`、`retry-after: 0` |
|
|
309
310
|
|
|
310
311
|
前七条(`PROMPT_TOO_LONG`、`TOOL_MISMATCH`、`CHANNEL_REJECT`、`IMAGE_INVALID`、`EMPTY_CONTENT`、
|
|
311
|
-
`ACCOUNT_QUOTA`、`RATE_LIMIT`)都带 `x-should-retry: false
|
|
312
|
+
`ACCOUNT_QUOTA`、`RATE_LIMIT`)都带 `x-should-retry: false`,**413 也带**;5xx 与网络类**不带**,保持可重试。
|
|
312
313
|
|
|
313
314
|
> 这个头只能出现在**非流式**响应上:流式响应头早就发出去了,收尾时只能改事件体的内容。
|
|
314
315
|
|
|
316
|
+
> 413 这一条值得单独说:同一份历史重发还是超限,重试没有任何意义。缺了这个头时
|
|
317
|
+
> Codex 会按状态码策略重连五轮(界面上显示「正在重新连接 5/5」),每轮把几十 MB
|
|
318
|
+
> 重新传一遍,最后仍拿到同一句拒绝。请求体上限默认 256 MiB,可用 `maxBodyBytes` 调整。
|
|
319
|
+
|
|
315
320
|
## 已知限制
|
|
316
321
|
|
|
317
322
|
写下来是为了省掉你的排查时间,不是待办清单:
|
|
@@ -339,14 +344,20 @@ wire_api = "responses"
|
|
|
339
344
|
## 开发与测试
|
|
340
345
|
|
|
341
346
|
```bash
|
|
347
|
+
npm test # 等价于下面两条
|
|
342
348
|
node tests/stream-failure.mjs
|
|
349
|
+
node tests/body-limit.mjs
|
|
343
350
|
```
|
|
344
351
|
|
|
345
|
-
六个用例覆盖流式失败上报的回归:上游失败必须发 `response.failed` / `error`
|
|
346
|
-
`response.completed` / `finish_reason: stop`,有半截正文时也一样;正常回答不受影响。
|
|
352
|
+
`stream-failure.mjs` 六个用例覆盖流式失败上报的回归:上游失败必须发 `response.failed` / `error` 帧
|
|
353
|
+
而不是伪装成 `response.completed` / `finish_reason: stop`,有半截正文时也一样;正常回答不受影响。
|
|
354
|
+
|
|
355
|
+
`body-limit.mjs` 四个用例真正起一个网关,覆盖请求体上限:超限必须回 413 且带
|
|
356
|
+
`x-should-retry: false` 与 `retry-after: 0`;`content-length` 缺失(分块上传)时仍按实际字节拦截;
|
|
357
|
+
上限可由 `maxBodyBytes` 调整;默认值容得下几十 MB 的带图历史。
|
|
347
358
|
|
|
348
359
|
未覆盖的部分(改代码时自己补测):请求转换与配对修复、槽位换算、路由解析、附件落地、状态码映射表、
|
|
349
|
-
|
|
360
|
+
认证。
|
|
350
361
|
|
|
351
362
|
`index.js` 单文件、零依赖,只用到 Node 内建模块与 Web 标准(`fetch`、`Response`、`ReadableStream`)。
|
|
352
363
|
|
package/docs/DETAIL.md
CHANGED
|
@@ -19,9 +19,10 @@ token accounting and provider adapters stay inside DSH.
|
|
|
19
19
|
- `POST /v1/responses` — Responses API (streaming and non-streaming), used by Codex.
|
|
20
20
|
|
|
21
21
|
By default the server listens on `127.0.0.1:8392`. Configuration lives in the
|
|
22
|
-
bundle patch (`host`, `port`, `apiKey`); the gateway does not define
|
|
23
|
-
so all values are read from the plugin config with defaults.
|
|
24
|
-
ignored silently.
|
|
22
|
+
bundle patch (`host`, `port`, `apiKey`, `maxBodyBytes`); the gateway does not define
|
|
23
|
+
a Config schema, so all values are read from the plugin config with defaults.
|
|
24
|
+
Unknown keys are ignored silently. `maxBodyBytes` defaults to 256 MiB: Codex resends
|
|
25
|
+
the whole history every turn, and image-heavy conversations get large quickly.
|
|
25
26
|
|
|
26
27
|
All routes require `Authorization: Bearer <apiKey>` when `apiKey` is non-empty,
|
|
27
28
|
including `/healthz`. The gateway sets no CORS headers and has no `OPTIONS`
|
|
@@ -117,9 +118,14 @@ Non-streaming errors are shaped `{error: {message, type}}`; `type` is
|
|
|
117
118
|
`server_error` or `upstream_error`. Streaming errors carry `message`, `type`,
|
|
118
119
|
`code` and `gateway_hint` in the event body.
|
|
119
120
|
|
|
120
|
-
A request body over
|
|
121
|
-
|
|
122
|
-
|
|
121
|
+
A request body over `maxBodyBytes` (256 MiB by default) returns 413 with
|
|
122
|
+
`x-should-retry: false` and `retry-after: 0` — resending the same history is just
|
|
123
|
+
as oversized, and without that header Codex retries five times, re-uploading tens
|
|
124
|
+
of megabytes each round. The size is counted while reading, and the remaining bytes
|
|
125
|
+
are drained before the reply, so the client actually reads the 413 instead of a
|
|
126
|
+
broken pipe. Malformed JSON returns 400; a turn that produced reasoning but no text
|
|
127
|
+
returns 502 `empty_reasoning_only` so the client retries instead of receiving an
|
|
128
|
+
empty success.
|
|
123
129
|
|
|
124
130
|
Cached token counts are written to both `prompt_tokens_details.cached_tokens` and
|
|
125
131
|
`prompt_cache_hit_tokens` (Responses: `input_tokens_details.cached_tokens`), and
|
|
@@ -174,5 +180,12 @@ turn can leave an SSE connection quiet.
|
|
|
174
180
|
`node tests/stream-failure.mjs` runs six regression cases for streaming failure
|
|
175
181
|
reporting: an upstream failure must emit `response.failed` / an `error` frame
|
|
176
182
|
rather than a `response.completed` or `finish_reason: stop`, including after
|
|
177
|
-
partial text; normal answers are unaffected.
|
|
178
|
-
|
|
183
|
+
partial text; normal answers are unaffected.
|
|
184
|
+
|
|
185
|
+
`node tests/body-limit.mjs` starts a real gateway and runs four cases for the
|
|
186
|
+
request-body limit: an oversized body must return 413 with `x-should-retry: false`
|
|
187
|
+
and `retry-after: 0`; a missing `content-length` (chunked upload) is still counted;
|
|
188
|
+
`maxBodyBytes` is honoured; and the default accepts tens of megabytes.
|
|
189
|
+
|
|
190
|
+
Conversion, pairing repair, slots, routing, attachments and the status map are not
|
|
191
|
+
covered.
|
package/index.js
CHANGED
|
@@ -17,7 +17,14 @@ export const name = 'dsh-llm-gateway';
|
|
|
17
17
|
// 没有该服务时退化为占位文本(见 imagePlaceholder)。
|
|
18
18
|
export const inject = ['llm', 'attachments'];
|
|
19
19
|
|
|
20
|
-
const DEFAULTS = {
|
|
20
|
+
const DEFAULTS = {
|
|
21
|
+
host: '127.0.0.1',
|
|
22
|
+
port: 8392,
|
|
23
|
+
apiKey: '',
|
|
24
|
+
// 请求体上限。Codex 每轮都会把整段历史重发一遍,带图的会话里 base64 图片
|
|
25
|
+
// 会把这一个请求推到几十 MB —— 默认值必须容得下正常的多图历史。
|
|
26
|
+
maxBodyBytes: 256 * 1024 * 1024,
|
|
27
|
+
};
|
|
21
28
|
const CACHE_MS = 10_000;
|
|
22
29
|
const GROUP_PREFIXES = new Set(['deepseek', 'buddy', 'free']);
|
|
23
30
|
|
|
@@ -115,10 +122,43 @@ function normalizeConfig(raw) {
|
|
|
115
122
|
if (typeof raw.host === 'string' && raw.host !== '') config.host = raw.host;
|
|
116
123
|
if (Number.isInteger(raw.port) && raw.port > 0 && raw.port < 65536) config.port = raw.port;
|
|
117
124
|
if (typeof raw.apiKey === 'string') config.apiKey = raw.apiKey;
|
|
125
|
+
if (Number.isInteger(raw.maxBodyBytes) && raw.maxBodyBytes > 0) config.maxBodyBytes = raw.maxBodyBytes;
|
|
118
126
|
}
|
|
119
127
|
return config;
|
|
120
128
|
}
|
|
121
129
|
|
|
130
|
+
/** 字节数 → 便于读的 MB/KB,用于日志。 */
|
|
131
|
+
function formatBytes(bytes) {
|
|
132
|
+
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
|
|
133
|
+
if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
134
|
+
if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
135
|
+
return `${bytes} B`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* 把入站请求体读完并丢弃。
|
|
140
|
+
*
|
|
141
|
+
* 用途只有一个:我们已经决定拒绝这个请求(例如超限),但客户端还在往上写。
|
|
142
|
+
* 此时直接 break 或 destroy socket 会让客户端看到 broken pipe,具体原因反而
|
|
143
|
+
* 传达不到;读完剩余字节再写响应,客户端才能正常读到 413 和它的错误体。
|
|
144
|
+
*
|
|
145
|
+
* 有上限保护:最多再排空 maxDrainBytes,防止恶意客户端用无限流占住连接。
|
|
146
|
+
*/
|
|
147
|
+
async function drain(request, maxDrainBytes = 512 * 1024 * 1024) {
|
|
148
|
+
let drained = 0;
|
|
149
|
+
try {
|
|
150
|
+
for await (const chunk of request) {
|
|
151
|
+
drained += chunk.length;
|
|
152
|
+
if (drained > maxDrainBytes) {
|
|
153
|
+
request.destroy();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
} catch {
|
|
158
|
+
/* 客户端先断了,无所谓 */
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
122
162
|
function textBlock(text) {
|
|
123
163
|
return { type: 'text', text };
|
|
124
164
|
}
|
|
@@ -963,33 +1003,33 @@ const NO_RETRY_HEADERS = Object.freeze({
|
|
|
963
1003
|
/**
|
|
964
1004
|
* 请求体超限。用一个具名类而不是「message 里带魔数」:
|
|
965
1005
|
* 调用方必须对它回 **413**(协议上的正确答案),当成普通内部错误会变成 500。
|
|
1006
|
+
*
|
|
1007
|
+
* 必须带 `x-should-retry: false`:超限是**确定性**失败,同一份历史重发还是超限。
|
|
1008
|
+
* 没有这个头时 Codex 会按 413 之外的状态码策略重试五轮(界面上显示
|
|
1009
|
+
* 「正在重新连接 5/5」),每一轮都把几十 MB 重新传一遍,然后拿到同一句拒绝。
|
|
966
1010
|
*/
|
|
967
1011
|
class RequestBodyTooLargeError extends HttpError {
|
|
968
1012
|
constructor(limitBytes) {
|
|
969
|
-
super(
|
|
1013
|
+
super(
|
|
1014
|
+
413,
|
|
1015
|
+
`request body too large (limit ${limitBytes} bytes); compact the conversation or start a new task`,
|
|
1016
|
+
'invalid_request_error',
|
|
1017
|
+
NO_RETRY_HEADERS,
|
|
1018
|
+
);
|
|
970
1019
|
this.name = 'RequestBodyTooLargeError';
|
|
971
1020
|
this.limitBytes = limitBytes;
|
|
972
1021
|
}
|
|
973
1022
|
}
|
|
974
1023
|
|
|
975
|
-
|
|
976
|
-
* 网关接受的请求体上限。
|
|
977
|
-
*
|
|
978
|
-
* 参考 dsh-connect-workbuddy 的 RequestBodyTooLargeError:超限必须回 **413**,
|
|
979
|
-
* 而不是让它变成一个内存爆掉后的 500。这里比插件宽松(图片 base64 会很大),
|
|
980
|
-
* 但仍然是有限的。
|
|
981
|
-
*/
|
|
982
|
-
const REQUEST_BODY_LIMIT = 64 * 1024 * 1024;
|
|
983
|
-
|
|
984
|
-
async function readJson(request) {
|
|
1024
|
+
async function readJson(request, limitBytes) {
|
|
985
1025
|
const declared = Number(request.headers.get('content-length') ?? 0);
|
|
986
|
-
if (Number.isFinite(declared) && declared >
|
|
987
|
-
throw new RequestBodyTooLargeError(
|
|
1026
|
+
if (Number.isFinite(declared) && declared > limitBytes) {
|
|
1027
|
+
throw new RequestBodyTooLargeError(limitBytes);
|
|
988
1028
|
}
|
|
989
1029
|
const text = await request.text();
|
|
990
1030
|
// content-length 不可信(可能缺失或撒谎),按实际读到的字节再卡一次。
|
|
991
|
-
if (Buffer.byteLength(text, 'utf8') >
|
|
992
|
-
throw new RequestBodyTooLargeError(
|
|
1031
|
+
if (Buffer.byteLength(text, 'utf8') > limitBytes) {
|
|
1032
|
+
throw new RequestBodyTooLargeError(limitBytes);
|
|
993
1033
|
}
|
|
994
1034
|
if (text.trim() === '') return {};
|
|
995
1035
|
try {
|
|
@@ -1679,7 +1719,7 @@ export function apply(ctx, rawConfig) {
|
|
|
1679
1719
|
}
|
|
1680
1720
|
|
|
1681
1721
|
if (request.method === 'POST' && path === '/v1/chat/completions') {
|
|
1682
|
-
const body = await readJson(request);
|
|
1722
|
+
const body = await readJson(request, config.maxBodyBytes);
|
|
1683
1723
|
let messages = chatMessagesToDsh(body.messages, { provider: 'gateway', model: body.model });
|
|
1684
1724
|
messages = await materializeImages(messages, { attachments: attachmentsService });
|
|
1685
1725
|
if (messages.length === 0) throw new HttpError(400, 'messages must not be empty');
|
|
@@ -1732,7 +1772,7 @@ export function apply(ctx, rawConfig) {
|
|
|
1732
1772
|
}
|
|
1733
1773
|
|
|
1734
1774
|
if (request.method === 'POST' && path === '/v1/responses') {
|
|
1735
|
-
const body = await readJson(request);
|
|
1775
|
+
const body = await readJson(request, config.maxBodyBytes);
|
|
1736
1776
|
let messages = responsesToDsh(body, { provider: 'gateway', model: body.model });
|
|
1737
1777
|
messages = await materializeImages(messages, { attachments: attachmentsService });
|
|
1738
1778
|
if (messages.length === 0) throw new HttpError(400, 'input must not be empty');
|
|
@@ -1800,16 +1840,48 @@ export function apply(ctx, rawConfig) {
|
|
|
1800
1840
|
let result;
|
|
1801
1841
|
try {
|
|
1802
1842
|
// node:http IncomingMessage has no .text(); wrap it as a Web Request.
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1843
|
+
//
|
|
1844
|
+
// 边读边计字节:先把几十 MB 全读进内存再判断超限,等于把「拒绝」变成
|
|
1845
|
+
// 「先占满内存再拒绝」。超限后**继续把剩下的字节读掉但丢弃**,而不是
|
|
1846
|
+
// 直接 break 或 destroy socket —— 前者会销毁入站流、后者会重置连接,
|
|
1847
|
+
// 两种情况下客户端都只看到 broken pipe,读不到 413 和 `x-should-retry:
|
|
1848
|
+
// false`,于是照样重试五轮。把请求体排空再回响应,客户端才能读到结论。
|
|
1849
|
+
const declared = Number(request.headers['content-length'] ?? 0);
|
|
1850
|
+
if (Number.isFinite(declared) && declared > config.maxBodyBytes) {
|
|
1851
|
+
log(`413 request body ${formatBytes(declared)} exceeds limit ${formatBytes(config.maxBodyBytes)} (${request.method} ${request.url})`);
|
|
1852
|
+
// 还没开始读:先把客户端可能已经发出的字节排掉,再让它读响应。
|
|
1853
|
+
await drain(request);
|
|
1854
|
+
result = errorResponse(new RequestBodyTooLargeError(config.maxBodyBytes));
|
|
1855
|
+
} else {
|
|
1856
|
+
const chunks = [];
|
|
1857
|
+
let received = 0;
|
|
1858
|
+
let overLimit = false;
|
|
1859
|
+
for await (const chunk of request) {
|
|
1860
|
+
received += chunk.length;
|
|
1861
|
+
if (received > config.maxBodyBytes) {
|
|
1862
|
+
// 超限:丢掉已读的,后续全部丢弃,但仍然读完。
|
|
1863
|
+
if (!overLimit) {
|
|
1864
|
+
overLimit = true;
|
|
1865
|
+
chunks.length = 0;
|
|
1866
|
+
}
|
|
1867
|
+
continue;
|
|
1868
|
+
}
|
|
1869
|
+
if (!overLimit) chunks.push(chunk);
|
|
1870
|
+
}
|
|
1871
|
+
if (overLimit) {
|
|
1872
|
+
log(`413 request body over limit ${formatBytes(config.maxBodyBytes)} (${request.method} ${request.url})`);
|
|
1873
|
+
result = errorResponse(new RequestBodyTooLargeError(config.maxBodyBytes));
|
|
1874
|
+
} else {
|
|
1875
|
+
const body = chunks.length === 0 ? undefined : Buffer.concat(chunks);
|
|
1876
|
+
const absolute = `http://${request.headers.host ?? `${config.host}:${config.port}`}${request.url ?? '/'}`;
|
|
1877
|
+
const webRequest = new Request(absolute, {
|
|
1878
|
+
method: request.method,
|
|
1879
|
+
headers: request.headers,
|
|
1880
|
+
body: request.method === 'GET' || request.method === 'HEAD' ? undefined : body,
|
|
1881
|
+
});
|
|
1882
|
+
result = await handle(webRequest);
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1813
1885
|
} catch (error) {
|
|
1814
1886
|
if (process.env.DSH_GATEWAY_DEBUG) process.stderr.write(`${error?.stack ?? String(error)}\n`);
|
|
1815
1887
|
result = errorResponse(error);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@morgan9668/dsh-llm-gateway",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Local OpenAI-compatible gateway that exposes every model registered on the DSH llm service (DeepSeek, WorkBuddy, our-free-model) so external clients such as Codex can use them.",
|
|
6
6
|
"author": "chenzhao",
|
|
@@ -48,6 +48,6 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"scripts": {
|
|
51
|
-
"test": "node tests/stream-failure.mjs"
|
|
51
|
+
"test": "node tests/stream-failure.mjs && node tests/body-limit.mjs"
|
|
52
52
|
}
|
|
53
53
|
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* 请求体上限的回归测试。
|
|
4
|
+
*
|
|
5
|
+
* 背景:Codex 每轮把整段历史重发,带图会话很容易几十 MB。旧实现的上限是 64 MB,
|
|
6
|
+
* 超限回 413 —— 但**没有带 `x-should-retry: false`**,于是 Codex 把它当瞬时故障
|
|
7
|
+
* 重连五轮(界面上「正在重新连接 5/5」),每轮重传几十 MB 换回同一句拒绝。
|
|
8
|
+
*
|
|
9
|
+
* 这些用例用假的 ctx 真正起一个网关,断言:
|
|
10
|
+
* 1. 超限回 413,且带 `x-should-retry: false` 与 `retry-after: 0`;
|
|
11
|
+
* 2. content-length 撒谎(缺失 / 分块)时仍按实际字节拦截;
|
|
12
|
+
* 3. 上限可通过 config.maxBodyBytes 调整;
|
|
13
|
+
* 4. 正常大小的请求不受影响。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import assert from 'node:assert/strict';
|
|
17
|
+
import http from 'node:http';
|
|
18
|
+
import net from 'node:net';
|
|
19
|
+
|
|
20
|
+
import { apply } from '../index.js';
|
|
21
|
+
|
|
22
|
+
let failures = 0;
|
|
23
|
+
let passed = 0;
|
|
24
|
+
const tests = [];
|
|
25
|
+
function test(name, fn) {
|
|
26
|
+
tests.push({ name, fn });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 拿一个当前空闲的端口。 */
|
|
30
|
+
function freePort() {
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
const srv = net.createServer();
|
|
33
|
+
srv.once('error', reject);
|
|
34
|
+
srv.listen(0, '127.0.0.1', () => {
|
|
35
|
+
const { port } = srv.address();
|
|
36
|
+
srv.close(() => resolve(port));
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 最小可用 ctx:只提供 apply() 真正会碰的那几项。 */
|
|
42
|
+
function fakeCtx() {
|
|
43
|
+
const cleanups = [];
|
|
44
|
+
return {
|
|
45
|
+
llm: {
|
|
46
|
+
listProviders: () => [],
|
|
47
|
+
listModels: async () => [],
|
|
48
|
+
resolveModelInfo: async () => ({}),
|
|
49
|
+
stream: () => (async function* empty() {})(),
|
|
50
|
+
},
|
|
51
|
+
get: () => undefined,
|
|
52
|
+
effect: (fn) => {
|
|
53
|
+
cleanups.push(fn());
|
|
54
|
+
},
|
|
55
|
+
dispose: () => {
|
|
56
|
+
for (const cleanup of cleanups) {
|
|
57
|
+
try {
|
|
58
|
+
cleanup();
|
|
59
|
+
} catch {
|
|
60
|
+
/* already closed */
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function withGateway(config, run) {
|
|
68
|
+
const port = await freePort();
|
|
69
|
+
const ctx = fakeCtx();
|
|
70
|
+
apply(ctx, { host: '127.0.0.1', port, ...config });
|
|
71
|
+
await new Promise((resolve) => setTimeout(resolve, 80));
|
|
72
|
+
try {
|
|
73
|
+
await run({ port });
|
|
74
|
+
} finally {
|
|
75
|
+
ctx.dispose();
|
|
76
|
+
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** 发一个原始 POST;hideLength 模拟 content-length 缺失、走分块上传的客户端。 */
|
|
81
|
+
function post(port, path, body, { hideLength = false } = {}) {
|
|
82
|
+
return new Promise((resolve, reject) => {
|
|
83
|
+
const headers = { 'content-type': 'application/json' };
|
|
84
|
+
if (hideLength) headers['transfer-encoding'] = 'chunked';
|
|
85
|
+
else headers['content-length'] = Buffer.byteLength(body);
|
|
86
|
+
const req = http.request({ host: '127.0.0.1', port, path, method: 'POST', headers }, (res) => {
|
|
87
|
+
const chunks = [];
|
|
88
|
+
res.on('data', (c) => chunks.push(c));
|
|
89
|
+
res.on('end', () =>
|
|
90
|
+
resolve({
|
|
91
|
+
status: res.statusCode,
|
|
92
|
+
headers: res.headers,
|
|
93
|
+
text: Buffer.concat(chunks).toString('utf8'),
|
|
94
|
+
}),
|
|
95
|
+
);
|
|
96
|
+
});
|
|
97
|
+
req.on('error', reject);
|
|
98
|
+
if (hideLength) {
|
|
99
|
+
req.write(body.slice(0, 1024));
|
|
100
|
+
req.end(body.slice(1024));
|
|
101
|
+
} else {
|
|
102
|
+
req.end(body);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
test('超限请求回 413,并显式声明不可重试', async () => {
|
|
108
|
+
await withGateway({ maxBodyBytes: 4096 }, async ({ port }) => {
|
|
109
|
+
const body = JSON.stringify({ model: 'buddy/deepseek-v4.1-flash', input: 'x'.repeat(8192) });
|
|
110
|
+
const res = await post(port, '/v1/responses', body);
|
|
111
|
+
assert.equal(res.status, 413, 'status 必须是 413');
|
|
112
|
+
assert.equal(res.headers['x-should-retry'], 'false', '必须带 x-should-retry: false');
|
|
113
|
+
assert.equal(res.headers['retry-after'], '0', '必须带 retry-after: 0');
|
|
114
|
+
assert.match(res.text, /request body too large/);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test('content-length 缺失(分块上传)时仍按实际字节拦截', async () => {
|
|
119
|
+
await withGateway({ maxBodyBytes: 4096 }, async ({ port }) => {
|
|
120
|
+
const body = JSON.stringify({ model: 'buddy/deepseek-v4.1-flash', input: 'y'.repeat(8192) });
|
|
121
|
+
const res = await post(port, '/v1/responses', body, { hideLength: true });
|
|
122
|
+
assert.equal(res.status, 413, '分块上传超限也必须 413');
|
|
123
|
+
assert.equal(res.headers['x-should-retry'], 'false');
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test('上限可通过 config.maxBodyBytes 调整', async () => {
|
|
128
|
+
await withGateway({ maxBodyBytes: 1024 * 1024 }, async ({ port }) => {
|
|
129
|
+
const body = JSON.stringify({ model: 'nope', input: 'z'.repeat(8192) });
|
|
130
|
+
const res = await post(port, '/v1/responses', body);
|
|
131
|
+
assert.notEqual(res.status, 413, '未超限时不能回 413');
|
|
132
|
+
assert.equal(res.status, 404, '请求体被接受后应走到模型解析,返回 404');
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('默认上限容得下几十 MB 的带图历史', async () => {
|
|
137
|
+
await withGateway({}, async ({ port }) => {
|
|
138
|
+
const body = JSON.stringify({ model: 'nope', input: 'w'.repeat(80 * 1024 * 1024) });
|
|
139
|
+
const res = await post(port, '/v1/responses', body);
|
|
140
|
+
assert.notEqual(res.status, 413, '默认上限必须明显大于 64 MB');
|
|
141
|
+
assert.equal(res.status, 404, '80 MB 的请求体应当被接受,然后由模型解析失败');
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
for (const { name, fn } of tests) {
|
|
146
|
+
try {
|
|
147
|
+
await fn();
|
|
148
|
+
passed += 1;
|
|
149
|
+
console.log(`✓ ${name}`);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
failures += 1;
|
|
152
|
+
console.error(`✗ ${name}`);
|
|
153
|
+
console.error(` ${error?.message ?? error}`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
console.log(`\n${failures === 0 ? '全部通过' : `${failures} 项失败`}(通过 ${passed}/${tests.length})`);
|
|
158
|
+
if (failures > 0) process.exit(1);
|