@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/collector.mjs
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import { StockError, fail, makeSecurity } from './market-model.mjs'
|
|
1
|
+
import { StockError, fail, isAfterMarketClose, makeSecurity, marketDate } from './market-model.mjs'
|
|
2
2
|
import { TRANSIENT_CODES } from './provider-router.mjs'
|
|
3
|
+
import { DEFAULT_FLOAT_REFRESH_SECONDS } from './schemas.mjs'
|
|
3
4
|
// 本地闸门错误: 请求没打到上游, 既不算成功也不算失败
|
|
4
5
|
const localGate = error => error?.local === true || error?.code === 'CANCELLED'
|
|
5
6
|
// 报价时间距获取时间不超过该秒数视为实时; 免凭据公开源常缺延迟声明, 由时间戳差派生
|
|
6
7
|
const REALTIME_WINDOW_SECONDS = 90
|
|
8
|
+
const TREND_QUOTE_MAX_AGE_MS = 60 * 1000
|
|
7
9
|
// 适配器未声明延迟但带报价时间时, 按时差派生 delayKind; 缺时间戳保持 unknown 不编造。
|
|
8
10
|
// 非交易时段(休市/午休/未开盘)报价停在最后成交那一刻, 时差是"多久没新数据"而不是"数据延迟", 单独标 closed 交给界面报时间点。
|
|
9
11
|
export function deriveDelay(quote, now, trading = true) {
|
|
@@ -16,8 +18,30 @@ export function deriveDelay(quote, now, trading = true) {
|
|
|
16
18
|
return quote
|
|
17
19
|
}
|
|
18
20
|
const BUSINESS = entry => JSON.stringify(entry && { ...entry, lastAttemptAt: undefined, quote: entry.quote && { ...entry.quote, receivedAt: undefined } })
|
|
21
|
+
|
|
22
|
+
function share(work) {
|
|
23
|
+
const controller = new AbortController()
|
|
24
|
+
let readers = 0, settled = false
|
|
25
|
+
const job = work(controller.signal).finally(() => { settled = true })
|
|
26
|
+
return { job, signal: controller.signal, join(signal) {
|
|
27
|
+
readers++
|
|
28
|
+
let onAbort, released = false
|
|
29
|
+
const release = () => {
|
|
30
|
+
if (released) return
|
|
31
|
+
released = true
|
|
32
|
+
signal.removeEventListener('abort', onAbort)
|
|
33
|
+
if (--readers === 0 && !settled) controller.abort()
|
|
34
|
+
}
|
|
35
|
+
const cancelled = new Promise((_, reject) => {
|
|
36
|
+
onAbort = () => { release(); reject(new StockError('CANCELLED', '刷新等待已取消', 504)) }
|
|
37
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
38
|
+
if (signal.aborted) onAbort()
|
|
39
|
+
})
|
|
40
|
+
return Promise.race([job, cancelled]).finally(release)
|
|
41
|
+
} }
|
|
42
|
+
}
|
|
19
43
|
export function createCollector({ getControl, router, registry, executor, resolveSecurity = null, changed = () => {}, touched = () => {}, now = Date.now, active = () => false, calendarState = () => ({ state: 'unknown' }), timers = globalThis, random = Math.random, ticks = null }) {
|
|
20
|
-
const quotes = new Map(), marketPhases = new Map(),
|
|
44
|
+
const quotes = new Map(), marketPhases = new Map(), periodicPhases = new Map(), rounds = new Map(), blocked = new Map(), failures = new Map(), controllers = new Set()
|
|
21
45
|
let generation = 0, timer, stopped = false, lastStart = -Infinity, manualWaiters = 0
|
|
22
46
|
const entries = () => Object.fromEntries([...quotes].map(([id, value]) => [id, structuredClone(value)]))
|
|
23
47
|
// 常驻快照只给自选: peek(详情/浏览临时打开的非自选)报价没有生命周期归属, 留在快照里会随浏览次数无界增长。
|
|
@@ -31,11 +55,33 @@ export function createCollector({ getControl, router, registry, executor, resolv
|
|
|
31
55
|
// 自选里的标的永远按当下自选判定: 否则移除自选与在飞批次之间的窗口会把刚删掉的标的写回来
|
|
32
56
|
// (快照过滤会挡住展示, 但内存仍无界)。
|
|
33
57
|
const stillWanted = (id, peek) => peek?.has(id) === true || getControl().watchlist.items[id] !== undefined
|
|
34
|
-
|
|
58
|
+
const freshQuote = (security, selected, revision, phase, at, maxAge, lastCloseDate) => {
|
|
59
|
+
const held = quotes.get(security.id), quote = held?.quote
|
|
60
|
+
// 用来源报的最后成交时刻判交易日; receivedAt 只是本地收到时间, 盘前收到上一收盘价时它已是今天
|
|
61
|
+
const quoteAt = Date.parse(quote?.quoteAt)
|
|
62
|
+
const quoteStamp = Number.isFinite(quoteAt) ? quoteAt : quote?.receivedAt
|
|
63
|
+
const quoteDay = Number.isFinite(quoteStamp) ? marketDate(security.exchange, quoteStamp) : null
|
|
64
|
+
const today = marketDate(security.exchange, at)
|
|
65
|
+
// 收盘价只在最近收盘日有效, 且必须是收盘后的成交; 午休没有新成交, 当天上午的收盘价也一直有效
|
|
66
|
+
const carriesClose = (phase === 'closed' || phase === 'preopen') && quoteDay === lastCloseDate && Number.isFinite(quoteStamp) && isAfterMarketClose(security.exchange, quoteStamp)
|
|
67
|
+
// 午休只复用午休期间取到的报价: 上午盘中的旧价在午休开始时必须换成本段收盘
|
|
68
|
+
const carriesBreak = phase === 'break' && quote?.sessionState === 'break' && quoteDay === today
|
|
69
|
+
const carries = carriesClose || carriesBreak
|
|
70
|
+
const ttl = carries ? Infinity : maxAge
|
|
71
|
+
return held?.health === 'ok' && quote?.routingRevision === revision && quote.routeEpoch === selected.routeEpoch && quote.providerInstanceId === selected.instance.id && (quote.sessionState === phase || carries) && Number.isFinite(quote.receivedAt) && at >= quote.receivedAt && at - quote.receivedAt < ttl && (quoteDay === today || carries)
|
|
72
|
+
}
|
|
35
73
|
const freshWithin = ms => {
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
|
|
74
|
+
const { watchlist, routingRevision } = getControl(), at = now(), markets = new Map()
|
|
75
|
+
return watchlist.order.length > 0 && watchlist.order.every(id => {
|
|
76
|
+
const s = watchlist.items[id]
|
|
77
|
+
if (!s) return false
|
|
78
|
+
if (!markets.has(s.exchange)) {
|
|
79
|
+
try { markets.set(s.exchange, [router.select('quotes', s.exchange), calendarState(s.exchange)]) }
|
|
80
|
+
catch { return false }
|
|
81
|
+
}
|
|
82
|
+
const [selected, phase] = markets.get(s.exchange)
|
|
83
|
+
return freshQuote(s, selected, routingRevision, phase.state || 'unknown', at, ms, phase.lastCloseDate)
|
|
84
|
+
})
|
|
39
85
|
}
|
|
40
86
|
function apply(id, entry, peek) {
|
|
41
87
|
if (!stillWanted(id, peek)) return
|
|
@@ -47,8 +93,8 @@ export function createCollector({ getControl, router, registry, executor, resolv
|
|
|
47
93
|
function spareOf(selected, config) {
|
|
48
94
|
const route = config.routes.find(r => r.id === selected.route.id)
|
|
49
95
|
if (!route || route.failoverMode !== 'network') return null
|
|
50
|
-
const id = router.nextInRing(route.id, selected.instance.id)
|
|
51
|
-
const instance = id ? config.providers.find(p => p.id === id
|
|
96
|
+
const id = router.nextInRing(route.id, selected.instance.id, p => !p || p.enabled === false || p.budget?.requestsPerMinute === null)
|
|
97
|
+
const instance = id ? config.providers.find(p => p.id === id) : null
|
|
52
98
|
return instance && instance.id !== selected.instance.id ? { ...selected, instance } : null
|
|
53
99
|
}
|
|
54
100
|
function backoff(id, error) {
|
|
@@ -60,10 +106,20 @@ export function createCollector({ getControl, router, registry, executor, resolv
|
|
|
60
106
|
const delay = error.code === 'RATE_LIMIT' ? error.retryAfterMs || 60 * 1000 : Math.min(120, 15 * 2 ** (n - 1)) * 1000 * (1 + random() / 5)
|
|
61
107
|
blocked.set(id, permanent ? Infinity : now() + delay)
|
|
62
108
|
}
|
|
63
|
-
|
|
109
|
+
function isCurrent(selected, config, gen, phaseOf, day) {
|
|
110
|
+
const { route, instance, routeEpoch } = selected
|
|
111
|
+
if (stopped || gen !== generation || config.routingRevision !== getControl().routingRevision) return false
|
|
112
|
+
const current = router.select('quotes', route.market)
|
|
113
|
+
const phase = phaseOf(route.market), at = now()
|
|
114
|
+
return current.instance.id === instance.id && current.routeEpoch === routeEpoch && marketPhases.get(route.market) === phase.state && marketDate(route.market, at) === day
|
|
115
|
+
}
|
|
116
|
+
async function batch(selected, securities, periodic, config, gen, signal, phaseOf, day, peek, basis, deadline) {
|
|
64
117
|
const { route, instance, routeEpoch } = selected
|
|
65
118
|
const key = `${config.routingRevision}:${route.id}:${instance.id}:${routeEpoch}:${securities.map(s => s.id).sort().join(',')}`
|
|
66
|
-
|
|
119
|
+
const current = () => !signal.aborted && isCurrent(basis, config, gen, phaseOf, day)
|
|
120
|
+
const completedInPhase = () => current() && calendarState(route.market).state === phaseOf(route.market).state
|
|
121
|
+
const cancelled = () => fail('CANCELLED', '行情来源或交易时段已变化,旧报价已丢弃', 409)
|
|
122
|
+
if (!current()) cancelled()
|
|
67
123
|
const until = blocked.get(route.id) || 0
|
|
68
124
|
if (until > now()) {
|
|
69
125
|
// 本地闸门拦下的请求没打上游: 标记出来, 免得被当成一次真实的失败/成功去改路由计数
|
|
@@ -71,15 +127,9 @@ export function createCollector({ getControl, router, registry, executor, resolv
|
|
|
71
127
|
error.local = true
|
|
72
128
|
throw error
|
|
73
129
|
}
|
|
74
|
-
const controller = new AbortController(); controllers.add(controller)
|
|
75
|
-
// 调用方取消/断开时中止已发出的上游批次, 而不是只停止等待
|
|
76
|
-
const forwardAbort = () => controller.abort(signal?.reason)
|
|
77
|
-
signal?.addEventListener('abort', forwardAbort, { once: true })
|
|
78
|
-
if (signal?.aborted) forwardAbort()
|
|
79
|
-
const job = (async () => {
|
|
80
130
|
try {
|
|
81
|
-
const result = await executor.run(instance, 'quotes', { securities, routingRevision: config.routingRevision, routeEpoch, requestId: key, market: route.market }, { signal
|
|
82
|
-
if (
|
|
131
|
+
const result = await executor.run(instance, 'quotes', { securities, routingRevision: config.routingRevision, routeEpoch, requestId: key, market: route.market }, { signal, periodic, deadline })
|
|
132
|
+
if (!completedInPhase()) cancelled()
|
|
83
133
|
const map = new Map(), requested = new Set(securities.map(s => s.id))
|
|
84
134
|
for (const quote of result.items) {
|
|
85
135
|
if (!requested.has(quote.securityId)) continue
|
|
@@ -91,119 +141,147 @@ export function createCollector({ getControl, router, registry, executor, resolv
|
|
|
91
141
|
if (route.maxDelaySeconds !== null && quote.delayKind !== 'unknown' && quote.delaySeconds > route.maxDelaySeconds) fail('BAD_PAYLOAD', '报价延迟超过路由限制', 422)
|
|
92
142
|
map.set(quote.securityId, quote)
|
|
93
143
|
}
|
|
144
|
+
const batchEntries = []
|
|
94
145
|
for (const s of securities) {
|
|
95
146
|
const quote = map.get(s.id), old = quotes.get(s.id)
|
|
96
|
-
if (quote?.quoteAt && old?.quote?.quoteAt && old.quote.providerInstanceId === instance.id && old.quote.routeEpoch === routeEpoch && Date.parse(quote.quoteAt) < Date.parse(old.quote.quoteAt)) continue
|
|
147
|
+
if (quote?.quoteAt && old?.quote?.quoteAt && old.quote.providerInstanceId === instance.id && old.quote.routeEpoch === routeEpoch && Date.parse(quote.quoteAt) < Date.parse(old.quote.quoteAt)) { batchEntries.push([s.id, old]); continue }
|
|
97
148
|
const entry = quote ? { quote: { ...quote, routeId: route.id, routeEpoch, routingRevision: config.routingRevision, sessionState: phaseOf(s.exchange).state || 'unknown' }, health: 'ok', lastError: null, lastAttemptAt: now() } : { quote: old?.quote || null, health: 'no-data', lastError: result.errors?.find(e => e.securityId === s.id) || { code: 'NO_DATA', message: '来源未返回报价' }, lastAttemptAt: now() }
|
|
149
|
+
batchEntries.push([s.id, entry])
|
|
98
150
|
apply(s.id, entry, peek)
|
|
99
|
-
//
|
|
100
|
-
if (
|
|
151
|
+
// 离线补点也只认交易中的新鲜成交时间。
|
|
152
|
+
if (ticks && quote?.timestampKind === 'trade' && entry.quote.sessionState === 'trading') {
|
|
153
|
+
const at = Date.parse(quote.quoteAt), age = now() - at
|
|
154
|
+
if (age >= 0 && age < TREND_QUOTE_MAX_AGE_MS) ticks.push(s.id, s.exchange, Math.floor(at / 1000), quote.last)
|
|
155
|
+
}
|
|
101
156
|
}
|
|
102
|
-
return {
|
|
157
|
+
return { ok: true, ids: securities.map(s => s.id), peekEntries: batchEntries }
|
|
103
158
|
} catch (error) {
|
|
104
|
-
if (
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
159
|
+
if (error.code === 'CANCELLED') throw error
|
|
160
|
+
if (!completedInPhase()) cancelled()
|
|
161
|
+
const batchEntries = securities.map(s => {
|
|
162
|
+
const entry = { quote: quotes.get(s.id)?.quote || null, health: error.code === 'RATE_LIMIT' ? 'limited' : 'error', lastError: { code: error.code || 'NETWORK', message: error.message, retryAfterMs: error.retryAfterMs || null }, lastAttemptAt: now() }
|
|
163
|
+
apply(s.id, entry, peek)
|
|
164
|
+
return [s.id, entry]
|
|
165
|
+
})
|
|
166
|
+
return { ok: false, error, ids: securities.map(s => s.id), peekEntries: batchEntries }
|
|
167
|
+
}
|
|
112
168
|
}
|
|
113
169
|
async function refresh(ids, options = {}) {
|
|
114
170
|
if (stopped) fail('STOPPED', '股票工具已停止', 503)
|
|
115
171
|
if (!options.periodic) manualWaiters++
|
|
116
|
-
const refreshController = new AbortController()
|
|
172
|
+
const refreshController = new AbortController(); controllers.add(refreshController)
|
|
117
173
|
const forwardAbort = () => refreshController.abort(options.signal?.reason)
|
|
118
174
|
options.signal?.addEventListener('abort', forwardAbort, { once: true })
|
|
119
175
|
if (options.signal?.aborted) forwardAbort()
|
|
120
176
|
try {
|
|
177
|
+
if (refreshController.signal.aborted) fail('CANCELLED', '刷新等待已取消', 504)
|
|
121
178
|
const config = structuredClone(getControl()), gen = generation
|
|
122
179
|
// 一轮刷新内市场状态只算一次: 逐证券/逐批次重复调 calendarState 会反复全量扫描日历缓存
|
|
123
180
|
const phaseCache = new Map(), phaseOf = market => { if (!phaseCache.has(market)) phaseCache.set(market, calendarState(market)); return phaseCache.get(market) }
|
|
124
181
|
// 证券解析链: 对象形态(搜索候选peek, 客户端持有完整身份)直接构造; 字符串形态自选优先, 目录缓存兜底, 两者皆无拒 NOT_FOUND
|
|
125
|
-
const
|
|
126
|
-
|
|
182
|
+
const resolved = (ids || config.watchlist.order).map(id => typeof id === 'object' && id?.id ? makeSecurity(id.exchange, id.code, id.officialName || id.code, { catalogSource: 'peek' }) : config.watchlist.items[id] || resolveSecurity?.(id) || fail('NOT_FOUND', '自选证券不存在', 404))
|
|
183
|
+
const securities = [...new Map(resolved.map(s => [s.id, s])).values()]
|
|
127
184
|
const peek = ids ? new Set(securities.filter(s => config.watchlist.items[s.id] === undefined).map(s => s.id)) : null
|
|
185
|
+
const acceptsCache = options.periodic || options.automatic
|
|
186
|
+
const freshFor = Math.min(config.preferences?.refreshSeconds ?? Infinity, config.preferences?.floatRefreshSeconds ?? DEFAULT_FLOAT_REFRESH_SECONDS) * 1000
|
|
128
187
|
const grouped = new Map(), immediate = []
|
|
129
|
-
const closeMarkets = new Set(securities.map(s => s.exchange).filter(market => phaseOf(market).state === 'closed' &&
|
|
188
|
+
const closeMarkets = new Set(securities.map(s => s.exchange).filter(market => phaseOf(market).state === 'closed' && periodicPhases.get(market) === 'trading'))
|
|
130
189
|
for (const s of securities) {
|
|
131
190
|
const phase = phaseOf(s.exchange)
|
|
132
191
|
if (options.periodic && phase.nextAt > now() && !closeMarkets.has(s.exchange)) continue
|
|
133
192
|
marketPhases.set(s.exchange, phase.state)
|
|
193
|
+
if (options.periodic || phase.state === 'trading') periodicPhases.set(s.exchange, phase.state)
|
|
134
194
|
try {
|
|
135
195
|
const selected = router.select('quotes', s.exchange)
|
|
196
|
+
const at = now()
|
|
197
|
+
if (acceptsCache && freshQuote(s, selected, config.routingRevision, phase.state || 'unknown', at, freshFor, phase.lastCloseDate)) {
|
|
198
|
+
immediate.push({ ok: true, peekEntries: peek?.has(s.id) ? [[s.id, quotes.get(s.id)]] : [] }); continue
|
|
199
|
+
}
|
|
136
200
|
if (!grouped.has(selected.route.id)) grouped.set(selected.route.id, { selected, securities: [] })
|
|
137
201
|
grouped.get(selected.route.id).securities.push(s)
|
|
138
202
|
} catch (e) { immediate.push({ ok: false, error: e }); apply(s.id, { quote: null, health: 'unconfigured', lastError: { code: e.code, message: e.message }, lastAttemptAt: now() }, peek) }
|
|
139
203
|
}
|
|
140
|
-
lastStart = now()
|
|
141
|
-
const tasks = [...grouped.values()].
|
|
142
|
-
const { selected
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
return out
|
|
204
|
+
if (!options.automatic || !ids) lastStart = now()
|
|
205
|
+
const tasks = [...grouped.values()].flatMap(group => {
|
|
206
|
+
const { selected } = group, spare = spareOf(selected, config)
|
|
207
|
+
const day = marketDate(selected.route.market, now())
|
|
208
|
+
const routeKeyOf = sel => `${config.routingRevision}:${sel.route.id}:${sel.instance.id}:${sel.routeEpoch}:${phaseOf(sel.route.market).state}:${day}`
|
|
209
|
+
const routeKey = routeKeyOf(selected), activeRounds = rounds.get(routeKey) ?? new Map()
|
|
210
|
+
const owners = new Map(), list = []
|
|
211
|
+
for (const s of group.securities) {
|
|
212
|
+
const owner = activeRounds.get(s.id)
|
|
213
|
+
if (!owner || owner.signal.aborted) { list.push(s); continue }
|
|
214
|
+
if (!owners.has(owner)) owners.set(owner, new Set())
|
|
215
|
+
owners.get(owner).add(s.id)
|
|
153
216
|
}
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
const
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
if (
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
217
|
+
const joined = [...owners].map(([owner, wanted]) => owner.join(refreshController.signal).then(results => results.filter(result => result.ids.some(id => wanted.has(id)))))
|
|
218
|
+
if (!list.length) return joined
|
|
219
|
+
const flight = share(async signal => {
|
|
220
|
+
const pull = async (sel, basis = sel) => {
|
|
221
|
+
const size = Math.min(20, registry.get(sel.instance.adapterId).descriptor.maxQuoteBatch), out = []
|
|
222
|
+
for (let start = 0; start < list.length; start += size) {
|
|
223
|
+
const chunk = list.slice(start, start + size)
|
|
224
|
+
try { out.push(await batch(sel, chunk, !!options.periodic, config, gen, signal, phaseOf, day, peek, basis, options.deadline)) }
|
|
225
|
+
catch (e) { out.push({ ok: false, error: e, ids: list.slice(start).map(s => s.id) }); break }
|
|
226
|
+
}
|
|
227
|
+
return out
|
|
228
|
+
}
|
|
229
|
+
let results = await pull(selected)
|
|
230
|
+
if (signal.aborted || !isCurrent(selected, config, gen, phaseOf, day)) return [{ ok: false, error: new StockError('CANCELLED', '旧报价已丢弃', 409), ids: list.map(s => s.id) }]
|
|
231
|
+
const allSourceFailures = results.length && results.every(r => !r.ok && !localGate(r.error) && TRANSIENT_CODES.includes(r.error?.code))
|
|
232
|
+
// 本地闸门拦下的轮次不改变失败计数。
|
|
233
|
+
if (!results.every(r => !r.ok && localGate(r.error))) {
|
|
234
|
+
const failure = results.find(r => !r.ok && !localGate(r.error))?.error
|
|
235
|
+
backoff(selected.route.id, failure && TRANSIENT_CODES.includes(failure.code) && spare ? null : failure)
|
|
236
|
+
router.recordRound(selected.route.id, failure)
|
|
237
|
+
}
|
|
238
|
+
if (allSourceFailures) {
|
|
239
|
+
const chosen = router.select('quotes', selected.route.market)
|
|
240
|
+
const switched = chosen.instance.id !== selected.instance.id
|
|
241
|
+
const target = switched ? chosen : spare
|
|
242
|
+
if (target) {
|
|
243
|
+
if (switched) register(routeKeyOf(chosen))
|
|
244
|
+
const basis = switched ? chosen : selected
|
|
245
|
+
const retried = await pull(target, basis)
|
|
246
|
+
if (isCurrent(basis, config, gen, phaseOf, day)) {
|
|
247
|
+
if (retried.some(r => r.ok)) backoff(selected.route.id, null)
|
|
248
|
+
if (switched || retried.some(r => r.ok)) results = retried
|
|
249
|
+
} else if (switched) results = retried
|
|
180
250
|
}
|
|
181
251
|
}
|
|
252
|
+
return results
|
|
253
|
+
})
|
|
254
|
+
function register(key) {
|
|
255
|
+
const lane = rounds.get(key) ?? new Map()
|
|
256
|
+
for (const s of list) if (!lane.has(s.id) || lane.get(s.id).signal.aborted) lane.set(s.id, flight)
|
|
257
|
+
rounds.set(key, lane)
|
|
258
|
+
flight.job.catch(() => {}).finally(() => {
|
|
259
|
+
for (const { id } of list) if (lane.get(id) === flight) lane.delete(id)
|
|
260
|
+
if (!lane.size && rounds.get(key) === lane) rounds.delete(key)
|
|
261
|
+
})
|
|
182
262
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
263
|
+
register(routeKey)
|
|
264
|
+
return [...joined, flight.join(refreshController.signal)]
|
|
265
|
+
})
|
|
266
|
+
const completed = await Promise.all(tasks).catch(error => {
|
|
267
|
+
if (gen !== generation || config.routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '配置已变化,请重新刷新', 409)
|
|
268
|
+
throw error
|
|
188
269
|
})
|
|
189
|
-
const work = Promise.all(tasks)
|
|
190
|
-
let stopListening = () => {}
|
|
191
|
-
const waited = options.signal ? Promise.race([work, new Promise((_, reject) => {
|
|
192
|
-
const abort = () => reject(new StockError('CANCELLED', '刷新等待已取消', 504))
|
|
193
|
-
refreshController.signal.addEventListener('abort', abort, { once: true }); stopListening = () => refreshController.signal.removeEventListener('abort', abort)
|
|
194
|
-
if (refreshController.signal.aborted) abort()
|
|
195
|
-
})]) : work
|
|
196
|
-
let completed
|
|
197
|
-
try { completed = await waited } finally { stopListening() }
|
|
198
270
|
const results = [...immediate, ...completed.flat()]
|
|
199
271
|
if (gen !== generation || config.routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '配置已变化,请重新刷新', 409)
|
|
272
|
+
if (refreshController.signal.aborted) fail('CANCELLED', '刷新等待已取消', 504)
|
|
273
|
+
const response = entries()
|
|
274
|
+
for (const result of results) for (const [id, entry] of result.peekEntries || []) if (peek?.has(id) && !response[id]) response[id] = structuredClone(entry)
|
|
200
275
|
// 后台回切把路由换代次, 在飞批次会被判成旧路由丢弃: 只有整轮都是这种取消才静默交回上一份数据,
|
|
201
276
|
// 混着真实故障时必须照常报错, 不能拿旧数据盖住凭据失效/无路由
|
|
202
|
-
if (results.length && results.every(r => !r.ok
|
|
203
|
-
|
|
204
|
-
|
|
277
|
+
if (results.length && results.every(r => !r.ok)) {
|
|
278
|
+
const error = results.find(r => r.error?.code !== 'CANCELLED')?.error
|
|
279
|
+
if (error) throw Object.assign(new StockError(error.code, error.message, error.status, error), { quotes: response })
|
|
280
|
+
}
|
|
281
|
+
return response
|
|
205
282
|
} finally {
|
|
206
283
|
options.signal?.removeEventListener('abort', forwardAbort)
|
|
284
|
+
controllers.delete(refreshController)
|
|
207
285
|
if (!options.periodic) manualWaiters--
|
|
208
286
|
if (!active() && !manualWaiters) for (const c of controllers) c.abort()
|
|
209
287
|
}
|
|
@@ -216,7 +294,7 @@ export function createCollector({ getControl, router, registry, executor, resolv
|
|
|
216
294
|
const phaseCache = new Map(), phaseOf = market => { if (!phaseCache.has(market)) phaseCache.set(market, calendarState(market)); return phaseCache.get(market) }
|
|
217
295
|
const markets = [...new Set(config.watchlist.order.map(id => config.watchlist.items[id].exchange))]
|
|
218
296
|
const states = markets.map(exchange => phaseOf(exchange))
|
|
219
|
-
const closing = markets.some(market => phaseOf(market).state === 'closed' &&
|
|
297
|
+
const closing = markets.some(market => phaseOf(market).state === 'closed' && periodicPhases.get(market) === 'trading')
|
|
220
298
|
const allowed = closing || states.some(s => !s.nextAt)
|
|
221
299
|
const groupCosts = new Map(), available = []
|
|
222
300
|
for (const market of markets) {
|
|
@@ -258,8 +336,8 @@ export function createCollector({ getControl, router, registry, executor, resolv
|
|
|
258
336
|
resume() { blocked.clear(); failures.clear(); reconcile() },
|
|
259
337
|
// 路由换源: 只清这条路由的退避与失败计数并重排下一轮, 不动 generation/在飞请求
|
|
260
338
|
routeChanged(id) { blocked.delete(id); failures.delete(id); changed(); reconcile() },
|
|
261
|
-
reset() { generation++; for (const c of controllers) c.abort();
|
|
339
|
+
reset() { generation++; for (const c of controllers) c.abort(); rounds.clear(); quotes.clear(); marketPhases.clear(); periodicPhases.clear(); blocked.clear(); failures.clear(); ticks?.clear(); lastStart = -Infinity; touched(); changed(); reconcile() },
|
|
262
340
|
cancelIdle() { timers.clearTimeout(timer); if (!active() && !manualWaiters) for (const c of controllers) c.abort() },
|
|
263
|
-
dispose() { stopped = true; generation++; timers.clearTimeout(timer); for (const c of controllers) c.abort();
|
|
341
|
+
dispose() { stopped = true; generation++; timers.clearTimeout(timer); for (const c of controllers) c.abort(); rounds.clear(); ticks?.clear() },
|
|
264
342
|
}
|
|
265
343
|
}
|