@mzzsfy/dsh-stock-assistant 0.0.0-stage → 0.3.2

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.
@@ -0,0 +1,171 @@
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
+ }
package/src/demand.mjs ADDED
@@ -0,0 +1,33 @@
1
+ import { fail } from './market-model.mjs'
2
+ const TTL = 90 * 1000
3
+ export function createDemand(changed = () => {}, now = Date.now, timers = globalThis) {
4
+ const pages = new Map()
5
+ let timer, stopped = false
6
+ const clean = () => {
7
+ for (const [id, p] of pages) {
8
+ if (p.active && p.until <= now()) { p.active = false; p.until = now() + TTL }
9
+ else if (!p.active && p.until <= now()) pages.delete(id)
10
+ }
11
+ }
12
+ const active = () => { clean(); return [...pages.values()].some(p => p.active) }
13
+ function arm() {
14
+ timers.clearTimeout(timer)
15
+ if (stopped || !pages.size) return
16
+ const wait = Math.max(1, Math.min(...[...pages.values()].map(p => p.until)) - now())
17
+ timer = timers.setTimeout(() => { clean(); changed(); arm() }, wait); timer?.unref?.()
18
+ }
19
+ return {
20
+ active,
21
+ update(message) {
22
+ if (stopped || !message || typeof message.pageId !== 'string' || !/^[\da-f-]{36}$/i.test(message.pageId) || !Number.isSafeInteger(message.generation) || message.generation < 1 || typeof message.active !== 'boolean') return
23
+ clean()
24
+ const old = pages.get(message.pageId)
25
+ if (old && old.generation >= message.generation) return
26
+ if (!old && pages.size >= 512) fail('DEMAND_LIMIT', '页面需求数量超过上限', 429)
27
+ if (message.active && !old?.active && [...pages.values()].filter(p => p.active).length >= 256) fail('DEMAND_LIMIT', '活跃页面数量超过上限', 429)
28
+ pages.set(message.pageId, { generation: message.generation, active: message.active, until: now() + TTL })
29
+ changed(); arm()
30
+ },
31
+ dispose() { stopped = true; timers.clearTimeout(timer); pages.clear() },
32
+ }
33
+ }
@@ -0,0 +1,110 @@
1
+ import { StockError, fail } from './market-model.mjs'
2
+ // 每实例上游请求环形日志容量: 概览"最近请求"展示面
3
+ const REQUEST_LOG_LIMIT = 20
4
+ export function createExecutor({ registry, budget, env = process.env, fetch: fetchImpl = globalThis.fetch, now = Date.now, timers = globalThis, usSymbols = new Map(), proxyFactory = null }) {
5
+ const queues = new Map(), controllers = new Set(), starts = new Map()
6
+ const requestLogs = new Map(), proxies = new Map()
7
+ let stopped = false, running = 0
8
+ const record = (instanceId, url, status, startedAt) => {
9
+ const log = requestLogs.get(instanceId) || []
10
+ log.unshift({ at: now(), url: String(url), status, ms: Math.max(0, now() - startedAt) })
11
+ if (log.length > REQUEST_LOG_LIMIT) log.length = REQUEST_LOG_LIMIT
12
+ requestLogs.set(instanceId, log)
13
+ }
14
+ // 实例代理 dispatcher: 按代理 URL 惰性创建缓存(多实例共享同代理不重复建); proxyFactory 由宿主注入(undici ProxyAgent)
15
+ const dispatcherFor = proxy => {
16
+ if (!proxy) return null
17
+ if (!proxies.has(proxy)) {
18
+ try { proxies.set(proxy, proxyFactory ? proxyFactory(proxy) : null) } catch { proxies.set(proxy, null) }
19
+ }
20
+ return proxies.get(proxy)
21
+ }
22
+ // 组内节拍等待:上取整加裕度。setTimeout 对非整数 ms 向下取整且唤醒有抖动,
23
+ // 直接 setTimeout(gap) 会在 now-starts<间隔 时醒来,预算层同源时钟误判 RATE_LIMIT
24
+ // (CI 双架构高发竞态);唤醒后 now-starts>=间隔 恒成立,预算门恒过。
25
+ const THROTTLE_SLACK_MS = 5
26
+ const throttleDelay = gap => Math.ceil(gap) + THROTTLE_SLACK_MS
27
+ const slots = []
28
+ async function acquire(signal) {
29
+ if (running < 2) { running++; return }
30
+ await new Promise((resolve, reject) => {
31
+ const slot = { resolve: () => { signal.removeEventListener('abort', abort); resolve() } }
32
+ const abort = () => { const i = slots.indexOf(slot); if (i >= 0) slots.splice(i, 1); reject(new StockError('CANCELLED', '请求已取消', 503)) }
33
+ slots.push(slot); signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort()
34
+ })
35
+ }
36
+ function release() { if (slots.length) slots.shift().resolve(); else running-- }
37
+ return {
38
+ run(instance, capability, request, options = {}) {
39
+ const previous = queues.get(instance.quotaGroup) || Promise.resolve()
40
+ const job = previous.catch(() => {}).then(async () => {
41
+ if (stopped || options.signal?.aborted) fail('CANCELLED', '请求已取消', 503)
42
+ const controller = new AbortController(); controllers.add(controller)
43
+ const abort = () => controller.abort(options.signal?.reason)
44
+ options.signal?.addEventListener('abort', abort, { once: true })
45
+ let timeout, acquired = false
46
+ const startedAt = now()
47
+ try {
48
+ const gap = Math.max(0, (starts.get(instance.quotaGroup) ?? -Infinity) + (instance.budget?.requestsPerMinute === null ? 10 * 1000 : 1000) - now())
49
+ if (gap) await new Promise((resolve, reject) => {
50
+ const abortWait = () => { timers.clearTimeout(wait); reject(new StockError('CANCELLED', '请求已取消', 503)) }
51
+ const wait = timers.setTimeout(() => { controller.signal.removeEventListener('abort', abortWait); resolve() }, throttleDelay(gap))
52
+ controller.signal.addEventListener('abort', abortWait, { once: true })
53
+ })
54
+ await acquire(controller.signal); acquired = true
55
+ starts.set(instance.quotaGroup, now())
56
+ const adapter = registry.get(instance.adapterId), method = options.probe ? 'probe' : capability
57
+ if (typeof adapter[method] !== 'function') fail('UNSUPPORTED_CAPABILITY', '来源不支持该能力', 422)
58
+ let used = false, timeout
59
+ // 超时计时覆盖整个能力调用;分页适配器每次网络活动重置计时,空闲超过窗口才判超时。
60
+ const armTimeout = () => { timers.clearTimeout(timeout); timeout = timers.setTimeout(() => controller.abort(new StockError('TIMEOUT', '来源请求超时', 504, { retryable: true })), 8 * 1000) }
61
+ armTimeout()
62
+ const ctx = { now, signal: controller.signal, usSymbols, endpoints: instance.endpoints || null, credential: () => instance.credentialEnv === null ? undefined : env[instance.credentialEnv] || fail('AUTH', '未在Host环境中配置凭据', 422),
63
+ fetch: async (...args) => {
64
+ if (used) {
65
+ const gap = Math.max(0, starts.get(instance.quotaGroup) + (instance.budget?.requestsPerMinute === null ? 10 * 1000 : 1000) - now())
66
+ if (gap) await new Promise((resolve, reject) => {
67
+ const cancel = () => { timers.clearTimeout(id); reject(new StockError('CANCELLED', '请求已取消', 503)) }
68
+ const id = timers.setTimeout(() => { controller.signal.removeEventListener('abort', cancel); resolve() }, throttleDelay(gap))
69
+ controller.signal.addEventListener('abort', cancel, { once: true }); if (controller.signal.aborted) cancel()
70
+ })
71
+ }
72
+ if (controller.signal.aborted) fail('CANCELLED', '请求已取消', 503)
73
+ armTimeout()
74
+ budget.reserve(instance, capability, request.securities?.length || 1, !!options.periodic, !!options.probe); used = true; starts.set(instance.quotaGroup, now())
75
+ const dispatcher = dispatcherFor(instance.proxy)
76
+ const response = await fetchImpl(args[0], { ...(args[1] || {}), ...(dispatcher ? { dispatcher } : {}) })
77
+ armTimeout()
78
+ return response
79
+ } }
80
+ // 免凭据实例(credentialEnv=null)跳过Host环境检查;其余沿用原守卫。
81
+ if (instance.credentialEnv !== null && !env[instance.credentialEnv]) fail('AUTH', '未在Host环境中配置凭据', 422)
82
+ const work = Promise.resolve(adapter[method]({ ...request, providerInstanceId: instance.id, capability }, ctx))
83
+ const result = await new Promise((resolve, reject) => {
84
+ const aborted = () => reject(controller.signal.reason instanceof StockError ? controller.signal.reason : new StockError('CANCELLED', '请求已取消', 503))
85
+ controller.signal.addEventListener('abort', aborted, { once: true })
86
+ work.then(resolve, reject).finally(() => controller.signal.removeEventListener('abort', aborted))
87
+ if (controller.signal.aborted) aborted()
88
+ })
89
+ if (!used) budget.reserve(instance, capability, request.securities?.length || 1, !!options.periodic, !!options.probe)
90
+ record(instance.id, `${options.probe ? 'probe' : capability} ${instance.adapterId}`, 'ok', startedAt)
91
+ return result
92
+ } catch (e) {
93
+ const code = e instanceof StockError ? e.code : 'NETWORK'
94
+ record(instance.id, `${options.probe ? 'probe' : capability} ${instance.adapterId}`, code, startedAt)
95
+ if (controller.signal.aborted && controller.signal.reason?.code === 'TIMEOUT') throw controller.signal.reason
96
+ if (e.code === 'RATE_LIMIT') budget.block?.(instance, e.retryAfterMs || 60 * 1000)
97
+ if (e instanceof StockError) throw e
98
+ throw new StockError('NETWORK', '数据源请求失败', 502, { retryable: true })
99
+ } finally {
100
+ timers.clearTimeout(timeout); controllers.delete(controller); options.signal?.removeEventListener('abort', abort); if (acquired) release()
101
+ }
102
+ })
103
+ queues.set(instance.quotaGroup, job)
104
+ job.catch(() => {}).finally(() => { if (queues.get(instance.quotaGroup) === job) queues.delete(instance.quotaGroup) })
105
+ return job
106
+ },
107
+ recentRequests: instanceId => [...(requestLogs.get(instanceId) || [])],
108
+ dispose() { stopped = true; for (const c of controllers) c.abort(); controllers.clear() },
109
+ }
110
+ }
package/src/index.js ADDED
@@ -0,0 +1,33 @@
1
+ export const name = 'dsh-stock-assistant'
2
+ export const inject = ['webServer', 'storageDomain']
3
+ import { setupCommonTools, createChangeNotifier } from '@mzzsfy/dsh-common-tools/host'
4
+ import { createApplication } from './application.mjs'
5
+ import { registerRoutes } from './routes.mjs'
6
+ import { serveVendor, VENDOR_PREFIX, vendorReadable } from './serve-vendor.mjs'
7
+ export async function apply(ctx) {
8
+ if (typeof ctx.webServer?.register !== 'function' || typeof ctx.webServer?.registerUpgrade !== 'function' || typeof ctx.storageDomain?.open !== 'function') {
9
+ ctx.logger?.warn?.('股票工具已禁用:缺少webServer或storageDomain能力')
10
+ return
11
+ }
12
+ let disposed = false, application, stopRoutes, unsubscribe, notifier, bus
13
+ ctx.effect(() => () => {
14
+ disposed = true; stopRoutes?.(); unsubscribe?.(); notifier?.dispose()
15
+ return application?.close()
16
+ }, 'stock-assistant lifecycle')
17
+ try {
18
+ // vendor 可读性预判定先于应用构建: vendorAvailable=false 随快照下发→client 直接降级数字详情
19
+ let vendorAvailable = true
20
+ try { vendorAvailable = vendorReadable() } catch { vendorAvailable = false }
21
+ application = await createApplication({ storageDomain: ctx.storageDomain, publish: () => notifier?.refresh(), vendorAvailable })
22
+ if (disposed) { await application.close(); return }
23
+ bus = setupCommonTools(ctx)
24
+ notifier = createChangeNotifier(() => bus.publish({ type: 'invalidate', serverEpoch: application.snapshot().serverEpoch, snapshotSeq: application.snapshot().snapshotSeq }))
25
+ unsubscribe = bus.subscribe(message => { if (message?.type === 'watch-demand') application.demand(message) })
26
+ stopRoutes = registerRoutes(ctx.webServer, application)
27
+ // 注册异常仅告警: client ensureLwc 失败同样走降级路径
28
+ try { ctx.webServer.register({ kind: 'prefix', path: VENDOR_PREFIX, handler: serveVendor }) } catch (e) { ctx.logger?.warn?.('图表组件路由注册失败,详情将降级为数字详情') }
29
+ } catch (e) {
30
+ stopRoutes?.(); unsubscribe?.(); notifier?.dispose(); await application?.close()
31
+ ctx.logger?.warn?.('股票工具未激活:独立数据域或依赖初始化失败')
32
+ }
33
+ }
@@ -0,0 +1,29 @@
1
+ // K线缓存: 复用 storageDomain.cache 表壳, key 命名空间隔离, TTL 与 routingRevision 双失效
2
+ const HOUR = 60 * 60 * 1000
3
+ const DAY = 24 * HOUR
4
+ // TTL 唯一事实源(design.md 数据结构节): trend 0=不缓存, 其余按周期
5
+ const TTL_BY_PERIOD = { trend: 0, '1d': HOUR, '1w': DAY, '1M': DAY }
6
+ const keyOf = ({ providerInstanceId, market, period, code }) => `kline:${providerInstanceId}:${market}:${period}:${code}`
7
+
8
+ export function createKlineCache({ cacheTable, now }) {
9
+ const key = keyParts => keyOf(keyParts)
10
+ async function get(keyParts, routingRevision) {
11
+ const raw = await cacheTable.get(key(keyParts))
12
+ if (!raw || raw.kind !== 'kline') return null
13
+ const ttl = TTL_BY_PERIOD[keyParts.period]
14
+ if (now() - raw.fetchedAt >= ttl || raw.payload?.routingRevision !== routingRevision) {
15
+ await cacheTable.update(key(keyParts), () => undefined).catch(() => {})
16
+ return null
17
+ }
18
+ return raw
19
+ }
20
+ async function put(keyParts, result, routingRevision) {
21
+ if (!TTL_BY_PERIOD[keyParts.period]) return
22
+ const value = { kind: 'kline', source: result.providerInstanceId, fetchedAt: now(), payload: { ...result, routingRevision } }
23
+ await cacheTable.put(key(keyParts), value).catch(() => {})
24
+ }
25
+ async function invalidate(keyParts) {
26
+ await cacheTable.update(key(keyParts), () => undefined).catch(() => {})
27
+ }
28
+ return { get, put, invalidate }
29
+ }
@@ -0,0 +1,99 @@
1
+ // 每市场的币种/时区/价格精度/代码形态/探针门控——securitySchema 与 makeSecurity 的派生源(来源标注见 design.md)
2
+ // sessions 是该市场连续竞价的时段(市场本地时间), 用来判断报价此刻处在交易中/午休/休市;
3
+ // 只描述周内时点, 法定节假日仍以数据本身(最后一根K线的日期)为准。
4
+ export const MARKET_META = {
5
+ XSHG: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']] },
6
+ XSHE: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']] },
7
+ XHKG: { currency: 'HKD', timezone: 'Asia/Hong_Kong', priceScale: 2, codePattern: /^\d{4,5}$/, verifiedByDefault: true, sessions: [['09:30', '12:00'], ['13:00', '16:00']] },
8
+ XNAS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']] },
9
+ XNYS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']] },
10
+ XJPX: { currency: 'JPY', timezone: 'Asia/Tokyo', priceScale: 0, codePattern: /^\d{4}$/, verifiedByDefault: true, sessions: [['09:00', '11:30'], ['12:30', '15:30']] },
11
+ XKRX: { currency: 'KRW', timezone: 'Asia/Seoul', priceScale: 0, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:00', '15:30']] },
12
+ XLON: { currency: 'GBP', timezone: 'Europe/London', priceScale: 2, codePattern: /^[A-Z0-9.]{1,10}$/, verifiedByDefault: true, sessions: [['08:00', '16:30']] },
13
+ }
14
+ // 报价此刻落在市场交易日的哪个阶段; 周末恒为休市, 节假日不做推断(没有日历能力时会误判)
15
+ export function sessionStateOf(exchange, nowMs) {
16
+ const meta = MARKET_META[exchange]
17
+ if (!meta?.sessions?.length) return 'unknown'
18
+ const parts = new Intl.DateTimeFormat('en-US', { timeZone: meta.timezone, hour12: false, weekday: 'short', hour: '2-digit', minute: '2-digit' }).formatToParts(new Date(nowMs))
19
+ const pick = type => parts.find(part => part.type === type)?.value
20
+ if (pick('weekday') === 'Sat' || pick('weekday') === 'Sun') return 'closed'
21
+ const minutes = (Number(pick('hour')) % 24) * 60 + Number(pick('minute'))
22
+ const bounds = meta.sessions.map(([from, to]) => [toMinutes(from), toMinutes(to)])
23
+ if (minutes < bounds[0][0]) return 'preopen'
24
+ if (bounds.some(([from, to]) => minutes >= from && minutes < to)) return 'trading'
25
+ // 午休只存在于两段之间: 只比前一段的收尾会把收盘后也算成午休
26
+ if (bounds.some(([, to], index) => index < bounds.length - 1 && minutes >= to && minutes < bounds[index + 1][0])) return 'break'
27
+ return 'closed'
28
+ }
29
+ const toMinutes = stamp => { const [hh, mm] = stamp.split(':').map(Number); return hh * 60 + mm }
30
+
31
+ export function securityId(exchange, code, instrument = 'equity') {
32
+ const meta = MARKET_META[exchange]
33
+ if (!meta || instrument !== 'equity' || typeof code !== 'string' || !meta.codePattern.test(code)) throw new Error('不支持的证券身份')
34
+ return `${exchange}:${instrument}:${code}`
35
+ }
36
+
37
+ export function parseSecurityId(securityIdValue) {
38
+ const parts = String(securityIdValue || '').split(':')
39
+ const [exchange, instrument, code] = parts
40
+ if (parts.length !== 3 || instrument !== 'equity' || !MARKET_META[exchange]) throw new Error('不支持的证券身份')
41
+ return { exchange, instrument, code: securityId(exchange, code, instrument).split(':')[2], meta: MARKET_META[exchange] }
42
+ }
43
+ // 定点基准是分;来源允许多于两位小数(美股常见三位),超出部分四舍五入到分
44
+ function cents(value) {
45
+ if (value === null || value === undefined || value === '') return null
46
+ const text = String(value)
47
+ const match = /^(\d+)(?:\.(\d{1,6}))?$/.exec(text)
48
+ if (!match) return null
49
+ const [, whole, fraction = ''] = match
50
+ let n = BigInt(whole) * 100n + BigInt(fraction.slice(0, 2).padEnd(2, '0'))
51
+ if (fraction.length > 2 && Number(fraction[2]) >= 5) n += 1n
52
+ return n > 0n ? n : null
53
+ }
54
+ function decimal(n) {
55
+ const sign = n < 0n ? '-' : ''
56
+ const abs = n < 0n ? -n : n
57
+ return `${sign}${abs / 100n}.${String(abs % 100n).padStart(2, '0')}`
58
+ }
59
+ export function normalizeQuote(input) {
60
+ const last = cents(input.last), previous = cents(input.previousClose)
61
+ const change = last !== null && previous !== null ? last - previous : null
62
+ const numerator = change === null ? null : change * 10000n
63
+ const abs = numerator === null ? null : numerator < 0n ? -numerator : numerator
64
+ const pct = abs === null ? null : (abs + previous / 2n) / previous * (numerator < 0n ? -1n : 1n)
65
+ const price = key => { const n = cents(input[key]); return n === null ? null : decimal(n) }
66
+ return { ...input, last: price('last'), previousClose: price('previousClose'), open: price('open'), high: price('high'), low: price('low'), change: change === null ? null : decimal(change), changePct: pct === null ? null : decimal(pct) }
67
+ }
68
+ export function parseQuoteTime(value) {
69
+ if (typeof value !== 'string') return null
70
+ const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})?$/.exec(value)
71
+ if (!match) return null
72
+ const [, y, m, d, hh, mm, ss] = match
73
+ const day = new Date(Date.UTC(+y, +m - 1, +d))
74
+ if (day.getUTCFullYear() !== +y || day.getUTCMonth() + 1 !== +m || day.getUTCDate() !== +d || +hh > 23 || +mm > 59 || +ss > 59) return null
75
+ const time = Date.parse(value.replace(' ', 'T') + (match[8] ? '' : '+08:00'))
76
+ return Number.isFinite(time) ? new Date(time).toISOString() : null
77
+ }
78
+
79
+ export function makeSecurity(exchange, code, officialName, extra = {}) {
80
+ const meta = MARKET_META[exchange]
81
+ if (!meta) throw new Error('不支持的证券身份')
82
+ return { ...extra, id: securityId(exchange, code), exchange, code, officialName, instrument: 'equity', currency: meta.currency, timezone: meta.timezone, priceScale: meta.priceScale, listingStatus: 'listed' }
83
+ }
84
+
85
+ // 成交量单位换算: 沪深来源按手报价(1 手 = 100 股), 港美来源直接给股。对外统一按股呈现。
86
+ export const LOTS_EXCHANGES = new Set(['XSHG', 'XSHE'])
87
+ export const sharesFromLots = (volume, exchange) => (volume === null || volume === undefined ? null : LOTS_EXCHANGES.has(exchange) ? volume * 100 : volume)
88
+ // 成交额单位换算: 沪深来源按万元给, 港美来源直接给元。
89
+ export const LOTS_AMOUNT_EXCHANGES = new Set(['XSHG', 'XSHE'])
90
+ export const amountFromWan = (amount, exchange) => (amount === null || amount === undefined ? null : LOTS_AMOUNT_EXCHANGES.has(exchange) ? Math.round(amount * 10000) : amount)
91
+
92
+ export class StockError extends Error {
93
+ constructor(code, message, status = 400, extra = {}) {
94
+ super(message)
95
+ Object.assign(this, { code, status, retryable: false, retryAfterMs: null }, extra)
96
+ }
97
+ }
98
+ export const fail = (code, message, status = 400, extra = {}) => { throw new StockError(code, message, status, extra) }
99
+
@@ -0,0 +1,18 @@
1
+ import { fail } from './market-model.mjs'
2
+ export function createRegistry(providers = []) {
3
+ const entries = new Map()
4
+ for (const provider of providers) {
5
+ const d = provider.descriptor
6
+ if (!d || entries.has(d.adapterId) || typeof provider.probe !== 'function' || d.capabilities.some(c => !['quotes', 'catalog', 'search', 'calendar', 'kline'].includes(c) || typeof provider[c] !== 'function') || (d.capabilities.includes('quotes') && !(d.maxQuoteBatch > 0))) fail('INVALID_ADAPTER', '数据适配器合同不完整', 422)
7
+ entries.set(d.adapterId, provider)
8
+ }
9
+ const get = id => entries.get(id) || fail('UNKNOWN_ADAPTER', '未安装此数据适配器', 422)
10
+ return {
11
+ get,
12
+ descriptors: () => [...entries.values()].map(p => p.descriptor),
13
+ validate(instance, route) {
14
+ const d = get(instance.adapterId).descriptor
15
+ if (!d.capabilities.includes(route.capability) || !d.markets.includes(route.market) || !d.instruments.includes(route.instrument)) fail('UNSUPPORTED_CAPABILITY', '数据源不支持目标能力或市场', 422)
16
+ },
17
+ }
18
+ }
@@ -0,0 +1,33 @@
1
+ import { fail } from './market-model.mjs'
2
+ export function createRouter(getConfig, now = Date.now, changed = () => {}) {
3
+ const states = new Map()
4
+ function state(route) {
5
+ if (!states.has(route.id)) states.set(route.id, { providerInstanceId: route.primaryInstanceId, routeEpoch: 0, failures: 0, switchedAt: null })
6
+ return states.get(route.id)
7
+ }
8
+ function find(id) { return getConfig().routes.find(r => r.id === id) || fail('NO_ROUTE', '未配置此数据路由', 422) }
9
+ return {
10
+ select(capability, market, instrument = 'equity') {
11
+ const config = getConfig(), route = config.routes.find(r => r.capability === capability && r.market === market && r.instrument === instrument)
12
+ if (!route) fail('NO_ROUTE', '未配置该市场的数据来源', 422)
13
+ const selected = state(route), instance = config.providers.find(p => p.id === selected.providerInstanceId)
14
+ if (!instance || instance.enabled === false) fail('NO_ROUTE', '数据源已停用', 422)
15
+ return { route, instance, routeEpoch: selected.routeEpoch }
16
+ },
17
+ recordRound(id, error) {
18
+ const route = find(id), s = state(route)
19
+ s.failures = error && ['NETWORK', 'TIMEOUT'].includes(error.code) ? s.failures + 1 : 0
20
+ if (s.failures >= 3 && route.failoverMode === 'network' && s.providerInstanceId === route.primaryInstanceId && route.fallbackInstanceIds.length) {
21
+ s.providerInstanceId = route.fallbackInstanceIds[0]; s.routeEpoch++; s.switchedAt = now(); s.failures = 0; changed(id)
22
+ }
23
+ },
24
+ switchPrimary(id, expectedEpoch) {
25
+ const route = find(id), s = state(route)
26
+ if (s.routeEpoch !== expectedEpoch) fail('ROUTE_CONFLICT', '路由已变化,请重新检查', 409)
27
+ if (s.switchedAt !== null && now() - s.switchedAt < 10 * 60 * 1000) fail('ROUTE_DWELL', '备用源驻留期尚未结束', 409)
28
+ s.providerInstanceId = route.primaryInstanceId; s.routeEpoch++; s.failures = 0; s.switchedAt = null; changed(id)
29
+ },
30
+ selections: () => Object.fromEntries(getConfig().routes.map(r => [r.id, { ...state(r) }])),
31
+ reset() { states.clear() },
32
+ }
33
+ }