@mzzsfy/dsh-stock-assistant 0.8.1 → 0.10.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 +95 -4
- package/README.md +16 -12
- package/package.json +1 -1
- package/src/application.mjs +185 -72
- package/src/catalog.mjs +51 -40
- package/src/client.js +686 -256
- package/src/collector.mjs +169 -91
- package/src/executor.mjs +97 -20
- package/src/index.js +5 -3
- package/src/market-model.mjs +35 -8
- package/src/memory-cache.mjs +5 -1
- package/src/provider-router.mjs +9 -3
- package/src/providers/eastmoney.mjs +9 -3
- package/src/providers/sina.mjs +2 -2
- package/src/providers/tencent.mjs +14 -1
- package/src/providers/tushare.mjs +11 -2
- package/src/providers/xueqiu.mjs +9 -7
- package/src/routes.mjs +11 -1
- package/src/schemas.mjs +12 -17
- package/src/state.mjs +17 -2
- package/src/trend-cache.mjs +96 -11
- package/src/us-symbols.mjs +30 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +215 -13
package/src/application.mjs
CHANGED
|
@@ -13,29 +13,44 @@ import { openState, digest } from './state.mjs'
|
|
|
13
13
|
import { parseConfiguration, preferencesSchema, defaultConfig, klineQuerySchema, refreshSecuritiesSchema, CAPABILITIES, TREND_ROUTE_MIGRATION, tickPeriodMs } from './schemas.mjs'
|
|
14
14
|
import { createWatchlistService } from './service.mjs'
|
|
15
15
|
import { createBudget } from './budget.mjs'
|
|
16
|
-
import {
|
|
16
|
+
import { createUsSymbols } from './us-symbols.mjs'
|
|
17
|
+
import { createExecutor, routeTimeoutMs, requestBudgetMs, groupGapMs, UPSTREAM_TIMEOUT_MS, EXECUTOR_CONCURRENCY } from './executor.mjs'
|
|
17
18
|
import { createCollector, deriveDelay } from './collector.mjs'
|
|
18
19
|
import { createCatalog } from './catalog.mjs'
|
|
19
20
|
import { createDemand } from './demand.mjs'
|
|
20
21
|
import { createKlineCache } from './kline-cache.mjs'
|
|
21
|
-
import { createTrendCache } from './trend-cache.mjs'
|
|
22
|
+
import { createTrendCache, trendSessionDate } from './trend-cache.mjs'
|
|
22
23
|
import { createTickStore } from './ticks.mjs'
|
|
23
24
|
import { fail, parseSecurityId, MARKET_META, clockInZone } from './market-model.mjs'
|
|
24
25
|
const WINDOW = 5 * 60 * 1000
|
|
26
|
+
// 探针诊断的节流窗口内最多发起多少次检查: 检查会真的打上游, 不能由页面无限触发
|
|
27
|
+
const PROBE_CHECK_LIMIT = 64
|
|
28
|
+
// 探针总预算上限: 目标多到推导值超过它时不再加长请求, 改为交出已完成的部分诊断
|
|
29
|
+
const PROBE_TIMEOUT_CEILING_MS = 2 * 60 * 1000
|
|
30
|
+
// 响应收尾(序列化 + 写日志)留在路由计时之内的裕度
|
|
31
|
+
const PROBE_RESPONSE_MARGIN_MS = 2 * 1000
|
|
25
32
|
// 分时来源(东财/腾讯)的时间戳统一按北京时间给出, 拍点线的横轴必须与之一致, 否则切到离线时整体偏移
|
|
26
33
|
const TREND_SOURCE_TIME_ZONE = 'Asia/Shanghai'
|
|
27
|
-
const US_SYMBOL_TTL = 24 * 60 * 60 * 1000
|
|
28
|
-
const US_SYMBOL_LIMIT = 500
|
|
29
34
|
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()
|
|
35
|
+
const serverEpoch = randomUUID()
|
|
36
|
+
// 检查节流按最近一次窗口内的时间戳计: 固定窗口会在边界放行双倍突发, 探针是真的打上游
|
|
37
|
+
const probeTimes = []
|
|
31
38
|
// 凭据解析: 宿主提供 credentials 服务时交给它(插件存储层优先, 再逐层回退到进程环境与 .env 文件),
|
|
32
39
|
// 否则退回进程环境变量。引用只表示"哪个密钥", 值始终由宿主保管。
|
|
33
40
|
// 接口按能力逐个核对: 宿主给的对象缺哪个方法, 就只退回哪条路径, 而不是在取数时炸掉。
|
|
34
|
-
|
|
35
|
-
const
|
|
41
|
+
// 服务按次取: 宿主凭据 fiber 可能晚于插件 apply 就绪, 只取一次会把"晚到"固化成永久缺失
|
|
42
|
+
const credentialService = () => typeof credentials === 'function' ? credentials() : credentials
|
|
43
|
+
const credentialStoreOf = () => {
|
|
44
|
+
const service = credentialService()
|
|
45
|
+
return service && ['resolve', 'set', 'unset'].every(method => typeof service[method] === 'function') ? service : null
|
|
46
|
+
}
|
|
47
|
+
const resolveCredential = async ref => {
|
|
48
|
+
const store = credentialStoreOf()
|
|
49
|
+
return store ? (await store.resolve(ref))?.value : env[ref]
|
|
50
|
+
}
|
|
36
51
|
let snapshotSeq = 0, stopped = false, collector, catalog, demand, watchlist, recoveryLoop
|
|
37
52
|
let ensuring = null, lastEnsure = -Infinity, ensureError = null, hadDemand = false, ensureCaches = () => {}
|
|
38
|
-
const usSymbols =
|
|
53
|
+
const usSymbols = createUsSymbols({ now })
|
|
39
54
|
const touched = () => snapshotSeq++
|
|
40
55
|
const changed = () => { touched(); publish({ type: 'invalidate', serverEpoch, snapshotSeq, scopes: ['snapshot'] }) }
|
|
41
56
|
// 凭据存在性只给设置页看, 而解析是异步的、快照是同步的: 保存配置与启动时各算一次, 快照读这份结果。
|
|
@@ -70,14 +85,16 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
70
85
|
trendCache = createTrendCache({ table: state.trendCache, now })
|
|
71
86
|
ticks = createTickStore({ now })
|
|
72
87
|
// 回探跟着面板活跃走: 有人看时每 RECOVERY_PROBE_MS 把已降级路由的上级全探一遍, 没人看就停
|
|
73
|
-
|
|
88
|
+
// 回探要的是当前生效的 provider/route 表: 传控制记录读取器(整条记录)会让 getConfig() 直接抛错,
|
|
89
|
+
// 而循环把异常吞掉 —— 降级路由的自动回切会静默地一次都不跑
|
|
90
|
+
recoveryLoop = createRecoveryLoop({ probe: createRecovery({ getConfig: () => state.get(), router, executor }), timers, interval: RECOVERY_PROBE_MS, canRun: () => executor.idle() })
|
|
74
91
|
catalog = createCatalog({ state, getControl, router, executor, registry, now, changed })
|
|
75
92
|
demand = createDemand(() => {
|
|
76
93
|
const wanted = demand.active(), opening = wanted && !hadDemand; hadDemand = wanted
|
|
77
94
|
if (wanted) {
|
|
78
95
|
// 缓存新鲜时进入面板不重复打上游(限流主因); 过期才拉取, 定时器照常量节奏维持
|
|
79
96
|
const freshFor = (getControl().preferences?.refreshSeconds ?? 15) * 1000
|
|
80
|
-
if (opening && !collector?.freshWithin(freshFor)) collector?.refresh().catch(() => {})
|
|
97
|
+
if (opening && !collector?.freshWithin(freshFor)) collector?.refresh(undefined, { automatic: true }).catch(() => {})
|
|
81
98
|
collector?.reconcile()
|
|
82
99
|
} else {
|
|
83
100
|
// 后台预热只在面板空闲时做: 之前只写在 wanted 分支又要求 !demand.active(), 两个条件互斥,
|
|
@@ -105,38 +122,94 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
105
122
|
throw e
|
|
106
123
|
}
|
|
107
124
|
const snapshot = () => {
|
|
108
|
-
|
|
109
|
-
|
|
125
|
+
// 台账不随快照下发; 读侧共享同一份冻结快照, 不能原地删字段
|
|
126
|
+
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 || 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
128
|
}
|
|
111
129
|
function assertLive() { if (stopped) fail('STOPPED', '股票工具已停止', 503) }
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const
|
|
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 = []
|
|
130
|
+
// 待测目标表: 一条路由的每个实例各算一个探针, 同 (实例, 能力, 市场) 只测一次。
|
|
131
|
+
// 组内串行由执行器的额度组间隔保证, 所以并行度按额度组切分, 而不是按目标数。
|
|
132
|
+
const probePlan = (config, caps) => {
|
|
133
|
+
const plan = [], seen = new Set(), groups = new Map()
|
|
120
134
|
for (const route of config.routes.filter(r => caps.includes(r.capability))) for (const target of [route.primaryInstanceId, ...route.fallbackInstanceIds]) {
|
|
121
135
|
const instance = config.providers.find(p => p.id === target)
|
|
122
136
|
registry.validate(instance, route)
|
|
123
137
|
const key = `${instance.id}:${route.capability}:${route.market}`
|
|
124
|
-
if (
|
|
125
|
-
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
138
|
+
if (seen.has(key)) continue
|
|
139
|
+
seen.add(key)
|
|
140
|
+
const probe = { key, instance, route, capability: route.capability, market: route.market }
|
|
141
|
+
plan.push(probe)
|
|
142
|
+
const gap = groupGapMs(instance)
|
|
143
|
+
const group = groups.get(instance.quotaGroup)
|
|
144
|
+
groups.set(instance.quotaGroup, { count: (group?.count || 0) + 1, gap: Math.max(group?.gap || 0, gap) })
|
|
145
|
+
}
|
|
146
|
+
return { plan, groups }
|
|
147
|
+
}
|
|
148
|
+
// 预算跟着工作量走: 48 个探针按 1 秒间隔排开已接近一分钟, 再套固定 60 秒必然在中途被掐断。
|
|
149
|
+
// 组内串行、跨组并行, 但探针和行情共用执行器的并发槽: 最长的一组先占一个槽, 其余工作量按槽位数摊
|
|
150
|
+
const probeBudgetMs = groups => {
|
|
151
|
+
let work = 0, worst = 0
|
|
152
|
+
for (const group of groups.values()) {
|
|
153
|
+
const cost = group.count * (group.gap + UPSTREAM_TIMEOUT_MS)
|
|
154
|
+
work += cost
|
|
155
|
+
worst = Math.max(worst, cost)
|
|
133
156
|
}
|
|
134
|
-
|
|
135
|
-
|
|
157
|
+
// makespan 的上界: 最长一组独占一个槽, 剩余工作量由剩下的槽位分摊
|
|
158
|
+
return Math.min(worst + (work - worst) / EXECUTOR_CONCURRENCY + PROBE_RESPONSE_MARGIN_MS, PROBE_TIMEOUT_CEILING_MS)
|
|
159
|
+
}
|
|
160
|
+
const probeInput = input => {
|
|
161
|
+
const config = parseConfiguration({ providers: input.providers, routes: input.routes })
|
|
162
|
+
const caps = z.array(z.enum(CAPABILITIES)).min(1).max(CAPABILITIES.length).parse(input.capabilities)
|
|
163
|
+
return { config, caps, ...probePlan(config, caps) }
|
|
164
|
+
}
|
|
165
|
+
async function providerCheck(input, signal) {
|
|
166
|
+
assertLive()
|
|
167
|
+
const { config, plan, groups } = probeInput(input)
|
|
168
|
+
const at = now()
|
|
169
|
+
while (probeTimes.length && at - probeTimes[0] >= WINDOW) probeTimes.shift()
|
|
170
|
+
if (probeTimes.length >= PROBE_CHECK_LIMIT) fail('CHECK_LIMIT', '检查请求过多,请稍后重试', 429)
|
|
171
|
+
probeTimes.push(at)
|
|
172
|
+
// 自查截止时刻比路由预算早一个裕度: 预算用完时交出已完成的部分诊断, 而不是整条 504
|
|
173
|
+
const deadline = at + probeBudgetMs(groups) - PROBE_RESPONSE_MARGIN_MS
|
|
174
|
+
const results = new Array(plan.length)
|
|
175
|
+
const skipped = (probe, code, message) => ({ key: probe.key, providerInstanceId: probe.instance.id, capability: probe.capability, market: probe.market, status: 'skipped', ms: 0, error: { code, message } })
|
|
176
|
+
const byGroup = new Map()
|
|
177
|
+
for (const [index, probe] of plan.entries()) byGroup.set(probe.instance.quotaGroup, [...(byGroup.get(probe.instance.quotaGroup) || []), { index, probe }])
|
|
178
|
+
await Promise.all([...byGroup.values()].map(async group => {
|
|
179
|
+
for (const { index, probe } of group) {
|
|
180
|
+
if (signal?.aborted) { results[index] = skipped(probe, 'CANCELLED', '检查已取消'); continue }
|
|
181
|
+
if (now() >= deadline) { results[index] = skipped(probe, 'CHECK_DEADLINE', '检查预算用完,此项未执行'); continue }
|
|
182
|
+
// 截止时刻也要打断在途探针: 排队等并发槽的探针既不受现在剩余预算的约束,
|
|
183
|
+
// 也让整条请求越过路由计时器被 504 掉 —— 那样一条诊断都交不出来
|
|
184
|
+
const limiter = new AbortController()
|
|
185
|
+
const expire = () => limiter.abort()
|
|
186
|
+
const abortByOuter = () => limiter.abort()
|
|
187
|
+
const timer = timers.setTimeout(expire, Math.max(0, deadline - now()))
|
|
188
|
+
signal?.addEventListener('abort', abortByOuter, { once: true })
|
|
189
|
+
// 探针耗时就是这一条路由端到端拿数据的真实延迟, 用于把「能不能用」和「快不快」一起回给用户
|
|
190
|
+
const startedAt = now()
|
|
191
|
+
try {
|
|
192
|
+
const result = await executor.run(probe.instance, probe.capability, { market: probe.market, instrument: probe.route.instrument }, { probe: true, signal: limiter.signal })
|
|
193
|
+
// 探针必须由同名能力的端点产出: 适配器拿别的能力冒充(漏实现分支)时不能当就绪, 且要说清是谁被验了
|
|
194
|
+
const ready = result?.status === 'ready' && result.capability === probe.capability
|
|
195
|
+
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
|
+
} catch (e) {
|
|
197
|
+
// 到点被打断不是"目标不可用": 报 denied 会让客户端把这批好路由剪掉
|
|
198
|
+
results[index] = limiter.signal.aborted && !signal?.aborted
|
|
199
|
+
? skipped(probe, 'CHECK_DEADLINE', '检查预算用完,此项未执行')
|
|
200
|
+
: { 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 } }
|
|
201
|
+
} finally {
|
|
202
|
+
timers.clearTimeout(timer)
|
|
203
|
+
signal?.removeEventListener('abort', abortByOuter)
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}))
|
|
207
|
+
const completed = results.filter(Boolean)
|
|
136
208
|
// 解除采集暂停只认行情: 分时/目录/K 线的探针失败不该左右行情采集状态机
|
|
137
|
-
const quoteResults =
|
|
138
|
-
if (digest(config) === digest({ providers: getControl().providers, routes: getControl().routes })
|
|
139
|
-
|
|
209
|
+
const quoteResults = completed.filter(r => r.capability === 'quotes')
|
|
210
|
+
if (quoteResults.length && quoteResults.every(r => r.status === 'ready') && digest(config) === digest({ providers: getControl().providers, routes: getControl().routes })) collector.resume()
|
|
211
|
+
const partial = completed.some(r => r.status === 'skipped')
|
|
212
|
+
return { checkId: randomUUID(), checks: completed, partial }
|
|
140
213
|
}
|
|
141
214
|
async function configuration(operation) {
|
|
142
215
|
assertLive()
|
|
@@ -165,21 +238,27 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
165
238
|
}
|
|
166
239
|
// K 线类请求的即时故障转移: 触发码 NETWORK/TIMEOUT/BAD_PAYLOAD 时顺着「环上下一格」试一次;
|
|
167
240
|
// 只有当前选择自己的失败算一轮, 顺着链试备源是同一轮里的补救, 不额外计次
|
|
168
|
-
|
|
241
|
+
// 一条请求(含分批与备源链)共用的截止时刻: 超出即按超时收尾, 不让路由层 504 掉已成功的部分
|
|
242
|
+
const deadlineOf = () => Date.now() + requestBudgetMs(state.get().preferences)
|
|
243
|
+
|
|
244
|
+
async function runWithFailover(capability, route, primary, fallbacks, request, signal, reportRound = error => router.recordRound(route.id, error), deadline = null) {
|
|
169
245
|
const chain = [primary, ...fallbacks]
|
|
170
246
|
let lastError, unsupported
|
|
171
247
|
for (const [index, cand] of chain.entries()) {
|
|
172
248
|
try {
|
|
173
|
-
const result = await executor.run(cand, capability, request, { signal })
|
|
249
|
+
const result = await executor.run(cand, capability, request, { signal, deadline })
|
|
174
250
|
// 当前选择能出数就是最好的证据: 清掉它的失败计数与探测退避
|
|
175
|
-
if (index === 0)
|
|
251
|
+
if (index === 0) reportRound(null)
|
|
176
252
|
return result
|
|
177
253
|
} catch (e) {
|
|
178
|
-
if (
|
|
254
|
+
if (signal?.aborted) throw e
|
|
255
|
+
if (index === 0) reportRound(e)
|
|
179
256
|
// 备源不支持这个能力就继续试下一个; 用户该看到的是主源的真实错误, 不是备源的描述符差异
|
|
180
257
|
if (e.code === 'UNSUPPORTED_CAPABILITY') { unsupported ??= e; continue }
|
|
181
258
|
lastError = e
|
|
182
|
-
|
|
259
|
+
// 分时 429 只说明当前来源这一分钟没额度: 同轮换备源出数, 不能把整轮钉死在限流源上
|
|
260
|
+
const retryable = TRANSIENT_CODES.includes(e.code) || e.code === 'BAD_PAYLOAD' || (capability === 'trend' && e.code === 'RATE_LIMIT')
|
|
261
|
+
if (!retryable) throw e
|
|
183
262
|
}
|
|
184
263
|
}
|
|
185
264
|
throw lastError ?? unsupported
|
|
@@ -232,8 +311,9 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
232
311
|
|
|
233
312
|
// 分时离线兜底: 只续在当日真实分时后面。
|
|
234
313
|
// 没有真实分时打底时, 几个报价点连成的线说明不了走势, 不如把上游错误如实抛出去
|
|
235
|
-
async function offlineTrend(
|
|
236
|
-
const
|
|
314
|
+
async function offlineTrend(key, error) {
|
|
315
|
+
const { market, securityId } = key
|
|
316
|
+
const cached = await trendCache.get(key)
|
|
237
317
|
if (!cached) return null
|
|
238
318
|
const real = cached.payload.candles || []
|
|
239
319
|
const lastAt = Number(real.at(-1)?.at)
|
|
@@ -246,11 +326,16 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
246
326
|
...(appended.length ? { complete: false } : {}),
|
|
247
327
|
// 拍点只有收盘价: 开高低补齐成同一个值, 否则客户端按 OHLC 校验会把每根都丢掉, 图上仍然是空的
|
|
248
328
|
candles: [...real, ...appended],
|
|
329
|
+
sessionDate: cached.sessionDate,
|
|
249
330
|
offline: { kind: 'cache', cachedAt: cached.cachedAt, appended: appended.length, reason: error.message },
|
|
250
331
|
}
|
|
251
332
|
}
|
|
252
333
|
|
|
253
334
|
return {
|
|
335
|
+
// 路由层超时随刷新档位走: 节拍越慢, 落在拍后半段的请求要等越久, 超时必须盖住这段等待
|
|
336
|
+
routeTimeoutMs: () => routeTimeoutMs(state.get().preferences),
|
|
337
|
+
// 探针预算必须由路由层按同一口径取: 先解析输入算出待测目标数, 再定这条请求的时限
|
|
338
|
+
providerCheckTimeoutMs: input => probeBudgetMs(probeInput(input).groups),
|
|
254
339
|
snapshot, providerCheck, configuration,
|
|
255
340
|
demand(message) { assertLive(); demand.update(message) },
|
|
256
341
|
async search(q, phase = 'local', signal) {
|
|
@@ -258,18 +343,8 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
258
343
|
if (typeof q !== 'string' || [...q].length > 100) fail('INVALID_QUERY', '搜索词过长')
|
|
259
344
|
const items = phase === 'remote' ? await catalog.remote(q, signal) : catalog.search(q)
|
|
260
345
|
decorateWithMarketMeta(items)
|
|
261
|
-
|
|
262
|
-
|
|
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 }
|
|
346
|
+
// 美股映射由适配器写入, 上限与过期在容器里保证, 这里不再扫全表
|
|
347
|
+
return { items, catalogs: catalog.status(), routingRevision: state.get().routingRevision }
|
|
273
348
|
},
|
|
274
349
|
async kline(input, signal) {
|
|
275
350
|
assertLive()
|
|
@@ -281,27 +356,64 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
281
356
|
const config = state.get()
|
|
282
357
|
// 分时与日/周/月是两种上游, 各走各的路由: K 线来源不供分时时, 分时不该跟着一起死
|
|
283
358
|
const capability = period === 'trend' ? 'trend' : 'kline'
|
|
284
|
-
const { route, instance } = selectRoute(capability, exchange)
|
|
285
|
-
// 同轮补救只取环上的下一格: 走到末级时回到主源,
|
|
286
|
-
|
|
287
|
-
const
|
|
288
|
-
|
|
289
|
-
|
|
359
|
+
const { route, instance, routeEpoch } = selectRoute(capability, exchange)
|
|
360
|
+
// 同轮补救只取环上的下一格: 走到末级时回到主源, 否则末级是死胡同。
|
|
361
|
+
// 分时跳过停用/无预算成员, 与 recordRound 的切换口径一致; K 线维持原语义
|
|
362
|
+
const usable = provider => provider && provider.enabled !== false && provider.budget?.requestsPerMinute !== null
|
|
363
|
+
const next = capability === 'trend' ? router.nextInRing(route.id, instance.id, provider => !usable(provider)) : router.nextInRing(route.id, instance.id)
|
|
364
|
+
const fallbacks = next ? config.providers.filter(p => p.id === next && usable(p)) : []
|
|
365
|
+
const request = { securityId: sid, market: exchange, code, period, adjust: 'qfq', limit }
|
|
366
|
+
if (capability === 'trend') {
|
|
367
|
+
const keyOfSelection = (epoch, instanceId) => ({ market: exchange, code, limit, securityId: sid, routeKey: `${config.routingRevision}:${route.id}:${epoch}:${instanceId}` })
|
|
368
|
+
const key = keyOfSelection(routeEpoch, instance.id)
|
|
369
|
+
const assertRoute = epoch => {
|
|
370
|
+
if (config.routingRevision !== state.get().routingRevision || router.select('trend', exchange).routeEpoch !== epoch) fail('ROUTE_CONFLICT', '分时来源已变化,请重新刷新', 409)
|
|
371
|
+
}
|
|
372
|
+
const result = await trendCache.fetch(key, signal, async (sharedSignal, moveTo) => {
|
|
373
|
+
let epoch = routeEpoch, activeKey = key
|
|
374
|
+
const reportRound = error => {
|
|
375
|
+
assertRoute(epoch)
|
|
376
|
+
router.recordRound(route.id, error)
|
|
377
|
+
const current = router.select('trend', exchange)
|
|
378
|
+
if (current.routeEpoch !== epoch && fallbacks.some(spare => spare.id === current.instance.id)) {
|
|
379
|
+
epoch = current.routeEpoch
|
|
380
|
+
activeKey = keyOfSelection(epoch, current.instance.id)
|
|
381
|
+
moveTo(activeKey)
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
try {
|
|
385
|
+
const data = await runWithFailover(capability, route, instance, fallbacks, request, sharedSignal, reportRound, deadlineOf())
|
|
386
|
+
assertRoute(epoch)
|
|
387
|
+
await trendCache.put(activeKey, data)
|
|
388
|
+
return { ...data, routeEpoch: epoch }
|
|
389
|
+
} catch (error) {
|
|
390
|
+
if (!sharedSignal.aborted) {
|
|
391
|
+
assertRoute(epoch)
|
|
392
|
+
error.routeEpoch = epoch
|
|
393
|
+
}
|
|
394
|
+
throw error
|
|
395
|
+
}
|
|
396
|
+
}).catch(async error => {
|
|
397
|
+
if (['CANCELLED', 'ROUTE_CONFLICT'].includes(error.code)) throw error
|
|
398
|
+
const epoch = error.routeEpoch ?? routeEpoch
|
|
399
|
+
assertRoute(epoch)
|
|
400
|
+
const current = router.select('trend', exchange)
|
|
401
|
+
const offline = await offlineTrend(keyOfSelection(epoch, current.instance.id), error)
|
|
402
|
+
if (!offline) throw error
|
|
403
|
+
return { ...offline, routeEpoch: epoch }
|
|
404
|
+
})
|
|
405
|
+
assertRoute(result.routeEpoch)
|
|
406
|
+
const sessionDate = result.offline ? result.sessionDate : trendSessionDate(exchange, result)
|
|
407
|
+
return { ...result, source: result.providerInstanceId, revision: config.revision, serverEpoch, routingRevision: config.routingRevision, sessionDate }
|
|
408
|
+
}
|
|
409
|
+
if (force !== '1') {
|
|
290
410
|
for (const cand of [instance, ...fallbacks.filter(spare => spare.id !== instance.id)]) {
|
|
291
411
|
const cached = await klineCache.get({ providerInstanceId: cand.id, market: exchange, period, code, limit }, config.routingRevision)
|
|
292
412
|
if (cached) return { ...cached.payload, source: cand.id, revision: config.revision }
|
|
293
413
|
}
|
|
294
414
|
}
|
|
295
|
-
const result = await runWithFailover(capability, route, instance, fallbacks,
|
|
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)
|
|
415
|
+
const result = await runWithFailover(capability, route, instance, fallbacks, request, signal, undefined, deadlineOf())
|
|
416
|
+
await klineCache.put({ providerInstanceId: result.providerInstanceId, market: exchange, period, code, limit }, result, config.routingRevision)
|
|
305
417
|
return { ...result, source: result.providerInstanceId, revision: config.revision }
|
|
306
418
|
},
|
|
307
419
|
async browse(input) {
|
|
@@ -342,6 +454,7 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
342
454
|
// 密钥只写宿主的凭据存储, 不回显也不落插件状态;引用必须已被某个数据源声明, 插件不越界写别人的密钥空间。
|
|
343
455
|
async credential(input) {
|
|
344
456
|
assertLive()
|
|
457
|
+
const credentialStore = credentialStoreOf()
|
|
345
458
|
if (!credentialStore) fail('UNSUPPORTED', '宿主未提供凭据服务', 501)
|
|
346
459
|
const ref = z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).parse(input.ref)
|
|
347
460
|
if (!state.get().providers.some(p => p.credentialRef === ref || p.proxyCredentialRef === ref)) fail('INVALID_REQUEST', '该凭据未被任何数据源使用', 422)
|
|
@@ -372,10 +485,10 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
372
485
|
fail('INVALID_REFRESH', `刷新证券参数无效:${path} ${first.message}`, 400)
|
|
373
486
|
}
|
|
374
487
|
let quotes
|
|
375
|
-
try { quotes = await collector.refresh(submitted?.data, { signal }) } catch (e) {
|
|
488
|
+
try { quotes = await collector.refresh(submitted?.data, { signal, automatic: input.automatic === true, deadline: deadlineOf() }) } catch (e) {
|
|
376
489
|
// peek 刷新失败时 collector 里还留着带 lastError 的条目(否则详情只剩"等待报价");
|
|
377
490
|
// 常驻快照按自选过滤会顺手删掉它, 这里在快照构造前抓一份只随本次错误下发的报价。
|
|
378
|
-
const failed = collector.entries()
|
|
491
|
+
const failed = e.quotes ?? collector.entries()
|
|
379
492
|
e.snapshot = { ...snapshot(), quotes: failed }
|
|
380
493
|
throw e
|
|
381
494
|
}
|
|
@@ -395,6 +508,6 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
395
508
|
if (checked.status !== 'ready' || config.routingRevision !== state.get().routingRevision) fail('CHECK_REQUIRED', '主源未就绪或路由已变化', 422)
|
|
396
509
|
router.switchPrimary(route.id, input.expectedRouteEpoch); return snapshot()
|
|
397
510
|
},
|
|
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() },
|
|
511
|
+
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() },
|
|
399
512
|
}
|
|
400
513
|
}
|
package/src/catalog.mjs
CHANGED
|
@@ -45,17 +45,57 @@ export function createCatalog({ state, getControl = state.get, router, executor,
|
|
|
45
45
|
}
|
|
46
46
|
return result
|
|
47
47
|
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
48
|
+
// 整表展平与校验按"路由版本 + 缓存版本"记忆化: 一次搜索的 82% 成本是重复 zod 校验与建表,
|
|
49
|
+
// 目录本身只在 sync 写缓存时变, 缓存版本就是最直接的失效信号
|
|
50
|
+
let index = null
|
|
51
|
+
const indexOf = () => {
|
|
52
|
+
// 版本号是缓存的私有扩展: 传裸 Map 的调用方(基准/夹具)会静默失去失效能力, 宁可早炸
|
|
53
|
+
if (typeof state.cache.version !== 'number') fail('CACHE_CONTRACT', '目录缓存缺版本号', 500)
|
|
54
|
+
const version = `${getControl().routingRevision}:${state.cache.version}`
|
|
55
|
+
if (index?.version === version) return index.value
|
|
56
|
+
const byId = new Map()
|
|
57
|
+
// 同 id 后写者胜: 与缓存写入顺序一致, 换主源后新缓存必须盖掉旧的
|
|
58
|
+
for (const cache of records('catalog')) for (const s of cache.payload.items) byId.set(s.id, s)
|
|
59
|
+
index = { version, value: { items: [...byId.values()], byId } }
|
|
60
|
+
return index.value
|
|
52
61
|
}
|
|
53
62
|
function search(q, limit = 20) {
|
|
54
63
|
const query = q.trim().toLowerCase()
|
|
55
64
|
if (!query) return []
|
|
56
65
|
// 代码大小写不敏感: 美股代码全大写, 逐字比较会让本地目录搜不到 aapl/apple
|
|
57
66
|
const score = s => { const code = s.code.toLowerCase(), name = s.officialName.toLowerCase(); return code === query ? 0 : name === query ? 1 : code.startsWith(query) ? 2 : name.includes(query) ? 3 : s.cnspell?.toLowerCase().startsWith(query) ? 4 : 99 }
|
|
58
|
-
return
|
|
67
|
+
return indexOf().items.map(s => ({ s, rank: score(s) })).filter(r => r.rank < 99).sort((a, b) => a.rank - b.rank || a.s.id.localeCompare(b.s.id)).slice(0, limit).map(r => r.s)
|
|
68
|
+
}
|
|
69
|
+
// 目录同步走闭包: 挂在返回对象上时 this.sync 一旦被解构或换绑就丢 this
|
|
70
|
+
const sync = async (market, capabilities = ['catalog', 'calendar']) => {
|
|
71
|
+
const config = structuredClone(getControl()), key = `${config.routingRevision}:${market}:${capabilities.join(',')}`
|
|
72
|
+
if (flights.has(key)) return flights.get(key)
|
|
73
|
+
const controller = new AbortController(); controllers.add(controller)
|
|
74
|
+
const job = (async () => {
|
|
75
|
+
const status = []
|
|
76
|
+
for (const capability of capabilities) {
|
|
77
|
+
try {
|
|
78
|
+
const selected = router.select(capability, market)
|
|
79
|
+
const today = marketDate(market, now())
|
|
80
|
+
const request = { market, routingRevision: config.routingRevision, startDate: shiftDate(today, -7), endDate: shiftDate(today, 45) }
|
|
81
|
+
const batch = await executor.run(selected.instance, capability, request, { signal: controller.signal })
|
|
82
|
+
if (stopped || config.routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '来源已变化,旧目录已丢弃', 409)
|
|
83
|
+
if (!Array.isArray(batch.items) || capability === 'catalog' && batch.items.some(s => !securitySchema.safeParse(s).success || s.exchange !== market) || capability === 'calendar' && batch.items.some(d => !/^\d{4}-\d{2}-\d{2}$/.test(d.date) || typeof d.isOpen !== 'boolean')) fail('BAD_PAYLOAD', '目录来源返回不受支持的证券身份', 502)
|
|
84
|
+
const items = batch.items
|
|
85
|
+
await state.cache.put(`${capability}:${selected.instance.id}:${market}`, { kind: capability, source: selected.instance.id, fetchedAt: now(), payload: { routingRevision: config.routingRevision, market, complete: batch.complete ?? true, items } })
|
|
86
|
+
if (capability === 'calendar') marketStateCache.clear()
|
|
87
|
+
setBounded(syncAttempts, `${capability}:${market}`, { ok: true, at: now(), revision: config.routingRevision }, SYNC_ATTEMPT_LIMIT)
|
|
88
|
+
status.push({ capability, ok: true, count: items.length }); changed()
|
|
89
|
+
} catch (e) {
|
|
90
|
+
setBounded(syncAttempts, `${capability}:${market}`, { ok: false, at: now(), revision: config.routingRevision, error: { code: e.code, message: e.message } }, SYNC_ATTEMPT_LIMIT)
|
|
91
|
+
status.push({ capability, ok: false, error: { code: e.code, message: e.message } })
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return status
|
|
95
|
+
})()
|
|
96
|
+
flights.set(key, job)
|
|
97
|
+
job.finally(() => { flights.delete(key); controllers.delete(controller) }).catch(() => {})
|
|
98
|
+
return job
|
|
59
99
|
}
|
|
60
100
|
return {
|
|
61
101
|
search,
|
|
@@ -69,18 +109,18 @@ export function createCatalog({ state, getControl = state.get, router, executor,
|
|
|
69
109
|
// 只认当前路由版本下的失败: 换过路由还回旧版本的错误, 会把已经修好的市场显示成失败
|
|
70
110
|
const failed = attempt?.ok === false && attempt.revision === revision
|
|
71
111
|
const due = !failed || now() - attempt.at >= AUTO_SYNC_RETRY_MS
|
|
72
|
-
if (due)
|
|
112
|
+
if (due) sync(market, ['catalog']).catch(() => {})
|
|
73
113
|
return { syncing: true, syncError: failed ? attempt.error : null, syncAttemptAt: failed ? attempt.at : null, total: 0, items: [] }
|
|
74
114
|
}
|
|
75
115
|
// 已有目录但过期: 先展示旧数据, 同时后台刷新, 下一次浏览/轮询就能拿到新目录
|
|
76
116
|
const newest = Math.max(...cached.map(c => c.fetchedAt))
|
|
77
|
-
if (now() - newest > CATALOG_TTL)
|
|
78
|
-
const securities =
|
|
117
|
+
if (now() - newest > CATALOG_TTL) sync(market, ['catalog']).catch(() => {})
|
|
118
|
+
const securities = indexOf().items.filter(s => s.exchange === market).sort((a, b) => a.code.localeCompare(b.code))
|
|
79
119
|
const start = Math.max(0, Math.trunc(Number(offset) || 0)), size = Math.min(200, Math.max(1, Math.trunc(Number(limit) || 50)))
|
|
80
120
|
return { total: securities.length, items: securities.slice(start, start + size) }
|
|
81
121
|
},
|
|
82
122
|
resolve(id) {
|
|
83
|
-
const cached =
|
|
123
|
+
const cached = indexOf().byId.get(id)
|
|
84
124
|
if (cached) return cached
|
|
85
125
|
const candidate = candidates.get(id)
|
|
86
126
|
return candidate && candidate.until > now() && candidate.revision === getControl().routingRevision ? candidate.security : null
|
|
@@ -142,39 +182,10 @@ export function createCatalog({ state, getControl = state.get, router, executor,
|
|
|
142
182
|
const today = marketDate(route.market, now())
|
|
143
183
|
const ttl = route.capability === 'calendar' ? CALENDAR_TTL : CATALOG_TTL
|
|
144
184
|
const missing = !cache || now() - cache.fetchedAt > ttl || route.capability === 'calendar' && !cache.payload.items.some(day => day.date === today)
|
|
145
|
-
if (missing) await
|
|
185
|
+
if (missing) await sync(route.market, [route.capability])
|
|
146
186
|
}
|
|
147
187
|
},
|
|
148
|
-
|
|
149
|
-
const config = structuredClone(getControl()), key = `${config.routingRevision}:${market}:${capabilities.join(',')}`
|
|
150
|
-
if (flights.has(key)) return flights.get(key)
|
|
151
|
-
const controller = new AbortController(); controllers.add(controller)
|
|
152
|
-
const job = (async () => {
|
|
153
|
-
const status = []
|
|
154
|
-
for (const capability of capabilities) {
|
|
155
|
-
try {
|
|
156
|
-
const selected = router.select(capability, market)
|
|
157
|
-
const today = marketDate(market, now())
|
|
158
|
-
const request = { market, routingRevision: config.routingRevision, startDate: shiftDate(today, -7), endDate: shiftDate(today, 45) }
|
|
159
|
-
const batch = await executor.run(selected.instance, capability, request, { signal: controller.signal })
|
|
160
|
-
if (stopped || config.routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '来源已变化,旧目录已丢弃', 409)
|
|
161
|
-
if (!Array.isArray(batch.items) || capability === 'catalog' && batch.items.some(s => !securitySchema.safeParse(s).success || s.exchange !== market) || capability === 'calendar' && batch.items.some(d => !/^\d{4}-\d{2}-\d{2}$/.test(d.date) || typeof d.isOpen !== 'boolean')) fail('BAD_PAYLOAD', '目录来源返回不受支持的证券身份', 502)
|
|
162
|
-
const items = batch.items
|
|
163
|
-
await state.cache.put(`${capability}:${selected.instance.id}:${market}`, { kind: capability, source: selected.instance.id, fetchedAt: now(), payload: { routingRevision: config.routingRevision, market, complete: batch.complete ?? true, items } })
|
|
164
|
-
if (capability === 'calendar') marketStateCache.clear()
|
|
165
|
-
setBounded(syncAttempts, `${capability}:${market}`, { ok: true, at: now(), revision: config.routingRevision }, SYNC_ATTEMPT_LIMIT)
|
|
166
|
-
status.push({ capability, ok: true, count: items.length }); changed()
|
|
167
|
-
} catch (e) {
|
|
168
|
-
setBounded(syncAttempts, `${capability}:${market}`, { ok: false, at: now(), revision: config.routingRevision, error: { code: e.code, message: e.message } }, SYNC_ATTEMPT_LIMIT)
|
|
169
|
-
status.push({ capability, ok: false, error: { code: e.code, message: e.message } })
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
return status
|
|
173
|
-
})()
|
|
174
|
-
flights.set(key, job)
|
|
175
|
-
job.finally(() => { flights.delete(key); controllers.delete(controller) }).catch(() => {})
|
|
176
|
-
return job
|
|
177
|
-
},
|
|
188
|
+
sync,
|
|
178
189
|
marketState(market) {
|
|
179
190
|
const at = now(), date = marketDate(market, at), revision = getControl().routingRevision
|
|
180
191
|
const key = `${market}:${date}:${revision}`
|