@mzzsfy/dsh-stock-assistant 0.10.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/src/catalog.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { securitySchema } from './schemas.mjs'
2
- import { fail, marketDate, marketStateOf } from './market-model.mjs'
2
+ import { StockError, fail, marketDate, marketStateOf } from './market-model.mjs'
3
3
  const DAY = 24 * 60 * 60 * 1000
4
4
  const SEARCH_TTL = 60 * 1000
5
5
  const SEARCH_CACHE_LIMIT = 64
@@ -21,21 +21,50 @@ export function setBounded(map, key, value, limit) {
21
21
  while (map.size > limit) map.delete(map.keys().next().value)
22
22
  return map
23
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 || []))
24
+ const cancelled = () => new StockError('CANCELLED', '操作已取消', 503)
25
+ function joinFlight(flight, signal) {
26
+ const shared = flight.controller.signal
27
+ const waiting = signal ? AbortSignal.any([signal, shared]) : shared
28
+ flight.waiters++
29
+ let onAbort, released = false
30
+ const release = () => {
31
+ if (released) return
32
+ released = true
33
+ waiting.removeEventListener('abort', onAbort)
34
+ if (--flight.waiters === 0 && !flight.settled) flight.controller.abort(cancelled())
30
35
  }
31
- return map
36
+ return Promise.race([flight.job, new Promise((_, reject) => {
37
+ onAbort = () => { reject(waiting.reason instanceof StockError ? waiting.reason : cancelled()); release() }
38
+ waiting.addEventListener('abort', onAbort, { once: true })
39
+ if (waiting.aborted) onAbort()
40
+ })]).finally(release)
32
41
  }
33
42
 
34
43
  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 = () => {} }) {
44
+ export function createCatalog({ state, getControl = state.get, router, executor, now = Date.now, changed = () => {} }) {
36
45
  const flights = new Map(), candidates = new Map(), searchCache = new Map(), searchFlights = new Map(), marketStateCache = new Map(), syncAttempts = new Map()
37
46
  let stopped = false
38
- const controllers = new Set()
47
+ const activeFlights = new Set()
48
+ function share(map, key, signal, work) {
49
+ if (stopped || signal?.aborted) return Promise.reject(signal?.reason instanceof StockError ? signal.reason : cancelled())
50
+ let flight = map.get(key)
51
+ if (!flight || flight.controller.signal.aborted) {
52
+ const controller = new AbortController()
53
+ flight = { controller, waiters: 0, settled: false, job: null }
54
+ const current = flight
55
+ flight.job = Promise.resolve().then(() => {
56
+ controller.signal.throwIfAborted()
57
+ return work(controller.signal)
58
+ }).finally(() => {
59
+ current.settled = true
60
+ activeFlights.delete(current)
61
+ if (map.get(key) === current) map.delete(key)
62
+ })
63
+ map.set(key, flight)
64
+ activeFlights.add(flight)
65
+ }
66
+ return joinFlight(flight, signal)
67
+ }
39
68
  function records(kind) {
40
69
  const config = getControl(), result = []
41
70
  for (const [, cache] of state.cache.entries()) {
@@ -66,36 +95,48 @@ export function createCatalog({ state, getControl = state.get, router, executor,
66
95
  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 }
67
96
  return indexOf().items.map(s => ({ s, rank: score(s) })).filter(r => r.rank < 99).sort((a, b) => a.rank - b.rank || a.s.id.localeCompare(b.s.id)).slice(0, limit).map(r => r.s)
68
97
  }
98
+ function rememberCandidates(items, revision) {
99
+ const at = now()
100
+ for (const [id, candidate] of candidates) if (candidate.until <= at) candidates.delete(id)
101
+ for (const security of items) {
102
+ candidates.delete(security.id)
103
+ setBounded(candidates, security.id, { security, until: at + CANDIDATE_TTL, revision }, CANDIDATE_LIMIT)
104
+ }
105
+ }
69
106
  // 目录同步走闭包: 挂在返回对象上时 this.sync 一旦被解构或换绑就丢 this
70
- const sync = async (market, capabilities = ['catalog', 'calendar']) => {
71
- const config = structuredClone(getControl()), key = `${config.routingRevision}:${market}:${capabilities.join(',')}`
72
- if (flights.has(key)) return flights.get(key)
73
- const controller = new AbortController(); controllers.add(controller)
74
- const job = (async () => {
75
- const status = []
76
- for (const capability of capabilities) {
77
- try {
78
- const selected = router.select(capability, market)
79
- const today = marketDate(market, now())
80
- const request = { market, routingRevision: config.routingRevision, startDate: shiftDate(today, -7), endDate: shiftDate(today, 45) }
81
- const batch = await executor.run(selected.instance, capability, request, { signal: controller.signal })
82
- if (stopped || config.routingRevision !== getControl().routingRevision) fail('ROUTE_CONFLICT', '来源已变化,旧目录已丢弃', 409)
83
- if (!Array.isArray(batch.items) || capability === 'catalog' && batch.items.some(s => !securitySchema.safeParse(s).success || s.exchange !== market) || capability === 'calendar' && batch.items.some(d => !/^\d{4}-\d{2}-\d{2}$/.test(d.date) || typeof d.isOpen !== 'boolean')) fail('BAD_PAYLOAD', '目录来源返回不受支持的证券身份', 502)
84
- const items = batch.items
85
- await state.cache.put(`${capability}:${selected.instance.id}:${market}`, { kind: capability, source: selected.instance.id, fetchedAt: now(), payload: { routingRevision: config.routingRevision, market, complete: batch.complete ?? true, items } })
86
- if (capability === 'calendar') marketStateCache.clear()
87
- setBounded(syncAttempts, `${capability}:${market}`, { ok: true, at: now(), revision: config.routingRevision }, SYNC_ATTEMPT_LIMIT)
88
- status.push({ capability, ok: true, count: items.length }); changed()
89
- } catch (e) {
90
- setBounded(syncAttempts, `${capability}:${market}`, { ok: false, at: now(), revision: config.routingRevision, error: { code: e.code, message: e.message } }, SYNC_ATTEMPT_LIMIT)
91
- status.push({ capability, ok: false, error: { code: e.code, message: e.message } })
92
- }
107
+ const sync = async (market, capabilities = ['catalog', 'calendar'], signal) => {
108
+ const revision = getControl().routingRevision
109
+ const assertRevision = () => { if (getControl().routingRevision !== revision) fail('ROUTE_CONFLICT', '来源已变化,旧目录已丢弃', 409) }
110
+ const status = []
111
+ for (const capability of capabilities) {
112
+ assertRevision()
113
+ const key = `${revision}:${market}:${capability}`
114
+ status.push(await share(flights, key, signal, async sharedSignal => {
115
+ try {
116
+ assertRevision()
117
+ const selected = router.select(capability, market)
118
+ const today = marketDate(market, now())
119
+ const request = { market, routingRevision: revision, startDate: shiftDate(today, -7), endDate: shiftDate(today, 45) }
120
+ const batch = await executor.run(selected.instance, capability, request, { signal: sharedSignal, beforeDispatch: assertRevision })
121
+ sharedSignal.throwIfAborted()
122
+ assertRevision()
123
+ 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)
124
+ const items = batch.items
125
+ if (capability === 'catalog' && batch.complete !== true) fail('INCOMPLETE_CATALOG', '来源未返回完整目录,未更新目录缓存', 502)
126
+ await state.cache.put(`${capability}:${selected.instance.id}:${market}`, { kind: capability, source: selected.instance.id, fetchedAt: now(), payload: { routingRevision: revision, market, complete: batch.complete ?? true, items } })
127
+ if (capability === 'calendar') marketStateCache.clear()
128
+ setBounded(syncAttempts, `${capability}:${market}`, { ok: true, at: now(), revision }, SYNC_ATTEMPT_LIMIT)
129
+ changed()
130
+ return { capability, ok: true, count: items.length }
131
+ } catch (e) {
132
+ sharedSignal.throwIfAborted()
133
+ const error = { code: e.code, message: e.message }
134
+ if (getControl().routingRevision === revision) setBounded(syncAttempts, `${capability}:${market}`, { ok: false, at: now(), revision, error }, SYNC_ATTEMPT_LIMIT)
135
+ return { capability, ok: false, error }
93
136
  }
94
- return status
95
- })()
96
- flights.set(key, job)
97
- job.finally(() => { flights.delete(key); controllers.delete(controller) }).catch(() => {})
98
- return job
137
+ }))
138
+ }
139
+ return status
99
140
  }
100
141
  return {
101
142
  search,
@@ -103,21 +144,15 @@ export function createCatalog({ state, getControl = state.get, router, executor,
103
144
  // 缓存缺失不再报错甩给用户: 返回 syncing 态并触发后台同步(sync 内部 flights 去重), 同步后为空是合法状态。
104
145
  // 失败要带出口: 只回 syncing 会让"首次同步中"永远挂着, 用户既不知道失败也没有重试入口。
105
146
  const cached = records('catalog').filter(c => c.payload.market === market)
106
- if (!cached.length) {
107
- const revision = getControl().routingRevision
108
- const attempt = syncAttempts.get(`catalog:${market}`)
109
- // 只认当前路由版本下的失败: 换过路由还回旧版本的错误, 会把已经修好的市场显示成失败
110
- const failed = attempt?.ok === false && attempt.revision === revision
111
- const due = !failed || now() - attempt.at >= AUTO_SYNC_RETRY_MS
112
- if (due) sync(market, ['catalog']).catch(() => {})
113
- return { syncing: true, syncError: failed ? attempt.error : null, syncAttemptAt: failed ? attempt.at : null, total: 0, items: [] }
114
- }
115
- // 已有目录但过期: 先展示旧数据, 同时后台刷新, 下一次浏览/轮询就能拿到新目录
116
- const newest = Math.max(...cached.map(c => c.fetchedAt))
117
- if (now() - newest > CATALOG_TTL) sync(market, ['catalog']).catch(() => {})
147
+ const attempt = syncAttempts.get(`catalog:${market}`)
148
+ const failed = attempt?.ok === false && attempt.revision === getControl().routingRevision
149
+ const due = !failed || now() - attempt.at >= AUTO_SYNC_RETRY_MS
150
+ const newest = Math.max(...cached.map(c => c.fetchedAt)), stale = now() - newest > CATALOG_TTL
151
+ if (due && stale) sync(market, ['catalog']).catch(() => {})
152
+ if (!cached.length) return { syncing: true, syncError: failed ? attempt.error : null, syncAttemptAt: failed ? attempt.at : null, total: 0, items: [] }
118
153
  const securities = indexOf().items.filter(s => s.exchange === market).sort((a, b) => a.code.localeCompare(b.code))
119
154
  const start = Math.max(0, Math.trunc(Number(offset) || 0)), size = Math.min(200, Math.max(1, Math.trunc(Number(limit) || 50)))
120
- return { total: securities.length, items: securities.slice(start, start + size) }
155
+ return { total: securities.length, items: securities.slice(start, start + size), ...(stale ? { stale: true } : {}) }
121
156
  },
122
157
  resolve(id) {
123
158
  const cached = indexOf().byId.get(id)
@@ -127,50 +162,50 @@ export function createCatalog({ state, getControl = state.get, router, executor,
127
162
  },
128
163
  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) })),
129
164
  async remote(q, signal) {
130
- const config = structuredClone(getControl()), revision = config.routingRevision, key = `${revision}:${q.trim().toLowerCase()}`
131
- // 结果缓存与在途合并: 联想接口按查询词去重, 退格重输同一词零远端开销
165
+ if (stopped || signal?.aborted) throw cancelled()
166
+ const { routingRevision: revision, routes } = getControl(), key = `${revision}:${q.trim().toLowerCase()}`
132
167
  const cached = searchCache.get(key)
133
- if (cached && cached.until > now()) return cached.items
134
- const inflight = searchFlights.get(key)
135
- if (inflight && !inflight.signal?.aborted) return inflight.job
136
- const job = (async () => {
137
- const results = new Map(search(q).map(s => [s.id, s]))
138
- // 搜索市场面=启用实例的适配器市场并集(suggest 天然全市场, 已启用市场语义跟随实例能力而非路由)
139
- const adapterMarkets = adapterMarketsOf(config, registry)
140
- const searchAdapters = new Set((registry?.descriptors() || []).filter(d => d.capabilities.includes('search')).map(d => d.adapterId))
141
- const searchRoutes = new Map(config.routes.filter(r => r.capability === 'search').map(r => [r.market, r]))
142
- // 实例→负责市场: 有 search 路由用路由实例, 无路由用支持 search 的启用实例直连(市场过滤在适配器端)
168
+ if (cached && cached.until > now() && cached.catalogVersion === state.cache.version) {
169
+ rememberCandidates(cached.items, revision)
170
+ return cached.items
171
+ }
172
+ const searchRoutes = routes.filter(r => r.capability === 'search')
173
+ if (!searchRoutes.length) {
174
+ if (!records('catalog').length) fail('CATALOG_NOT_READY', '目录未就绪,请先在设置中配置目录来源或搜索来源并同步', 422)
175
+ return search(q)
176
+ }
177
+ if (!searchFlights.has(key) && searchFlights.size >= SEARCH_FLIGHT_LIMIT) fail('RATE_LIMIT', '搜索繁忙,请稍后重试', 429, { retryable: true })
178
+ const assertRevision = () => { if (getControl().routingRevision !== revision) fail('ROUTE_CONFLICT', '搜索路由已变化', 409) }
179
+ return share(searchFlights, key, signal, async sharedSignal => {
180
+ assertRevision()
143
181
  const assignments = new Map()
144
- for (const market of new Set([...adapterMarkets.values()].flatMap(set => [...set]))) {
145
- const instance = searchRoutes.has(market) ? router.select('search', market).instance
146
- : config.providers.find(p => p.enabled && searchAdapters.has(p.adapterId) && adapterMarkets.get(p.id)?.has(market))
147
- || config.providers.find(p => p.enabled && searchAdapters.has(p.adapterId))
148
- if (!instance) continue
182
+ for (const { market } of searchRoutes) {
183
+ const { instance } = router.select('search', market)
149
184
  const entry = assignments.get(instance.id) || { instance, markets: new Set() }
150
185
  entry.markets.add(market); assignments.set(instance.id, entry)
151
186
  }
152
- // 一个实例只请求一次: 联想端点为全市场端点, 按市场循环是重复请求同一份数据
153
- 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 }) })))
187
+ 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: sharedSignal, beforeDispatch: assertRevision }) })))
188
+ sharedSignal.throwIfAborted()
189
+ assertRevision()
190
+ const results = new Map(search(q).map(s => [s.id, s]))
191
+ let limited = false
154
192
  for (const settled of batches) {
155
- // 单来源限速不终止整个搜索: 其余实例候选照常下发
156
- if (settled.status === 'rejected') { if (settled.reason?.code === 'RATE_LIMIT') continue; throw settled.reason }
193
+ if (settled.status === 'rejected') {
194
+ if (settled.reason?.code !== 'RATE_LIMIT') throw settled.reason
195
+ limited = true
196
+ continue
197
+ }
157
198
  const { markets, batch } = settled.value
158
- if (stopped || getControl().routingRevision !== revision) fail('ROUTE_CONFLICT', '目录路由已变化', 409)
159
199
  for (const s of batch.items) {
160
200
  if (!securitySchema.safeParse(s).success) fail('BAD_PAYLOAD', '来源返回不受支持的证券身份', 502)
161
- if (!markets.has(s.exchange)) continue
162
- candidates.set(s.id, { security: s, until: now() + CANDIDATE_TTL, revision }); results.set(s.id, s)
201
+ if (markets.has(s.exchange)) results.set(s.id, s)
163
202
  }
164
203
  }
165
- for (const [id, c] of candidates) if (c.until <= now()) candidates.delete(id)
166
- while (candidates.size > CANDIDATE_LIMIT) candidates.delete(candidates.keys().next().value)
167
- if (!config.routes.some(r => r.capability === 'search') && !records('catalog').length) fail('CATALOG_NOT_READY', '目录未就绪,请先在设置中配置目录来源或搜索来源并同步', 422)
168
204
  const items = [...results.values()].slice(0, 20)
169
- setBounded(searchCache, key, { items, until: now() + SEARCH_TTL }, SEARCH_CACHE_LIMIT)
205
+ rememberCandidates(items, revision)
206
+ if (!limited) setBounded(searchCache, key, { items, until: now() + SEARCH_TTL, catalogVersion: state.cache.version }, SEARCH_CACHE_LIMIT)
170
207
  return items
171
- })()
172
- setBounded(searchFlights, key, { job, signal }, SEARCH_FLIGHT_LIMIT)
173
- try { return await job } finally { if (searchFlights.get(key)?.job === job) searchFlights.delete(key) }
208
+ })
174
209
  },
175
210
  // 内存占用可观测: 长跑核对缓存不越界
176
211
  stats: () => ({ searchCache: searchCache.size, candidates: candidates.size, searchFlights: searchFlights.size, syncFlights: flights.size, syncAttempts: syncAttempts.size }),
@@ -199,6 +234,12 @@ export function createCatalog({ state, getControl = state.get, router, executor,
199
234
  while (marketStateCache.size > MARKET_STATE_CACHE_LIMIT) marketStateCache.delete(marketStateCache.keys().next().value)
200
235
  return { ...value }
201
236
  },
202
- async dispose() { stopped = true; for (const c of controllers) c.abort(); candidates.clear(); await Promise.allSettled([...flights.values()]) },
237
+ async dispose() {
238
+ stopped = true
239
+ const pending = [...activeFlights]
240
+ for (const flight of pending) flight.controller.abort(cancelled())
241
+ candidates.clear(); searchCache.clear()
242
+ await Promise.allSettled(pending.map(flight => flight.job))
243
+ },
203
244
  }
204
245
  }