@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/catalog.mjs CHANGED
@@ -1,168 +1,193 @@
1
- import { securitySchema } from './schemas.mjs'
2
- import { fail, sessionStateOf } from './market-model.mjs'
3
- const DAY = 24 * 60 * 60 * 1000
4
- const SEARCH_TTL = 60 * 1000
5
- const SEARCH_CACHE_LIMIT = 64
6
- const SEARCH_FLIGHT_LIMIT = 32
7
- const CANDIDATE_TTL = 5 * 60 * 1000
8
- const CANDIDATE_LIMIT = 200
9
- // 有界写入: Map 迭代序即插入序, 超限淘汰最早条目, 保证长跑内存不随查询次数增长
10
- export function setBounded(map, key, value, limit) {
11
- map.set(key, value)
12
- while (map.size > limit) map.delete(map.keys().next().value)
13
- return map
14
- }
15
- const localDate = ms => new Date(ms + 8 * 60 * 60 * 1000).toISOString().slice(0, 10)
16
- // 实例id→其适配器 markets 集合(搜索市场面唯一事实源)
17
- function adapterMarketsOf(config, registry) {
18
- const map = new Map()
19
- for (const p of config.providers.filter(p => p.enabled)) {
20
- const adapter = (registry?.descriptors() || []).find(d => d.adapterId === p.adapterId)
21
- map.set(p.id, new Set(adapter?.markets || []))
22
- }
23
- return map
24
- }
25
-
26
- export function createCatalog({ state, getControl = state.get, router, executor, registry, now = Date.now, changed = () => {} }) {
27
- const flights = new Map(), candidates = new Map(), searchCache = new Map(), searchFlights = new Map()
28
- let stopped = false
29
- const controllers = new Set()
30
- function records(kind) {
31
- const config = getControl(), result = []
32
- for (const [, cache] of state.cache.entries()) {
33
- // 缓存表可能残留空记录(历史 update 语义写坏), 一条坏数据不能拖死整轮报价
34
- if (!cache || cache.kind !== kind || cache.payload?.routingRevision !== config.routingRevision || !Array.isArray(cache.payload?.items) || kind === 'catalog' && cache.payload.items.some(s => !securitySchema.safeParse(s).success) || kind === 'calendar' && cache.payload.items.some(d => !/^\d{4}-\d{2}-\d{2}$/.test(d.date) || typeof d.isOpen !== 'boolean')) continue
35
- result.push(cache)
36
- }
37
- return result
38
- }
39
- function all() {
40
- const map = new Map()
41
- for (const cache of records('catalog')) for (const s of cache.payload.items) if (securitySchema.safeParse(s).success) map.set(s.id, s)
42
- return [...map.values()]
43
- }
44
- function search(q, limit = 20) {
45
- const query = q.trim().toLowerCase()
46
- if (!query) return []
47
- // 代码大小写不敏感: 美股代码全大写, 逐字比较会让本地目录搜不到 aapl/apple
48
- const score = s => { const code = s.code.toLowerCase(), name = s.officialName.toLowerCase(); return code === query ? 0 : name === query ? 1 : code.startsWith(query) ? 2 : name.includes(query) ? 3 : s.cnspell?.toLowerCase().startsWith(query) ? 4 : 99 }
49
- return all().map(s => ({ s, rank: score(s) })).filter(r => r.rank < 99).sort((a, b) => a.rank - b.rank || a.s.id.localeCompare(b.s.id)).slice(0, limit).map(r => r.s)
50
- }
51
- return {
52
- search,
53
- async browse({ market, offset, limit }) {
54
- // 缓存缺失不再报错甩给用户: 返回 syncing 态并触发后台同步(sync 内部 flights 去重), 同步后为空是合法状态
55
- if (!records('catalog').some(c => c.payload.market === market)) {
56
- this.sync(market, ['catalog']).catch(() => {})
57
- return { syncing: true, total: 0, items: [] }
58
- }
59
- const securities = all().filter(s => s.exchange === market).sort((a, b) => a.code.localeCompare(b.code))
60
- const start = Math.max(0, Math.trunc(Number(offset) || 0)), size = Math.min(200, Math.max(1, Math.trunc(Number(limit) || 50)))
61
- return { total: securities.length, items: securities.slice(start, start + size) }
62
- },
63
- resolve(id) {
64
- const cached = all().find(s => s.id === id)
65
- if (cached) return cached
66
- const candidate = candidates.get(id)
67
- return candidate && candidate.until > now() && candidate.revision === getControl().routingRevision ? candidate.security : null
68
- },
69
- status: () => records('catalog').map(c => ({ source: c.source, fetchedAt: c.fetchedAt, complete: c.payload.complete, stale: now() - c.fetchedAt > (c.kind === 'calendar' ? 7 * DAY : DAY) })),
70
- async remote(q, signal) {
71
- const config = structuredClone(getControl()), revision = config.routingRevision, key = `${revision}:${q.trim().toLowerCase()}`
72
- // 结果缓存与在途合并: 联想接口按查询词去重, 退格重输同一词零远端开销
73
- const cached = searchCache.get(key)
74
- if (cached && cached.until > now()) return cached.items
75
- const inflight = searchFlights.get(key)
76
- if (inflight && !inflight.signal?.aborted) return inflight.job
77
- const job = (async () => {
78
- const results = new Map(search(q).map(s => [s.id, s]))
79
- // 搜索市场面=启用实例的适配器市场并集(suggest 天然全市场, 已启用市场语义跟随实例能力而非路由)
80
- const adapterMarkets = adapterMarketsOf(config, registry)
81
- const searchAdapters = new Set((registry?.descriptors() || []).filter(d => d.capabilities.includes('search')).map(d => d.adapterId))
82
- const searchRoutes = new Map(config.routes.filter(r => r.capability === 'search').map(r => [r.market, r]))
83
- // 实例→负责市场: 有 search 路由用路由实例, 无路由用支持 search 的启用实例直连(市场过滤在适配器端)
84
- const assignments = new Map()
85
- for (const market of new Set([...adapterMarkets.values()].flatMap(set => [...set]))) {
86
- const instance = searchRoutes.has(market) ? router.select('search', market).instance
87
- : config.providers.find(p => p.enabled && searchAdapters.has(p.adapterId) && adapterMarkets.get(p.id)?.has(market))
88
- || config.providers.find(p => p.enabled && searchAdapters.has(p.adapterId))
89
- if (!instance) continue
90
- const entry = assignments.get(instance.id) || { instance, markets: new Set() }
91
- entry.markets.add(market); assignments.set(instance.id, entry)
92
- }
93
- // 一个实例只请求一次: 联想端点为全市场端点, 按市场循环是重复请求同一份数据
94
- const batches = await Promise.allSettled([...assignments.values()].map(async ({ instance, markets }) => ({ markets, batch: await executor.run(instance, 'search', { q, limit: 20, market: null, routingRevision: revision }, { signal }) })))
95
- for (const settled of batches) {
96
- // 单来源限速不终止整个搜索: 其余实例候选照常下发
97
- if (settled.status === 'rejected') { if (settled.reason?.code === 'RATE_LIMIT') continue; throw settled.reason }
98
- const { markets, batch } = settled.value
99
- if (stopped || getControl().routingRevision !== revision) fail('ROUTE_CONFLICT', '目录路由已变化', 409)
100
- for (const s of batch.items) {
101
- if (!securitySchema.safeParse(s).success) fail('BAD_PAYLOAD', '来源返回不受支持的证券身份', 502)
102
- if (!markets.has(s.exchange)) continue
103
- candidates.set(s.id, { security: s, until: now() + CANDIDATE_TTL, revision }); results.set(s.id, s)
104
- }
105
- }
106
- for (const [id, c] of candidates) if (c.until <= now()) candidates.delete(id)
107
- while (candidates.size > CANDIDATE_LIMIT) candidates.delete(candidates.keys().next().value)
108
- if (!config.routes.some(r => r.capability === 'search') && !records('catalog').length) fail('CATALOG_NOT_READY', '目录未就绪,请先在设置中配置目录来源或搜索来源并同步', 422)
109
- const items = [...results.values()].slice(0, 20)
110
- setBounded(searchCache, key, { items, until: now() + SEARCH_TTL }, SEARCH_CACHE_LIMIT)
111
- return items
112
- })()
113
- setBounded(searchFlights, key, { job, signal }, SEARCH_FLIGHT_LIMIT)
114
- try { return await job } finally { if (searchFlights.get(key)?.job === job) searchFlights.delete(key) }
115
- },
116
- // 内存占用可观测: 长跑核对缓存不越界
117
- stats: () => ({ searchCache: searchCache.size, candidates: candidates.size, searchFlights: searchFlights.size, syncFlights: flights.size }),
118
- async ensure() {
119
- for (const route of getControl().routes.filter(r => ['catalog', 'calendar'].includes(r.capability))) {
120
- if (getControl().providers.find(p => p.id === route.primaryInstanceId)?.budget.requestsPerMinute === null) continue
121
- const caches = records(route.capability).filter(c => c.payload.market === route.market)
122
- const cache = caches[0]
123
- const today = localDate(now())
124
- const missing = !cache || now() - cache.fetchedAt > (route.capability === 'calendar' ? 7 * DAY : DAY) || route.capability === 'calendar' && !cache.payload.items.some(day => day.date === today)
125
- if (missing) await this.sync(route.market, [route.capability])
126
- }
127
- },
128
- async sync(market, capabilities = ['catalog', 'calendar']) {
129
- const config = structuredClone(getControl()), key = `${config.routingRevision}:${market}:${capabilities.join(',')}`
130
- if (flights.has(key)) return flights.get(key)
131
- const controller = new AbortController(); controllers.add(controller)
132
- const job = (async () => {
133
- const status = []
134
- for (const capability of capabilities) {
135
- try {
136
- const selected = router.select(capability, market)
137
- const request = { market, routingRevision: config.routingRevision, startDate: localDate(now() - 7 * DAY), endDate: localDate(now() + 45 * DAY) }
138
- const batch = await executor.run(selected.instance, capability, request, { signal: controller.signal })
139
- if (stopped || config.routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '来源已变化,旧目录已丢弃', 409)
140
- if (!Array.isArray(batch.items) || capability === 'catalog' && batch.items.some(s => !securitySchema.safeParse(s).success || s.exchange !== market) || capability === 'calendar' && batch.items.some(d => !/^\d{4}-\d{2}-\d{2}$/.test(d.date) || typeof d.isOpen !== 'boolean')) fail('BAD_PAYLOAD', '目录来源返回不受支持的证券身份', 502)
141
- const items = batch.items
142
- await state.cache.put(`${capability}:${selected.instance.id}:${market}`, { kind: capability, source: selected.instance.id, fetchedAt: now(), payload: { routingRevision: config.routingRevision, market, complete: batch.complete ?? true, items } })
143
- status.push({ capability, ok: true, count: items.length }); changed()
144
- } catch (e) { status.push({ capability, ok: false, error: { code: e.code, message: e.message } }) }
145
- }
146
- return status
147
- })()
148
- flights.set(key, job)
149
- job.finally(() => { flights.delete(key); controllers.delete(controller) }).catch(() => {})
150
- return job
151
- },
152
- marketState(market) {
153
- const date = localDate(now()), day = records('calendar').filter(c => c.payload.market === market).flatMap(c => c.payload.items).find(d => d.date === date)
154
- // 没同步过日历就按市场自身的时段判断, 别让八市场统一显示「未知」; 有日历数据时以日历(含节假日)为准
155
- if (!day || typeof day.isOpen !== 'boolean') return { state: sessionStateOf(market, now()) }
156
- const local = new Date(now() + 8 * 60 * 60 * 1000), minutes = local.getUTCHours() * 60 + local.getUTCMinutes()
157
- const at = minute => Date.parse(`${date}T00:00:00+08:00`) + minute * 60 * 1000
158
- if (!day.isOpen) return { state: 'closed', nextAt: at(24 * 60 + 9 * 60 + 15) }
159
- if (minutes < 9 * 60 + 15) return { state: 'preopen', nextAt: at(9 * 60 + 15) }
160
- if (minutes < 9 * 60 + 25) return { state: 'auction' }
161
- if (minutes < 9 * 60 + 30) return { state: 'preopen', nextAt: at(9 * 60 + 30) }
162
- if (minutes < 11 * 60 + 30 || minutes >= 13 * 60 && minutes < 15 * 60) return { state: 'trading' }
163
- if (minutes < 13 * 60) return { state: 'break', nextAt: at(13 * 60) }
164
- return { state: 'closed', nextAt: at(24 * 60 + 9 * 60 + 15) }
165
- },
166
- async dispose() { stopped = true; for (const c of controllers) c.abort(); candidates.clear(); await Promise.allSettled([...flights.values()]) },
167
- }
168
- }
1
+ import { securitySchema } from './schemas.mjs'
2
+ import { fail, marketDate, marketStateOf } from './market-model.mjs'
3
+ const DAY = 24 * 60 * 60 * 1000
4
+ const SEARCH_TTL = 60 * 1000
5
+ const SEARCH_CACHE_LIMIT = 64
6
+ const SEARCH_FLIGHT_LIMIT = 32
7
+ const CANDIDATE_TTL = 5 * 60 * 1000
8
+ const CANDIDATE_LIMIT = 200
9
+ // 同步失败后自动重试的间隔: 失败原因(缺路由/来源不可达)不会在一秒内自愈, 每次浏览都重试等于打上游;
10
+ // 用户仍可从设置页或浏览页手动重试
11
+ const AUTO_SYNC_RETRY_MS = 30 * 1000
12
+ const SYNC_ATTEMPT_LIMIT = 64
13
+ // 目录一天、日历一周过期: 过期数据仍可展示, 但浏览/后台预热要重新同步, 不能一直吃旧快照
14
+ const CATALOG_TTL = DAY, CALENDAR_TTL = 7 * DAY
15
+ // 市场状态只随分钟粒度的时段边界变化; 5 秒短缓存挡掉采集热路径的重复全量扫描
16
+ const MARKET_STATE_TTL = 5 * 1000
17
+ const MARKET_STATE_CACHE_LIMIT = 64
18
+ // 有界写入: Map 迭代序即插入序, 超限淘汰最早条目, 保证长跑内存不随查询次数增长
19
+ export function setBounded(map, key, value, limit) {
20
+ map.set(key, value)
21
+ while (map.size > limit) map.delete(map.keys().next().value)
22
+ return map
23
+ }
24
+ // 实例id→其适配器 markets 集合(搜索市场面唯一事实源)
25
+ function adapterMarketsOf(config, registry) {
26
+ const map = new Map()
27
+ for (const p of config.providers.filter(p => p.enabled)) {
28
+ const adapter = (registry?.descriptors() || []).find(d => d.adapterId === p.adapterId)
29
+ map.set(p.id, new Set(adapter?.markets || []))
30
+ }
31
+ return map
32
+ }
33
+
34
+ const shiftDate = (date, days) => new Date(Date.parse(`${date}T00:00:00Z`) + days * DAY).toISOString().slice(0, 10)
35
+ export function createCatalog({ state, getControl = state.get, router, executor, registry, now = Date.now, changed = () => {} }) {
36
+ const flights = new Map(), candidates = new Map(), searchCache = new Map(), searchFlights = new Map(), marketStateCache = new Map(), syncAttempts = new Map()
37
+ let stopped = false
38
+ const controllers = new Set()
39
+ function records(kind) {
40
+ const config = getControl(), result = []
41
+ for (const [, cache] of state.cache.entries()) {
42
+ // 缓存表可能残留空记录(历史 update 语义写坏), 一条坏数据不能拖死整轮报价
43
+ if (!cache || cache.kind !== kind || cache.payload?.routingRevision !== config.routingRevision || !Array.isArray(cache.payload?.items) || kind === 'catalog' && cache.payload.items.some(s => !securitySchema.safeParse(s).success) || kind === 'calendar' && cache.payload.items.some(d => !/^\d{4}-\d{2}-\d{2}$/.test(d.date) || typeof d.isOpen !== 'boolean')) continue
44
+ result.push(cache)
45
+ }
46
+ return result
47
+ }
48
+ function all() {
49
+ const map = new Map()
50
+ for (const cache of records('catalog')) for (const s of cache.payload.items) if (securitySchema.safeParse(s).success) map.set(s.id, s)
51
+ return [...map.values()]
52
+ }
53
+ function search(q, limit = 20) {
54
+ const query = q.trim().toLowerCase()
55
+ if (!query) return []
56
+ // 代码大小写不敏感: 美股代码全大写, 逐字比较会让本地目录搜不到 aapl/apple
57
+ const score = s => { const code = s.code.toLowerCase(), name = s.officialName.toLowerCase(); return code === query ? 0 : name === query ? 1 : code.startsWith(query) ? 2 : name.includes(query) ? 3 : s.cnspell?.toLowerCase().startsWith(query) ? 4 : 99 }
58
+ return all().map(s => ({ s, rank: score(s) })).filter(r => r.rank < 99).sort((a, b) => a.rank - b.rank || a.s.id.localeCompare(b.s.id)).slice(0, limit).map(r => r.s)
59
+ }
60
+ return {
61
+ search,
62
+ async browse({ market, offset, limit }) {
63
+ // 缓存缺失不再报错甩给用户: 返回 syncing 态并触发后台同步(sync 内部 flights 去重), 同步后为空是合法状态。
64
+ // 失败要带出口: 只回 syncing 会让"首次同步中"永远挂着, 用户既不知道失败也没有重试入口。
65
+ const cached = records('catalog').filter(c => c.payload.market === market)
66
+ if (!cached.length) {
67
+ const revision = getControl().routingRevision
68
+ const attempt = syncAttempts.get(`catalog:${market}`)
69
+ // 只认当前路由版本下的失败: 换过路由还回旧版本的错误, 会把已经修好的市场显示成失败
70
+ const failed = attempt?.ok === false && attempt.revision === revision
71
+ const due = !failed || now() - attempt.at >= AUTO_SYNC_RETRY_MS
72
+ if (due) this.sync(market, ['catalog']).catch(() => {})
73
+ return { syncing: true, syncError: failed ? attempt.error : null, syncAttemptAt: failed ? attempt.at : null, total: 0, items: [] }
74
+ }
75
+ // 已有目录但过期: 先展示旧数据, 同时后台刷新, 下一次浏览/轮询就能拿到新目录
76
+ const newest = Math.max(...cached.map(c => c.fetchedAt))
77
+ if (now() - newest > CATALOG_TTL) this.sync(market, ['catalog']).catch(() => {})
78
+ const securities = all().filter(s => s.exchange === market).sort((a, b) => a.code.localeCompare(b.code))
79
+ const start = Math.max(0, Math.trunc(Number(offset) || 0)), size = Math.min(200, Math.max(1, Math.trunc(Number(limit) || 50)))
80
+ return { total: securities.length, items: securities.slice(start, start + size) }
81
+ },
82
+ resolve(id) {
83
+ const cached = all().find(s => s.id === id)
84
+ if (cached) return cached
85
+ const candidate = candidates.get(id)
86
+ return candidate && candidate.until > now() && candidate.revision === getControl().routingRevision ? candidate.security : null
87
+ },
88
+ status: () => records('catalog').map(c => ({ source: c.source, fetchedAt: c.fetchedAt, complete: c.payload.complete, stale: now() - c.fetchedAt > (c.kind === 'calendar' ? CALENDAR_TTL : CATALOG_TTL) })),
89
+ async remote(q, signal) {
90
+ const config = structuredClone(getControl()), revision = config.routingRevision, key = `${revision}:${q.trim().toLowerCase()}`
91
+ // 结果缓存与在途合并: 联想接口按查询词去重, 退格重输同一词零远端开销
92
+ const cached = searchCache.get(key)
93
+ if (cached && cached.until > now()) return cached.items
94
+ const inflight = searchFlights.get(key)
95
+ if (inflight && !inflight.signal?.aborted) return inflight.job
96
+ const job = (async () => {
97
+ const results = new Map(search(q).map(s => [s.id, s]))
98
+ // 搜索市场面=启用实例的适配器市场并集(suggest 天然全市场, 已启用市场语义跟随实例能力而非路由)
99
+ const adapterMarkets = adapterMarketsOf(config, registry)
100
+ const searchAdapters = new Set((registry?.descriptors() || []).filter(d => d.capabilities.includes('search')).map(d => d.adapterId))
101
+ const searchRoutes = new Map(config.routes.filter(r => r.capability === 'search').map(r => [r.market, r]))
102
+ // 实例→负责市场: 有 search 路由用路由实例, 无路由用支持 search 的启用实例直连(市场过滤在适配器端)
103
+ const assignments = new Map()
104
+ for (const market of new Set([...adapterMarkets.values()].flatMap(set => [...set]))) {
105
+ const instance = searchRoutes.has(market) ? router.select('search', market).instance
106
+ : config.providers.find(p => p.enabled && searchAdapters.has(p.adapterId) && adapterMarkets.get(p.id)?.has(market))
107
+ || config.providers.find(p => p.enabled && searchAdapters.has(p.adapterId))
108
+ if (!instance) continue
109
+ const entry = assignments.get(instance.id) || { instance, markets: new Set() }
110
+ entry.markets.add(market); assignments.set(instance.id, entry)
111
+ }
112
+ // 一个实例只请求一次: 联想端点为全市场端点, 按市场循环是重复请求同一份数据
113
+ const batches = await Promise.allSettled([...assignments.values()].map(async ({ instance, markets }) => ({ markets, batch: await executor.run(instance, 'search', { q, limit: 20, market: null, routingRevision: revision }, { signal }) })))
114
+ for (const settled of batches) {
115
+ // 单来源限速不终止整个搜索: 其余实例候选照常下发
116
+ if (settled.status === 'rejected') { if (settled.reason?.code === 'RATE_LIMIT') continue; throw settled.reason }
117
+ const { markets, batch } = settled.value
118
+ if (stopped || getControl().routingRevision !== revision) fail('ROUTE_CONFLICT', '目录路由已变化', 409)
119
+ for (const s of batch.items) {
120
+ if (!securitySchema.safeParse(s).success) fail('BAD_PAYLOAD', '来源返回不受支持的证券身份', 502)
121
+ if (!markets.has(s.exchange)) continue
122
+ candidates.set(s.id, { security: s, until: now() + CANDIDATE_TTL, revision }); results.set(s.id, s)
123
+ }
124
+ }
125
+ for (const [id, c] of candidates) if (c.until <= now()) candidates.delete(id)
126
+ while (candidates.size > CANDIDATE_LIMIT) candidates.delete(candidates.keys().next().value)
127
+ if (!config.routes.some(r => r.capability === 'search') && !records('catalog').length) fail('CATALOG_NOT_READY', '目录未就绪,请先在设置中配置目录来源或搜索来源并同步', 422)
128
+ const items = [...results.values()].slice(0, 20)
129
+ setBounded(searchCache, key, { items, until: now() + SEARCH_TTL }, SEARCH_CACHE_LIMIT)
130
+ return items
131
+ })()
132
+ setBounded(searchFlights, key, { job, signal }, SEARCH_FLIGHT_LIMIT)
133
+ try { return await job } finally { if (searchFlights.get(key)?.job === job) searchFlights.delete(key) }
134
+ },
135
+ // 内存占用可观测: 长跑核对缓存不越界
136
+ stats: () => ({ searchCache: searchCache.size, candidates: candidates.size, searchFlights: searchFlights.size, syncFlights: flights.size, syncAttempts: syncAttempts.size }),
137
+ async ensure() {
138
+ for (const route of getControl().routes.filter(r => ['catalog', 'calendar'].includes(r.capability))) {
139
+ if (getControl().providers.find(p => p.id === route.primaryInstanceId)?.budget.requestsPerMinute === null) continue
140
+ const caches = records(route.capability).filter(c => c.payload.market === route.market)
141
+ const cache = caches[0]
142
+ const today = marketDate(route.market, now())
143
+ const ttl = route.capability === 'calendar' ? CALENDAR_TTL : CATALOG_TTL
144
+ const missing = !cache || now() - cache.fetchedAt > ttl || route.capability === 'calendar' && !cache.payload.items.some(day => day.date === today)
145
+ if (missing) await this.sync(route.market, [route.capability])
146
+ }
147
+ },
148
+ async sync(market, capabilities = ['catalog', 'calendar']) {
149
+ const config = structuredClone(getControl()), key = `${config.routingRevision}:${market}:${capabilities.join(',')}`
150
+ if (flights.has(key)) return flights.get(key)
151
+ const controller = new AbortController(); controllers.add(controller)
152
+ const job = (async () => {
153
+ const status = []
154
+ for (const capability of capabilities) {
155
+ try {
156
+ const selected = router.select(capability, market)
157
+ const today = marketDate(market, now())
158
+ const request = { market, routingRevision: config.routingRevision, startDate: shiftDate(today, -7), endDate: shiftDate(today, 45) }
159
+ const batch = await executor.run(selected.instance, capability, request, { signal: controller.signal })
160
+ if (stopped || config.routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '来源已变化,旧目录已丢弃', 409)
161
+ if (!Array.isArray(batch.items) || capability === 'catalog' && batch.items.some(s => !securitySchema.safeParse(s).success || s.exchange !== market) || capability === 'calendar' && batch.items.some(d => !/^\d{4}-\d{2}-\d{2}$/.test(d.date) || typeof d.isOpen !== 'boolean')) fail('BAD_PAYLOAD', '目录来源返回不受支持的证券身份', 502)
162
+ const items = batch.items
163
+ await state.cache.put(`${capability}:${selected.instance.id}:${market}`, { kind: capability, source: selected.instance.id, fetchedAt: now(), payload: { routingRevision: config.routingRevision, market, complete: batch.complete ?? true, items } })
164
+ if (capability === 'calendar') marketStateCache.clear()
165
+ setBounded(syncAttempts, `${capability}:${market}`, { ok: true, at: now(), revision: config.routingRevision }, SYNC_ATTEMPT_LIMIT)
166
+ status.push({ capability, ok: true, count: items.length }); changed()
167
+ } catch (e) {
168
+ setBounded(syncAttempts, `${capability}:${market}`, { ok: false, at: now(), revision: config.routingRevision, error: { code: e.code, message: e.message } }, SYNC_ATTEMPT_LIMIT)
169
+ status.push({ capability, ok: false, error: { code: e.code, message: e.message } })
170
+ }
171
+ }
172
+ return status
173
+ })()
174
+ flights.set(key, job)
175
+ job.finally(() => { flights.delete(key); controllers.delete(controller) }).catch(() => {})
176
+ return job
177
+ },
178
+ marketState(market) {
179
+ const at = now(), date = marketDate(market, at), revision = getControl().routingRevision
180
+ const key = `${market}:${date}:${revision}`
181
+ const cached = marketStateCache.get(key)
182
+ if (cached && at - cached.at < MARKET_STATE_TTL) return { ...cached.value }
183
+ // 没同步过日历就按市场自身时段判断(仍给 nextAt, 休市不再按秒轮询); 有日历时以日历(含节假日)为准
184
+ const days = new Map()
185
+ for (const cache of records('calendar')) if (cache.payload.market === market) for (const day of cache.payload.items) days.set(day.date, day.isOpen)
186
+ const value = marketStateOf(market, at, days)
187
+ marketStateCache.set(key, { at, value })
188
+ while (marketStateCache.size > MARKET_STATE_CACHE_LIMIT) marketStateCache.delete(marketStateCache.keys().next().value)
189
+ return { ...value }
190
+ },
191
+ async dispose() { stopped = true; for (const c of controllers) c.abort(); candidates.clear(); await Promise.allSettled([...flights.values()]) },
192
+ }
193
+ }