@mzzsfy/dsh-stock-assistant 0.7.1 → 0.8.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/src/collector.mjs CHANGED
@@ -1,171 +1,265 @@
1
- import { StockError, fail, makeSecurity } from './market-model.mjs'
2
- // 报价时间距获取时间不超过该秒数视为实时; 免凭据公开源常缺延迟声明, 由时间戳差派生
3
- const REALTIME_WINDOW_SECONDS = 90
4
- // 适配器未声明延迟但带报价时间时, 按时差派生 delayKind; 缺时间戳保持 unknown 不编造。
5
- // 非交易时段(休市/午休/未开盘)报价停在最后成交那一刻, 时差是"多久没新数据"而不是"数据延迟", 单独标 closed 交给界面报时间点。
6
- export function deriveDelay(quote, now, trading = true) {
7
- if (quote.delayKind !== 'unknown' || !quote.quoteAt) return quote
8
- const lagSeconds = Math.max(0, Math.round((now() - Date.parse(quote.quoteAt)) / 1000))
9
- if (!Number.isFinite(lagSeconds)) return quote
10
- if (lagSeconds <= REALTIME_WINDOW_SECONDS) { quote.delayKind = 'realtime'; return quote }
11
- if (!trading) { quote.delayKind = 'closed'; quote.delaySeconds = null; return quote }
12
- quote.delayKind = 'delayed'; quote.delaySeconds = lagSeconds
13
- return quote
14
- }
15
- const BUSINESS = entry => JSON.stringify(entry && { ...entry, lastAttemptAt: undefined, quote: entry.quote && { ...entry.quote, receivedAt: undefined } })
16
- export function createCollector({ getControl, router, registry, executor, resolveSecurity = null, changed = () => {}, touched = () => {}, now = Date.now, active = () => false, calendarState = () => ({ state: 'unknown' }), timers = globalThis, random = Math.random }) {
17
- const quotes = new Map(), marketPhases = new Map(), flights = new Map(), rounds = new Map(), blocked = new Map(), failures = new Map(), controllers = new Set()
18
- let generation = 0, timer, stopped = false, lastStart = -Infinity, manualWaiters = 0
19
- const entries = () => Object.fromEntries([...quotes].map(([id, value]) => [id, structuredClone(value)]))
20
- // 缓存新鲜度: 全部自选都有未过期报价才算新鲜, 用于进入面板时跳过重复拉取
21
- const freshWithin = ms => {
22
- const order = getControl().watchlist.order
23
- if (!order.length) return false
24
- return order.every(id => { const quote = quotes.get(id)?.quote; return quote && Number.isFinite(quote.receivedAt) && now() - quote.receivedAt < ms })
25
- }
26
- function apply(id, entry) {
27
- const before = quotes.get(id)
28
- quotes.set(id, entry); touched()
29
- if (BUSINESS(before) !== BUSINESS(entry)) changed()
30
- }
31
- function backoff(id, error) {
32
- if (!error) { failures.delete(id); blocked.delete(id); return }
33
- const n = (failures.get(id) || 0) + 1; failures.set(id, n)
34
- const permanent = ['AUTH', 'PERMISSION', 'BAD_PAYLOAD', 'UNSUPPORTED_CAPABILITY', 'BUDGET_UNKNOWN'].includes(error.code)
35
- const delay = error.code === 'RATE_LIMIT' ? error.retryAfterMs || 60 * 1000 : Math.min(120, 15 * 2 ** (n - 1)) * 1000 * (1 + random() / 5)
36
- blocked.set(id, permanent ? Infinity : now() + delay)
37
- }
38
- async function batch(selected, securities, periodic, config, gen) {
39
- const { route, instance, routeEpoch } = selected
40
- const key = `${config.routingRevision}:${route.id}:${routeEpoch}:${securities.map(s => s.id).sort().join(',')}`
41
- if (flights.has(key)) return flights.get(key)
42
- const until = blocked.get(route.id) || 0
43
- if (until > now()) fail(Number.isFinite(until) ? 'RATE_LIMIT' : 'SOURCE_PAUSED', Number.isFinite(until) ? '来源正在退避,请稍后刷新' : '来源已暂停,请在设置中检查', Number.isFinite(until) ? 429 : 422, { retryAfterMs: Number.isFinite(until) ? Math.ceil(until - now()) : null })
44
- const controller = new AbortController(); controllers.add(controller)
45
- const job = (async () => {
46
- try {
47
- const result = await executor.run(instance, 'quotes', { securities, routingRevision: config.routingRevision, routeEpoch, requestId: key, market: route.market }, { signal: controller.signal, periodic })
48
- if (stopped || gen !== generation || getControl().routingRevision !== config.routingRevision || router.select('quotes', route.market).routeEpoch !== routeEpoch) throw new StockError('CANCELLED', '路由已变化,旧报价已丢弃', 409)
49
- const map = new Map(), requested = new Set(securities.map(s => s.id))
50
- for (const quote of result.items) {
51
- if (!requested.has(quote.securityId)) continue
52
- if (map.has(quote.securityId) || quote.providerInstanceId !== instance.id) fail('BAD_PAYLOAD', '报价身份或来源冲突', 502)
53
- // 只有明确处于非交易时段才改口径; 日历缺失(unknown)不能当成休市, 否则等于凭空断言收盘
54
- const marketState = calendarState(securities.find(s => s.id === quote.securityId)?.exchange).state
55
- deriveDelay(quote, now, marketState === 'unknown' || marketState === 'trading' || marketState === 'auction')
56
- if (quote.delayKind === 'unknown' && !route.acceptUnknownDelay) fail('BAD_PAYLOAD', '路由不接受未知延迟行情', 422)
57
- if (route.maxDelaySeconds !== null && quote.delayKind !== 'unknown' && quote.delaySeconds > route.maxDelaySeconds) fail('BAD_PAYLOAD', '报价延迟超过路由限制', 422)
58
- map.set(quote.securityId, quote)
59
- }
60
- for (const s of securities) {
61
- const quote = map.get(s.id), old = quotes.get(s.id)
62
- 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
63
- const entry = quote ? { quote: { ...quote, routeId: route.id, routeEpoch, routingRevision: config.routingRevision, sessionState: calendarState(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() }
64
- apply(s.id, entry)
65
- }
66
- return { routeId: route.id, ok: true }
67
- } catch (error) {
68
- if (gen !== generation || stopped || error.code === 'CANCELLED') throw error
69
- for (const s of securities) apply(s.id, { 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() })
70
- return { routeId: route.id, ok: false, error }
71
- } finally { controllers.delete(controller) }
72
- })()
73
- flights.set(key, job)
74
- job.catch(() => {}).finally(() => { if (flights.get(key) === job) flights.delete(key) })
75
- return job
76
- }
77
- async function refresh(ids, options = {}) {
78
- if (stopped) fail('STOPPED', '股票工具已停止', 503)
79
- if (!options.periodic) manualWaiters++
80
- try {
81
- const config = structuredClone(getControl()), gen = generation
82
- // 证券解析链: 对象形态(搜索候选peek, 客户端持有完整身份)直接构造; 字符串形态自选优先, 目录缓存兜底, 两者皆无拒 NOT_FOUND
83
- const securities = (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))
84
- const grouped = new Map(), immediate = []
85
- const closeMarkets = new Set(securities.map(s => s.exchange).filter(market => calendarState(market).state === 'closed' && marketPhases.get(market) === 'trading'))
86
- for (const s of securities) {
87
- const phase = calendarState(s.exchange)
88
- if (options.periodic && phase.nextAt > now() && !closeMarkets.has(s.exchange)) continue
89
- marketPhases.set(s.exchange, phase.state)
90
- try {
91
- const selected = router.select('quotes', s.exchange)
92
- if (!grouped.has(selected.route.id)) grouped.set(selected.route.id, { selected, securities: [] })
93
- grouped.get(selected.route.id).securities.push(s)
94
- } catch (e) { immediate.push({ ok: false, error: e }); apply(s.id, { quote: null, health: 'unconfigured', lastError: { code: e.code, message: e.message }, lastAttemptAt: now() }) }
95
- }
96
- lastStart = now()
97
- const tasks = [...grouped.values()].map(async group => {
98
- const { selected, securities: list } = group, size = Math.min(20, registry.get(selected.instance.adapterId).descriptor.maxQuoteBatch)
99
- const roundKey = `${config.routingRevision}:${selected.route.id}:${selected.routeEpoch}:${list.map(s => s.id).sort().join(',')}`
100
- if (rounds.has(roundKey)) return rounds.get(roundKey)
101
- const job = (async () => {
102
- const results = []
103
- for (let start = 0; start < list.length; start += size) {
104
- try { results.push(await batch(selected, list.slice(start, start + size), !!options.periodic, config, gen)) }
105
- catch (e) { results.push({ ok: false, error: e }); break }
106
- }
107
- if (gen === generation) {
108
- const error = results.every(r => !r.ok) ? results[0]?.error : null
109
- backoff(selected.route.id, error)
110
- const allNetwork = results.length && results.every(r => !r.ok && ['NETWORK', 'TIMEOUT'].includes(r.error?.code))
111
- router.recordRound(selected.route.id, allNetwork ? error : null)
112
- }
113
- return results
114
- })()
115
- rounds.set(roundKey, job)
116
- job.catch(() => {}).finally(() => { if (rounds.get(roundKey) === job) rounds.delete(roundKey) })
117
- return job
118
- })
119
- const work = Promise.all(tasks)
120
- let stopListening = () => {}
121
- const waited = options.signal ? Promise.race([work, new Promise((_, reject) => {
122
- const abort = () => reject(new StockError('CANCELLED', '刷新等待已取消', 504))
123
- options.signal.addEventListener('abort', abort, { once: true }); stopListening = () => options.signal.removeEventListener('abort', abort)
124
- if (options.signal.aborted) abort()
125
- })]) : work
126
- let completed
127
- try { completed = await waited } finally { stopListening() }
128
- const results = [...immediate, ...completed.flat()]
129
- if (gen !== generation || config.routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '配置已变化,请重新刷新', 409)
130
- if (results.length && results.every(r => !r.ok)) throw results[0].error
131
- return entries()
132
- } finally { if (!options.periodic) manualWaiters--; if (!active() && !manualWaiters) for (const c of controllers) c.abort() }
133
- }
134
- function reconcile() {
135
- timers.clearTimeout(timer)
136
- if (stopped || !active()) return
137
- const config = getControl()
138
- if (!config.watchlist.order.length) return
139
- const states = [...new Set(config.watchlist.order.map(id => config.watchlist.items[id].exchange))].map(exchange => calendarState(exchange))
140
- const closing = [...new Set(config.watchlist.order.map(id => config.watchlist.items[id].exchange))].some(market => calendarState(market).state === 'closed' && marketPhases.get(market) === 'trading')
141
- const allowed = closing || states.some(s => !s.nextAt)
142
- const groupCosts = new Map(), available = []
143
- for (const market of new Set(config.watchlist.order.map(id => config.watchlist.items[id].exchange))) {
144
- try {
145
- const { route, instance } = router.select('quotes', market)
146
- if (instance.budget?.requestsPerMinute === null) continue
147
- const until = blocked.get(route.id) || 0
148
- if (Number.isFinite(until)) available.push(until)
149
- const count = config.watchlist.order.filter(id => config.watchlist.items[id].exchange === market).length
150
- const size = Math.min(20, registry.get(instance.adapterId).descriptor.maxQuoteBatch), batches = Math.ceil(count / size)
151
- const budget = instance.budget
152
- const total = groupCosts.get(instance.quotaGroup || instance.id) || { count: 0, limit: Infinity }
153
- total.count += batches
154
- total.limit = Math.min(total.limit, budget?.requestsPerMinute || 50, budget?.capabilityLimits?.quotes || budget?.requestsPerMinute || 50)
155
- groupCosts.set(instance.quotaGroup || instance.id, total)
156
- } catch {}
157
- }
158
- if (!available.length) return
159
- const quotaInterval = Math.max(0, ...[...groupCosts.values()].map(g => g.count / Math.max(1, Math.floor(g.limit * 0.9)) * 60 * 1000))
160
- const base = Math.max(config.preferences.refreshSeconds * 1000, quotaInterval, states.some(s => s.state === 'unknown') ? 60 * 1000 : 0)
161
- const wake = allowed ? Math.max(now(), lastStart + base, Math.min(...available)) : Math.min(...states.map(s => s.nextAt))
162
- timer = timers.setTimeout(() => { refresh(undefined, { periodic: true }).catch(() => {}).finally(reconcile) }, Math.max(1000, wake - now())); timer?.unref?.()
163
- }
164
- return {
165
- refresh, entries, reconcile, freshWithin,
166
- resume() { blocked.clear(); failures.clear(); reconcile() },
167
- reset() { generation++; for (const c of controllers) c.abort(); flights.clear(); quotes.clear(); marketPhases.clear(); blocked.clear(); failures.clear(); lastStart = -Infinity; touched(); changed(); reconcile() },
168
- cancelIdle() { timers.clearTimeout(timer); if (!active() && !manualWaiters) for (const c of controllers) c.abort() },
169
- dispose() { stopped = true; generation++; timers.clearTimeout(timer); for (const c of controllers) c.abort(); flights.clear() },
170
- }
171
- }
1
+ import { StockError, fail, makeSecurity } from './market-model.mjs'
2
+ import { TRANSIENT_CODES } from './provider-router.mjs'
3
+ // 本地闸门错误: 请求没打到上游, 既不算成功也不算失败
4
+ const localGate = error => error?.local === true || error?.code === 'CANCELLED'
5
+ // 报价时间距获取时间不超过该秒数视为实时; 免凭据公开源常缺延迟声明, 由时间戳差派生
6
+ const REALTIME_WINDOW_SECONDS = 90
7
+ // 适配器未声明延迟但带报价时间时, 按时差派生 delayKind; 缺时间戳保持 unknown 不编造。
8
+ // 非交易时段(休市/午休/未开盘)报价停在最后成交那一刻, 时差是"多久没新数据"而不是"数据延迟", 单独标 closed 交给界面报时间点。
9
+ export function deriveDelay(quote, now, trading = true) {
10
+ if (quote.delayKind !== 'unknown' || !quote.quoteAt) return quote
11
+ const lagSeconds = Math.max(0, Math.round((now() - Date.parse(quote.quoteAt)) / 1000))
12
+ if (!Number.isFinite(lagSeconds)) return quote
13
+ if (lagSeconds <= REALTIME_WINDOW_SECONDS) { quote.delayKind = 'realtime'; return quote }
14
+ if (!trading) { quote.delayKind = 'closed'; quote.delaySeconds = null; return quote }
15
+ quote.delayKind = 'delayed'; quote.delaySeconds = lagSeconds
16
+ return quote
17
+ }
18
+ const BUSINESS = entry => JSON.stringify(entry && { ...entry, lastAttemptAt: undefined, quote: entry.quote && { ...entry.quote, receivedAt: undefined } })
19
+ 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(), flights = new Map(), rounds = new Map(), blocked = new Map(), failures = new Map(), controllers = new Set()
21
+ let generation = 0, timer, stopped = false, lastStart = -Infinity, manualWaiters = 0
22
+ const entries = () => Object.fromEntries([...quotes].map(([id, value]) => [id, structuredClone(value)]))
23
+ // 常驻快照只给自选: peek(详情/浏览临时打开的非自选)报价没有生命周期归属, 留在快照里会随浏览次数无界增长。
24
+ // 读取时顺带清掉非自选键, 让"详情关闭后无人再要"的报价在下一拍自然释放。
25
+ function watchEntries() {
26
+ const order = getControl().watchlist.order, wanted = new Set(order)
27
+ for (const id of [...quotes.keys()]) if (!wanted.has(id)) quotes.delete(id)
28
+ return Object.fromEntries(order.filter(id => quotes.has(id)).map(id => [id, structuredClone(quotes.get(id))]))
29
+ }
30
+ // 本拍显式请求且请求开始时不在自选的证券(peek): 只有它们能在"当前不在自选"时写入报价。
31
+ // 自选里的标的永远按当下自选判定: 否则移除自选与在飞批次之间的窗口会把刚删掉的标的写回来
32
+ // (快照过滤会挡住展示, 但内存仍无界)。
33
+ const stillWanted = (id, peek) => peek?.has(id) === true || getControl().watchlist.items[id] !== undefined
34
+ // 缓存新鲜度: 全部自选都有未过期报价才算新鲜, 用于进入面板时跳过重复拉取
35
+ const freshWithin = ms => {
36
+ const order = getControl().watchlist.order
37
+ if (!order.length) return false
38
+ return order.every(id => { const quote = quotes.get(id)?.quote; return quote && Number.isFinite(quote.receivedAt) && now() - quote.receivedAt < ms })
39
+ }
40
+ function apply(id, entry, peek) {
41
+ if (!stillWanted(id, peek)) return
42
+ const before = quotes.get(id)
43
+ quotes.set(id, entry); touched()
44
+ if (BUSINESS(before) !== BUSINESS(entry)) changed()
45
+ }
46
+ // 同轮补救的下一格: 沿环前进一格, 到末级时回到主源; 不给无预算或已停用的实例派活
47
+ function spareOf(selected, config) {
48
+ const route = config.routes.find(r => r.id === selected.route.id)
49
+ 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 && p.enabled !== false && p.budget?.requestsPerMinute !== null) : null
52
+ return instance && instance.id !== selected.instance.id ? { ...selected, instance } : null
53
+ }
54
+ function backoff(id, error) {
55
+ if (!error) { failures.delete(id); blocked.delete(id); return }
56
+ // 调用方取消不是来源故障: 不记失败、不进入退避
57
+ if (error.code === 'CANCELLED') return
58
+ const n = (failures.get(id) || 0) + 1; failures.set(id, n)
59
+ const permanent = ['AUTH', 'PERMISSION', 'BAD_PAYLOAD', 'UNSUPPORTED_CAPABILITY', 'BUDGET_UNKNOWN'].includes(error.code)
60
+ const delay = error.code === 'RATE_LIMIT' ? error.retryAfterMs || 60 * 1000 : Math.min(120, 15 * 2 ** (n - 1)) * 1000 * (1 + random() / 5)
61
+ blocked.set(id, permanent ? Infinity : now() + delay)
62
+ }
63
+ async function batch(selected, securities, periodic, config, gen, signal, phaseOf, peek) {
64
+ const { route, instance, routeEpoch } = selected
65
+ const key = `${config.routingRevision}:${route.id}:${instance.id}:${routeEpoch}:${securities.map(s => s.id).sort().join(',')}`
66
+ if (flights.has(key)) return flights.get(key)
67
+ const until = blocked.get(route.id) || 0
68
+ if (until > now()) {
69
+ // 本地闸门拦下的请求没打上游: 标记出来, 免得被当成一次真实的失败/成功去改路由计数
70
+ const error = new StockError(Number.isFinite(until) ? 'RATE_LIMIT' : 'SOURCE_PAUSED', Number.isFinite(until) ? '来源正在退避,请稍后刷新' : '来源已暂停,请在设置中检查', Number.isFinite(until) ? 429 : 422, { retryAfterMs: Number.isFinite(until) ? Math.ceil(until - now()) : null })
71
+ error.local = true
72
+ throw error
73
+ }
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
+ try {
81
+ const result = await executor.run(instance, 'quotes', { securities, routingRevision: config.routingRevision, routeEpoch, requestId: key, market: route.market }, { signal: controller.signal, periodic })
82
+ if (stopped || gen !== generation || getControl().routingRevision !== config.routingRevision || router.select('quotes', route.market).routeEpoch !== routeEpoch) throw new StockError('CANCELLED', '路由已变化,旧报价已丢弃', 409)
83
+ const map = new Map(), requested = new Set(securities.map(s => s.id))
84
+ for (const quote of result.items) {
85
+ if (!requested.has(quote.securityId)) continue
86
+ if (map.has(quote.securityId) || quote.providerInstanceId !== instance.id) fail('BAD_PAYLOAD', '报价身份或来源冲突', 502)
87
+ // 只有明确处于非交易时段才改口径; 日历缺失(unknown)不能当成休市, 否则等于凭空断言收盘
88
+ const marketState = phaseOf(securities.find(s => s.id === quote.securityId)?.exchange).state
89
+ deriveDelay(quote, now, marketState === 'unknown' || marketState === 'trading' || marketState === 'auction')
90
+ if (quote.delayKind === 'unknown' && !route.acceptUnknownDelay) fail('BAD_PAYLOAD', '路由不接受未知延迟行情', 422)
91
+ if (route.maxDelaySeconds !== null && quote.delayKind !== 'unknown' && quote.delaySeconds > route.maxDelaySeconds) fail('BAD_PAYLOAD', '报价延迟超过路由限制', 422)
92
+ map.set(quote.securityId, quote)
93
+ }
94
+ for (const s of securities) {
95
+ 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
97
+ 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() }
98
+ apply(s.id, entry, peek)
99
+ // 每拍报价都留一个点: 分时上游断开时, 这些点要续在当日真实分时后面
100
+ if (quote) ticks?.push(s.id, s.exchange, quote.quoteAt ? Math.floor(Date.parse(quote.quoteAt) / 1000) : Math.floor(now() / 1000), quote.last)
101
+ }
102
+ return { routeId: route.id, ok: true }
103
+ } catch (error) {
104
+ if (gen !== generation || stopped || error.code === 'CANCELLED') throw error
105
+ for (const s of securities) apply(s.id, { 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() }, peek)
106
+ return { routeId: route.id, ok: false, error }
107
+ } finally { signal?.removeEventListener('abort', forwardAbort); controllers.delete(controller) }
108
+ })()
109
+ flights.set(key, job)
110
+ job.catch(() => {}).finally(() => { if (flights.get(key) === job) flights.delete(key) })
111
+ return job
112
+ }
113
+ async function refresh(ids, options = {}) {
114
+ if (stopped) fail('STOPPED', '股票工具已停止', 503)
115
+ if (!options.periodic) manualWaiters++
116
+ const refreshController = new AbortController()
117
+ const forwardAbort = () => refreshController.abort(options.signal?.reason)
118
+ options.signal?.addEventListener('abort', forwardAbort, { once: true })
119
+ if (options.signal?.aborted) forwardAbort()
120
+ try {
121
+ const config = structuredClone(getControl()), gen = generation
122
+ // 一轮刷新内市场状态只算一次: 逐证券/逐批次重复调 calendarState 会反复全量扫描日历缓存
123
+ const phaseCache = new Map(), phaseOf = market => { if (!phaseCache.has(market)) phaseCache.set(market, calendarState(market)); return phaseCache.get(market) }
124
+ // 证券解析链: 对象形态(搜索候选peek, 客户端持有完整身份)直接构造; 字符串形态自选优先, 目录缓存兜底, 两者皆无拒 NOT_FOUND
125
+ const securities = (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))
126
+ // peek 集合只在请求开始时确定: 请求开始仍在自选的标的按当下自选判定, 避免移除竞态把旧报价写回来
127
+ const peek = ids ? new Set(securities.filter(s => config.watchlist.items[s.id] === undefined).map(s => s.id)) : null
128
+ const grouped = new Map(), immediate = []
129
+ const closeMarkets = new Set(securities.map(s => s.exchange).filter(market => phaseOf(market).state === 'closed' && marketPhases.get(market) === 'trading'))
130
+ for (const s of securities) {
131
+ const phase = phaseOf(s.exchange)
132
+ if (options.periodic && phase.nextAt > now() && !closeMarkets.has(s.exchange)) continue
133
+ marketPhases.set(s.exchange, phase.state)
134
+ try {
135
+ const selected = router.select('quotes', s.exchange)
136
+ if (!grouped.has(selected.route.id)) grouped.set(selected.route.id, { selected, securities: [] })
137
+ grouped.get(selected.route.id).securities.push(s)
138
+ } 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
+ }
140
+ lastStart = now()
141
+ const tasks = [...grouped.values()].map(async group => {
142
+ const { selected, securities: list } = group, spare = spareOf(selected, config)
143
+ const roundKey = `${config.routingRevision}:${selected.route.id}:${selected.instance.id}:${selected.routeEpoch}:${list.map(s => s.id).sort().join(',')}`
144
+ if (rounds.has(roundKey)) return rounds.get(roundKey)
145
+ // 同一来源的分批: 主源与备源各自按自己的批量上限切, 但核对/落库逻辑完全一致
146
+ const pull = async sel => {
147
+ const size = Math.min(20, registry.get(sel.instance.adapterId).descriptor.maxQuoteBatch), out = []
148
+ for (let start = 0; start < list.length; start += size) {
149
+ try { out.push(await batch(sel, list.slice(start, start + size), !!options.periodic, config, gen, refreshController.signal, phaseOf, peek)) }
150
+ catch (e) { out.push({ ok: false, error: e }); break }
151
+ }
152
+ return out
153
+ }
154
+ const job = (async () => {
155
+ let results = await pull(selected)
156
+ const allNetwork = results.length && results.every(r => !r.ok && TRANSIENT_CODES.includes(r.error?.code))
157
+ // 本地闸门拦下的轮次没打上游, 不能当成功也不能当失败: 否则末级退避会把失败计数反复清零, 环永远转不回去
158
+ const localOnly = results.length && results.every(r => !r.ok && localGate(r.error))
159
+ const upstreamError = results.find(r => !r.ok && !localGate(r.error))?.error
160
+ if (gen === generation && !localOnly) {
161
+ const failure = allNetwork || upstreamError ? upstreamError ?? results[0]?.error : null
162
+ const transient = failure && TRANSIENT_CODES.includes(failure.code)
163
+ // 网络类失败且有环可退时不设退避: 下一轮还能先试当前来源, 计满三次由路由器持久切走。
164
+ // 凭据/响应畸形这类永久故障跟环无关, 照旧退避, 否则每轮都拿同一个错误去撞上游
165
+ backoff(selected.route.id, transient && spare ? null : failure)
166
+ router.recordRound(selected.route.id, failure)
167
+ }
168
+ // 主源整轮断网: 本轮就换备源, 不让用户等三次刷新的空窗。
169
+ // 计满三次的那一轮 recordRound 可能已经把当前选择挪到备源, 这时必须按新选择取代次,
170
+ // 否则 batch 的代次校验会把备源结果当成旧路由丢弃
171
+ if (allNetwork) {
172
+ let target = null
173
+ if (!stopped && gen === generation) { try { const current = router.select('quotes', selected.route.market); if (current.instance.id !== selected.instance.id) target = current } catch {} }
174
+ target ??= spare
175
+ if (target) {
176
+ const retried = await pull(target)
177
+ if (retried.some(r => r.ok)) {
178
+ if (gen === generation) backoff(selected.route.id, null)
179
+ results = retried
180
+ }
181
+ }
182
+ }
183
+ return results
184
+ })()
185
+ rounds.set(roundKey, job)
186
+ job.catch(() => {}).finally(() => { if (rounds.get(roundKey) === job) rounds.delete(roundKey) })
187
+ return job
188
+ })
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
+ const results = [...immediate, ...completed.flat()]
199
+ if (gen !== generation || config.routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '配置已变化,请重新刷新', 409)
200
+ // 后台回切把路由换代次, 在飞批次会被判成旧路由丢弃: 只有整轮都是这种取消才静默交回上一份数据,
201
+ // 混着真实故障时必须照常报错, 不能拿旧数据盖住凭据失效/无路由
202
+ if (results.length && results.every(r => !r.ok && r.error?.code === 'CANCELLED')) return entries()
203
+ if (results.length && results.every(r => !r.ok)) throw results.find(r => r.error?.code !== 'CANCELLED')?.error ?? results[0].error
204
+ return entries()
205
+ } finally {
206
+ options.signal?.removeEventListener('abort', forwardAbort)
207
+ if (!options.periodic) manualWaiters--
208
+ if (!active() && !manualWaiters) for (const c of controllers) c.abort()
209
+ }
210
+ }
211
+ function reconcile() {
212
+ timers.clearTimeout(timer)
213
+ if (stopped || !active()) return
214
+ const config = getControl()
215
+ if (!config.watchlist.order.length) return
216
+ const phaseCache = new Map(), phaseOf = market => { if (!phaseCache.has(market)) phaseCache.set(market, calendarState(market)); return phaseCache.get(market) }
217
+ const markets = [...new Set(config.watchlist.order.map(id => config.watchlist.items[id].exchange))]
218
+ const states = markets.map(exchange => phaseOf(exchange))
219
+ const closing = markets.some(market => phaseOf(market).state === 'closed' && marketPhases.get(market) === 'trading')
220
+ const allowed = closing || states.some(s => !s.nextAt)
221
+ const groupCosts = new Map(), available = []
222
+ for (const market of markets) {
223
+ try {
224
+ const { route, instance } = router.select('quotes', market)
225
+ if (instance.budget?.requestsPerMinute === null) continue
226
+ const until = blocked.get(route.id) || 0
227
+ if (Number.isFinite(until)) available.push(until)
228
+ const count = config.watchlist.order.filter(id => config.watchlist.items[id].exchange === market).length
229
+ const size = Math.min(20, registry.get(instance.adapterId).descriptor.maxQuoteBatch), batches = Math.ceil(count / size)
230
+ const budget = instance.budget
231
+ const total = groupCosts.get(instance.quotaGroup || instance.id) || { count: 0, limit: Infinity }
232
+ total.count += batches
233
+ total.limit = Math.min(total.limit, budget?.requestsPerMinute || 50, budget?.capabilityLimits?.quotes || budget?.requestsPerMinute || 50)
234
+ groupCosts.set(instance.quotaGroup || instance.id, total)
235
+ } catch {}
236
+ }
237
+ if (!available.length) return
238
+ const quotaInterval = Math.max(0, ...[...groupCosts.values()].map(g => g.count / Math.max(1, Math.floor(g.limit * 0.9)) * 60 * 1000))
239
+ const base = Math.max(config.preferences.refreshSeconds * 1000, quotaInterval, states.some(s => s.state === 'unknown') ? 60 * 1000 : 0)
240
+ const wake = allowed ? Math.max(now(), lastStart + base, Math.min(...available)) : Math.min(...states.map(s => s.nextAt))
241
+ timer = timers.setTimeout(() => { refresh(undefined, { periodic: true }).catch(() => {}).finally(reconcile) }, Math.max(1000, wake - now())); timer?.unref?.()
242
+ }
243
+ return {
244
+ refresh, entries, watchEntries, reconcile, freshWithin,
245
+ // 自选移除后清掉它的行情, 否则 quotes 与 /snapshot 随增删次数无界增长
246
+ prune(id) { quotes.delete(id); ticks?.delete(id); touched() },
247
+ // 凭据更新成功: 清掉引用该凭据(数据源或代理)的路由失败/AUTH 暂停, 下一次刷新立即重试
248
+ recoverCredential(ref) {
249
+ const config = getControl()
250
+ for (const route of config.routes) {
251
+ const targets = [route.primaryInstanceId, ...route.fallbackInstanceIds]
252
+ if (targets.some(id => { const provider = config.providers.find(p => p.id === id); return provider && (provider.credentialRef === ref || provider.proxyCredentialRef === ref) })) {
253
+ blocked.delete(route.id); failures.delete(route.id)
254
+ }
255
+ }
256
+ reconcile()
257
+ },
258
+ resume() { blocked.clear(); failures.clear(); reconcile() },
259
+ // 路由换源: 只清这条路由的退避与失败计数并重排下一轮, 不动 generation/在飞请求
260
+ routeChanged(id) { blocked.delete(id); failures.delete(id); changed(); reconcile() },
261
+ reset() { generation++; for (const c of controllers) c.abort(); flights.clear(); quotes.clear(); marketPhases.clear(); blocked.clear(); failures.clear(); ticks?.clear(); lastStart = -Infinity; touched(); changed(); reconcile() },
262
+ 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(); flights.clear(); ticks?.clear() },
264
+ }
265
+ }