dsh-zcode-startplan 0.5.2 → 1.0.3
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/CHANGELOG.md +1963 -672
- package/README.md +92 -472
- package/bin/cli.mjs +509 -450
- package/client.js +2459 -1002
- package/cordis.patch.yml +4 -2
- package/index.js +109 -11
- package/lib/adapter.js +476 -449
- package/lib/anthropic-body.js +513 -469
- package/lib/assemble.js +808 -542
- package/lib/auto-claim.js +229 -0
- package/lib/captcha/minter.js +61 -7
- package/lib/distribution-keys.js +202 -0
- package/lib/errors.js +281 -125
- package/lib/fallback.js +120 -0
- package/lib/local-endpoint.js +367 -352
- package/lib/manage-routes.js +1245 -652
- package/lib/model-catalog.js +57 -0
- package/lib/openai-gateway.js +776 -0
- package/lib/plan-client.js +942 -532
- package/lib/pool.js +771 -478
- package/lib/sse.js +429 -317
- package/lib/upstream-api.js +948 -611
- package/lib/upstream.js +294 -134
- package/lib/version-probe.js +110 -0
- package/package.json +84 -81
- package/scripts/analyze-grant-intervals.mjs +171 -0
- package/scripts/check-compat-rc3.mjs +21 -11
- package/scripts/debug-claimable.mjs +130 -0
- package/scripts/probe-marketing.mjs +203 -0
- package/scripts/restart-dsh.ps1 +119 -116
- package/scripts/test-claimed-pending.mjs +152 -0
- package/scripts/verify_compat.mjs +75 -64
- package/scripts/watch-marketing.mjs +155 -0
- package/tests/auto-claim.test.mjs +318 -0
- package/tests/claim-routes.test.mjs +438 -293
- package/tests/client-panel.test.mjs +1141 -356
- package/tests/distribution-keys.test.mjs +123 -0
- package/tests/e2e.test.mjs +388 -353
- package/tests/fallback-scrub.test.mjs +105 -0
- package/tests/launch-command.test.mjs +68 -0
- package/tests/openai-gateway.test.mjs +454 -0
- package/tests/pinned-models.test.mjs +505 -497
- package/tests/plan-client.test.mjs +582 -222
- package/tests/pool.test.mjs +319 -93
- package/tests/quota-blackhole.test.mjs +409 -0
- package/tests/restart-script.test.mjs +53 -0
- package/tests/routing-quota.test.mjs +251 -0
- package/tests/support/hanging-stream.mjs +48 -0
- package/tests/upstream-error-200.test.mjs +164 -125
- package/tests/upstream.test.mjs +330 -250
- package/tests/version-probe.test.mjs +172 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/routing` 的**准入口径**回归测试(1.0.1 审计)。
|
|
3
|
+
*
|
|
4
|
+
* 用户实测故障:「面板显示额度开启,对话却提示额度耗尽」。
|
|
5
|
+
*
|
|
6
|
+
* 根因口径差:
|
|
7
|
+
* - 面板 `/balance` 统计上游 `data.balances` 里**所有已激活 plan 的桶**;
|
|
8
|
+
* - 对话准入看的是**当前生效**的那一桶 + 「账号 × 模型」的 1005 硬过滤标记。
|
|
9
|
+
* 两者可以同时成立 —— 于是出现「显示有余量、下一句话立刻 zero content / 1005」。
|
|
10
|
+
*
|
|
11
|
+
* 本文件锁死两件事:
|
|
12
|
+
* 1. `/routing` 必须把准入判定依据(`quota.available/limited/expired`)显式下发;
|
|
13
|
+
* 2. `preview` 必须带 `?model=` 参与筛选,否则会预测一个 `pick` 根本不会选的账号。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import test from 'node:test'
|
|
17
|
+
import assert from 'node:assert/strict'
|
|
18
|
+
|
|
19
|
+
import { makeManageRoutes } from '../lib/manage-routes.js'
|
|
20
|
+
import { AccountPool, SqliteStore } from '../lib/pool.js'
|
|
21
|
+
import { mkdtempSync, rmSync } from 'node:fs'
|
|
22
|
+
import { tmpdir } from 'node:os'
|
|
23
|
+
import { join } from 'node:path'
|
|
24
|
+
|
|
25
|
+
const credential = (id) => ({ zcode_jwt: `jwt-${id}`, device_mid: `dev-${id}`, user_id: `u-${id}` })
|
|
26
|
+
|
|
27
|
+
function makeReqRes({ url = '/' } = {}) {
|
|
28
|
+
const req = {
|
|
29
|
+
method: 'GET',
|
|
30
|
+
url,
|
|
31
|
+
socket: { remoteAddress: '127.0.0.1' },
|
|
32
|
+
headers: { host: '127.0.0.1:58962' },
|
|
33
|
+
on() {
|
|
34
|
+
return req
|
|
35
|
+
},
|
|
36
|
+
destroy() {},
|
|
37
|
+
}
|
|
38
|
+
let captured
|
|
39
|
+
let status = 200
|
|
40
|
+
const res = {
|
|
41
|
+
writableEnded: false,
|
|
42
|
+
destroyed: false,
|
|
43
|
+
writeHead(code) {
|
|
44
|
+
status = code
|
|
45
|
+
},
|
|
46
|
+
end(text) {
|
|
47
|
+
res.writableEnded = true
|
|
48
|
+
captured = text
|
|
49
|
+
},
|
|
50
|
+
get body() {
|
|
51
|
+
return captured === undefined ? undefined : JSON.parse(captured)
|
|
52
|
+
},
|
|
53
|
+
get status() {
|
|
54
|
+
return status
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
return { req, res }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function call(routes, path, options) {
|
|
61
|
+
const route = routes.find((item) => item.path === path)
|
|
62
|
+
assert.ok(route !== undefined, `没有注册 ${path}`)
|
|
63
|
+
const { req, res } = makeReqRes(options)
|
|
64
|
+
await route.handler(req, res)
|
|
65
|
+
return res
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function withPool(fn) {
|
|
69
|
+
return async () => {
|
|
70
|
+
const dir = mkdtempSync(join(tmpdir(), 'zsp-routing-'))
|
|
71
|
+
const store = await new SqliteStore(join(dir, 'accounts.db'))
|
|
72
|
+
try {
|
|
73
|
+
await fn(new AccountPool({ store }), store, dir)
|
|
74
|
+
} finally {
|
|
75
|
+
store.close()
|
|
76
|
+
rmSync(dir, { recursive: true, force: true })
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 上游余额:**已激活** plan 里还有一个 3 亿的桶,但 `balances` 里当前生效桶为 0。 */
|
|
82
|
+
const BALANCE_SHAPES = {
|
|
83
|
+
/** 面板口径「有额度」:生效桶尚有余额。 */
|
|
84
|
+
healthy: { remaining: 300_000_000, total: 300_000_000, expiresAt: Date.now() + 86_400_000 },
|
|
85
|
+
/** 面板口径「有额度」,但实际生效桶为空(未生效领取包还在 balances 里)。 */
|
|
86
|
+
onlyZeroBuckets: { remaining: 0, total: 0 },
|
|
87
|
+
/** 余额接口整体不可用。 */
|
|
88
|
+
failed: undefined,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const routesFor = (pool, balance) =>
|
|
92
|
+
makeManageRoutes({
|
|
93
|
+
pool,
|
|
94
|
+
client: {},
|
|
95
|
+
fetchBalance: async () => BALANCE_SHAPES[balance],
|
|
96
|
+
settings: {},
|
|
97
|
+
log: () => {},
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
/** 等待后台余额拉取落进缓存(2s 轮询模型的第一次 tick 就发生在响应之后)。 */
|
|
101
|
+
const settle = () => new Promise((resolve) => setTimeout(resolve, 10))
|
|
102
|
+
|
|
103
|
+
test('/routing: 上游已判额度用尽时,把「显示有额度 / 实际不可用」同时说清楚', withPool(async (pool) => {
|
|
104
|
+
const a = pool.add(credential('a'), '主号').entry
|
|
105
|
+
const model = 'GLM-5.3-Flash'
|
|
106
|
+
/** 对话刚刚在这个账号上吃了 1005 / 零内容 → 当日硬过滤标记落库。 */
|
|
107
|
+
pool.markModelRateLimited(a.id, model, Date.now() + 3_600_000)
|
|
108
|
+
|
|
109
|
+
const routes = routesFor(pool, 'healthy')
|
|
110
|
+
/**
|
|
111
|
+
* 第一次:缓存还空(`source: pending`),只能报「准入层面已拒绝」。
|
|
112
|
+
* 这正是用户看到的那一刻——面板还没刷新,对话已经报错。
|
|
113
|
+
*/
|
|
114
|
+
const first = await call(routes, '/api/zcode-start-plan/routing', { url: `/api/zcode-start-plan/routing?model=${model}` })
|
|
115
|
+
assert.equal(first.status, 200)
|
|
116
|
+
const firstAccount = first.body.accounts.find((entry) => entry.accountId === a.id)
|
|
117
|
+
assert.equal(firstAccount.quota.limited, true, '1005 标记必须暴露')
|
|
118
|
+
/**
|
|
119
|
+
* 准入已拒:`usable` 必定 false(即使 `source: pending` 还没拉到余额);
|
|
120
|
+
* `available` 此时是 null(未知),因为面板口径还没数据。
|
|
121
|
+
*/
|
|
122
|
+
assert.equal(firstAccount.quota.usable, false, '准入已拒 → 综合结论不可用')
|
|
123
|
+
assert.equal(firstAccount.quota.available, null, '面板口径未知 ≠ 已用光')
|
|
124
|
+
assert.equal(firstAccount.quota.source, 'pending')
|
|
125
|
+
|
|
126
|
+
/** 第二次:后台拉到了「生效桶还有 3 亿」→ 冲突组合完整呈现。 */
|
|
127
|
+
await settle()
|
|
128
|
+
const second = await call(routes, '/api/zcode-start-plan/routing', { url: `/api/zcode-start-plan/routing?model=${model}` })
|
|
129
|
+
const secondAccount = second.body.accounts.find((entry) => entry.accountId === a.id)
|
|
130
|
+
assert.equal(secondAccount.quota.source, 'upstream')
|
|
131
|
+
assert.equal(secondAccount.quota.available, true, '面板口径:上游生效桶有余量')
|
|
132
|
+
assert.equal(secondAccount.quota.limited, true, '对话口径:该账号×模型已被硬过滤')
|
|
133
|
+
assert.equal(secondAccount.quota.usable, false, '综合结论:不可用')
|
|
134
|
+
/** 前端靠 available && limited 判定「需要显式警告」的那个组合。 */
|
|
135
|
+
assert.equal(secondAccount.quota.available === true && secondAccount.quota.limited === true, true)
|
|
136
|
+
assert.match(secondAccount.quota.reason, /额度用尽/)
|
|
137
|
+
/** 绝不下发凭据。 */
|
|
138
|
+
assert.equal(JSON.stringify(second.body).includes('jwt-a'), false)
|
|
139
|
+
assert.equal(JSON.stringify(second.body).includes('dev-a'), false)
|
|
140
|
+
}))
|
|
141
|
+
|
|
142
|
+
test('/routing: preview 必须带 ?model= 才与 pick 同口径', withPool(async (pool) => {
|
|
143
|
+
const a = pool.add(credential('a'), 'A').entry
|
|
144
|
+
const b = pool.add(credential('b'), 'B').entry
|
|
145
|
+
pool.markModelRateLimited(a.id, 'GLM-5.3-Flash', Date.now() + 3_600_000)
|
|
146
|
+
|
|
147
|
+
const routes = routesFor(pool, 'healthy')
|
|
148
|
+
/** 带模型:跳过 A,预测 B(= pick 结果)。 */
|
|
149
|
+
const withModel = await call(routes, '/api/zcode-start-plan/routing', {
|
|
150
|
+
url: '/api/zcode-start-plan/routing?model=GLM-5.3-Flash',
|
|
151
|
+
})
|
|
152
|
+
assert.equal(withModel.body.preview.accountId, b.id)
|
|
153
|
+
assert.equal(withModel.body.preview.model, 'GLM-5.3-Flash')
|
|
154
|
+
|
|
155
|
+
/** 不带模型:语义是「不按模型过滤」,会预测 A —— 这就是 1.0.0 的 bug。 */
|
|
156
|
+
const withoutModel = await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
|
|
157
|
+
assert.equal(withoutModel.body.preview.accountId, a.id)
|
|
158
|
+
assert.equal(withoutModel.body.preview.model, null, '响应必须标明「这次没有按模型预览」')
|
|
159
|
+
}))
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 判据边界(2026-11-10 变更):`quotaState.limited` **只看 `model_rate_limits`**。
|
|
163
|
+
*
|
|
164
|
+
* `last_error` 是无时间戳的历史文本,已从选号判据中删除;若 `/routing` 仍旧
|
|
165
|
+
* 按它判 limited,面板会与对话**再次矛盾** —— 对话照常发请求(能成功),
|
|
166
|
+
* 面板却红着说「已判额度用尽」。这条锁死两边同口径。
|
|
167
|
+
*/
|
|
168
|
+
test('/routing: 只有 last_error 写着 1005、model_rate_limits 为空 → 不判 limited', withPool(async (pool) => {
|
|
169
|
+
const a = pool.add(credential('a'), '主号').entry
|
|
170
|
+
const model = 'GLM-5.3-Flash'
|
|
171
|
+
/** 历史文本(额度次日恢复后仍会留着)—— 不是判据。 */
|
|
172
|
+
pool.noteError(a.id, '额度用尽(1005 exceed quota limit)')
|
|
173
|
+
|
|
174
|
+
assert.deepEqual(pool.list()[0].model_rate_limits, {}, '前置:硬标记表为空')
|
|
175
|
+
|
|
176
|
+
const routes = routesFor(pool, 'healthy')
|
|
177
|
+
/** 等后台余额拉取落进缓存(否则面板口径还是 pending / available=null)。 */
|
|
178
|
+
await call(routes, '/api/zcode-start-plan/routing', { url: `/api/zcode-start-plan/routing?model=${model}` })
|
|
179
|
+
await settle()
|
|
180
|
+
const response = await call(routes, '/api/zcode-start-plan/routing', {
|
|
181
|
+
url: `/api/zcode-start-plan/routing?model=${model}`,
|
|
182
|
+
})
|
|
183
|
+
const account = response.body.accounts.find((entry) => entry.accountId === a.id)
|
|
184
|
+
assert.equal(account.quota.source, 'upstream', '前置:面板口径已拉到上游余额')
|
|
185
|
+
assert.equal(account.quota.limited, false, 'last_error 不是准入判据:没有当日硬标记就不许判 limited')
|
|
186
|
+
assert.equal(account.quota.usable, true, '面板口径有额度 + 无否决位 → 可用(与对话一致)')
|
|
187
|
+
assert.equal(account.quota.reason, null, '不得给出「已判额度用尽」这类结论')
|
|
188
|
+
|
|
189
|
+
/** 对照:同一个账号一旦真的落了硬标记,limited 立刻为 true。 */
|
|
190
|
+
pool.markModelRateLimited(a.id, model, Date.now() + 3_600_000)
|
|
191
|
+
const after = await call(routes, '/api/zcode-start-plan/routing', {
|
|
192
|
+
url: `/api/zcode-start-plan/routing?model=${model}`,
|
|
193
|
+
})
|
|
194
|
+
assert.equal(
|
|
195
|
+
after.body.accounts.find((entry) => entry.accountId === a.id).quota.limited,
|
|
196
|
+
true,
|
|
197
|
+
'硬标记才是 limited 的唯一依据',
|
|
198
|
+
)
|
|
199
|
+
}))
|
|
200
|
+
|
|
201
|
+
test('/routing: 余额接口失败走退避,不把 null 当成「已用光」', withPool(async (pool) => {
|
|
202
|
+
let calls = 0
|
|
203
|
+
pool.add(credential('a'), 'A')
|
|
204
|
+
const routes = makeManageRoutes({
|
|
205
|
+
pool,
|
|
206
|
+
client: {},
|
|
207
|
+
fetchBalance: async () => {
|
|
208
|
+
calls += 1
|
|
209
|
+
return undefined
|
|
210
|
+
},
|
|
211
|
+
settings: {},
|
|
212
|
+
log: () => {},
|
|
213
|
+
})
|
|
214
|
+
await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
|
|
215
|
+
await settle()
|
|
216
|
+
assert.equal(calls, 1)
|
|
217
|
+
const again = await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
|
|
218
|
+
/** 失败条目在退避窗口内不再重试(否则 2s 轮询每轮打一次上游)。 */
|
|
219
|
+
assert.equal(calls, 1, '失败后必须退避')
|
|
220
|
+
const account = again.body.accounts[0]
|
|
221
|
+
assert.equal(account.usedRatio, null, '未知不能显示成 100%')
|
|
222
|
+
assert.equal(account.quota.source, 'failed')
|
|
223
|
+
assert.equal(account.quota.available, null, '未知不能显示成「有额度」')
|
|
224
|
+
}))
|
|
225
|
+
|
|
226
|
+
test('/routing: 账号删除后额度缓存同步丢弃', withPool(async (pool) => {
|
|
227
|
+
const a = pool.add(credential('a'), 'A').entry
|
|
228
|
+
const routes = routesFor(pool, 'healthy')
|
|
229
|
+
await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
|
|
230
|
+
await settle()
|
|
231
|
+
|
|
232
|
+
const req = {
|
|
233
|
+
method: 'POST',
|
|
234
|
+
url: '/api/zcode-start-plan/remove',
|
|
235
|
+
socket: { remoteAddress: '127.0.0.1' },
|
|
236
|
+
headers: { host: '127.0.0.1:58962', 'content-type': 'application/json' },
|
|
237
|
+
on(event, handler) {
|
|
238
|
+
if (event === 'data') handler(Buffer.from(JSON.stringify({ id: a.id })))
|
|
239
|
+
if (event === 'end') handler()
|
|
240
|
+
return req
|
|
241
|
+
},
|
|
242
|
+
destroy() {},
|
|
243
|
+
}
|
|
244
|
+
const res = makeReqRes().res
|
|
245
|
+
await routes.find((item) => item.path === '/api/zcode-start-plan/remove').handler(req, res)
|
|
246
|
+
assert.equal(pool.list().length, 0)
|
|
247
|
+
/** 再查一次不应因残留缓存而崩溃或复活该账号。 */
|
|
248
|
+
const after = await call(routes, '/api/zcode-start-plan/routing', { url: '/api/zcode-start-plan/routing' })
|
|
249
|
+
assert.equal(after.body.accounts.length, 0)
|
|
250
|
+
assert.equal(after.body.preview, null)
|
|
251
|
+
}))
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「上游黑洞」测试夹具:一个**永不产出、也永不结束**的响应流。
|
|
3
|
+
*
|
|
4
|
+
* 复刻 issue #4 的真实形态 —— 额度用尽后上游对该账号不再出流:
|
|
5
|
+
* HTTP 200 已经回来了,但 body 里一个字节都没有。谁在等它,就必须有自己的超时,
|
|
6
|
+
* 否则最终只会被宿主 ~300s 的超时收成一句笼统的 `PROVIDER_ERROR`。
|
|
7
|
+
*
|
|
8
|
+
* 用法:
|
|
9
|
+
* ```js
|
|
10
|
+
* const hanging = new HangingStream()
|
|
11
|
+
* ... body: hanging.stream ...
|
|
12
|
+
* t.after(() => hanging.release()) // 让挂起的读操作优雅退出,别把测试进程吊死
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export class HangingStream {
|
|
16
|
+
/** @type {ReadableStream<Uint8Array>} */
|
|
17
|
+
stream
|
|
18
|
+
#controllers = []
|
|
19
|
+
#released = false
|
|
20
|
+
|
|
21
|
+
constructor() {
|
|
22
|
+
let captured
|
|
23
|
+
this.stream = new ReadableStream({
|
|
24
|
+
start: (controller) => {
|
|
25
|
+
captured = controller
|
|
26
|
+
this.#controllers.push(controller)
|
|
27
|
+
},
|
|
28
|
+
cancel: () => {
|
|
29
|
+
/** 被消费者取消(超时后 `decoder.cancel()`)—— 标记已释放,避免后续写报错。 */
|
|
30
|
+
this.#released = true
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
this.#controller = captured
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
#controller
|
|
37
|
+
|
|
38
|
+
/** 主动结束这条流(测试收尾用;读操作会以 `done` 退出)。 */
|
|
39
|
+
release() {
|
|
40
|
+
if (this.#released) return
|
|
41
|
+
this.#released = true
|
|
42
|
+
try {
|
|
43
|
+
this.#controller?.close()
|
|
44
|
+
} catch {
|
|
45
|
+
/** 已经被取消:无需再关。 */
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -1,125 +1,164 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 「HTTP 200 里包裹业务错误」的识别。
|
|
3
|
-
*
|
|
4
|
-
* 实测(2026-10-23,本渠道):额度用尽时上游返回
|
|
5
|
-
* `200 + application/json + {"code":1005,"msg":"exceed quota limit"}`。
|
|
6
|
-
*
|
|
7
|
-
* 若把它当成「空响应」处理,会:
|
|
8
|
-
* ① 丢掉真正的错误码,用户只看到误导性的「200 但零内容」;
|
|
9
|
-
* ② 无法据此正确决策(1005 该标号换号;3012 该直接失败不重试)。
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import test from 'node:test'
|
|
13
|
-
import assert from 'node:assert/strict'
|
|
14
|
-
import { readFileSync } from 'node:fs'
|
|
15
|
-
import { fileURLToPath } from 'node:url'
|
|
16
|
-
import { dirname, join } from 'node:path'
|
|
17
|
-
|
|
18
|
-
import { extractUpstreamError, readContentHead } from '../lib/sse.js'
|
|
19
|
-
import { classifyUpstreamError } from '../lib/errors.js'
|
|
20
|
-
import { ZcodePlanClient } from '../lib/plan-client.js'
|
|
21
|
-
|
|
22
|
-
const here = dirname(fileURLToPath(import.meta.url))
|
|
23
|
-
const fixture = (file) => readFileSync(join(here, 'fixtures', file))
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
)
|
|
43
|
-
})
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
})
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
assert.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
assert.
|
|
67
|
-
assert.
|
|
68
|
-
assert.match(
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 「HTTP 200 里包裹业务错误」的识别。
|
|
3
|
+
*
|
|
4
|
+
* 实测(2026-10-23,本渠道):额度用尽时上游返回
|
|
5
|
+
* `200 + application/json + {"code":1005,"msg":"exceed quota limit"}`。
|
|
6
|
+
*
|
|
7
|
+
* 若把它当成「空响应」处理,会:
|
|
8
|
+
* ① 丢掉真正的错误码,用户只看到误导性的「200 但零内容」;
|
|
9
|
+
* ② 无法据此正确决策(1005 该标号换号;3012 该直接失败不重试)。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import test from 'node:test'
|
|
13
|
+
import assert from 'node:assert/strict'
|
|
14
|
+
import { readFileSync } from 'node:fs'
|
|
15
|
+
import { fileURLToPath } from 'node:url'
|
|
16
|
+
import { dirname, join } from 'node:path'
|
|
17
|
+
|
|
18
|
+
import { extractUpstreamError, readContentHead } from '../lib/sse.js'
|
|
19
|
+
import { classifyUpstreamError, extractBusinessCode, hasBusinessCode } from '../lib/errors.js'
|
|
20
|
+
import { ZcodePlanClient } from '../lib/plan-client.js'
|
|
21
|
+
|
|
22
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
23
|
+
const fixture = (file) => readFileSync(join(here, 'fixtures', file))
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 回归:数字业务码必须按**结构**判定,不能裸子串匹配。
|
|
27
|
+
*
|
|
28
|
+
* 实测踩点:网关 502 页正文里带 `Request ID 3f8a-1005-b27c`,旧实现
|
|
29
|
+
* `body.includes('1005')` 判成「额度用尽」→ 把一个健康账号标限流到**当日结束**。
|
|
30
|
+
*/
|
|
31
|
+
test('classifyUpstreamError: 非 JSON 错误页里的数字片段不再误判为额度用尽', () => {
|
|
32
|
+
const html = '<html><head><title>502 Bad Gateway</title></head><body><p>Request ID 3f8a-1005-b27c</p></body></html>'
|
|
33
|
+
assert.equal(classifyUpstreamError(500, html), 'other')
|
|
34
|
+
assert.equal(hasBusinessCode(html, 1005), false)
|
|
35
|
+
const another = '<html><body>Error 1113 detected in upstream module</body></html>'
|
|
36
|
+
assert.equal(classifyUpstreamError(502, another), 'other')
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
test('classifyUpstreamError: 结构化业务码(数字/字符串/嵌套)照旧识别', () => {
|
|
40
|
+
assert.equal(classifyUpstreamError(200, '{"code":1005,"msg":"exceed quota limit"}'), 'quota')
|
|
41
|
+
assert.equal(classifyUpstreamError(200, '{"code":"1005"}'), 'quota')
|
|
42
|
+
assert.equal(classifyUpstreamError(200, '{"error":{"code":3012}}'), 'risk')
|
|
43
|
+
assert.equal(classifyUpstreamError(200, '{"code":3009}'), 'concurrency')
|
|
44
|
+
assert.equal(classifyUpstreamError(200, '{"code":3007}'), 'captcha')
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
test('extractBusinessCode: 只认 JSON 结构,纯文本/HTML 一律 undefined', () => {
|
|
48
|
+
assert.equal(extractBusinessCode('{"code":0}'), 0)
|
|
49
|
+
assert.equal(extractBusinessCode('{"msg":"ok"}'), undefined)
|
|
50
|
+
assert.equal(extractBusinessCode('<html>1005</html>'), undefined)
|
|
51
|
+
/** 被包裹的 JSON 片段仍能取出(上游偶有前后缀)。 */
|
|
52
|
+
assert.equal(extractBusinessCode('gateway: {"code":3007} trailing'), 3007)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test('hasBusinessCode: 结构化 code 优先于兜底数字 token', () => {
|
|
56
|
+
/** 有结构化 code 时,出现别的数字串不算。 */
|
|
57
|
+
assert.equal(hasBusinessCode('{"code":3009,"msg":"1005 is a doc id"}', 1005), false)
|
|
58
|
+
assert.equal(hasBusinessCode('{"code":3009,"msg":"1005 is a doc id"}', 3009), true)
|
|
59
|
+
/** 无结构时裸业务码仍可识别(上游偶尔回纯文本)。 */
|
|
60
|
+
assert.equal(hasBusinessCode('1005 exceed quota limit', 1005), true)
|
|
61
|
+
assert.equal(hasBusinessCode('upstream 3009x timeout', 3009), false)
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
test('extractUpstreamError: 200 + {code:1005} 被识别为业务错误', () => {
|
|
65
|
+
const error = extractUpstreamError({ code: 1005, msg: 'exceed quota limit' }, '')
|
|
66
|
+
assert.notEqual(error, undefined)
|
|
67
|
+
assert.match(error.text, /1005/)
|
|
68
|
+
assert.match(error.text, /exceed quota limit/)
|
|
69
|
+
/** 交给错误表后应判成 quota(而不是 other / 无权益)。 */
|
|
70
|
+
assert.equal(classifyUpstreamError(200, error.text), 'quota')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
test('extractUpstreamError: 3012 风控与 3009 并发同样能从 200 里认出来', () => {
|
|
74
|
+
assert.equal(
|
|
75
|
+
classifyUpstreamError(200, extractUpstreamError({ code: 3012, msg: 'unusual activity' }, '').text),
|
|
76
|
+
'risk',
|
|
77
|
+
)
|
|
78
|
+
assert.equal(
|
|
79
|
+
classifyUpstreamError(200, extractUpstreamError({ code: 3009, msg: 'concurrency limit' }, '').text),
|
|
80
|
+
'concurrency',
|
|
81
|
+
)
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
test('extractUpstreamError: 成功码 0 与正常 message 不算错误', () => {
|
|
85
|
+
assert.equal(extractUpstreamError({ code: 0, msg: '' }, ''), undefined)
|
|
86
|
+
assert.equal(extractUpstreamError({ id: 'msg_1', type: 'message', content: [] }, ''), undefined)
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
test('extractUpstreamError: Anthropic 标准错误载荷与裸 error 字段', () => {
|
|
90
|
+
const standard = extractUpstreamError({ type: 'error', error: { type: 'api_error', message: 'boom' } }, '')
|
|
91
|
+
assert.notEqual(standard, undefined)
|
|
92
|
+
assert.match(standard.text, /api_error/)
|
|
93
|
+
const bare = extractUpstreamError({ error: { message: 'boom' } }, '')
|
|
94
|
+
assert.notEqual(bare, undefined)
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
test('readContentHead: 200 + 业务错误的 JSON 不再被当成「零内容」', async () => {
|
|
98
|
+
const body = new ReadableStream({
|
|
99
|
+
start(controller) {
|
|
100
|
+
controller.enqueue(fixture('quota-200.json'))
|
|
101
|
+
controller.close()
|
|
102
|
+
},
|
|
103
|
+
})
|
|
104
|
+
const head = await readContentHead(body, { contentType: 'application/json; charset=utf-8' })
|
|
105
|
+
assert.equal(head.hasContent, false)
|
|
106
|
+
assert.notEqual(head.upstreamError, undefined)
|
|
107
|
+
assert.match(head.upstreamError.text, /1005/)
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
test('plan-client: 200 里的 1005 标记该账号当日用尽并换号(而不是「零内容」)', async () => {
|
|
111
|
+
const quotaBody = () =>
|
|
112
|
+
new ReadableStream({
|
|
113
|
+
start(controller) {
|
|
114
|
+
controller.enqueue(fixture('quota-200.json'))
|
|
115
|
+
controller.close()
|
|
116
|
+
},
|
|
117
|
+
})
|
|
118
|
+
const pool = {
|
|
119
|
+
state: [
|
|
120
|
+
{ id: 'acct-a', enabled: true, model_rate_limits: {}, credential: { zcode_jwt: 'jwt-a', device_mid: 'dev-a' } },
|
|
121
|
+
{ id: 'acct-b', enabled: true, model_rate_limits: {}, credential: { zcode_jwt: 'jwt-b', device_mid: 'dev-b' } },
|
|
122
|
+
],
|
|
123
|
+
list() {
|
|
124
|
+
return this.state
|
|
125
|
+
},
|
|
126
|
+
pick(_model, exclude) {
|
|
127
|
+
const hit = this.state.find((entry) => entry.enabled && !(exclude?.has(entry.id) ?? false))
|
|
128
|
+
return hit === undefined ? null : { entry: hit, credential: hit.credential }
|
|
129
|
+
},
|
|
130
|
+
markModelRateLimited(id, model) {
|
|
131
|
+
const hit = this.state.find((entry) => entry.id === id)
|
|
132
|
+
if (hit !== undefined) hit.model_rate_limits[model] = Date.now() + 60_000
|
|
133
|
+
},
|
|
134
|
+
noteError() {},
|
|
135
|
+
}
|
|
136
|
+
const marks = []
|
|
137
|
+
const originalMark = pool.markModelRateLimited.bind(pool)
|
|
138
|
+
pool.markModelRateLimited = (id, model, at) => {
|
|
139
|
+
marks.push({ id, code: 'quota' })
|
|
140
|
+
originalMark(id, model, at)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const client = new ZcodePlanClient({
|
|
144
|
+
pool,
|
|
145
|
+
minter: { async mint() { return { param: 'p', interactive: false } }, async fetchConfig() { return undefined } },
|
|
146
|
+
fetchImpl: async () => ({
|
|
147
|
+
ok: true,
|
|
148
|
+
status: 200,
|
|
149
|
+
headers: new Headers({ 'content-type': 'application/json; charset=utf-8' }),
|
|
150
|
+
body: quotaBody(),
|
|
151
|
+
}),
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
await assert.rejects(
|
|
155
|
+
() => client.call({ options: { model: 'GLM-5.3-Flash', messages: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }] } }),
|
|
156
|
+
(error) => {
|
|
157
|
+
assert.equal(error.code, 'QUOTA')
|
|
158
|
+
assert.match(error.message, /1005/)
|
|
159
|
+
return true
|
|
160
|
+
},
|
|
161
|
+
)
|
|
162
|
+
/** 两个账号都被按「额度用尽」标记过(而不是被当成无权益)。 */
|
|
163
|
+
assert.deepEqual(marks.map((mark) => mark.id), ['acct-a', 'acct-b'])
|
|
164
|
+
})
|