@mzzsfy/dsh-stock-assistant 0.10.0 → 0.11.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/CHANGELOG.md +32 -0
- package/README.md +14 -12
- package/package.json +1 -1
- package/src/application.mjs +240 -99
- package/src/budget.mjs +16 -15
- package/src/catalog.mjs +124 -83
- package/src/client.js +487 -196
- package/src/client.js~RF25ea9e49.TMP +3301 -0
- package/src/collector.mjs +4 -4
- package/src/executor.mjs +141 -66
- package/src/kline-cache.mjs +10 -13
- package/src/provider-router.mjs +4 -4
- package/src/providers/eastmoney.mjs +119 -54
- package/src/providers/sina.mjs +61 -39
- package/src/providers/tencent.mjs +5 -4
- package/src/providers/us-markets.mjs +4 -0
- package/src/providers/xueqiu.mjs +62 -23
- package/src/recovery.mjs +29 -14
- package/src/routes.mjs +7 -4
- package/src/schemas.mjs +3 -5
- package/src/trend-cache.mjs +21 -4
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +25 -1
package/src/application.mjs
CHANGED
|
@@ -21,8 +21,20 @@ import { createDemand } from './demand.mjs'
|
|
|
21
21
|
import { createKlineCache } from './kline-cache.mjs'
|
|
22
22
|
import { createTrendCache, trendSessionDate } from './trend-cache.mjs'
|
|
23
23
|
import { createTickStore } from './ticks.mjs'
|
|
24
|
-
import { fail, parseSecurityId, MARKET_META, clockInZone } from './market-model.mjs'
|
|
24
|
+
import { fail, StockError, parseSecurityId, MARKET_META, clockInZone } from './market-model.mjs'
|
|
25
25
|
const WINDOW = 5 * 60 * 1000
|
|
26
|
+
const OVERVIEW_TIMEOUT_MS = 250
|
|
27
|
+
const CREDENTIAL_PRESENCE_TIMEOUT_MS = 2 * 1000
|
|
28
|
+
const MARKET_INDEX = {
|
|
29
|
+
XSHG: { id: 'XSHG:index:000001', exchange: 'XSHG', code: '000001', name: '上证指数' },
|
|
30
|
+
XSHE: { id: 'XSHE:index:399001', exchange: 'XSHE', code: '399001', name: '深证成指' },
|
|
31
|
+
XHKG: { id: 'XHKG:index:HSI', exchange: 'XHKG', code: 'HSI', name: '恒生指数' },
|
|
32
|
+
XNAS: { id: 'XNAS:index:NDX', exchange: 'XNAS', code: 'NDX', name: '纳斯达克100' },
|
|
33
|
+
XNYS: { id: 'XNYS:index:DJI', exchange: 'XNYS', code: 'DJI', name: '道琼斯' },
|
|
34
|
+
XJPX: { id: 'XJPX:index:N225', exchange: 'XJPX', code: 'N225', name: '日经225' },
|
|
35
|
+
XKRX: { id: 'XKRX:index:KOSPI', exchange: 'XKRX', code: 'KOSPI', name: '韩国综指' },
|
|
36
|
+
XLON: { id: 'XLON:index:FTSE', exchange: 'XLON', code: 'FTSE', name: '富时100' },
|
|
37
|
+
}
|
|
26
38
|
// 探针诊断的节流窗口内最多发起多少次检查: 检查会真的打上游, 不能由页面无限触发
|
|
27
39
|
const PROBE_CHECK_LIMIT = 64
|
|
28
40
|
// 探针总预算上限: 目标多到推导值超过它时不再加长请求, 改为交出已完成的部分诊断
|
|
@@ -45,26 +57,40 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
45
57
|
return service && ['resolve', 'set', 'unset'].every(method => typeof service[method] === 'function') ? service : null
|
|
46
58
|
}
|
|
47
59
|
const resolveCredential = async ref => {
|
|
48
|
-
|
|
49
|
-
|
|
60
|
+
try {
|
|
61
|
+
const store = credentialStoreOf()
|
|
62
|
+
return store ? (await store.resolve(ref))?.value : env[ref]
|
|
63
|
+
} catch {
|
|
64
|
+
fail('NETWORK', '暂时无法读取来源凭据', 502, { retryable: true })
|
|
65
|
+
}
|
|
50
66
|
}
|
|
51
67
|
let snapshotSeq = 0, stopped = false, collector, catalog, demand, watchlist, recoveryLoop
|
|
52
68
|
let ensuring = null, lastEnsure = -Infinity, ensureError = null, hadDemand = false, ensureCaches = () => {}
|
|
53
69
|
const usSymbols = createUsSymbols({ now })
|
|
54
70
|
const touched = () => snapshotSeq++
|
|
55
71
|
const changed = () => { touched(); publish({ type: 'invalidate', serverEpoch, snapshotSeq, scopes: ['snapshot'] }) }
|
|
56
|
-
//
|
|
57
|
-
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
72
|
+
// 凭据状态与当前配置绑定。探测期间或解析失败按未就绪显示,旧探测只写自己的状态表。
|
|
73
|
+
let credentialPresence = null
|
|
74
|
+
const credentialPresent = (control, ref) => credentialPresence?.routingRevision === control.routingRevision && credentialPresence.byRef.get(ref) === true
|
|
75
|
+
const refreshCredentialPresence = async (notify = true) => {
|
|
76
|
+
const { providers, routingRevision } = state.get()
|
|
77
|
+
const view = { routingRevision, byRef: new Map() }
|
|
78
|
+
credentialPresence = view
|
|
79
|
+
const refs = new Set(providers.flatMap(p => [p.credentialRef, p.proxyCredentialRef]).filter(Boolean))
|
|
80
|
+
if (!refs.size) return
|
|
81
|
+
let timer
|
|
82
|
+
const expired = new Promise(resolve => { timer = timers.setTimeout(() => resolve(false), CREDENTIAL_PRESENCE_TIMEOUT_MS) })
|
|
83
|
+
try {
|
|
84
|
+
await Promise.all([...refs].map(async ref => {
|
|
85
|
+
const present = await Promise.race([resolveCredential(ref).then(Boolean, () => false), expired])
|
|
86
|
+
view.byRef.set(ref, present)
|
|
87
|
+
}))
|
|
88
|
+
} finally { timers.clearTimeout(timer) }
|
|
89
|
+
if (notify && !stopped && credentialPresence === view && state.get().routingRevision === routingRevision) changed()
|
|
63
90
|
}
|
|
64
91
|
let state, registry, executor, getControl, router, klineCache, trendCache, ticks
|
|
65
92
|
try {
|
|
66
93
|
state = await openState(storageDomain, changed, now)
|
|
67
|
-
await refreshCredentialPresence()
|
|
68
94
|
registry = createRegistry(providers)
|
|
69
95
|
const budget = createBudget(now)
|
|
70
96
|
// 代理出口: undici ProxyAgent + 同一份 undici.fetch。dispatcher 是 undici 私有契约,
|
|
@@ -77,9 +103,16 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
77
103
|
} catch {}
|
|
78
104
|
executor = createExecutor({ registry, budget, env, resolveCredential, fetch, proxyFetch, now, timers, usSymbols, proxyFactory, tickPeriodMs: () => tickPeriodMs(state.get().preferences) })
|
|
79
105
|
getControl = state.get
|
|
80
|
-
//
|
|
81
|
-
|
|
82
|
-
router = createRouter(
|
|
106
|
+
// 路由状态跟随已落盘的配置版本,在第一次读取新配置前切代。
|
|
107
|
+
let routerRevision = getControl().routingRevision
|
|
108
|
+
router = createRouter(() => {
|
|
109
|
+
const control = getControl()
|
|
110
|
+
if (control.routingRevision !== routerRevision) {
|
|
111
|
+
routerRevision = control.routingRevision
|
|
112
|
+
router.reset()
|
|
113
|
+
}
|
|
114
|
+
return control
|
|
115
|
+
}, now, routeId => collector?.routeChanged(routeId))
|
|
83
116
|
klineCache = createKlineCache({ cacheTable: state.klineCache, now })
|
|
84
117
|
// 分时当日缓存走独立小池: 它与报价拍点都只放内存, 不入配置记录
|
|
85
118
|
trendCache = createTrendCache({ table: state.trendCache, now })
|
|
@@ -87,8 +120,14 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
87
120
|
// 回探跟着面板活跃走: 有人看时每 RECOVERY_PROBE_MS 把已降级路由的上级全探一遍, 没人看就停
|
|
88
121
|
// 回探要的是当前生效的 provider/route 表: 传控制记录读取器(整条记录)会让 getConfig() 直接抛错,
|
|
89
122
|
// 而循环把异常吞掉 —— 降级路由的自动回切会静默地一次都不跑
|
|
90
|
-
|
|
91
|
-
|
|
123
|
+
const probe = createRecovery({
|
|
124
|
+
getConfig: getControl, router, executor,
|
|
125
|
+
deadlineOf: () => now() + routeTimeoutMs(getControl().preferences),
|
|
126
|
+
canProbe: (route, instance, revision) => sourceWait(route.capability, instance.id, revision) === 0,
|
|
127
|
+
onError: (route, instance, error, revision) => coolOnError(route.capability, instance.id, revision, error),
|
|
128
|
+
})
|
|
129
|
+
recoveryLoop = createRecoveryLoop({ probe, timers, interval: RECOVERY_PROBE_MS, canRun: () => executor.idle() })
|
|
130
|
+
catalog = createCatalog({ state, getControl, router, executor, now, changed })
|
|
92
131
|
demand = createDemand(() => {
|
|
93
132
|
const wanted = demand.active(), opening = wanted && !hadDemand; hadDemand = wanted
|
|
94
133
|
if (wanted) {
|
|
@@ -109,6 +148,7 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
109
148
|
// 存量配置升级: 分时能力独立后没有 trend 路由的库在打开时补齐。
|
|
110
149
|
// 补齐失败不该让整个面板躺下(面板可用性高于分时), 记下原因继续, 与目录预热同构
|
|
111
150
|
try { await ensureTrendRoutes() } catch (e) { ensureError = { message: `分时来源补齐失败:${e.message}`, at: now() } }
|
|
151
|
+
await refreshCredentialPresence(false)
|
|
112
152
|
// 面板活跃(demand)时让路: 目录后台同步占满并发槽会拖死交互请求(浏览504实测), 仅在面板空闲时补目录
|
|
113
153
|
ensureCaches = () => {
|
|
114
154
|
if (ensuring || now() - lastEnsure < 60 * 1000 || demand.active()) return
|
|
@@ -124,9 +164,22 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
124
164
|
const snapshot = () => {
|
|
125
165
|
// 台账不随快照下发; 读侧共享同一份冻结快照, 不能原地删字段
|
|
126
166
|
const { operations, ...control } = state.get()
|
|
127
|
-
return { serverEpoch, snapshotSeq, routingRevision: control.routingRevision, control, quotes: collector.watchEntries(), timeouts: { route: routeTimeoutMs(control.preferences) }, routeSelections: router.selections(), catalogs: catalog.status(), adapters: registry.descriptors(), suggested: defaultConfig(), ensureError, vendorAvailable, providerStatus: control.providers.map(p => ({ id: p.id, credentialPresent: p.credentialRef === null ||
|
|
167
|
+
return { serverEpoch, snapshotSeq, routingRevision: control.routingRevision, control, quotes: collector.watchEntries(), timeouts: { route: routeTimeoutMs(control.preferences) }, routeSelections: router.selections(), catalogs: catalog.status(), adapters: registry.descriptors(), suggested: defaultConfig(), ensureError, vendorAvailable, providerStatus: control.providers.map(p => ({ id: p.id, credentialPresent: p.credentialRef === null || credentialPresent(control, p.credentialRef), credentialRef: p.credentialRef, proxy: !!p.proxy, proxyCredentialRef: p.proxyCredentialRef ?? null, proxyCredentialPresent: p.proxyCredentialRef ? credentialPresent(control, p.proxyCredentialRef) : null, endpointsCovered: Object.keys(p.endpoints || {}).length, recentRequests: executor.recentRequests(p.id) })), klineReady: Object.fromEntries(control.routes.filter(r => r.capability === 'kline').map(r => [r.market, true])), markets: Object.fromEntries(Object.entries(MARKET_META).map(([market, meta]) => [market, { currency: meta.currency, verified: meta.verifiedByDefault }])) }
|
|
128
168
|
}
|
|
129
169
|
function assertLive() { if (stopped) fail('STOPPED', '股票工具已停止', 503) }
|
|
170
|
+
function sourceWait(capability, instanceId, revision) {
|
|
171
|
+
return capability === 'trend' ? trendCache.sourceWait(revision, instanceId) : 0
|
|
172
|
+
}
|
|
173
|
+
function cooled(retryAfterMs, local = false) {
|
|
174
|
+
return new StockError('RATE_LIMIT', '分时来源正在冷却,请稍后重试', 429, { retryable: true, retryAfterMs, local })
|
|
175
|
+
}
|
|
176
|
+
function assertSourceReady(capability, id, revision) {
|
|
177
|
+
const remaining = sourceWait(capability, id, revision)
|
|
178
|
+
if (remaining > 0) throw cooled(remaining, true)
|
|
179
|
+
}
|
|
180
|
+
function coolOnError(capability, instanceId, revision, error) {
|
|
181
|
+
if (capability === 'trend' && !error.local && error.code === 'RATE_LIMIT' && getControl().routingRevision === revision) trendCache.coolSource(revision, instanceId, error.retryAfterMs)
|
|
182
|
+
}
|
|
130
183
|
// 待测目标表: 一条路由的每个实例各算一个探针, 同 (实例, 能力, 市场) 只测一次。
|
|
131
184
|
// 组内串行由执行器的额度组间隔保证, 所以并行度按额度组切分, 而不是按目标数。
|
|
132
185
|
const probePlan = (config, caps) => {
|
|
@@ -165,6 +218,7 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
165
218
|
async function providerCheck(input, signal) {
|
|
166
219
|
assertLive()
|
|
167
220
|
const { config, plan, groups } = probeInput(input)
|
|
221
|
+
const { routingRevision } = getControl()
|
|
168
222
|
const at = now()
|
|
169
223
|
while (probeTimes.length && at - probeTimes[0] >= WINDOW) probeTimes.shift()
|
|
170
224
|
if (probeTimes.length >= PROBE_CHECK_LIMIT) fail('CHECK_LIMIT', '检查请求过多,请稍后重试', 429)
|
|
@@ -189,15 +243,26 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
189
243
|
// 探针耗时就是这一条路由端到端拿数据的真实延迟, 用于把「能不能用」和「快不快」一起回给用户
|
|
190
244
|
const startedAt = now()
|
|
191
245
|
try {
|
|
192
|
-
const
|
|
246
|
+
const beforeDispatch = () => {
|
|
247
|
+
if (probe.capability !== 'trend') return
|
|
248
|
+
if (routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '路由配置已变化', 409, { local: true })
|
|
249
|
+
assertSourceReady(probe.capability, probe.instance.id, routingRevision)
|
|
250
|
+
}
|
|
251
|
+
beforeDispatch()
|
|
252
|
+
const result = await executor.run(probe.instance, probe.capability, { market: probe.market, instrument: probe.route.instrument }, { probe: true, signal: limiter.signal, beforeDispatch })
|
|
193
253
|
// 探针必须由同名能力的端点产出: 适配器拿别的能力冒充(漏实现分支)时不能当就绪, 且要说清是谁被验了
|
|
194
254
|
const ready = result?.status === 'ready' && result.capability === probe.capability
|
|
195
255
|
results[index] = { key: probe.key, providerInstanceId: probe.instance.id, capability: probe.capability, market: probe.market, status: ready ? 'ready' : 'unavailable', ms: now() - startedAt, ...(ready ? {} : { error: { code: 'PROBE_MISMATCH', message: `探针校验的是${result?.capability ?? '未知'}能力` } }) }
|
|
196
256
|
} catch (e) {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
257
|
+
if (!limiter.signal.aborted) coolOnError(probe.capability, probe.instance.id, routingRevision, e)
|
|
258
|
+
// 已在冷却的分时源没有实际受检,不能作为剪除配置来源的证据。
|
|
259
|
+
if (probe.capability === 'trend' && e.code === 'RATE_LIMIT') {
|
|
260
|
+
results[index] = { ...skipped(probe, e.code, e.message), error: { code: e.code, message: e.message, retryAfterMs: e.retryAfterMs } }
|
|
261
|
+
} else {
|
|
262
|
+
results[index] = limiter.signal.aborted && !signal?.aborted
|
|
263
|
+
? skipped(probe, 'CHECK_DEADLINE', '检查预算用完,此项未执行')
|
|
264
|
+
: { key: probe.key, providerInstanceId: probe.instance.id, capability: probe.capability, market: probe.market, status: 'denied', ms: now() - startedAt, error: { code: e.code, message: e.message } }
|
|
265
|
+
}
|
|
201
266
|
} finally {
|
|
202
267
|
timers.clearTimeout(timer)
|
|
203
268
|
signal?.removeEventListener('abort', abortByOuter)
|
|
@@ -213,6 +278,7 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
213
278
|
}
|
|
214
279
|
async function configuration(operation) {
|
|
215
280
|
assertLive()
|
|
281
|
+
if (operation.expectedServerEpoch !== undefined && operation.expectedServerEpoch !== serverEpoch) fail('REVISION_CONFLICT', '服务已重启,请刷新配置后重新确认', 409, { revision: state.get().revision })
|
|
216
282
|
const config = parseConfiguration(operation.payload)
|
|
217
283
|
const replay = state.replay({ ...operation, action: 'configuration', payload: config })
|
|
218
284
|
if (replay) return replay
|
|
@@ -225,7 +291,10 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
225
291
|
if (JSON.stringify(current.providers) === JSON.stringify(config.providers) && JSON.stringify(current.routes) === JSON.stringify(config.routes)) return current
|
|
226
292
|
return { ...current, ...config, routingRevision: current.routingRevision + 1 }
|
|
227
293
|
})
|
|
228
|
-
if (!result.unchanged
|
|
294
|
+
if (!result.unchanged && credentialPresence?.routingRevision !== state.get().routingRevision) {
|
|
295
|
+
collector.reset()
|
|
296
|
+
await refreshCredentialPresence()
|
|
297
|
+
}
|
|
229
298
|
return result
|
|
230
299
|
}
|
|
231
300
|
|
|
@@ -239,29 +308,51 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
239
308
|
// K 线类请求的即时故障转移: 触发码 NETWORK/TIMEOUT/BAD_PAYLOAD 时顺着「环上下一格」试一次;
|
|
240
309
|
// 只有当前选择自己的失败算一轮, 顺着链试备源是同一轮里的补救, 不额外计次
|
|
241
310
|
// 一条请求(含分批与备源链)共用的截止时刻: 超出即按超时收尾, 不让路由层 504 掉已成功的部分
|
|
242
|
-
const deadlineOf = () =>
|
|
311
|
+
const deadlineOf = () => now() + requestBudgetMs(state.get().preferences)
|
|
243
312
|
|
|
244
|
-
async function runWithFailover(capability,
|
|
245
|
-
const
|
|
246
|
-
|
|
247
|
-
|
|
313
|
+
async function runWithFailover(capability, primary, fallbacks, request, signal, generation) {
|
|
314
|
+
const deadline = deadlineOf(), trend = capability === 'trend'
|
|
315
|
+
const { routingRevision } = request
|
|
316
|
+
let lastError, unsupported, retryAt = Infinity
|
|
317
|
+
const coolingOf = cand => sourceWait(capability, cand.id, routingRevision)
|
|
318
|
+
for (const cand of [primary, ...fallbacks]) {
|
|
319
|
+
generation.assertCurrent()
|
|
320
|
+
const wait = coolingOf(cand)
|
|
321
|
+
if (wait > 0) { retryAt = Math.min(retryAt, now() + wait); continue }
|
|
322
|
+
let result
|
|
323
|
+
const beforeDispatch = () => {
|
|
324
|
+
generation.assertCurrent()
|
|
325
|
+
assertSourceReady(capability, cand.id, routingRevision)
|
|
326
|
+
}
|
|
248
327
|
try {
|
|
249
|
-
|
|
250
|
-
// 当前选择能出数就是最好的证据: 清掉它的失败计数与探测退避
|
|
251
|
-
if (index === 0) reportRound(null)
|
|
252
|
-
return result
|
|
328
|
+
result = await executor.run(cand, capability, { ...request, routeEpoch: generation.epoch }, { signal, deadline, beforeDispatch })
|
|
253
329
|
} catch (e) {
|
|
254
330
|
if (signal?.aborted) throw e
|
|
255
|
-
|
|
256
|
-
|
|
331
|
+
generation.assertCurrent()
|
|
332
|
+
if (e.local) {
|
|
333
|
+
if (!trend || e.code !== 'RATE_LIMIT') throw e
|
|
334
|
+
retryAt = Math.min(retryAt, now() + e.retryAfterMs)
|
|
335
|
+
continue
|
|
336
|
+
}
|
|
337
|
+
if (cand === primary) generation.report(e)
|
|
338
|
+
if (trend && e.code === 'RATE_LIMIT') {
|
|
339
|
+
coolOnError(capability, cand.id, routingRevision, e)
|
|
340
|
+
retryAt = Math.min(retryAt, now() + coolingOf(cand))
|
|
341
|
+
continue
|
|
342
|
+
}
|
|
257
343
|
if (e.code === 'UNSUPPORTED_CAPABILITY') { unsupported ??= e; continue }
|
|
258
344
|
lastError = e
|
|
259
|
-
//
|
|
260
|
-
|
|
261
|
-
|
|
345
|
+
// 普通瞬时故障只补救一跳;分时冷却中的实例不占这次尝试。
|
|
346
|
+
if (!TRANSIENT_CODES.includes(e.code) || cand !== primary) throw e
|
|
347
|
+
continue
|
|
262
348
|
}
|
|
349
|
+
generation.assertCurrent()
|
|
350
|
+
if (cand === primary) generation.report(null)
|
|
351
|
+
return result
|
|
263
352
|
}
|
|
264
|
-
|
|
353
|
+
if (lastError) throw lastError
|
|
354
|
+
if (Number.isFinite(retryAt)) throw cooled(Math.max(1, retryAt - now()))
|
|
355
|
+
throw unsupported
|
|
265
356
|
}
|
|
266
357
|
// 分时没有路由时用户只会看到"未配置数据来源", 看不出缺的是哪一种能力
|
|
267
358
|
function selectRoute(capability, market) {
|
|
@@ -331,6 +422,25 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
331
422
|
}
|
|
332
423
|
}
|
|
333
424
|
|
|
425
|
+
async function browseOverview(index, signal) {
|
|
426
|
+
const timeout = new AbortController()
|
|
427
|
+
const timer = timers.setTimeout(() => timeout.abort(), OVERVIEW_TIMEOUT_MS)
|
|
428
|
+
const overviewSignal = signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal
|
|
429
|
+
try {
|
|
430
|
+
const { exchange, id, code, name } = index
|
|
431
|
+
const { routingRevision } = state.get()
|
|
432
|
+
const { instance, routeEpoch } = router.select('quotes', exchange)
|
|
433
|
+
const result = await executor.run(instance, 'quotes', { securities: [{ id, exchange, code }], routingRevision }, { signal: overviewSignal, deadline: now() + OVERVIEW_TIMEOUT_MS })
|
|
434
|
+
if (overviewSignal.aborted || state.get().routingRevision !== routingRevision || router.select('quotes', exchange).routeEpoch !== routeEpoch) return null
|
|
435
|
+
const quote = result.items?.find(q => q.securityId === id)
|
|
436
|
+
if (!quote || quote.last == null) return null
|
|
437
|
+
const phase = catalog.marketState(exchange)
|
|
438
|
+
deriveDelay(quote, now, ['trading', 'auction', 'unknown'].includes(phase.state))
|
|
439
|
+
return { name, last: quote.last, change: quote.change, changePct: quote.changePct, quoteAt: quote.quoteAt, delayKind: quote.delayKind, delaySeconds: quote.delaySeconds, sessionState: phase.state, source: quote.providerInstanceId }
|
|
440
|
+
} catch { return null }
|
|
441
|
+
finally { timers.clearTimeout(timer) }
|
|
442
|
+
}
|
|
443
|
+
|
|
334
444
|
return {
|
|
335
445
|
// 路由层超时随刷新档位走: 节拍越慢, 落在拍后半段的请求要等越久, 超时必须盖住这段等待
|
|
336
446
|
routeTimeoutMs: () => routeTimeoutMs(state.get().preferences),
|
|
@@ -357,39 +467,49 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
357
467
|
// 分时与日/周/月是两种上游, 各走各的路由: K 线来源不供分时时, 分时不该跟着一起死
|
|
358
468
|
const capability = period === 'trend' ? 'trend' : 'kline'
|
|
359
469
|
const { route, instance, routeEpoch } = selectRoute(capability, exchange)
|
|
360
|
-
|
|
361
|
-
|
|
470
|
+
const { routingRevision } = config
|
|
471
|
+
const trend = capability === 'trend'
|
|
362
472
|
const usable = provider => provider && provider.enabled !== false && provider.budget?.requestsPerMinute !== null
|
|
363
|
-
|
|
364
|
-
const
|
|
365
|
-
const
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
473
|
+
// 日周月保留环上的单次补救。分时可越过冷却中的配置来源,按同一环继续选择。
|
|
474
|
+
const ring = [route.primaryInstanceId, ...route.fallbackInstanceIds], selectedIndex = ring.indexOf(instance.id)
|
|
475
|
+
const next = trend ? [...ring.slice(selectedIndex + 1), ...ring.slice(0, selectedIndex)] : [router.nextInRing(route.id, instance.id)]
|
|
476
|
+
const fallbacks = next.map(id => config.providers.find(p => p.id === id)).filter(usable)
|
|
477
|
+
const request = { securityId: sid, market: exchange, code, period, adjust: 'qfq', limit, routingRevision }
|
|
478
|
+
const assertRoute = epoch => {
|
|
479
|
+
if (stopped || routingRevision !== state.get().routingRevision || router.select(capability, exchange).routeEpoch !== epoch) fail('ROUTE_CONFLICT', `${trend ? '分时' : 'K线'}来源已变化,请重新刷新`, 409)
|
|
480
|
+
}
|
|
481
|
+
const generationOf = (onMove = () => {}) => {
|
|
482
|
+
let epoch = routeEpoch
|
|
483
|
+
const assertCurrent = () => assertRoute(epoch)
|
|
484
|
+
return {
|
|
485
|
+
get epoch() { return epoch },
|
|
486
|
+
assertCurrent,
|
|
487
|
+
report(error) {
|
|
488
|
+
assertCurrent()
|
|
376
489
|
router.recordRound(route.id, error)
|
|
377
|
-
const current = router.select(
|
|
378
|
-
if (current.routeEpoch !== epoch
|
|
490
|
+
const current = router.select(capability, exchange)
|
|
491
|
+
if (current.routeEpoch !== epoch) {
|
|
379
492
|
epoch = current.routeEpoch
|
|
380
|
-
|
|
381
|
-
moveTo(activeKey)
|
|
493
|
+
onMove(epoch, current.instance.id)
|
|
382
494
|
}
|
|
383
|
-
}
|
|
495
|
+
},
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
const response = (result, epoch) => ({ ...result, source: result.providerInstanceId, revision: config.revision, serverEpoch, routingRevision, routeEpoch: epoch })
|
|
499
|
+
if (trend) {
|
|
500
|
+
const keyOfSelection = (epoch, instanceId) => ({ market: exchange, code, limit, securityId: sid, routeKey: `${serverEpoch}:${routingRevision}:${route.id}:${epoch}:${instanceId}` })
|
|
501
|
+
const key = keyOfSelection(routeEpoch, instance.id)
|
|
502
|
+
const result = await trendCache.fetch(key, signal, async (sharedSignal, moveTo) => {
|
|
503
|
+
const generation = generationOf((epoch, id) => moveTo(keyOfSelection(epoch, id)))
|
|
384
504
|
try {
|
|
385
|
-
const data = await runWithFailover(capability,
|
|
386
|
-
|
|
387
|
-
await trendCache.put(
|
|
388
|
-
return { ...data, routeEpoch: epoch }
|
|
505
|
+
const data = await runWithFailover(capability, instance, fallbacks, request, sharedSignal, generation)
|
|
506
|
+
generation.assertCurrent()
|
|
507
|
+
await trendCache.put(key, data)
|
|
508
|
+
return { ...data, routeEpoch: generation.epoch }
|
|
389
509
|
} catch (error) {
|
|
390
510
|
if (!sharedSignal.aborted) {
|
|
391
|
-
|
|
392
|
-
error.routeEpoch = epoch
|
|
511
|
+
generation.assertCurrent()
|
|
512
|
+
error.routeEpoch = generation.epoch
|
|
393
513
|
}
|
|
394
514
|
throw error
|
|
395
515
|
}
|
|
@@ -397,52 +517,53 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
397
517
|
if (['CANCELLED', 'ROUTE_CONFLICT'].includes(error.code)) throw error
|
|
398
518
|
const epoch = error.routeEpoch ?? routeEpoch
|
|
399
519
|
assertRoute(epoch)
|
|
400
|
-
const
|
|
401
|
-
const offline = await offlineTrend(keyOfSelection(epoch, current.instance.id), error)
|
|
520
|
+
const offline = await offlineTrend(key, error)
|
|
402
521
|
if (!offline) throw error
|
|
403
522
|
return { ...offline, routeEpoch: epoch }
|
|
404
523
|
})
|
|
405
524
|
assertRoute(result.routeEpoch)
|
|
406
525
|
const sessionDate = result.offline ? result.sessionDate : trendSessionDate(exchange, result)
|
|
407
|
-
return { ...result,
|
|
526
|
+
return { ...response(result, result.routeEpoch), sessionDate }
|
|
408
527
|
}
|
|
528
|
+
const generation = generationOf()
|
|
529
|
+
const keyOf = providerInstanceId => ({ providerInstanceId, market: exchange, period, code, limit, serverEpoch, routingRevision, routeEpoch: generation.epoch })
|
|
409
530
|
if (force !== '1') {
|
|
410
|
-
for (const cand of [instance, ...fallbacks
|
|
411
|
-
const cached = await klineCache.get(
|
|
412
|
-
|
|
531
|
+
for (const cand of [instance, ...fallbacks]) {
|
|
532
|
+
const cached = await klineCache.get(keyOf(cand.id))
|
|
533
|
+
generation.assertCurrent()
|
|
534
|
+
if (cached) return response(cached.payload, generation.epoch)
|
|
413
535
|
}
|
|
414
536
|
}
|
|
415
|
-
const result = await runWithFailover(capability,
|
|
416
|
-
|
|
417
|
-
|
|
537
|
+
const result = await runWithFailover(capability, instance, fallbacks, request, signal, generation)
|
|
538
|
+
generation.assertCurrent()
|
|
539
|
+
await klineCache.put(keyOf(result.providerInstanceId), result)
|
|
540
|
+
generation.assertCurrent()
|
|
541
|
+
return response(result, generation.epoch)
|
|
418
542
|
},
|
|
419
|
-
async browse(input) {
|
|
543
|
+
async browse(input, signal) {
|
|
420
544
|
assertLive()
|
|
421
545
|
if (!MARKET_META[input.market]) fail('INVALID_REQUEST', '市场参数无效')
|
|
422
|
-
|
|
423
|
-
const
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
}
|
|
436
|
-
} catch {}
|
|
437
|
-
return { ...await catalog.browse(input), overview, catalogs: catalog.status(), routingRevision: state.get().routingRevision }
|
|
546
|
+
if (signal?.aborted) fail('CANCELLED', '浏览请求已取消', 503)
|
|
547
|
+
const { routingRevision } = state.get()
|
|
548
|
+
// 冷目录和过期目录优先同步,指数只装饰已就绪的首页。
|
|
549
|
+
const { stale, ...data } = await catalog.browse(input)
|
|
550
|
+
const assertDirectory = () => {
|
|
551
|
+
if (signal?.aborted) fail('CANCELLED', '浏览请求已取消', 503)
|
|
552
|
+
if (routingRevision !== state.get().routingRevision) fail('ROUTE_CONFLICT', '目录路由已变化', 409)
|
|
553
|
+
}
|
|
554
|
+
assertDirectory()
|
|
555
|
+
const index = MARKET_INDEX[input.market]
|
|
556
|
+
const overview = index && !data.syncing && !stale && !(Number(input.offset) > 0) ? await browseOverview(index, signal) : null
|
|
557
|
+
assertDirectory()
|
|
558
|
+
return { ...data, overview, catalogs: catalog.status(), routingRevision }
|
|
438
559
|
},
|
|
439
|
-
async sync(input) {
|
|
560
|
+
async sync(input, signal) {
|
|
440
561
|
assertLive()
|
|
441
562
|
if (!MARKET_META[input.market] || input.expectedRoutingRevision !== state.get().routingRevision) fail('ROUTE_CONFLICT', '目录路由已变化', 409)
|
|
442
563
|
// 只同步该市场真实配置的能力: 默认参数同时要目录+日历, 没配日历时每次手动同步都必然回一条 NO_ROUTE 错误
|
|
443
564
|
const capabilities = ['catalog', 'calendar'].filter(capability => state.get().routes.some(route => route.capability === capability && route.market === input.market))
|
|
444
565
|
if (!capabilities.length) fail('NO_ROUTE', '该市场未配置目录或日历来源', 422)
|
|
445
|
-
const result = await catalog.sync(input.market, capabilities); collector.reconcile(); return result
|
|
566
|
+
const result = await catalog.sync(input.market, capabilities, signal); collector.reconcile(); return result
|
|
446
567
|
},
|
|
447
568
|
async watchlist(operation) {
|
|
448
569
|
assertLive()
|
|
@@ -454,10 +575,13 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
454
575
|
// 密钥只写宿主的凭据存储, 不回显也不落插件状态;引用必须已被某个数据源声明, 插件不越界写别人的密钥空间。
|
|
455
576
|
async credential(input) {
|
|
456
577
|
assertLive()
|
|
578
|
+
const control = getControl()
|
|
579
|
+
if (input.expectedServerEpoch !== undefined && input.expectedServerEpoch !== serverEpoch) fail('REVISION_CONFLICT', '服务已重启,请刷新配置后重新确认', 409, { revision: control.revision })
|
|
580
|
+
if (input.expectedRoutingRevision !== undefined && input.expectedRoutingRevision !== control.routingRevision) fail('ROUTE_CONFLICT', '路由配置已变化', 409)
|
|
457
581
|
const credentialStore = credentialStoreOf()
|
|
458
582
|
if (!credentialStore) fail('UNSUPPORTED', '宿主未提供凭据服务', 501)
|
|
459
583
|
const ref = z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).parse(input.ref)
|
|
460
|
-
if (!
|
|
584
|
+
if (!control.providers.some(p => p.credentialRef === ref || p.proxyCredentialRef === ref)) fail('INVALID_REQUEST', '该凭据未被任何数据源使用', 422)
|
|
461
585
|
const value = input.value === null ? null : z.string().min(1).max(512).parse(input.value)
|
|
462
586
|
if (value === null) await credentialStore.unset(ref)
|
|
463
587
|
else await credentialStore.set(ref, value)
|
|
@@ -499,14 +623,31 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
499
623
|
assertLive()
|
|
500
624
|
const config = state.get(), route = config.routes.find(r => r.id === input.routeId)
|
|
501
625
|
if (!route || input.target !== 'primary' || input.expectedRoutingRevision !== config.routingRevision) fail('ROUTE_CONFLICT', '路由配置已变化', 409)
|
|
626
|
+
const { routingRevision } = config
|
|
502
627
|
const instance = config.providers.find(p => p.id === route.primaryInstanceId)
|
|
503
|
-
const
|
|
504
|
-
|
|
628
|
+
const assertCurrent = () => {
|
|
629
|
+
if (routingRevision !== getControl().routingRevision || router.selections()[route.id]?.routeEpoch !== input.expectedRouteEpoch) fail('ROUTE_CONFLICT', '来源已变化', 409)
|
|
630
|
+
}
|
|
631
|
+
const beforeDispatch = () => {
|
|
632
|
+
assertCurrent()
|
|
633
|
+
assertSourceReady(route.capability, instance.id, routingRevision)
|
|
634
|
+
}
|
|
505
635
|
registry.validate(instance, route)
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
636
|
+
beforeDispatch()
|
|
637
|
+
// 回切前按路由自身的能力探测一次。
|
|
638
|
+
let checked
|
|
639
|
+
try {
|
|
640
|
+
checked = await executor.run(instance, route.capability, { market: route.market, instrument: route.instrument }, { probe: true, signal, beforeDispatch })
|
|
641
|
+
} catch (e) {
|
|
642
|
+
if (signal?.aborted) throw e
|
|
643
|
+
assertCurrent()
|
|
644
|
+
coolOnError(route.capability, instance.id, routingRevision, e)
|
|
645
|
+
throw e
|
|
646
|
+
}
|
|
647
|
+
beforeDispatch()
|
|
648
|
+
if (checked?.status !== 'ready' || checked.capability !== route.capability) fail('CHECK_REQUIRED', '主源未就绪', 422)
|
|
649
|
+
router.switchPrimary(route.id, input.expectedRouteEpoch)
|
|
650
|
+
return snapshot()
|
|
510
651
|
},
|
|
511
652
|
async close() { stopped = true; recoveryLoop?.stop(); trendCache.dispose(); executor.dispose(); await recoveryLoop?.idle?.(); demand.dispose(); collector.dispose(); const cacheClosed = catalog.dispose(); await cacheClosed; await ensuring; await state.close() },
|
|
512
653
|
}
|
package/src/budget.mjs
CHANGED
|
@@ -1,33 +1,34 @@
|
|
|
1
1
|
import { fail } from './market-model.mjs'
|
|
2
|
-
const
|
|
2
|
+
export const BUDGET_MINUTE_MS = 60 * 1000
|
|
3
|
+
const MINUTE = BUDGET_MINUTE_MS
|
|
3
4
|
export function createBudget(now = Date.now) {
|
|
4
5
|
const groups = new Map()
|
|
5
6
|
return {
|
|
6
|
-
reserve(instance, capability, count = 1, periodic = false, probe = false) {
|
|
7
|
+
reserve(instance, capability, count = 1, periodic = false, probe = false, at = now()) {
|
|
7
8
|
const key = instance.quotaGroup, budget = instance.budget
|
|
8
|
-
const day = new Date(
|
|
9
|
+
const day = new Date(at + 8 * 60 * MINUTE).toISOString().slice(0, 10)
|
|
9
10
|
if (!groups.has(key)) groups.set(key, { day, dayCount: 0, rows: [], last: -Infinity, blocked: 0 })
|
|
10
11
|
const s = groups.get(key)
|
|
11
12
|
if (day !== s.day) { s.day = day; s.dayCount = 0 }
|
|
12
|
-
s.rows = s.rows.filter(r =>
|
|
13
|
-
const limited = wait => fail('RATE_LIMIT', '数据源额度受限,请稍后重试', 429, { retryAfterMs: Math.max(1000, wait), retryable: true })
|
|
13
|
+
s.rows = s.rows.filter(r => at - r.at < MINUTE)
|
|
14
|
+
const limited = (wait, budgetLimit) => fail('RATE_LIMIT', '数据源额度受限,请稍后重试', 429, { retryAfterMs: Math.max(1000, wait), retryable: true, ...(budgetLimit ? { budgetLimit } : {}) })
|
|
14
15
|
if (budget.requestsPerMinute === null) {
|
|
15
16
|
if (!probe) fail('BUDGET_UNKNOWN', '账号额度未确认,请先在设置中填写实际预算', 422)
|
|
16
|
-
if (
|
|
17
|
-
if (s.blocked >
|
|
18
|
-
s.last =
|
|
17
|
+
if (at - s.last < 10 * 1000) limited(10 * 1000 - (at - s.last))
|
|
18
|
+
if (s.blocked > at) limited(s.blocked - at)
|
|
19
|
+
s.last = at; s.rows.push({ at, capability, count }); s.dayCount++; return
|
|
19
20
|
}
|
|
20
|
-
if (s.blocked >
|
|
21
|
-
if (
|
|
21
|
+
if (s.blocked > at) limited(s.blocked - at)
|
|
22
|
+
if (at - s.last < 1000) limited(1000 - (at - s.last))
|
|
22
23
|
const fraction = periodic ? 0.9 : 1
|
|
23
24
|
const cap = Math.max(1, Math.floor(budget.requestsPerMinute * fraction))
|
|
24
25
|
const subcap = Math.max(1, Math.floor((budget.capabilityLimits[capability] || budget.requestsPerMinute) * fraction))
|
|
25
26
|
const sub = s.rows.filter(r => r.capability === capability)
|
|
26
|
-
if (s.
|
|
27
|
-
if (
|
|
28
|
-
if (
|
|
29
|
-
if (budget.billingUnit === 'symbol' && s.rows.reduce((sum, r) => sum + r.count, 0) + count > budget.symbolCreditsPerMinute) limited((s.rows[0]?.at ??
|
|
30
|
-
s.rows.push({ at
|
|
27
|
+
if (budget.dailyRequestLimit && s.dayCount >= budget.dailyRequestLimit) limited(24 * 60 * MINUTE - (at + 8 * 60 * MINUTE) % (24 * 60 * MINUTE), 'day')
|
|
28
|
+
if (s.rows.length >= cap) limited(s.rows[0].at + MINUTE - at, 'minute')
|
|
29
|
+
if (sub.length >= subcap) limited(sub[0].at + MINUTE - at, 'minute')
|
|
30
|
+
if (budget.billingUnit === 'symbol' && s.rows.reduce((sum, r) => sum + r.count, 0) + count > budget.symbolCreditsPerMinute) limited((s.rows[0]?.at ?? at) + MINUTE - at, 'minute')
|
|
31
|
+
s.rows.push({ at, capability, count }); s.last = at; s.dayCount++
|
|
31
32
|
},
|
|
32
33
|
block(instance, ms) { const s = groups.get(instance.quotaGroup); if (s) s.blocked = Math.max(s.blocked, now() + ms) },
|
|
33
34
|
}
|