@mzzsfy/dsh-stock-assistant 0.8.0 → 0.9.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.
@@ -1,400 +1,400 @@
1
- import { randomUUID } from 'node:crypto'
2
- import { z } from 'zod'
3
- import { createRegistry } from './provider-registry.mjs'
4
- import { createRouter, RECOVERY_PROBE_MS, TRANSIENT_CODES } from './provider-router.mjs'
5
- import { createRecovery, createRecoveryLoop } from './recovery.mjs'
6
- import { tushare } from './providers/tushare.mjs'
7
- import { tencent } from './providers/tencent.mjs'
8
- import { sina } from './providers/sina.mjs'
9
- import { eastmoney } from './providers/eastmoney.mjs'
10
- import { xueqiu } from './providers/xueqiu.mjs'
11
- import { finnhub } from './providers/finnhub.mjs'
12
- import { openState, digest } from './state.mjs'
13
- import { parseConfiguration, preferencesSchema, defaultConfig, klineQuerySchema, refreshSecuritiesSchema, CAPABILITIES, TREND_ROUTE_MIGRATION, tickPeriodMs } from './schemas.mjs'
14
- import { createWatchlistService } from './service.mjs'
15
- import { createBudget } from './budget.mjs'
16
- import { createExecutor } from './executor.mjs'
17
- import { createCollector, deriveDelay } from './collector.mjs'
18
- import { createCatalog } from './catalog.mjs'
19
- import { createDemand } from './demand.mjs'
20
- import { createKlineCache } from './kline-cache.mjs'
21
- import { createTrendCache } from './trend-cache.mjs'
22
- import { createTickStore } from './ticks.mjs'
23
- import { fail, parseSecurityId, MARKET_META, clockInZone } from './market-model.mjs'
24
- const WINDOW = 5 * 60 * 1000
25
- // 分时来源(东财/腾讯)的时间戳统一按北京时间给出, 拍点线的横轴必须与之一致, 否则切到离线时整体偏移
26
- const TREND_SOURCE_TIME_ZONE = 'Asia/Shanghai'
27
- const US_SYMBOL_TTL = 24 * 60 * 60 * 1000
28
- const US_SYMBOL_LIMIT = 500
29
- export async function createApplication({ storageDomain, providers = [tushare, tencent, sina, eastmoney, xueqiu, finnhub], publish = () => {}, env = process.env, credentials = null, fetch = globalThis.fetch, now = Date.now, timers = globalThis, vendorAvailable = true }) {
30
- const serverEpoch = randomUUID(), checks = new Map()
31
- // 凭据解析: 宿主提供 credentials 服务时交给它(插件存储层优先, 再逐层回退到进程环境与 .env 文件),
32
- // 否则退回进程环境变量。引用只表示"哪个密钥", 值始终由宿主保管。
33
- // 接口按能力逐个核对: 宿主给的对象缺哪个方法, 就只退回哪条路径, 而不是在取数时炸掉。
34
- const credentialStore = credentials && ['resolve', 'set', 'unset'].every(method => typeof credentials[method] === 'function') ? credentials : null
35
- const resolveCredential = credentialStore ? async ref => (await credentialStore.resolve(ref))?.value : async ref => env[ref]
36
- let snapshotSeq = 0, stopped = false, collector, catalog, demand, watchlist, recoveryLoop
37
- let ensuring = null, lastEnsure = -Infinity, ensureError = null, hadDemand = false, ensureCaches = () => {}
38
- const usSymbols = new Map()
39
- const touched = () => snapshotSeq++
40
- const changed = () => { touched(); publish({ type: 'invalidate', serverEpoch, snapshotSeq, scopes: ['snapshot'] }) }
41
- // 凭据存在性只给设置页看, 而解析是异步的、快照是同步的: 保存配置与启动时各算一次, 快照读这份结果。
42
- const credentialPresence = new Map()
43
- const refreshCredentialPresence = async () => {
44
- for (const p of state.get().providers) {
45
- credentialPresence.set(`${p.id}:credential`, p.credentialRef === null || !!(await resolveCredential(p.credentialRef)))
46
- if (p.proxyCredentialRef) credentialPresence.set(`${p.id}:proxy`, !!(await resolveCredential(p.proxyCredentialRef)))
47
- }
48
- }
49
- let state, registry, executor, getControl, router, klineCache, trendCache, ticks
50
- try {
51
- state = await openState(storageDomain, changed, now)
52
- await refreshCredentialPresence()
53
- registry = createRegistry(providers)
54
- const budget = createBudget(now)
55
- // 代理出口: undici ProxyAgent + 同一份 undici.fetch。dispatcher 是 undici 私有契约,
56
- // Node 内置 fetch 不认 userland dispatcher(invalid onRequestStart method), 不能混用。
57
- // 包不可用时两者都为 null, 代理实例在请求时明确 NETWORK/502, 不静默直连。
58
- let proxyFactory = null, proxyFetch = null
59
- try {
60
- const undici = await import('undici')
61
- if (typeof undici.fetch === 'function') { proxyFactory = url => new undici.ProxyAgent(url); proxyFetch = (...args) => undici.fetch(...args) }
62
- } catch {}
63
- executor = createExecutor({ registry, budget, env, resolveCredential, fetch, proxyFetch, now, timers, usSymbols, proxyFactory, tickPeriodMs: () => tickPeriodMs(state.get().preferences) })
64
- getControl = state.get
65
- // 自动故障切换/手动回主源只换来源: 清掉该路由的退避与失败计数即可, 不能重置 collector。
66
- // 重置会递增代次并中止在飞请求, 当前刷新随后被判定成"配置已变化"抛假 ROUTE_CONFLICT。
67
- router = createRouter(getControl, now, routeId => collector?.routeChanged(routeId))
68
- klineCache = createKlineCache({ cacheTable: state.klineCache, now })
69
- // 分时当日缓存走独立小池: 它与报价拍点都只放内存, 不入配置记录
70
- trendCache = createTrendCache({ table: state.trendCache, now })
71
- ticks = createTickStore({ now })
72
- // 回探跟着面板活跃走: 有人看时每 RECOVERY_PROBE_MS 把已降级路由的上级全探一遍, 没人看就停
73
- recoveryLoop = createRecoveryLoop({ probe: createRecovery({ getControl, router, executor }), timers, interval: RECOVERY_PROBE_MS, canRun: () => executor.idle() })
74
- catalog = createCatalog({ state, getControl, router, executor, registry, now, changed })
75
- demand = createDemand(() => {
76
- const wanted = demand.active(), opening = wanted && !hadDemand; hadDemand = wanted
77
- if (wanted) {
78
- // 缓存新鲜时进入面板不重复打上游(限流主因); 过期才拉取, 定时器照常量节奏维持
79
- const freshFor = (getControl().preferences?.refreshSeconds ?? 15) * 1000
80
- if (opening && !collector?.freshWithin(freshFor)) collector?.refresh().catch(() => {})
81
- collector?.reconcile()
82
- } else {
83
- // 后台预热只在面板空闲时做: 之前只写在 wanted 分支又要求 !demand.active(), 两个条件互斥,
84
- // 目录/日历永远不会在后台补, 过期目录只能等用户手动同步。
85
- collector?.cancelIdle(); ensureCaches()
86
- }
87
- // 排在首屏刷新之后: 探测也占额度, 不该跟用户要的数据抢顺序
88
- recoveryLoop.sync(wanted)
89
- }, now, timers)
90
- collector = createCollector({ getControl, router, registry, executor, resolveSecurity: catalog.resolve, changed, touched, now, timers, active: demand.active, calendarState: catalog.marketState, ticks })
91
- watchlist = createWatchlistService(state, catalog.resolve, now)
92
- // 存量配置升级: 分时能力独立后没有 trend 路由的库在打开时补齐。
93
- // 补齐失败不该让整个面板躺下(面板可用性高于分时), 记下原因继续, 与目录预热同构
94
- try { await ensureTrendRoutes() } catch (e) { ensureError = { message: `分时来源补齐失败:${e.message}`, at: now() } }
95
- // 面板活跃(demand)时让路: 目录后台同步占满并发槽会拖死交互请求(浏览504实测), 仅在面板空闲时补目录
96
- ensureCaches = () => {
97
- if (ensuring || now() - lastEnsure < 60 * 1000 || demand.active()) return
98
- lastEnsure = now()
99
- ensuring = catalog.ensure().catch(e => { ensureError = { message: e.message, at: now() }; changed() }).finally(() => { ensuring = null; collector?.reconcile() })
100
- }
101
- } catch (e) {
102
- // 打开成功后任何一步初始化失败都要关域: 否则同名域一直占着已打开槽位, 重载只会一直 already-open。
103
- // 关域自身抛错不能盖掉原始原因。
104
- try { await state?.close() } catch {}
105
- throw e
106
- }
107
- const snapshot = () => {
108
- const control = state.get(); delete control.operations
109
- return { serverEpoch, snapshotSeq, routingRevision: control.routingRevision, control, quotes: collector.watchEntries(), 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 || credentialPresence.get(`${p.id}:credential`) === true, credentialRef: p.credentialRef, proxy: !!p.proxy, proxyCredentialRef: p.proxyCredentialRef ?? null, proxyCredentialPresent: p.proxyCredentialRef ? credentialPresence.get(`${p.id}:proxy`) === true : 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 }])) }
110
- }
111
- function assertLive() { if (stopped) fail('STOPPED', '股票工具已停止', 503) }
112
- async function providerCheck(input, signal) {
113
- assertLive()
114
- const config = parseConfiguration({ providers: input.providers, routes: input.routes })
115
- const caps = z.array(z.enum(CAPABILITIES)).min(1).max(CAPABILITIES.length).parse(input.capabilities)
116
- const at = now()
117
- for (const [id, check] of checks) if (check.until <= at) checks.delete(id)
118
- if (checks.size >= 64) fail('CHECK_LIMIT', '检查请求过多,请稍后重试', 429)
119
- const results = []
120
- for (const route of config.routes.filter(r => caps.includes(r.capability))) for (const target of [route.primaryInstanceId, ...route.fallbackInstanceIds]) {
121
- const instance = config.providers.find(p => p.id === target)
122
- registry.validate(instance, route)
123
- const key = `${instance.id}:${route.capability}:${route.market}`
124
- if (results.some(r => r.key === key)) continue
125
- // 探针耗时就是这一条路由端到端拿数据的真实延迟, 用于把「能不能用」和「快不快」一起回给用户
126
- const startedAt = now()
127
- try {
128
- const result = await executor.run(instance, route.capability, { market: route.market, instrument: route.instrument }, { probe: true, signal })
129
- // 探针必须由同名能力的端点产出: 适配器拿别的能力冒充(漏实现分支)时不能当就绪, 且要说清是谁被验了
130
- const ready = result?.status === 'ready' && result.capability === route.capability
131
- results.push({ key, providerInstanceId: instance.id, capability: route.capability, market: route.market, status: ready ? 'ready' : 'unavailable', ms: now() - startedAt, ...(ready ? {} : { error: { code: 'PROBE_MISMATCH', message: `探针校验的是${result?.capability ?? '未知'}能力` } }) })
132
- } catch (e) { results.push({ key, providerInstanceId: instance.id, capability: route.capability, market: route.market, status: 'denied', ms: now() - startedAt, error: { code: e.code, message: e.message } }) }
133
- }
134
- const checkId = randomUUID()
135
- checks.set(checkId, { hash: digest(config), until: now() + WINDOW, results })
136
- // 解除采集暂停只认行情: 分时/目录/K 线的探针失败不该左右行情采集状态机
137
- const quoteResults = results.filter(r => r.capability === 'quotes')
138
- if (digest(config) === digest({ providers: getControl().providers, routes: getControl().routes }) && quoteResults.length && quoteResults.every(r => r.status === 'ready')) collector.resume()
139
- return { checkId, checks: results }
140
- }
141
- async function configuration(operation) {
142
- assertLive()
143
- const config = parseConfiguration(operation.payload)
144
- const replay = state.replay({ ...operation, action: 'configuration', payload: config })
145
- if (replay) return replay
146
- // 保存不做连通性闸门: 探针是给人看的诊断信息, 不该把人挡在门外。契约只校验路由自身的合法性,
147
- // 按能力挑源已经由前端按适配器能力过滤, 后端再校验一次目标是否具备该能力即可。
148
- for (const route of config.routes) {
149
- for (const target of [route.primaryInstanceId, ...route.fallbackInstanceIds]) registry.validate(config.providers.find(p => p.id === target), route)
150
- }
151
- const result = await state.mutate({ ...operation, action: 'configuration', payload: config }, current => {
152
- if (JSON.stringify(current.providers) === JSON.stringify(config.providers) && JSON.stringify(current.routes) === JSON.stringify(config.routes)) return current
153
- return { ...current, ...config, routingRevision: current.routingRevision + 1 }
154
- })
155
- if (!result.unchanged) { router.reset(); collector.reset(); await refreshCredentialPresence() }
156
- return result
157
- }
158
-
159
- // 搜索候选项服务端补全市场元数据(单一事实源 MARKET_META),client 零映射表。
160
- function decorateWithMarketMeta(items) {
161
- for (const item of items) if (item?.exchange && !item.currency) {
162
- const meta = MARKET_META[item.exchange]
163
- if (meta) { item.currency = meta.currency; item.priceScale = meta.priceScale }
164
- }
165
- }
166
- // K 线类请求的即时故障转移: 触发码 NETWORK/TIMEOUT/BAD_PAYLOAD 时顺着「环上下一格」试一次;
167
- // 只有当前选择自己的失败算一轮, 顺着链试备源是同一轮里的补救, 不额外计次
168
- async function runWithFailover(capability, route, primary, fallbacks, request, signal) {
169
- const chain = [primary, ...fallbacks]
170
- let lastError, unsupported
171
- for (const [index, cand] of chain.entries()) {
172
- try {
173
- const result = await executor.run(cand, capability, request, { signal })
174
- // 当前选择能出数就是最好的证据: 清掉它的失败计数与探测退避
175
- if (index === 0) router.recordRound(route.id, null)
176
- return result
177
- } catch (e) {
178
- if (index === 0) router.recordRound(route.id, e)
179
- // 备源不支持这个能力就继续试下一个; 用户该看到的是主源的真实错误, 不是备源的描述符差异
180
- if (e.code === 'UNSUPPORTED_CAPABILITY') { unsupported ??= e; continue }
181
- lastError = e
182
- if (!TRANSIENT_CODES.includes(e.code) && e.code !== 'BAD_PAYLOAD') throw e
183
- }
184
- }
185
- throw lastError ?? unsupported
186
- }
187
- // 分时没有路由时用户只会看到"未配置数据来源", 看不出缺的是哪一种能力
188
- function selectRoute(capability, market) {
189
- try { return router.select(capability, market, 'equity') }
190
- catch (e) {
191
- if (capability === 'trend' && e.code === 'NO_ROUTE') fail('NO_ROUTE', '未配置分时来源:请在设置的能力路由里为分时指定来源', 422)
192
- throw e
193
- }
194
- }
195
- // 分时拆成独立能力之前的存量配置没有 trend 路由: 打开时按适配器能力声明补齐, 优先沿用该市场 K 线的来源。
196
- // 不能假设某个具体来源: 谁声明了 trend 且覆盖该市场, 谁才有资格承接下来。
197
- async function ensureTrendRoutes() {
198
- const control = state.get()
199
- if (control.routeMigration >= TREND_ROUTE_MIGRATION) return
200
- const declared = registry.descriptors()
201
- const capable = (instance, market) => {
202
- const descriptor = declared.find(d => d.adapterId === instance.adapterId)
203
- return !!descriptor?.capabilities.includes('trend') && descriptor.markets.includes(market)
204
- }
205
- // 市场面取现有任意路由: 分时不依赖 K 线, 用户删掉 K 线路由不代表这个市场不要分时
206
- const markets = [...new Set(control.routes.map(r => r.market))]
207
- const missing = [], spares = []
208
- for (const market of markets) {
209
- const route = control.routes.find(r => r.market === market && r.capability === 'trend')
210
- if (!route) {
211
- const kline = control.routes.find(r => r.market === market && r.capability === 'kline')
212
- const order = [kline?.primaryInstanceId, ...control.providers.map(p => p.id)].filter(Boolean)
213
- const target = order.map(id => control.providers.find(p => p.id === id)).find(instance => instance?.enabled !== false && capable(instance, market))
214
- if (target) missing.push({ id: `${market.toLowerCase()}-trend`, capability: 'trend', market, instrument: 'equity', primaryInstanceId: target.id, fallbackInstanceIds: [], failoverMode: 'off', maxDelaySeconds: null, acceptUnknownDelay: true })
215
- continue
216
- }
217
- // 主源不该是唯一来源: 分时只有一个来源时, 它一断就整块空白。把其它声明分时的实例登记为网络失败后的备源
218
- // 已有备用源的不再追加: 自动切换是用户开关, 迁移既不替他打开, 也不改他已经配好的备用链
219
- if (route.fallbackInstanceIds.length) continue
220
- const spare = control.providers.find(p => p.enabled !== false && p.id !== route.primaryInstanceId && capable(p, market))
221
- if (spare) spares.push({ id: route.id, fallback: spare.id })
222
- }
223
- // 一条也补不出来且当前没有任何分时路由, 说明只是「暂时没有可用分时源」: 不烧迁移标记,
224
- // 之后装上声明分时的源还能自动补; 已有分时路由(或刚补出来)才算迁移完成, 用户删掉后不该复活
225
- if (!missing.length && !spares.length && !control.routes.some(r => r.capability === 'trend')) return
226
- const patch = route => {
227
- const spare = spares.find(s => s.id === route.id)
228
- return spare ? { ...route, fallbackInstanceIds: [...route.fallbackInstanceIds, spare.fallback], failoverMode: 'network' } : route
229
- }
230
- await state.mutate({ operationId: randomUUID(), expectedRevision: control.revision, action: 'trend-routes', payload: { added: missing.map(r => r.id), spared: spares.map(s => s.id) } }, current => ({ ...current, routeMigration: TREND_ROUTE_MIGRATION, routes: [...current.routes.map(patch), ...missing], routingRevision: missing.length || spares.length ? current.routingRevision + 1 : current.routingRevision }))
231
- }
232
-
233
- // 分时离线兜底: 只续在当日真实分时后面。
234
- // 没有真实分时打底时, 几个报价点连成的线说明不了走势, 不如把上游错误如实抛出去
235
- async function offlineTrend({ market, code, limit, securityId }, error) {
236
- const cached = await trendCache.get({ market, code, limit })
237
- if (!cached) return null
238
- const real = cached.payload.candles || []
239
- const lastAt = Number(real.at(-1)?.at)
240
- // 只补最后一根之后、且不在同一分钟的新报价: 早于它的已经在图里, 同一分钟的会画成重复的一根
241
- const lastMinute = Math.floor(lastAt / 60)
242
- const extra = Number.isFinite(lastAt) ? ticks.series(securityId, market).filter(point => point.at > lastAt && Math.floor(point.at / 60) > lastMinute) : []
243
- const appended = extra.map(point => ({ time: clockInZone(TREND_SOURCE_TIME_ZONE, point.at), at: point.at, open: point.price, high: point.price, low: point.price, close: point.price }))
244
- return {
245
- ...cached.payload,
246
- ...(appended.length ? { complete: false } : {}),
247
- // 拍点只有收盘价: 开高低补齐成同一个值, 否则客户端按 OHLC 校验会把每根都丢掉, 图上仍然是空的
248
- candles: [...real, ...appended],
249
- offline: { kind: 'cache', cachedAt: cached.cachedAt, appended: appended.length, reason: error.message },
250
- }
251
- }
252
-
253
- return {
254
- snapshot, providerCheck, configuration,
255
- demand(message) { assertLive(); demand.update(message) },
256
- async search(q, phase = 'local', signal) {
257
- assertLive()
258
- if (typeof q !== 'string' || [...q].length > 100) fail('INVALID_QUERY', '搜索词过长')
259
- const items = phase === 'remote' ? await catalog.remote(q, signal) : catalog.search(q)
260
- decorateWithMarketMeta(items)
261
- const routingRevision = state.get().routingRevision
262
- if (phase === 'remote') {
263
- for (const item of items) {
264
- const row = item.raw && typeof item.raw === 'object' ? item.raw : null
265
- if (row?.MktNum && /^10[567]$/.test(row.MktNum)) {
266
- usSymbols.set(`US:${row.Code}`, { mktNum: row.MktNum, jys: row.JYS || null, at: now() })
267
- while (usSymbols.size > US_SYMBOL_LIMIT) usSymbols.delete(usSymbols.keys().next().value)
268
- }
269
- }
270
- }
271
- for (const [key, value] of usSymbols) if (now() - value.at > US_SYMBOL_TTL) usSymbols.delete(key)
272
- return { items, catalogs: catalog.status(), routingRevision }
273
- },
274
- async kline(input, signal) {
275
- assertLive()
276
- const parsed = klineQuerySchema.safeParse(input)
277
- if (!parsed.success) fail('INVALID_PARAM', 'K线请求参数无效', 400)
278
- const { securityId: sid, period, limit, force } = parsed.data
279
- let exchange, code
280
- try { ({ exchange, code } = parseSecurityId(sid)) } catch { fail('INVALID_PARAM', '证券身份无效', 400) }
281
- const config = state.get()
282
- // 分时与日/周/月是两种上游, 各走各的路由: K 线来源不供分时时, 分时不该跟着一起死
283
- const capability = period === 'trend' ? 'trend' : 'kline'
284
- const { route, instance } = selectRoute(capability, exchange)
285
- // 同轮补救只取环上的下一格: 走到末级时回到主源, 否则末级是死胡同
286
- const next = router.nextInRing(route.id, instance.id)
287
- const fallbacks = next ? config.providers.filter(p => p.id === next && p.enabled !== false && p.budget?.requestsPerMinute !== null) : []
288
- // force=1 跳过缓存读(详情页手动刷新);分时每次真取, 缓存只在上游失败时用
289
- if (capability === 'kline' && force !== '1') {
290
- for (const cand of [instance, ...fallbacks.filter(spare => spare.id !== instance.id)]) {
291
- const cached = await klineCache.get({ providerInstanceId: cand.id, market: exchange, period, code, limit }, config.routingRevision)
292
- if (cached) return { ...cached.payload, source: cand.id, revision: config.revision }
293
- }
294
- }
295
- const result = await runWithFailover(capability, route, instance, fallbacks, { securityId: sid, market: exchange, code, period, adjust: 'qfq', limit }, signal).catch(async error => {
296
- // 分时没有别的来源可退: 有当日真实分时就拿它兜底并续上之后的报价点, 没有就如实报错
297
- if (capability !== 'trend') throw error
298
- const offline = await offlineTrend({ market: exchange, code, limit, securityId: sid }, error)
299
- if (!offline) throw error
300
- return offline
301
- })
302
- if (capability === 'kline') await klineCache.put({ providerInstanceId: result.providerInstanceId, market: exchange, period, code, limit }, result, config.routingRevision)
303
- // 成功一次就覆盖当日缓存: 离线时它就是"最后一个完整的分时"; 兜底结果与空结果由缓存自己挡掉
304
- else await trendCache.put({ market: exchange, code, limit }, result)
305
- return { ...result, source: result.providerInstanceId, revision: config.revision }
306
- },
307
- async browse(input) {
308
- assertLive()
309
- if (!MARKET_META[input.market]) fail('INVALID_REQUEST', '市场参数无效')
310
- // 市场概览: 代表指数不入目录/自选, 走 quotes 管道直拉; 失败静默为 null 不阻断目录浏览
311
- const INDEX = { XSHG: { id: 'XSHG:index:000001', exchange: 'XSHG', code: '000001', name: '上证指数' }, XSHE: { id: 'XSHE:index:399001', exchange: 'XSHE', code: '399001', name: '深证成指' }, XHKG: { id: 'XHKG:index:HSI', exchange: 'XHKG', code: 'HSI', name: '恒生指数' }, XNAS: { id: 'XNAS:index:NDX', exchange: 'XNAS', code: 'NDX', name: '纳斯达克100' }, XNYS: { id: 'XNYS:index:DJI', exchange: 'XNYS', code: 'DJI', name: '道琼斯' }, XJPX: { id: 'XJPX:index:N225', exchange: 'XJPX', code: 'N225', name: '日经225' }, XKRX: { id: 'XKRX:index:KOSPI', exchange: 'XKRX', code: 'KOSPI', name: '韩国综指' }, XLON: { id: 'XLON:index:FTSE', exchange: 'XLON', code: 'FTSE', name: '富时100' } }
312
- const index = INDEX[input.market]
313
- // 概览指数是装饰性数据: 无路由或拉取失败(含5s短超时不与目录翻页争槽)都静默为 null, 不阻断目录浏览
314
- let overview = null
315
- // 概览时段与采集同源: 都走 catalog.marketState(日历 + 市场本地时段), 不用来源字段猜
316
- const phase = catalog.marketState(input.market)
317
- try {
318
- const route = router.select('quotes', input.market)
319
- if (route.instance) {
320
- const result = await executor.run(route.instance, 'quotes', { securities: [{ id: index.id, exchange: index.exchange, code: index.code }], routingRevision: state.get().routingRevision }, { signal: AbortSignal.timeout(5 * 1000) })
321
- const quote = result.items?.find(q => q.securityId === index.id)
322
- if (quote && quote.last !== null) { deriveDelay(quote, now, ['trading', 'auction', 'unknown'].includes(phase.state)); overview = { name: index.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 } }
323
- }
324
- } catch {}
325
- return { ...await catalog.browse(input), overview, catalogs: catalog.status(), routingRevision: state.get().routingRevision }
326
- },
327
- async sync(input) {
328
- assertLive()
329
- if (!MARKET_META[input.market] || input.expectedRoutingRevision !== state.get().routingRevision) fail('ROUTE_CONFLICT', '目录路由已变化', 409)
330
- // 只同步该市场真实配置的能力: 默认参数同时要目录+日历, 没配日历时每次手动同步都必然回一条 NO_ROUTE 错误
331
- const capabilities = ['catalog', 'calendar'].filter(capability => state.get().routes.some(route => route.capability === capability && route.market === input.market))
332
- if (!capabilities.length) fail('NO_ROUTE', '该市场未配置目录或日历来源', 422)
333
- const result = await catalog.sync(input.market, capabilities); collector.reconcile(); return result
334
- },
335
- async watchlist(operation) {
336
- assertLive()
337
- const result = await watchlist.execute(operation)
338
- // 移除后立即丢弃该标的行情; 否则已删自选的旧报价仍留在 /snapshot 并无限累积
339
- if (operation.action === 'remove' && operation.payload?.securityId) collector.prune(operation.payload.securityId)
340
- collector.reconcile(); return result
341
- },
342
- // 密钥只写宿主的凭据存储, 不回显也不落插件状态;引用必须已被某个数据源声明, 插件不越界写别人的密钥空间。
343
- async credential(input) {
344
- assertLive()
345
- if (!credentialStore) fail('UNSUPPORTED', '宿主未提供凭据服务', 501)
346
- const ref = z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).parse(input.ref)
347
- if (!state.get().providers.some(p => p.credentialRef === ref || p.proxyCredentialRef === ref)) fail('INVALID_REQUEST', '该凭据未被任何数据源使用', 422)
348
- const value = input.value === null ? null : z.string().min(1).max(512).parse(input.value)
349
- if (value === null) await credentialStore.unset(ref)
350
- else await credentialStore.set(ref, value)
351
- await refreshCredentialPresence()
352
- // 填入正确密钥后立即解除引用该凭据实例的 AUTH 永久暂停, 不必再点一次"检查所有来源"
353
- collector.recoverCredential(ref)
354
- return { ref, present: value !== null }
355
- },
356
- async preferences(operation) {
357
- assertLive()
358
- const parsed = preferencesSchema.partial().safeParse(operation.payload)
359
- if (!parsed.success) fail('INVALID_PREFERENCES', '显示偏好无效')
360
- // partial 会给缺省键补默认值, 合并时只取本次提交的键, 否则半更新会把另一项重置成默认
361
- const submitted = operation.payload && typeof operation.payload === 'object' ? operation.payload : {}
362
- const patch = Object.fromEntries(Object.entries(parsed.data).filter(([key, value]) => Object.hasOwn(submitted, key) && value !== undefined))
363
- const result = await state.mutate({ ...operation, action: 'preferences' }, current => ({ ...current, preferences: { ...current.preferences, ...patch } }))
364
- collector.reconcile(); return result
365
- },
366
- async refresh(input = {}, signal) {
367
- assertLive()
368
- if (input.expectedRoutingRevision !== undefined && input.expectedRoutingRevision !== state.get().routingRevision) fail('ROUTE_CONFLICT', '路由配置已变化', 409)
369
- const submitted = input.securities === undefined ? undefined : refreshSecuritiesSchema.safeParse(input.securities)
370
- if (submitted && !submitted.success) {
371
- const [first] = submitted.error.issues, path = first.path.length ? first.path.join('.') : '根'
372
- fail('INVALID_REFRESH', `刷新证券参数无效:${path} ${first.message}`, 400)
373
- }
374
- let quotes
375
- try { quotes = await collector.refresh(submitted?.data, { signal }) } catch (e) {
376
- // peek 刷新失败时 collector 里还留着带 lastError 的条目(否则详情只剩"等待报价");
377
- // 常驻快照按自选过滤会顺手删掉它, 这里在快照构造前抓一份只随本次错误下发的报价。
378
- const failed = collector.entries()
379
- e.snapshot = { ...snapshot(), quotes: failed }
380
- throw e
381
- }
382
- // peek 报价只随本次响应下发, 不进常驻快照: 详情关闭后服务端不再保留任何非自选报价
383
- return { ...snapshot(), quotes }
384
- },
385
- async routeSelection(input, signal) {
386
- assertLive()
387
- const config = state.get(), route = config.routes.find(r => r.id === input.routeId)
388
- if (!route || input.target !== 'primary' || input.expectedRoutingRevision !== config.routingRevision) fail('ROUTE_CONFLICT', '路由配置已变化', 409)
389
- const instance = config.providers.find(p => p.id === route.primaryInstanceId)
390
- const selected = router.selections()[route.id]
391
- if (selected.routeEpoch !== input.expectedRouteEpoch) fail('ROUTE_CONFLICT', '来源已变化', 409)
392
- registry.validate(instance, route)
393
- // 探针按这条路由自身的能力: 用 quotes 探针验 K 线路由会在来源缺报价时误判, 也没验到要切过去的能力
394
- const checked = await executor.run(instance, route.capability, { capability: route.capability, market: route.market, instrument: route.instrument }, { probe: true, signal })
395
- if (checked.status !== 'ready' || config.routingRevision !== state.get().routingRevision) fail('CHECK_REQUIRED', '主源未就绪或路由已变化', 422)
396
- router.switchPrimary(route.id, input.expectedRouteEpoch); return snapshot()
397
- },
398
- async close() { stopped = true; recoveryLoop?.stop(); executor.dispose(); await recoveryLoop?.idle?.(); demand.dispose(); collector.dispose(); const cacheClosed = catalog.dispose(); await cacheClosed; await ensuring; await state.close() },
399
- }
400
- }
1
+ import { randomUUID } from 'node:crypto'
2
+ import { z } from 'zod'
3
+ import { createRegistry } from './provider-registry.mjs'
4
+ import { createRouter, RECOVERY_PROBE_MS, TRANSIENT_CODES } from './provider-router.mjs'
5
+ import { createRecovery, createRecoveryLoop } from './recovery.mjs'
6
+ import { tushare } from './providers/tushare.mjs'
7
+ import { tencent } from './providers/tencent.mjs'
8
+ import { sina } from './providers/sina.mjs'
9
+ import { eastmoney } from './providers/eastmoney.mjs'
10
+ import { xueqiu } from './providers/xueqiu.mjs'
11
+ import { finnhub } from './providers/finnhub.mjs'
12
+ import { openState, digest } from './state.mjs'
13
+ import { parseConfiguration, preferencesSchema, defaultConfig, klineQuerySchema, refreshSecuritiesSchema, CAPABILITIES, TREND_ROUTE_MIGRATION, tickPeriodMs } from './schemas.mjs'
14
+ import { createWatchlistService } from './service.mjs'
15
+ import { createBudget } from './budget.mjs'
16
+ import { createExecutor } from './executor.mjs'
17
+ import { createCollector, deriveDelay } from './collector.mjs'
18
+ import { createCatalog } from './catalog.mjs'
19
+ import { createDemand } from './demand.mjs'
20
+ import { createKlineCache } from './kline-cache.mjs'
21
+ import { createTrendCache } from './trend-cache.mjs'
22
+ import { createTickStore } from './ticks.mjs'
23
+ import { fail, parseSecurityId, MARKET_META, clockInZone } from './market-model.mjs'
24
+ const WINDOW = 5 * 60 * 1000
25
+ // 分时来源(东财/腾讯)的时间戳统一按北京时间给出, 拍点线的横轴必须与之一致, 否则切到离线时整体偏移
26
+ const TREND_SOURCE_TIME_ZONE = 'Asia/Shanghai'
27
+ const US_SYMBOL_TTL = 24 * 60 * 60 * 1000
28
+ const US_SYMBOL_LIMIT = 500
29
+ export async function createApplication({ storageDomain, providers = [tushare, tencent, sina, eastmoney, xueqiu, finnhub], publish = () => {}, env = process.env, credentials = null, fetch = globalThis.fetch, now = Date.now, timers = globalThis, vendorAvailable = true }) {
30
+ const serverEpoch = randomUUID(), checks = new Map()
31
+ // 凭据解析: 宿主提供 credentials 服务时交给它(插件存储层优先, 再逐层回退到进程环境与 .env 文件),
32
+ // 否则退回进程环境变量。引用只表示"哪个密钥", 值始终由宿主保管。
33
+ // 接口按能力逐个核对: 宿主给的对象缺哪个方法, 就只退回哪条路径, 而不是在取数时炸掉。
34
+ const credentialStore = credentials && ['resolve', 'set', 'unset'].every(method => typeof credentials[method] === 'function') ? credentials : null
35
+ const resolveCredential = credentialStore ? async ref => (await credentialStore.resolve(ref))?.value : async ref => env[ref]
36
+ let snapshotSeq = 0, stopped = false, collector, catalog, demand, watchlist, recoveryLoop
37
+ let ensuring = null, lastEnsure = -Infinity, ensureError = null, hadDemand = false, ensureCaches = () => {}
38
+ const usSymbols = new Map()
39
+ const touched = () => snapshotSeq++
40
+ const changed = () => { touched(); publish({ type: 'invalidate', serverEpoch, snapshotSeq, scopes: ['snapshot'] }) }
41
+ // 凭据存在性只给设置页看, 而解析是异步的、快照是同步的: 保存配置与启动时各算一次, 快照读这份结果。
42
+ const credentialPresence = new Map()
43
+ const refreshCredentialPresence = async () => {
44
+ for (const p of state.get().providers) {
45
+ credentialPresence.set(`${p.id}:credential`, p.credentialRef === null || !!(await resolveCredential(p.credentialRef)))
46
+ if (p.proxyCredentialRef) credentialPresence.set(`${p.id}:proxy`, !!(await resolveCredential(p.proxyCredentialRef)))
47
+ }
48
+ }
49
+ let state, registry, executor, getControl, router, klineCache, trendCache, ticks
50
+ try {
51
+ state = await openState(storageDomain, changed, now)
52
+ await refreshCredentialPresence()
53
+ registry = createRegistry(providers)
54
+ const budget = createBudget(now)
55
+ // 代理出口: undici ProxyAgent + 同一份 undici.fetch。dispatcher 是 undici 私有契约,
56
+ // Node 内置 fetch 不认 userland dispatcher(invalid onRequestStart method), 不能混用。
57
+ // 包不可用时两者都为 null, 代理实例在请求时明确 NETWORK/502, 不静默直连。
58
+ let proxyFactory = null, proxyFetch = null
59
+ try {
60
+ const undici = await import('undici')
61
+ if (typeof undici.fetch === 'function') { proxyFactory = url => new undici.ProxyAgent(url); proxyFetch = (...args) => undici.fetch(...args) }
62
+ } catch {}
63
+ executor = createExecutor({ registry, budget, env, resolveCredential, fetch, proxyFetch, now, timers, usSymbols, proxyFactory, tickPeriodMs: () => tickPeriodMs(state.get().preferences) })
64
+ getControl = state.get
65
+ // 自动故障切换/手动回主源只换来源: 清掉该路由的退避与失败计数即可, 不能重置 collector。
66
+ // 重置会递增代次并中止在飞请求, 当前刷新随后被判定成"配置已变化"抛假 ROUTE_CONFLICT。
67
+ router = createRouter(getControl, now, routeId => collector?.routeChanged(routeId))
68
+ klineCache = createKlineCache({ cacheTable: state.klineCache, now })
69
+ // 分时当日缓存走独立小池: 它与报价拍点都只放内存, 不入配置记录
70
+ trendCache = createTrendCache({ table: state.trendCache, now })
71
+ ticks = createTickStore({ now })
72
+ // 回探跟着面板活跃走: 有人看时每 RECOVERY_PROBE_MS 把已降级路由的上级全探一遍, 没人看就停
73
+ recoveryLoop = createRecoveryLoop({ probe: createRecovery({ getControl, router, executor }), timers, interval: RECOVERY_PROBE_MS, canRun: () => executor.idle() })
74
+ catalog = createCatalog({ state, getControl, router, executor, registry, now, changed })
75
+ demand = createDemand(() => {
76
+ const wanted = demand.active(), opening = wanted && !hadDemand; hadDemand = wanted
77
+ if (wanted) {
78
+ // 缓存新鲜时进入面板不重复打上游(限流主因); 过期才拉取, 定时器照常量节奏维持
79
+ const freshFor = (getControl().preferences?.refreshSeconds ?? 15) * 1000
80
+ if (opening && !collector?.freshWithin(freshFor)) collector?.refresh().catch(() => {})
81
+ collector?.reconcile()
82
+ } else {
83
+ // 后台预热只在面板空闲时做: 之前只写在 wanted 分支又要求 !demand.active(), 两个条件互斥,
84
+ // 目录/日历永远不会在后台补, 过期目录只能等用户手动同步。
85
+ collector?.cancelIdle(); ensureCaches()
86
+ }
87
+ // 排在首屏刷新之后: 探测也占额度, 不该跟用户要的数据抢顺序
88
+ recoveryLoop.sync(wanted)
89
+ }, now, timers)
90
+ collector = createCollector({ getControl, router, registry, executor, resolveSecurity: catalog.resolve, changed, touched, now, timers, active: demand.active, calendarState: catalog.marketState, ticks })
91
+ watchlist = createWatchlistService(state, catalog.resolve, now)
92
+ // 存量配置升级: 分时能力独立后没有 trend 路由的库在打开时补齐。
93
+ // 补齐失败不该让整个面板躺下(面板可用性高于分时), 记下原因继续, 与目录预热同构
94
+ try { await ensureTrendRoutes() } catch (e) { ensureError = { message: `分时来源补齐失败:${e.message}`, at: now() } }
95
+ // 面板活跃(demand)时让路: 目录后台同步占满并发槽会拖死交互请求(浏览504实测), 仅在面板空闲时补目录
96
+ ensureCaches = () => {
97
+ if (ensuring || now() - lastEnsure < 60 * 1000 || demand.active()) return
98
+ lastEnsure = now()
99
+ ensuring = catalog.ensure().catch(e => { ensureError = { message: e.message, at: now() }; changed() }).finally(() => { ensuring = null; collector?.reconcile() })
100
+ }
101
+ } catch (e) {
102
+ // 打开成功后任何一步初始化失败都要关域: 否则同名域一直占着已打开槽位, 重载只会一直 already-open。
103
+ // 关域自身抛错不能盖掉原始原因。
104
+ try { await state?.close() } catch {}
105
+ throw e
106
+ }
107
+ const snapshot = () => {
108
+ const control = state.get(); delete control.operations
109
+ return { serverEpoch, snapshotSeq, routingRevision: control.routingRevision, control, quotes: collector.watchEntries(), 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 || credentialPresence.get(`${p.id}:credential`) === true, credentialRef: p.credentialRef, proxy: !!p.proxy, proxyCredentialRef: p.proxyCredentialRef ?? null, proxyCredentialPresent: p.proxyCredentialRef ? credentialPresence.get(`${p.id}:proxy`) === true : 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 }])) }
110
+ }
111
+ function assertLive() { if (stopped) fail('STOPPED', '股票工具已停止', 503) }
112
+ async function providerCheck(input, signal) {
113
+ assertLive()
114
+ const config = parseConfiguration({ providers: input.providers, routes: input.routes })
115
+ const caps = z.array(z.enum(CAPABILITIES)).min(1).max(CAPABILITIES.length).parse(input.capabilities)
116
+ const at = now()
117
+ for (const [id, check] of checks) if (check.until <= at) checks.delete(id)
118
+ if (checks.size >= 64) fail('CHECK_LIMIT', '检查请求过多,请稍后重试', 429)
119
+ const results = []
120
+ for (const route of config.routes.filter(r => caps.includes(r.capability))) for (const target of [route.primaryInstanceId, ...route.fallbackInstanceIds]) {
121
+ const instance = config.providers.find(p => p.id === target)
122
+ registry.validate(instance, route)
123
+ const key = `${instance.id}:${route.capability}:${route.market}`
124
+ if (results.some(r => r.key === key)) continue
125
+ // 探针耗时就是这一条路由端到端拿数据的真实延迟, 用于把「能不能用」和「快不快」一起回给用户
126
+ const startedAt = now()
127
+ try {
128
+ const result = await executor.run(instance, route.capability, { market: route.market, instrument: route.instrument }, { probe: true, signal })
129
+ // 探针必须由同名能力的端点产出: 适配器拿别的能力冒充(漏实现分支)时不能当就绪, 且要说清是谁被验了
130
+ const ready = result?.status === 'ready' && result.capability === route.capability
131
+ results.push({ key, providerInstanceId: instance.id, capability: route.capability, market: route.market, status: ready ? 'ready' : 'unavailable', ms: now() - startedAt, ...(ready ? {} : { error: { code: 'PROBE_MISMATCH', message: `探针校验的是${result?.capability ?? '未知'}能力` } }) })
132
+ } catch (e) { results.push({ key, providerInstanceId: instance.id, capability: route.capability, market: route.market, status: 'denied', ms: now() - startedAt, error: { code: e.code, message: e.message } }) }
133
+ }
134
+ const checkId = randomUUID()
135
+ checks.set(checkId, { hash: digest(config), until: now() + WINDOW, results })
136
+ // 解除采集暂停只认行情: 分时/目录/K 线的探针失败不该左右行情采集状态机
137
+ const quoteResults = results.filter(r => r.capability === 'quotes')
138
+ if (digest(config) === digest({ providers: getControl().providers, routes: getControl().routes }) && quoteResults.length && quoteResults.every(r => r.status === 'ready')) collector.resume()
139
+ return { checkId, checks: results }
140
+ }
141
+ async function configuration(operation) {
142
+ assertLive()
143
+ const config = parseConfiguration(operation.payload)
144
+ const replay = state.replay({ ...operation, action: 'configuration', payload: config })
145
+ if (replay) return replay
146
+ // 保存不做连通性闸门: 探针是给人看的诊断信息, 不该把人挡在门外。契约只校验路由自身的合法性,
147
+ // 按能力挑源已经由前端按适配器能力过滤, 后端再校验一次目标是否具备该能力即可。
148
+ for (const route of config.routes) {
149
+ for (const target of [route.primaryInstanceId, ...route.fallbackInstanceIds]) registry.validate(config.providers.find(p => p.id === target), route)
150
+ }
151
+ const result = await state.mutate({ ...operation, action: 'configuration', payload: config }, current => {
152
+ if (JSON.stringify(current.providers) === JSON.stringify(config.providers) && JSON.stringify(current.routes) === JSON.stringify(config.routes)) return current
153
+ return { ...current, ...config, routingRevision: current.routingRevision + 1 }
154
+ })
155
+ if (!result.unchanged) { router.reset(); collector.reset(); await refreshCredentialPresence() }
156
+ return result
157
+ }
158
+
159
+ // 搜索候选项服务端补全市场元数据(单一事实源 MARKET_META),client 零映射表。
160
+ function decorateWithMarketMeta(items) {
161
+ for (const item of items) if (item?.exchange && !item.currency) {
162
+ const meta = MARKET_META[item.exchange]
163
+ if (meta) { item.currency = meta.currency; item.priceScale = meta.priceScale }
164
+ }
165
+ }
166
+ // K 线类请求的即时故障转移: 触发码 NETWORK/TIMEOUT/BAD_PAYLOAD 时顺着「环上下一格」试一次;
167
+ // 只有当前选择自己的失败算一轮, 顺着链试备源是同一轮里的补救, 不额外计次
168
+ async function runWithFailover(capability, route, primary, fallbacks, request, signal) {
169
+ const chain = [primary, ...fallbacks]
170
+ let lastError, unsupported
171
+ for (const [index, cand] of chain.entries()) {
172
+ try {
173
+ const result = await executor.run(cand, capability, request, { signal })
174
+ // 当前选择能出数就是最好的证据: 清掉它的失败计数与探测退避
175
+ if (index === 0) router.recordRound(route.id, null)
176
+ return result
177
+ } catch (e) {
178
+ if (index === 0) router.recordRound(route.id, e)
179
+ // 备源不支持这个能力就继续试下一个; 用户该看到的是主源的真实错误, 不是备源的描述符差异
180
+ if (e.code === 'UNSUPPORTED_CAPABILITY') { unsupported ??= e; continue }
181
+ lastError = e
182
+ if (!TRANSIENT_CODES.includes(e.code) && e.code !== 'BAD_PAYLOAD') throw e
183
+ }
184
+ }
185
+ throw lastError ?? unsupported
186
+ }
187
+ // 分时没有路由时用户只会看到"未配置数据来源", 看不出缺的是哪一种能力
188
+ function selectRoute(capability, market) {
189
+ try { return router.select(capability, market, 'equity') }
190
+ catch (e) {
191
+ if (capability === 'trend' && e.code === 'NO_ROUTE') fail('NO_ROUTE', '未配置分时来源:请在设置的能力路由里为分时指定来源', 422)
192
+ throw e
193
+ }
194
+ }
195
+ // 分时拆成独立能力之前的存量配置没有 trend 路由: 打开时按适配器能力声明补齐, 优先沿用该市场 K 线的来源。
196
+ // 不能假设某个具体来源: 谁声明了 trend 且覆盖该市场, 谁才有资格承接下来。
197
+ async function ensureTrendRoutes() {
198
+ const control = state.get()
199
+ if (control.routeMigration >= TREND_ROUTE_MIGRATION) return
200
+ const declared = registry.descriptors()
201
+ const capable = (instance, market) => {
202
+ const descriptor = declared.find(d => d.adapterId === instance.adapterId)
203
+ return !!descriptor?.capabilities.includes('trend') && descriptor.markets.includes(market)
204
+ }
205
+ // 市场面取现有任意路由: 分时不依赖 K 线, 用户删掉 K 线路由不代表这个市场不要分时
206
+ const markets = [...new Set(control.routes.map(r => r.market))]
207
+ const missing = [], spares = []
208
+ for (const market of markets) {
209
+ const route = control.routes.find(r => r.market === market && r.capability === 'trend')
210
+ if (!route) {
211
+ const kline = control.routes.find(r => r.market === market && r.capability === 'kline')
212
+ const order = [kline?.primaryInstanceId, ...control.providers.map(p => p.id)].filter(Boolean)
213
+ const target = order.map(id => control.providers.find(p => p.id === id)).find(instance => instance?.enabled !== false && capable(instance, market))
214
+ if (target) missing.push({ id: `${market.toLowerCase()}-trend`, capability: 'trend', market, instrument: 'equity', primaryInstanceId: target.id, fallbackInstanceIds: [], failoverMode: 'off', maxDelaySeconds: null, acceptUnknownDelay: true })
215
+ continue
216
+ }
217
+ // 主源不该是唯一来源: 分时只有一个来源时, 它一断就整块空白。把其它声明分时的实例登记为网络失败后的备源
218
+ // 已有备用源的不再追加: 自动切换是用户开关, 迁移既不替他打开, 也不改他已经配好的备用链
219
+ if (route.fallbackInstanceIds.length) continue
220
+ const spare = control.providers.find(p => p.enabled !== false && p.id !== route.primaryInstanceId && capable(p, market))
221
+ if (spare) spares.push({ id: route.id, fallback: spare.id })
222
+ }
223
+ // 一条也补不出来且当前没有任何分时路由, 说明只是「暂时没有可用分时源」: 不烧迁移标记,
224
+ // 之后装上声明分时的源还能自动补; 已有分时路由(或刚补出来)才算迁移完成, 用户删掉后不该复活
225
+ if (!missing.length && !spares.length && !control.routes.some(r => r.capability === 'trend')) return
226
+ const patch = route => {
227
+ const spare = spares.find(s => s.id === route.id)
228
+ return spare ? { ...route, fallbackInstanceIds: [...route.fallbackInstanceIds, spare.fallback], failoverMode: 'network' } : route
229
+ }
230
+ await state.mutate({ operationId: randomUUID(), expectedRevision: control.revision, action: 'trend-routes', payload: { added: missing.map(r => r.id), spared: spares.map(s => s.id) } }, current => ({ ...current, routeMigration: TREND_ROUTE_MIGRATION, routes: [...current.routes.map(patch), ...missing], routingRevision: missing.length || spares.length ? current.routingRevision + 1 : current.routingRevision }))
231
+ }
232
+
233
+ // 分时离线兜底: 只续在当日真实分时后面。
234
+ // 没有真实分时打底时, 几个报价点连成的线说明不了走势, 不如把上游错误如实抛出去
235
+ async function offlineTrend({ market, code, limit, securityId }, error) {
236
+ const cached = await trendCache.get({ market, code, limit })
237
+ if (!cached) return null
238
+ const real = cached.payload.candles || []
239
+ const lastAt = Number(real.at(-1)?.at)
240
+ // 只补最后一根之后、且不在同一分钟的新报价: 早于它的已经在图里, 同一分钟的会画成重复的一根
241
+ const lastMinute = Math.floor(lastAt / 60)
242
+ const extra = Number.isFinite(lastAt) ? ticks.series(securityId, market).filter(point => point.at > lastAt && Math.floor(point.at / 60) > lastMinute) : []
243
+ const appended = extra.map(point => ({ time: clockInZone(TREND_SOURCE_TIME_ZONE, point.at), at: point.at, open: point.price, high: point.price, low: point.price, close: point.price }))
244
+ return {
245
+ ...cached.payload,
246
+ ...(appended.length ? { complete: false } : {}),
247
+ // 拍点只有收盘价: 开高低补齐成同一个值, 否则客户端按 OHLC 校验会把每根都丢掉, 图上仍然是空的
248
+ candles: [...real, ...appended],
249
+ offline: { kind: 'cache', cachedAt: cached.cachedAt, appended: appended.length, reason: error.message },
250
+ }
251
+ }
252
+
253
+ return {
254
+ snapshot, providerCheck, configuration,
255
+ demand(message) { assertLive(); demand.update(message) },
256
+ async search(q, phase = 'local', signal) {
257
+ assertLive()
258
+ if (typeof q !== 'string' || [...q].length > 100) fail('INVALID_QUERY', '搜索词过长')
259
+ const items = phase === 'remote' ? await catalog.remote(q, signal) : catalog.search(q)
260
+ decorateWithMarketMeta(items)
261
+ const routingRevision = state.get().routingRevision
262
+ if (phase === 'remote') {
263
+ for (const item of items) {
264
+ const row = item.raw && typeof item.raw === 'object' ? item.raw : null
265
+ if (row?.MktNum && /^10[567]$/.test(row.MktNum)) {
266
+ usSymbols.set(`US:${row.Code}`, { mktNum: row.MktNum, jys: row.JYS || null, at: now() })
267
+ while (usSymbols.size > US_SYMBOL_LIMIT) usSymbols.delete(usSymbols.keys().next().value)
268
+ }
269
+ }
270
+ }
271
+ for (const [key, value] of usSymbols) if (now() - value.at > US_SYMBOL_TTL) usSymbols.delete(key)
272
+ return { items, catalogs: catalog.status(), routingRevision }
273
+ },
274
+ async kline(input, signal) {
275
+ assertLive()
276
+ const parsed = klineQuerySchema.safeParse(input)
277
+ if (!parsed.success) fail('INVALID_PARAM', 'K线请求参数无效', 400)
278
+ const { securityId: sid, period, limit, force } = parsed.data
279
+ let exchange, code
280
+ try { ({ exchange, code } = parseSecurityId(sid)) } catch { fail('INVALID_PARAM', '证券身份无效', 400) }
281
+ const config = state.get()
282
+ // 分时与日/周/月是两种上游, 各走各的路由: K 线来源不供分时时, 分时不该跟着一起死
283
+ const capability = period === 'trend' ? 'trend' : 'kline'
284
+ const { route, instance } = selectRoute(capability, exchange)
285
+ // 同轮补救只取环上的下一格: 走到末级时回到主源, 否则末级是死胡同
286
+ const next = router.nextInRing(route.id, instance.id)
287
+ const fallbacks = next ? config.providers.filter(p => p.id === next && p.enabled !== false && p.budget?.requestsPerMinute !== null) : []
288
+ // force=1 跳过缓存读(详情页手动刷新);分时每次真取, 缓存只在上游失败时用
289
+ if (capability === 'kline' && force !== '1') {
290
+ for (const cand of [instance, ...fallbacks.filter(spare => spare.id !== instance.id)]) {
291
+ const cached = await klineCache.get({ providerInstanceId: cand.id, market: exchange, period, code, limit }, config.routingRevision)
292
+ if (cached) return { ...cached.payload, source: cand.id, revision: config.revision }
293
+ }
294
+ }
295
+ const result = await runWithFailover(capability, route, instance, fallbacks, { securityId: sid, market: exchange, code, period, adjust: 'qfq', limit }, signal).catch(async error => {
296
+ // 分时没有别的来源可退: 有当日真实分时就拿它兜底并续上之后的报价点, 没有就如实报错
297
+ if (capability !== 'trend') throw error
298
+ const offline = await offlineTrend({ market: exchange, code, limit, securityId: sid }, error)
299
+ if (!offline) throw error
300
+ return offline
301
+ })
302
+ if (capability === 'kline') await klineCache.put({ providerInstanceId: result.providerInstanceId, market: exchange, period, code, limit }, result, config.routingRevision)
303
+ // 成功一次就覆盖当日缓存: 离线时它就是"最后一个完整的分时"; 兜底结果与空结果由缓存自己挡掉
304
+ else await trendCache.put({ market: exchange, code, limit }, result)
305
+ return { ...result, source: result.providerInstanceId, revision: config.revision }
306
+ },
307
+ async browse(input) {
308
+ assertLive()
309
+ if (!MARKET_META[input.market]) fail('INVALID_REQUEST', '市场参数无效')
310
+ // 市场概览: 代表指数不入目录/自选, 走 quotes 管道直拉; 失败静默为 null 不阻断目录浏览
311
+ const INDEX = { XSHG: { id: 'XSHG:index:000001', exchange: 'XSHG', code: '000001', name: '上证指数' }, XSHE: { id: 'XSHE:index:399001', exchange: 'XSHE', code: '399001', name: '深证成指' }, XHKG: { id: 'XHKG:index:HSI', exchange: 'XHKG', code: 'HSI', name: '恒生指数' }, XNAS: { id: 'XNAS:index:NDX', exchange: 'XNAS', code: 'NDX', name: '纳斯达克100' }, XNYS: { id: 'XNYS:index:DJI', exchange: 'XNYS', code: 'DJI', name: '道琼斯' }, XJPX: { id: 'XJPX:index:N225', exchange: 'XJPX', code: 'N225', name: '日经225' }, XKRX: { id: 'XKRX:index:KOSPI', exchange: 'XKRX', code: 'KOSPI', name: '韩国综指' }, XLON: { id: 'XLON:index:FTSE', exchange: 'XLON', code: 'FTSE', name: '富时100' } }
312
+ const index = INDEX[input.market]
313
+ // 概览指数是装饰性数据: 无路由或拉取失败(含5s短超时不与目录翻页争槽)都静默为 null, 不阻断目录浏览
314
+ let overview = null
315
+ // 概览时段与采集同源: 都走 catalog.marketState(日历 + 市场本地时段), 不用来源字段猜
316
+ const phase = catalog.marketState(input.market)
317
+ try {
318
+ const route = router.select('quotes', input.market)
319
+ if (route.instance) {
320
+ const result = await executor.run(route.instance, 'quotes', { securities: [{ id: index.id, exchange: index.exchange, code: index.code }], routingRevision: state.get().routingRevision }, { signal: AbortSignal.timeout(5 * 1000) })
321
+ const quote = result.items?.find(q => q.securityId === index.id)
322
+ if (quote && quote.last !== null) { deriveDelay(quote, now, ['trading', 'auction', 'unknown'].includes(phase.state)); overview = { name: index.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 } }
323
+ }
324
+ } catch {}
325
+ return { ...await catalog.browse(input), overview, catalogs: catalog.status(), routingRevision: state.get().routingRevision }
326
+ },
327
+ async sync(input) {
328
+ assertLive()
329
+ if (!MARKET_META[input.market] || input.expectedRoutingRevision !== state.get().routingRevision) fail('ROUTE_CONFLICT', '目录路由已变化', 409)
330
+ // 只同步该市场真实配置的能力: 默认参数同时要目录+日历, 没配日历时每次手动同步都必然回一条 NO_ROUTE 错误
331
+ const capabilities = ['catalog', 'calendar'].filter(capability => state.get().routes.some(route => route.capability === capability && route.market === input.market))
332
+ if (!capabilities.length) fail('NO_ROUTE', '该市场未配置目录或日历来源', 422)
333
+ const result = await catalog.sync(input.market, capabilities); collector.reconcile(); return result
334
+ },
335
+ async watchlist(operation) {
336
+ assertLive()
337
+ const result = await watchlist.execute(operation)
338
+ // 移除后立即丢弃该标的行情; 否则已删自选的旧报价仍留在 /snapshot 并无限累积
339
+ if (operation.action === 'remove' && operation.payload?.securityId) collector.prune(operation.payload.securityId)
340
+ collector.reconcile(); return result
341
+ },
342
+ // 密钥只写宿主的凭据存储, 不回显也不落插件状态;引用必须已被某个数据源声明, 插件不越界写别人的密钥空间。
343
+ async credential(input) {
344
+ assertLive()
345
+ if (!credentialStore) fail('UNSUPPORTED', '宿主未提供凭据服务', 501)
346
+ const ref = z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).parse(input.ref)
347
+ if (!state.get().providers.some(p => p.credentialRef === ref || p.proxyCredentialRef === ref)) fail('INVALID_REQUEST', '该凭据未被任何数据源使用', 422)
348
+ const value = input.value === null ? null : z.string().min(1).max(512).parse(input.value)
349
+ if (value === null) await credentialStore.unset(ref)
350
+ else await credentialStore.set(ref, value)
351
+ await refreshCredentialPresence()
352
+ // 填入正确密钥后立即解除引用该凭据实例的 AUTH 永久暂停, 不必再点一次"检查所有来源"
353
+ collector.recoverCredential(ref)
354
+ return { ref, present: value !== null }
355
+ },
356
+ async preferences(operation) {
357
+ assertLive()
358
+ const parsed = preferencesSchema.partial().safeParse(operation.payload)
359
+ if (!parsed.success) fail('INVALID_PREFERENCES', '显示偏好无效')
360
+ // partial 会给缺省键补默认值, 合并时只取本次提交的键, 否则半更新会把另一项重置成默认
361
+ const submitted = operation.payload && typeof operation.payload === 'object' ? operation.payload : {}
362
+ const patch = Object.fromEntries(Object.entries(parsed.data).filter(([key, value]) => Object.hasOwn(submitted, key) && value !== undefined))
363
+ const result = await state.mutate({ ...operation, action: 'preferences' }, current => ({ ...current, preferences: { ...current.preferences, ...patch } }))
364
+ collector.reconcile(); return result
365
+ },
366
+ async refresh(input = {}, signal) {
367
+ assertLive()
368
+ if (input.expectedRoutingRevision !== undefined && input.expectedRoutingRevision !== state.get().routingRevision) fail('ROUTE_CONFLICT', '路由配置已变化', 409)
369
+ const submitted = input.securities === undefined ? undefined : refreshSecuritiesSchema.safeParse(input.securities)
370
+ if (submitted && !submitted.success) {
371
+ const [first] = submitted.error.issues, path = first.path.length ? first.path.join('.') : '根'
372
+ fail('INVALID_REFRESH', `刷新证券参数无效:${path} ${first.message}`, 400)
373
+ }
374
+ let quotes
375
+ try { quotes = await collector.refresh(submitted?.data, { signal }) } catch (e) {
376
+ // peek 刷新失败时 collector 里还留着带 lastError 的条目(否则详情只剩"等待报价");
377
+ // 常驻快照按自选过滤会顺手删掉它, 这里在快照构造前抓一份只随本次错误下发的报价。
378
+ const failed = collector.entries()
379
+ e.snapshot = { ...snapshot(), quotes: failed }
380
+ throw e
381
+ }
382
+ // peek 报价只随本次响应下发, 不进常驻快照: 详情关闭后服务端不再保留任何非自选报价
383
+ return { ...snapshot(), quotes }
384
+ },
385
+ async routeSelection(input, signal) {
386
+ assertLive()
387
+ const config = state.get(), route = config.routes.find(r => r.id === input.routeId)
388
+ if (!route || input.target !== 'primary' || input.expectedRoutingRevision !== config.routingRevision) fail('ROUTE_CONFLICT', '路由配置已变化', 409)
389
+ const instance = config.providers.find(p => p.id === route.primaryInstanceId)
390
+ const selected = router.selections()[route.id]
391
+ if (selected.routeEpoch !== input.expectedRouteEpoch) fail('ROUTE_CONFLICT', '来源已变化', 409)
392
+ registry.validate(instance, route)
393
+ // 探针按这条路由自身的能力: 用 quotes 探针验 K 线路由会在来源缺报价时误判, 也没验到要切过去的能力
394
+ const checked = await executor.run(instance, route.capability, { capability: route.capability, market: route.market, instrument: route.instrument }, { probe: true, signal })
395
+ if (checked.status !== 'ready' || config.routingRevision !== state.get().routingRevision) fail('CHECK_REQUIRED', '主源未就绪或路由已变化', 422)
396
+ router.switchPrimary(route.id, input.expectedRouteEpoch); return snapshot()
397
+ },
398
+ async close() { stopped = true; recoveryLoop?.stop(); executor.dispose(); await recoveryLoop?.idle?.(); demand.dispose(); collector.dispose(); const cacheClosed = catalog.dispose(); await cacheClosed; await ensuring; await state.close() },
399
+ }
400
+ }