@mzzsfy/dsh-stock-assistant 0.9.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 +117 -4
- package/README.md +24 -18
- package/package.json +1 -1
- package/src/application.mjs +377 -123
- package/src/budget.mjs +16 -15
- package/src/catalog.mjs +145 -93
- package/src/client.js +1067 -380
- package/src/client.js~RF25ea9e49.TMP +3301 -0
- package/src/collector.mjs +171 -93
- package/src/executor.mjs +212 -60
- package/src/index.js +5 -3
- package/src/kline-cache.mjs +10 -13
- package/src/market-model.mjs +35 -8
- package/src/memory-cache.mjs +5 -1
- package/src/provider-router.mjs +13 -7
- package/src/providers/eastmoney.mjs +128 -57
- package/src/providers/sina.mjs +63 -41
- package/src/providers/tencent.mjs +19 -5
- package/src/providers/tushare.mjs +11 -2
- package/src/providers/us-markets.mjs +4 -0
- package/src/providers/xueqiu.mjs +68 -27
- package/src/recovery.mjs +29 -14
- package/src/routes.mjs +18 -5
- package/src/schemas.mjs +15 -22
- package/src/state.mjs +17 -2
- package/src/trend-cache.mjs +114 -12
- package/src/us-symbols.mjs +30 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +239 -13
package/src/application.mjs
CHANGED
|
@@ -13,43 +13,84 @@ 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
|
-
import { fail, parseSecurityId, MARKET_META, clockInZone } from './market-model.mjs'
|
|
24
|
+
import { fail, StockError, parseSecurityId, MARKET_META, clockInZone } from './market-model.mjs'
|
|
24
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
|
+
}
|
|
38
|
+
// 探针诊断的节流窗口内最多发起多少次检查: 检查会真的打上游, 不能由页面无限触发
|
|
39
|
+
const PROBE_CHECK_LIMIT = 64
|
|
40
|
+
// 探针总预算上限: 目标多到推导值超过它时不再加长请求, 改为交出已完成的部分诊断
|
|
41
|
+
const PROBE_TIMEOUT_CEILING_MS = 2 * 60 * 1000
|
|
42
|
+
// 响应收尾(序列化 + 写日志)留在路由计时之内的裕度
|
|
43
|
+
const PROBE_RESPONSE_MARGIN_MS = 2 * 1000
|
|
25
44
|
// 分时来源(东财/腾讯)的时间戳统一按北京时间给出, 拍点线的横轴必须与之一致, 否则切到离线时整体偏移
|
|
26
45
|
const TREND_SOURCE_TIME_ZONE = 'Asia/Shanghai'
|
|
27
|
-
const US_SYMBOL_TTL = 24 * 60 * 60 * 1000
|
|
28
|
-
const US_SYMBOL_LIMIT = 500
|
|
29
46
|
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()
|
|
47
|
+
const serverEpoch = randomUUID()
|
|
48
|
+
// 检查节流按最近一次窗口内的时间戳计: 固定窗口会在边界放行双倍突发, 探针是真的打上游
|
|
49
|
+
const probeTimes = []
|
|
31
50
|
// 凭据解析: 宿主提供 credentials 服务时交给它(插件存储层优先, 再逐层回退到进程环境与 .env 文件),
|
|
32
51
|
// 否则退回进程环境变量。引用只表示"哪个密钥", 值始终由宿主保管。
|
|
33
52
|
// 接口按能力逐个核对: 宿主给的对象缺哪个方法, 就只退回哪条路径, 而不是在取数时炸掉。
|
|
34
|
-
|
|
35
|
-
const
|
|
53
|
+
// 服务按次取: 宿主凭据 fiber 可能晚于插件 apply 就绪, 只取一次会把"晚到"固化成永久缺失
|
|
54
|
+
const credentialService = () => typeof credentials === 'function' ? credentials() : credentials
|
|
55
|
+
const credentialStoreOf = () => {
|
|
56
|
+
const service = credentialService()
|
|
57
|
+
return service && ['resolve', 'set', 'unset'].every(method => typeof service[method] === 'function') ? service : null
|
|
58
|
+
}
|
|
59
|
+
const resolveCredential = async ref => {
|
|
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
|
+
}
|
|
66
|
+
}
|
|
36
67
|
let snapshotSeq = 0, stopped = false, collector, catalog, demand, watchlist, recoveryLoop
|
|
37
68
|
let ensuring = null, lastEnsure = -Infinity, ensureError = null, hadDemand = false, ensureCaches = () => {}
|
|
38
|
-
const usSymbols =
|
|
69
|
+
const usSymbols = createUsSymbols({ now })
|
|
39
70
|
const touched = () => snapshotSeq++
|
|
40
71
|
const changed = () => { touched(); publish({ type: 'invalidate', serverEpoch, snapshotSeq, scopes: ['snapshot'] }) }
|
|
41
|
-
//
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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()
|
|
48
90
|
}
|
|
49
91
|
let state, registry, executor, getControl, router, klineCache, trendCache, ticks
|
|
50
92
|
try {
|
|
51
93
|
state = await openState(storageDomain, changed, now)
|
|
52
|
-
await refreshCredentialPresence()
|
|
53
94
|
registry = createRegistry(providers)
|
|
54
95
|
const budget = createBudget(now)
|
|
55
96
|
// 代理出口: undici ProxyAgent + 同一份 undici.fetch。dispatcher 是 undici 私有契约,
|
|
@@ -62,22 +103,37 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
62
103
|
} catch {}
|
|
63
104
|
executor = createExecutor({ registry, budget, env, resolveCredential, fetch, proxyFetch, now, timers, usSymbols, proxyFactory, tickPeriodMs: () => tickPeriodMs(state.get().preferences) })
|
|
64
105
|
getControl = state.get
|
|
65
|
-
//
|
|
66
|
-
|
|
67
|
-
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))
|
|
68
116
|
klineCache = createKlineCache({ cacheTable: state.klineCache, now })
|
|
69
117
|
// 分时当日缓存走独立小池: 它与报价拍点都只放内存, 不入配置记录
|
|
70
118
|
trendCache = createTrendCache({ table: state.trendCache, now })
|
|
71
119
|
ticks = createTickStore({ now })
|
|
72
120
|
// 回探跟着面板活跃走: 有人看时每 RECOVERY_PROBE_MS 把已降级路由的上级全探一遍, 没人看就停
|
|
73
|
-
|
|
74
|
-
|
|
121
|
+
// 回探要的是当前生效的 provider/route 表: 传控制记录读取器(整条记录)会让 getConfig() 直接抛错,
|
|
122
|
+
// 而循环把异常吞掉 —— 降级路由的自动回切会静默地一次都不跑
|
|
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 })
|
|
75
131
|
demand = createDemand(() => {
|
|
76
132
|
const wanted = demand.active(), opening = wanted && !hadDemand; hadDemand = wanted
|
|
77
133
|
if (wanted) {
|
|
78
134
|
// 缓存新鲜时进入面板不重复打上游(限流主因); 过期才拉取, 定时器照常量节奏维持
|
|
79
135
|
const freshFor = (getControl().preferences?.refreshSeconds ?? 15) * 1000
|
|
80
|
-
if (opening && !collector?.freshWithin(freshFor)) collector?.refresh().catch(() => {})
|
|
136
|
+
if (opening && !collector?.freshWithin(freshFor)) collector?.refresh(undefined, { automatic: true }).catch(() => {})
|
|
81
137
|
collector?.reconcile()
|
|
82
138
|
} else {
|
|
83
139
|
// 后台预热只在面板空闲时做: 之前只写在 wanted 分支又要求 !demand.active(), 两个条件互斥,
|
|
@@ -92,6 +148,7 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
92
148
|
// 存量配置升级: 分时能力独立后没有 trend 路由的库在打开时补齐。
|
|
93
149
|
// 补齐失败不该让整个面板躺下(面板可用性高于分时), 记下原因继续, 与目录预热同构
|
|
94
150
|
try { await ensureTrendRoutes() } catch (e) { ensureError = { message: `分时来源补齐失败:${e.message}`, at: now() } }
|
|
151
|
+
await refreshCredentialPresence(false)
|
|
95
152
|
// 面板活跃(demand)时让路: 目录后台同步占满并发槽会拖死交互请求(浏览504实测), 仅在面板空闲时补目录
|
|
96
153
|
ensureCaches = () => {
|
|
97
154
|
if (ensuring || now() - lastEnsure < 60 * 1000 || demand.active()) return
|
|
@@ -105,41 +162,123 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
105
162
|
throw e
|
|
106
163
|
}
|
|
107
164
|
const snapshot = () => {
|
|
108
|
-
|
|
109
|
-
|
|
165
|
+
// 台账不随快照下发; 读侧共享同一份冻结快照, 不能原地删字段
|
|
166
|
+
const { operations, ...control } = state.get()
|
|
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 }])) }
|
|
110
168
|
}
|
|
111
169
|
function assertLive() { if (stopped) fail('STOPPED', '股票工具已停止', 503) }
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
const
|
|
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
|
+
}
|
|
183
|
+
// 待测目标表: 一条路由的每个实例各算一个探针, 同 (实例, 能力, 市场) 只测一次。
|
|
184
|
+
// 组内串行由执行器的额度组间隔保证, 所以并行度按额度组切分, 而不是按目标数。
|
|
185
|
+
const probePlan = (config, caps) => {
|
|
186
|
+
const plan = [], seen = new Set(), groups = new Map()
|
|
120
187
|
for (const route of config.routes.filter(r => caps.includes(r.capability))) for (const target of [route.primaryInstanceId, ...route.fallbackInstanceIds]) {
|
|
121
188
|
const instance = config.providers.find(p => p.id === target)
|
|
122
189
|
registry.validate(instance, route)
|
|
123
190
|
const key = `${instance.id}:${route.capability}:${route.market}`
|
|
124
|
-
if (
|
|
125
|
-
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
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 } }) }
|
|
191
|
+
if (seen.has(key)) continue
|
|
192
|
+
seen.add(key)
|
|
193
|
+
const probe = { key, instance, route, capability: route.capability, market: route.market }
|
|
194
|
+
plan.push(probe)
|
|
195
|
+
const gap = groupGapMs(instance)
|
|
196
|
+
const group = groups.get(instance.quotaGroup)
|
|
197
|
+
groups.set(instance.quotaGroup, { count: (group?.count || 0) + 1, gap: Math.max(group?.gap || 0, gap) })
|
|
133
198
|
}
|
|
134
|
-
|
|
135
|
-
|
|
199
|
+
return { plan, groups }
|
|
200
|
+
}
|
|
201
|
+
// 预算跟着工作量走: 48 个探针按 1 秒间隔排开已接近一分钟, 再套固定 60 秒必然在中途被掐断。
|
|
202
|
+
// 组内串行、跨组并行, 但探针和行情共用执行器的并发槽: 最长的一组先占一个槽, 其余工作量按槽位数摊
|
|
203
|
+
const probeBudgetMs = groups => {
|
|
204
|
+
let work = 0, worst = 0
|
|
205
|
+
for (const group of groups.values()) {
|
|
206
|
+
const cost = group.count * (group.gap + UPSTREAM_TIMEOUT_MS)
|
|
207
|
+
work += cost
|
|
208
|
+
worst = Math.max(worst, cost)
|
|
209
|
+
}
|
|
210
|
+
// makespan 的上界: 最长一组独占一个槽, 剩余工作量由剩下的槽位分摊
|
|
211
|
+
return Math.min(worst + (work - worst) / EXECUTOR_CONCURRENCY + PROBE_RESPONSE_MARGIN_MS, PROBE_TIMEOUT_CEILING_MS)
|
|
212
|
+
}
|
|
213
|
+
const probeInput = input => {
|
|
214
|
+
const config = parseConfiguration({ providers: input.providers, routes: input.routes })
|
|
215
|
+
const caps = z.array(z.enum(CAPABILITIES)).min(1).max(CAPABILITIES.length).parse(input.capabilities)
|
|
216
|
+
return { config, caps, ...probePlan(config, caps) }
|
|
217
|
+
}
|
|
218
|
+
async function providerCheck(input, signal) {
|
|
219
|
+
assertLive()
|
|
220
|
+
const { config, plan, groups } = probeInput(input)
|
|
221
|
+
const { routingRevision } = getControl()
|
|
222
|
+
const at = now()
|
|
223
|
+
while (probeTimes.length && at - probeTimes[0] >= WINDOW) probeTimes.shift()
|
|
224
|
+
if (probeTimes.length >= PROBE_CHECK_LIMIT) fail('CHECK_LIMIT', '检查请求过多,请稍后重试', 429)
|
|
225
|
+
probeTimes.push(at)
|
|
226
|
+
// 自查截止时刻比路由预算早一个裕度: 预算用完时交出已完成的部分诊断, 而不是整条 504
|
|
227
|
+
const deadline = at + probeBudgetMs(groups) - PROBE_RESPONSE_MARGIN_MS
|
|
228
|
+
const results = new Array(plan.length)
|
|
229
|
+
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 } })
|
|
230
|
+
const byGroup = new Map()
|
|
231
|
+
for (const [index, probe] of plan.entries()) byGroup.set(probe.instance.quotaGroup, [...(byGroup.get(probe.instance.quotaGroup) || []), { index, probe }])
|
|
232
|
+
await Promise.all([...byGroup.values()].map(async group => {
|
|
233
|
+
for (const { index, probe } of group) {
|
|
234
|
+
if (signal?.aborted) { results[index] = skipped(probe, 'CANCELLED', '检查已取消'); continue }
|
|
235
|
+
if (now() >= deadline) { results[index] = skipped(probe, 'CHECK_DEADLINE', '检查预算用完,此项未执行'); continue }
|
|
236
|
+
// 截止时刻也要打断在途探针: 排队等并发槽的探针既不受现在剩余预算的约束,
|
|
237
|
+
// 也让整条请求越过路由计时器被 504 掉 —— 那样一条诊断都交不出来
|
|
238
|
+
const limiter = new AbortController()
|
|
239
|
+
const expire = () => limiter.abort()
|
|
240
|
+
const abortByOuter = () => limiter.abort()
|
|
241
|
+
const timer = timers.setTimeout(expire, Math.max(0, deadline - now()))
|
|
242
|
+
signal?.addEventListener('abort', abortByOuter, { once: true })
|
|
243
|
+
// 探针耗时就是这一条路由端到端拿数据的真实延迟, 用于把「能不能用」和「快不快」一起回给用户
|
|
244
|
+
const startedAt = now()
|
|
245
|
+
try {
|
|
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 })
|
|
253
|
+
// 探针必须由同名能力的端点产出: 适配器拿别的能力冒充(漏实现分支)时不能当就绪, 且要说清是谁被验了
|
|
254
|
+
const ready = result?.status === 'ready' && result.capability === probe.capability
|
|
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 ?? '未知'}能力` } }) }
|
|
256
|
+
} catch (e) {
|
|
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
|
+
}
|
|
266
|
+
} finally {
|
|
267
|
+
timers.clearTimeout(timer)
|
|
268
|
+
signal?.removeEventListener('abort', abortByOuter)
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}))
|
|
272
|
+
const completed = results.filter(Boolean)
|
|
136
273
|
// 解除采集暂停只认行情: 分时/目录/K 线的探针失败不该左右行情采集状态机
|
|
137
|
-
const quoteResults =
|
|
138
|
-
if (digest(config) === digest({ providers: getControl().providers, routes: getControl().routes })
|
|
139
|
-
|
|
274
|
+
const quoteResults = completed.filter(r => r.capability === 'quotes')
|
|
275
|
+
if (quoteResults.length && quoteResults.every(r => r.status === 'ready') && digest(config) === digest({ providers: getControl().providers, routes: getControl().routes })) collector.resume()
|
|
276
|
+
const partial = completed.some(r => r.status === 'skipped')
|
|
277
|
+
return { checkId: randomUUID(), checks: completed, partial }
|
|
140
278
|
}
|
|
141
279
|
async function configuration(operation) {
|
|
142
280
|
assertLive()
|
|
281
|
+
if (operation.expectedServerEpoch !== undefined && operation.expectedServerEpoch !== serverEpoch) fail('REVISION_CONFLICT', '服务已重启,请刷新配置后重新确认', 409, { revision: state.get().revision })
|
|
143
282
|
const config = parseConfiguration(operation.payload)
|
|
144
283
|
const replay = state.replay({ ...operation, action: 'configuration', payload: config })
|
|
145
284
|
if (replay) return replay
|
|
@@ -152,7 +291,10 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
152
291
|
if (JSON.stringify(current.providers) === JSON.stringify(config.providers) && JSON.stringify(current.routes) === JSON.stringify(config.routes)) return current
|
|
153
292
|
return { ...current, ...config, routingRevision: current.routingRevision + 1 }
|
|
154
293
|
})
|
|
155
|
-
if (!result.unchanged
|
|
294
|
+
if (!result.unchanged && credentialPresence?.routingRevision !== state.get().routingRevision) {
|
|
295
|
+
collector.reset()
|
|
296
|
+
await refreshCredentialPresence()
|
|
297
|
+
}
|
|
156
298
|
return result
|
|
157
299
|
}
|
|
158
300
|
|
|
@@ -165,24 +307,52 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
165
307
|
}
|
|
166
308
|
// K 线类请求的即时故障转移: 触发码 NETWORK/TIMEOUT/BAD_PAYLOAD 时顺着「环上下一格」试一次;
|
|
167
309
|
// 只有当前选择自己的失败算一轮, 顺着链试备源是同一轮里的补救, 不额外计次
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
310
|
+
// 一条请求(含分批与备源链)共用的截止时刻: 超出即按超时收尾, 不让路由层 504 掉已成功的部分
|
|
311
|
+
const deadlineOf = () => now() + requestBudgetMs(state.get().preferences)
|
|
312
|
+
|
|
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
|
+
}
|
|
172
327
|
try {
|
|
173
|
-
|
|
174
|
-
// 当前选择能出数就是最好的证据: 清掉它的失败计数与探测退避
|
|
175
|
-
if (index === 0) router.recordRound(route.id, null)
|
|
176
|
-
return result
|
|
328
|
+
result = await executor.run(cand, capability, { ...request, routeEpoch: generation.epoch }, { signal, deadline, beforeDispatch })
|
|
177
329
|
} catch (e) {
|
|
178
|
-
if (
|
|
179
|
-
|
|
330
|
+
if (signal?.aborted) throw e
|
|
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
|
+
}
|
|
180
343
|
if (e.code === 'UNSUPPORTED_CAPABILITY') { unsupported ??= e; continue }
|
|
181
344
|
lastError = e
|
|
182
|
-
|
|
345
|
+
// 普通瞬时故障只补救一跳;分时冷却中的实例不占这次尝试。
|
|
346
|
+
if (!TRANSIENT_CODES.includes(e.code) || cand !== primary) throw e
|
|
347
|
+
continue
|
|
183
348
|
}
|
|
349
|
+
generation.assertCurrent()
|
|
350
|
+
if (cand === primary) generation.report(null)
|
|
351
|
+
return result
|
|
184
352
|
}
|
|
185
|
-
|
|
353
|
+
if (lastError) throw lastError
|
|
354
|
+
if (Number.isFinite(retryAt)) throw cooled(Math.max(1, retryAt - now()))
|
|
355
|
+
throw unsupported
|
|
186
356
|
}
|
|
187
357
|
// 分时没有路由时用户只会看到"未配置数据来源", 看不出缺的是哪一种能力
|
|
188
358
|
function selectRoute(capability, market) {
|
|
@@ -232,8 +402,9 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
232
402
|
|
|
233
403
|
// 分时离线兜底: 只续在当日真实分时后面。
|
|
234
404
|
// 没有真实分时打底时, 几个报价点连成的线说明不了走势, 不如把上游错误如实抛出去
|
|
235
|
-
async function offlineTrend(
|
|
236
|
-
const
|
|
405
|
+
async function offlineTrend(key, error) {
|
|
406
|
+
const { market, securityId } = key
|
|
407
|
+
const cached = await trendCache.get(key)
|
|
237
408
|
if (!cached) return null
|
|
238
409
|
const real = cached.payload.candles || []
|
|
239
410
|
const lastAt = Number(real.at(-1)?.at)
|
|
@@ -246,11 +417,35 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
246
417
|
...(appended.length ? { complete: false } : {}),
|
|
247
418
|
// 拍点只有收盘价: 开高低补齐成同一个值, 否则客户端按 OHLC 校验会把每根都丢掉, 图上仍然是空的
|
|
248
419
|
candles: [...real, ...appended],
|
|
420
|
+
sessionDate: cached.sessionDate,
|
|
249
421
|
offline: { kind: 'cache', cachedAt: cached.cachedAt, appended: appended.length, reason: error.message },
|
|
250
422
|
}
|
|
251
423
|
}
|
|
252
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
|
+
|
|
253
444
|
return {
|
|
445
|
+
// 路由层超时随刷新档位走: 节拍越慢, 落在拍后半段的请求要等越久, 超时必须盖住这段等待
|
|
446
|
+
routeTimeoutMs: () => routeTimeoutMs(state.get().preferences),
|
|
447
|
+
// 探针预算必须由路由层按同一口径取: 先解析输入算出待测目标数, 再定这条请求的时限
|
|
448
|
+
providerCheckTimeoutMs: input => probeBudgetMs(probeInput(input).groups),
|
|
254
449
|
snapshot, providerCheck, configuration,
|
|
255
450
|
demand(message) { assertLive(); demand.update(message) },
|
|
256
451
|
async search(q, phase = 'local', signal) {
|
|
@@ -258,18 +453,8 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
258
453
|
if (typeof q !== 'string' || [...q].length > 100) fail('INVALID_QUERY', '搜索词过长')
|
|
259
454
|
const items = phase === 'remote' ? await catalog.remote(q, signal) : catalog.search(q)
|
|
260
455
|
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 }
|
|
456
|
+
// 美股映射由适配器写入, 上限与过期在容器里保证, 这里不再扫全表
|
|
457
|
+
return { items, catalogs: catalog.status(), routingRevision: state.get().routingRevision }
|
|
273
458
|
},
|
|
274
459
|
async kline(input, signal) {
|
|
275
460
|
assertLive()
|
|
@@ -281,56 +466,104 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
281
466
|
const config = state.get()
|
|
282
467
|
// 分时与日/周/月是两种上游, 各走各的路由: K 线来源不供分时时, 分时不该跟着一起死
|
|
283
468
|
const capability = period === 'trend' ? 'trend' : 'kline'
|
|
284
|
-
const { route, instance } = selectRoute(capability, exchange)
|
|
285
|
-
|
|
286
|
-
const
|
|
287
|
-
const
|
|
288
|
-
//
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
469
|
+
const { route, instance, routeEpoch } = selectRoute(capability, exchange)
|
|
470
|
+
const { routingRevision } = config
|
|
471
|
+
const trend = capability === 'trend'
|
|
472
|
+
const usable = provider => provider && provider.enabled !== false && provider.budget?.requestsPerMinute !== null
|
|
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()
|
|
489
|
+
router.recordRound(route.id, error)
|
|
490
|
+
const current = router.select(capability, exchange)
|
|
491
|
+
if (current.routeEpoch !== epoch) {
|
|
492
|
+
epoch = current.routeEpoch
|
|
493
|
+
onMove(epoch, current.instance.id)
|
|
494
|
+
}
|
|
495
|
+
},
|
|
293
496
|
}
|
|
294
497
|
}
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
const
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
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)))
|
|
504
|
+
try {
|
|
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 }
|
|
509
|
+
} catch (error) {
|
|
510
|
+
if (!sharedSignal.aborted) {
|
|
511
|
+
generation.assertCurrent()
|
|
512
|
+
error.routeEpoch = generation.epoch
|
|
513
|
+
}
|
|
514
|
+
throw error
|
|
515
|
+
}
|
|
516
|
+
}).catch(async error => {
|
|
517
|
+
if (['CANCELLED', 'ROUTE_CONFLICT'].includes(error.code)) throw error
|
|
518
|
+
const epoch = error.routeEpoch ?? routeEpoch
|
|
519
|
+
assertRoute(epoch)
|
|
520
|
+
const offline = await offlineTrend(key, error)
|
|
521
|
+
if (!offline) throw error
|
|
522
|
+
return { ...offline, routeEpoch: epoch }
|
|
523
|
+
})
|
|
524
|
+
assertRoute(result.routeEpoch)
|
|
525
|
+
const sessionDate = result.offline ? result.sessionDate : trendSessionDate(exchange, result)
|
|
526
|
+
return { ...response(result, result.routeEpoch), sessionDate }
|
|
527
|
+
}
|
|
528
|
+
const generation = generationOf()
|
|
529
|
+
const keyOf = providerInstanceId => ({ providerInstanceId, market: exchange, period, code, limit, serverEpoch, routingRevision, routeEpoch: generation.epoch })
|
|
530
|
+
if (force !== '1') {
|
|
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)
|
|
535
|
+
}
|
|
536
|
+
}
|
|
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)
|
|
306
542
|
},
|
|
307
|
-
async browse(input) {
|
|
543
|
+
async browse(input, signal) {
|
|
308
544
|
assertLive()
|
|
309
545
|
if (!MARKET_META[input.market]) fail('INVALID_REQUEST', '市场参数无效')
|
|
310
|
-
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
}
|
|
324
|
-
} catch {}
|
|
325
|
-
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 }
|
|
326
559
|
},
|
|
327
|
-
async sync(input) {
|
|
560
|
+
async sync(input, signal) {
|
|
328
561
|
assertLive()
|
|
329
562
|
if (!MARKET_META[input.market] || input.expectedRoutingRevision !== state.get().routingRevision) fail('ROUTE_CONFLICT', '目录路由已变化', 409)
|
|
330
563
|
// 只同步该市场真实配置的能力: 默认参数同时要目录+日历, 没配日历时每次手动同步都必然回一条 NO_ROUTE 错误
|
|
331
564
|
const capabilities = ['catalog', 'calendar'].filter(capability => state.get().routes.some(route => route.capability === capability && route.market === input.market))
|
|
332
565
|
if (!capabilities.length) fail('NO_ROUTE', '该市场未配置目录或日历来源', 422)
|
|
333
|
-
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
|
|
334
567
|
},
|
|
335
568
|
async watchlist(operation) {
|
|
336
569
|
assertLive()
|
|
@@ -342,9 +575,13 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
342
575
|
// 密钥只写宿主的凭据存储, 不回显也不落插件状态;引用必须已被某个数据源声明, 插件不越界写别人的密钥空间。
|
|
343
576
|
async credential(input) {
|
|
344
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)
|
|
581
|
+
const credentialStore = credentialStoreOf()
|
|
345
582
|
if (!credentialStore) fail('UNSUPPORTED', '宿主未提供凭据服务', 501)
|
|
346
583
|
const ref = z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).parse(input.ref)
|
|
347
|
-
if (!
|
|
584
|
+
if (!control.providers.some(p => p.credentialRef === ref || p.proxyCredentialRef === ref)) fail('INVALID_REQUEST', '该凭据未被任何数据源使用', 422)
|
|
348
585
|
const value = input.value === null ? null : z.string().min(1).max(512).parse(input.value)
|
|
349
586
|
if (value === null) await credentialStore.unset(ref)
|
|
350
587
|
else await credentialStore.set(ref, value)
|
|
@@ -372,10 +609,10 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
372
609
|
fail('INVALID_REFRESH', `刷新证券参数无效:${path} ${first.message}`, 400)
|
|
373
610
|
}
|
|
374
611
|
let quotes
|
|
375
|
-
try { quotes = await collector.refresh(submitted?.data, { signal }) } catch (e) {
|
|
612
|
+
try { quotes = await collector.refresh(submitted?.data, { signal, automatic: input.automatic === true, deadline: deadlineOf() }) } catch (e) {
|
|
376
613
|
// peek 刷新失败时 collector 里还留着带 lastError 的条目(否则详情只剩"等待报价");
|
|
377
614
|
// 常驻快照按自选过滤会顺手删掉它, 这里在快照构造前抓一份只随本次错误下发的报价。
|
|
378
|
-
const failed = collector.entries()
|
|
615
|
+
const failed = e.quotes ?? collector.entries()
|
|
379
616
|
e.snapshot = { ...snapshot(), quotes: failed }
|
|
380
617
|
throw e
|
|
381
618
|
}
|
|
@@ -386,15 +623,32 @@ export async function createApplication({ storageDomain, providers = [tushare, t
|
|
|
386
623
|
assertLive()
|
|
387
624
|
const config = state.get(), route = config.routes.find(r => r.id === input.routeId)
|
|
388
625
|
if (!route || input.target !== 'primary' || input.expectedRoutingRevision !== config.routingRevision) fail('ROUTE_CONFLICT', '路由配置已变化', 409)
|
|
626
|
+
const { routingRevision } = config
|
|
389
627
|
const instance = config.providers.find(p => p.id === route.primaryInstanceId)
|
|
390
|
-
const
|
|
391
|
-
|
|
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
|
+
}
|
|
392
635
|
registry.validate(instance, route)
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
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()
|
|
397
651
|
},
|
|
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() },
|
|
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() },
|
|
399
653
|
}
|
|
400
654
|
}
|