@mzzsfy/dsh-stock-assistant 0.4.0 → 0.5.1
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/README.md +110 -100
- package/cordis.patch.yml +6 -0
- package/package.json +2 -2
- package/src/application.mjs +64 -32
- package/src/client.js +204 -129
- package/src/executor.mjs +7 -4
- package/src/index.js +12 -4
- package/src/kline-cache.mjs +1 -1
- package/src/market-model.mjs +8 -8
- package/src/memory-cache.mjs +19 -0
- package/src/providers/eastmoney.mjs +40 -41
- package/src/providers/finnhub.mjs +53 -0
- package/src/providers/tushare.mjs +1 -1
- package/src/routes.mjs +1 -0
- package/src/schemas.mjs +61 -9
- package/src/service.mjs +32 -10
- package/src/state.mjs +14 -5
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +41 -5
package/src/executor.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { StockError, fail } from './market-model.mjs'
|
|
2
2
|
// 每实例上游请求环形日志容量: 概览"最近请求"展示面
|
|
3
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 }) {
|
|
4
|
+
export function createExecutor({ registry, budget, env = process.env, resolveCredential = async ref => env[ref], fetch: fetchImpl = globalThis.fetch, now = Date.now, timers = globalThis, usSymbols = new Map(), proxyFactory = null }) {
|
|
5
5
|
const queues = new Map(), controllers = new Set(), starts = new Map()
|
|
6
6
|
const requestLogs = new Map(), proxies = new Map()
|
|
7
7
|
let stopped = false, running = 0
|
|
@@ -56,10 +56,14 @@ export function createExecutor({ registry, budget, env = process.env, fetch: fet
|
|
|
56
56
|
const adapter = registry.get(instance.adapterId), method = options.probe ? 'probe' : capability
|
|
57
57
|
if (typeof adapter[method] !== 'function') fail('UNSUPPORTED_CAPABILITY', '来源不支持该能力', 422)
|
|
58
58
|
let used = false, timeout
|
|
59
|
+
// 凭据每次操作解析一次, 不跨操作缓存: 存储层改了密钥, 下一次请求就生效, 不必重启插件。
|
|
60
|
+
// 解析在超时计时之前完成——读本地存储不该占用上游的 8 秒预算。
|
|
61
|
+
const secret = instance.credentialRef === null ? undefined : await resolveCredential(instance.credentialRef)
|
|
62
|
+
if (instance.credentialRef !== null && !secret) fail('AUTH', '未配置凭据', 422)
|
|
59
63
|
// 超时计时覆盖整个能力调用;分页适配器每次网络活动重置计时,空闲超过窗口才判超时。
|
|
60
64
|
const armTimeout = () => { timers.clearTimeout(timeout); timeout = timers.setTimeout(() => controller.abort(new StockError('TIMEOUT', '来源请求超时', 504, { retryable: true })), 8 * 1000) }
|
|
61
65
|
armTimeout()
|
|
62
|
-
const ctx = { now, signal: controller.signal, usSymbols, endpoints: instance.endpoints || null, credential: () =>
|
|
66
|
+
const ctx = { now, signal: controller.signal, usSymbols, endpoints: instance.endpoints || null, credential: () => secret,
|
|
63
67
|
fetch: async (...args) => {
|
|
64
68
|
if (used) {
|
|
65
69
|
const gap = Math.max(0, starts.get(instance.quotaGroup) + (instance.budget?.requestsPerMinute === null ? 10 * 1000 : 1000) - now())
|
|
@@ -77,8 +81,7 @@ export function createExecutor({ registry, budget, env = process.env, fetch: fet
|
|
|
77
81
|
armTimeout()
|
|
78
82
|
return response
|
|
79
83
|
} }
|
|
80
|
-
// 免凭据实例(
|
|
81
|
-
if (instance.credentialEnv !== null && !env[instance.credentialEnv]) fail('AUTH', '未在Host环境中配置凭据', 422)
|
|
84
|
+
// 免凭据实例(credentialRef=null)解析结果恒为空, 上述守卫不触发。
|
|
82
85
|
const work = Promise.resolve(adapter[method]({ ...request, providerInstanceId: instance.id, capability }, ctx))
|
|
83
86
|
const result = await new Promise((resolve, reject) => {
|
|
84
87
|
const aborted = () => reject(controller.signal.reason instanceof StockError ? controller.signal.reason : new StockError('CANCELLED', '请求已取消', 503))
|
package/src/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export const name = 'dsh-stock-assistant'
|
|
2
|
-
export const inject = ['webServer', 'storageDomain']
|
|
2
|
+
export const inject = ['webServer', 'storageDomain', 'credentials']
|
|
3
3
|
import { setupCommonTools, createChangeNotifier } from '@mzzsfy/dsh-common-tools/host'
|
|
4
4
|
import { createApplication } from './application.mjs'
|
|
5
5
|
import { registerRoutes } from './routes.mjs'
|
|
@@ -18,7 +18,8 @@ export async function apply(ctx) {
|
|
|
18
18
|
// vendor 可读性预判定先于应用构建: vendorAvailable=false 随快照下发→client 直接降级数字详情
|
|
19
19
|
let vendorAvailable = true
|
|
20
20
|
try { vendorAvailable = vendorReadable() } catch { vendorAvailable = false }
|
|
21
|
-
|
|
21
|
+
// 凭据服务由宿主提供; 接口不全时应用层会整体退回进程环境变量, 不因此拒绝启动
|
|
22
|
+
application = await createApplication({ storageDomain: ctx.storageDomain, credentials: ctx.credentials ?? null, publish: () => notifier?.refresh(), vendorAvailable })
|
|
22
23
|
if (disposed) { await application.close(); return }
|
|
23
24
|
bus = setupCommonTools(ctx)
|
|
24
25
|
notifier = createChangeNotifier(() => bus.publish({ type: 'invalidate', serverEpoch: application.snapshot().serverEpoch, snapshotSeq: application.snapshot().snapshotSeq }))
|
|
@@ -27,7 +28,14 @@ export async function apply(ctx) {
|
|
|
27
28
|
// 注册异常仅告警: client ensureLwc 失败同样走降级路径
|
|
28
29
|
try { ctx.webServer.register({ kind: 'prefix', path: VENDOR_PREFIX, handler: serveVendor }) } catch (e) { ctx.logger?.warn?.('图表组件路由注册失败,详情将降级为数字详情') }
|
|
29
30
|
} catch (e) {
|
|
30
|
-
|
|
31
|
-
|
|
31
|
+
// 失败原因先落日志再清理: 清理自身抛错不能盖掉原始原因。
|
|
32
|
+
// 数据域的 invalid-record 只有表/键有用, 记录值不能进日志。
|
|
33
|
+
const location = e?.detail?.table === undefined ? '' : `,记录 ${e.detail.table}/${e.detail.key}`
|
|
34
|
+
const reason = e && typeof e === 'object' ? `${e.code ? `${e.code}: ` : ''}${e.message || String(e)}${location}` : String(e)
|
|
35
|
+
ctx.logger?.warn?.(`股票工具未激活:独立数据域或依赖初始化失败 (${reason})`)
|
|
36
|
+
// 逐步清理: 任一步抛错都不能跳过关闭应用, 否则数据域占位留在宿主里, 重载只会一直 already-open
|
|
37
|
+
for (const step of [() => stopRoutes?.(), () => unsubscribe?.(), () => notifier?.dispose(), () => application?.close()]) {
|
|
38
|
+
try { await step() } catch (cleanupError) { ctx.logger?.warn?.(`股票工具清理失败: ${cleanupError?.message || cleanupError}`) }
|
|
39
|
+
}
|
|
32
40
|
}
|
|
33
41
|
}
|
package/src/kline-cache.mjs
CHANGED
package/src/market-model.mjs
CHANGED
|
@@ -2,14 +2,14 @@
|
|
|
2
2
|
// sessions 是该市场连续竞价的时段(市场本地时间), 用来判断报价此刻处在交易中/午休/休市;
|
|
3
3
|
// 只描述周内时点, 法定节假日仍以数据本身(最后一根K线的日期)为准。
|
|
4
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']] },
|
|
5
|
+
XSHG: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']], tag: '沪A' },
|
|
6
|
+
XSHE: { currency: 'CNY', timezone: 'Asia/Shanghai', priceScale: 2, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:30', '11:30'], ['13:00', '15:00']], tag: '深A' },
|
|
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']], tag: '港股' },
|
|
8
|
+
XNAS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']], tag: '纳斯达克' },
|
|
9
|
+
XNYS: { currency: 'USD', timezone: 'America/New_York', priceScale: 2, codePattern: /^[A-Z]{1,5}$/, verifiedByDefault: true, sessions: [['09:30', '16:00']], tag: '纽交所' },
|
|
10
|
+
XJPX: { currency: 'JPY', timezone: 'Asia/Tokyo', priceScale: 0, codePattern: /^\d{4}$/, verifiedByDefault: true, sessions: [['09:00', '11:30'], ['12:30', '15:30']], tag: '日本' },
|
|
11
|
+
XKRX: { currency: 'KRW', timezone: 'Asia/Seoul', priceScale: 0, codePattern: /^\d{6}$/, verifiedByDefault: true, sessions: [['09:00', '15:30']], tag: '韩国' },
|
|
12
|
+
XLON: { currency: 'GBP', timezone: 'Europe/London', priceScale: 2, codePattern: /^[A-Z0-9.]{1,10}$/, verifiedByDefault: true, sessions: [['08:00', '16:30']], tag: '英国' },
|
|
13
13
|
}
|
|
14
14
|
// 报价此刻落在市场交易日的哪个阶段; 周末恒为休市, 节假日不做推断(没有日历能力时会误判)
|
|
15
15
|
export function sessionStateOf(exchange, nowMs) {
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// 可重建的派生数据只放内存: K 线、目录、日历丢了重拉即可, 落盘只会把控制记录一起拖大
|
|
2
|
+
const CACHE_LIMIT = 512
|
|
3
|
+
|
|
4
|
+
// 与数据域 table 同形的最小实现: catalog 只遍历 entries, kline-cache 只 get/put/delete
|
|
5
|
+
export function createMemoryCache({ limit = CACHE_LIMIT } = {}) {
|
|
6
|
+
const records = new Map()
|
|
7
|
+
return {
|
|
8
|
+
get: key => records.get(key),
|
|
9
|
+
async put(key, value) {
|
|
10
|
+
records.delete(key)
|
|
11
|
+
records.set(key, value)
|
|
12
|
+
// 超限先丢最久未写的: 缓存的命门是内存, 不是命中率
|
|
13
|
+
while (records.size > limit) records.delete(records.keys().next().value)
|
|
14
|
+
},
|
|
15
|
+
async delete(key) { return records.delete(key) },
|
|
16
|
+
entries: () => records.entries(),
|
|
17
|
+
get size() { return records.size },
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -9,15 +9,18 @@ const DEFAULT_ENDPOINTS = {
|
|
|
9
9
|
trend: 'https://push2his.eastmoney.com/api/qt/stock/trends2/get',
|
|
10
10
|
}
|
|
11
11
|
const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
|
|
12
|
-
//
|
|
12
|
+
// 沪深市场代码(其余市场的 secid 前缀见 SECID_PREFIX)
|
|
13
13
|
const MARKET = { XSHG: '1', XSHE: '0' }
|
|
14
14
|
// 搜索联想 MktNum→交易所全集(实测: 1/0 沪深, 116 港, 105/106/107 美三大, 176/177/155 日韩英)
|
|
15
15
|
const SEARCH_EXCHANGE = { 1: 'XSHG', 0: 'XSHE', 116: 'XHKG', 105: 'XNAS', 106: 'XNYS', 107: 'XNYS', 176: 'XJPX', 177: 'XKRX', 155: 'XLON' }
|
|
16
16
|
const SECID_PREFIX = { XSHG: '1', XSHE: '0', XHKG: '116', XNAS: '105', XNYS: '106', XJPX: '176', XKRX: '177', XLON: '155' }
|
|
17
|
-
const US_DEFAULT_MKT = '105'
|
|
18
17
|
// 美股三大市场号: 105 纳斯达克 / 106 纽约 / 107 美交所。secid 前缀必须精确匹配, 探针期据此逐个试探。
|
|
19
18
|
const US_MKTNUMS = ['105', '106', '107']
|
|
20
19
|
const isUSExchange = exchange => exchange === 'XNAS' || exchange === 'XNYS'
|
|
20
|
+
// 美股 secid 前缀候选序: 搜索缓存 > 交易所静态前缀 > 其余美股市场号。XNYS 实横跨 106 与 107, 静态前缀只取其一。
|
|
21
|
+
// 缓存只加速重复查询, 缺失或过期不改变正确性: 进程重启后 usSymbols 为空, 取报价不得依赖此前的搜索行为。
|
|
22
|
+
const usSecidPrefixes = (security, ctx) => [...new Set([ctx.usSymbols?.get(`US:${security.code}`)?.mktNum, SECID_PREFIX[security.exchange], ...US_MKTNUMS].filter(mktNum => US_MKTNUMS.includes(mktNum)))]
|
|
23
|
+
const secidFor = (security, ctx) => isUSExchange(security.exchange) ? `${usSecidPrefixes(security, ctx)[0]}.${security.code}` : `${SECID_PREFIX[security.exchange]}.${security.code}`
|
|
21
24
|
// klt 周期映射(实测): 日101/周102/月103; trends2 无 klt。
|
|
22
25
|
const KLT = { '1d': 101, '1w': 102, '1M': 103 }
|
|
23
26
|
// 目录 fs 按市场给出; 英股 m:155 含债券与结构性产品, 加 t:1 只取股票; 日韩不支持 t: 细分, 全量即股票
|
|
@@ -30,8 +33,6 @@ const KLINE_FIELDS = 'f51,f52,f53,f54,f55,f56,f57'
|
|
|
30
33
|
const TREND_FIELDS = 'f51,f52,f53,f54,f55,f56,f57,f58'
|
|
31
34
|
// 分时时间戳的来源时区: 东财统一用北京时间, 与证券所属市场无关
|
|
32
35
|
const SOURCE_ZONE = 'Asia/Shanghai'
|
|
33
|
-
// quotes secid 与 kline secidOf 同源(八市场前缀表);美股 quotes 同样走 usSymbols 动态归属。
|
|
34
|
-
const symbolOf = security => `${SECID_PREFIX[security.exchange]}.${security.code}`
|
|
35
36
|
const num = value => value == null || typeof value === 'number' && !Number.isFinite(value) ? null : value === '-' ? null : String(value)
|
|
36
37
|
async function getJson(ctx, url) {
|
|
37
38
|
let response
|
|
@@ -61,41 +62,44 @@ export const eastmoney = {
|
|
|
61
62
|
if (!result.candles.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
62
63
|
return { status: 'ready', capability: 'kline', market: request.market, instrument: 'equity' }
|
|
63
64
|
}
|
|
64
|
-
//
|
|
65
|
+
// 美股前缀的逐个试探已收敛进 quotes,探针只需一次结果,避免探针与真实取价走两套路径
|
|
65
66
|
const security = request.securities?.[0] || { exchange: request.market, code: PROBE_SECURITY[request.market] || '000001' }
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const rows = await this.quotes({ ...request, securities: [security] }, scope)
|
|
70
|
-
if (rows.items.length) return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
|
|
71
|
-
}
|
|
72
|
-
throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
67
|
+
const rows = await this.quotes({ ...request, securities: [security] }, ctx)
|
|
68
|
+
if (!rows.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
69
|
+
return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
|
|
73
70
|
},
|
|
74
71
|
async quotes(request, ctx) {
|
|
75
|
-
|
|
76
|
-
const secidOf = security => isUSExchange(security.exchange) ? `${ctx.usSymbols?.get(`US:${security.code}`)?.mktNum || US_DEFAULT_MKT}.${security.code}` : `${SECID_PREFIX[security.exchange]}.${security.code}`
|
|
77
|
-
const symbols = new Map(request.securities.map(s => [secidOf(s), s]))
|
|
78
|
-
const body = await getJson(ctx, `${endpointOf(ctx, 'quotes')}?secids=${[...symbols.keys()].join(',')}&fields=f2,f3,f4,f5,f6,f12,f13,f14,f15,f16,f17,f18,f124&fltt=2&invt=2`)
|
|
79
|
-
const rows = body?.data?.diff
|
|
80
|
-
// data:null表示全部secids无效(如整批退市),降级为逐证券缺失,不让单批坏行瘫痪路由。
|
|
81
|
-
if (!Array.isArray(rows)) return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items: [], errors: request.securities.map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
|
|
72
|
+
const fields = 'f2,f3,f4,f5,f6,f12,f13,f14,f15,f16,f17,f18,f124'
|
|
82
73
|
const seen = new Set(), items = []
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
74
|
+
// 一次请求取一批 secid;data:null 表示整批 secid 均无效(如整批退市),降级为逐证券缺失。
|
|
75
|
+
const ingest = async symbols => {
|
|
76
|
+
const body = await getJson(ctx, `${endpointOf(ctx, 'quotes')}?secids=${[...symbols.keys()].join(',')}&fields=${fields}&fltt=2&invt=2`)
|
|
77
|
+
const rows = body?.data?.diff
|
|
78
|
+
if (!Array.isArray(rows)) return
|
|
79
|
+
for (const row of rows) {
|
|
80
|
+
const security = symbols.get(`${row.f13}.${row.f12}`)
|
|
81
|
+
if (!security) continue
|
|
82
|
+
if (seen.has(security.id)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
|
|
83
|
+
seen.add(security.id)
|
|
84
|
+
// fltt=2时价格为已缩放数值, "-"表示停牌等无值;f124为来源Unix秒;成交额币种按市场派生(单一事实源 MARKET_META.currency)。
|
|
85
|
+
const quoteAt = Number.isFinite(row.f124) ? new Date(row.f124 * 1000).toISOString() : null
|
|
86
|
+
const currency = MARKET_META[security.exchange]?.currency || 'CNY'
|
|
87
|
+
items.push(normalizeQuote({
|
|
88
|
+
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'eastmoney', providerSymbol: `${row.f13}.${row.f12}`,
|
|
89
|
+
last: num(row.f2), previousClose: num(row.f18), open: num(row.f17), high: num(row.f15), low: num(row.f16),
|
|
90
|
+
volume: sharesFromLots(num(row.f5), security.exchange), volumeUnit: 'share', amount: num(row.f6), amountUnit: currency,
|
|
91
|
+
quoteAt, timestampKind: 'trade',
|
|
92
|
+
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
93
|
+
}))
|
|
94
|
+
}
|
|
98
95
|
}
|
|
96
|
+
await ingest(new Map(request.securities.map(s => [secidFor(s, ctx), s])))
|
|
97
|
+
// 美股前缀兜底: 静态前缀只对应一个市场号,而交易所归属未必精确(实测 NYSE 的票分属 106/107)。
|
|
98
|
+
// 只对首轮落空的美股补齐剩余候选,一次批量发完,不逐证券重试。
|
|
99
|
+
const orphanUS = request.securities.filter(s => !seen.has(s.id) && isUSExchange(s.exchange))
|
|
100
|
+
const altSymbols = new Map()
|
|
101
|
+
for (const security of orphanUS) for (const mktNum of usSecidPrefixes(security, ctx).slice(1)) altSymbols.set(`${mktNum}.${security.code}`, security)
|
|
102
|
+
if (altSymbols.size) await ingest(altSymbols)
|
|
99
103
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: request.securities.filter(s => !seen.has(s.id)).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
|
|
100
104
|
},
|
|
101
105
|
async catalog(request, ctx) {
|
|
@@ -144,14 +148,9 @@ export const eastmoney = {
|
|
|
144
148
|
}
|
|
145
149
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: [] }
|
|
146
150
|
},
|
|
147
|
-
//
|
|
151
|
+
// 与 quotes 同源的 secid;猜错时调用方走 suggest 重试路径(搜索结果是市场号的权威来源)。
|
|
148
152
|
secidOf(request, ctx) {
|
|
149
|
-
|
|
150
|
-
if (market === 'XNAS' || market === 'XNYS') {
|
|
151
|
-
const mktNum = ctx.usSymbols?.get(`US:${code}`)?.mktNum
|
|
152
|
-
return `${mktNum || US_DEFAULT_MKT}.${code}`
|
|
153
|
-
}
|
|
154
|
-
return `${SECID_PREFIX[market]}.${code}`
|
|
153
|
+
return secidFor({ exchange: request.market, code: request.code }, ctx)
|
|
155
154
|
},
|
|
156
155
|
async kline(request, ctx) {
|
|
157
156
|
if (request.period === 'trend') return this.trend(request, ctx)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Finnhub 免费公开接口: 美股实时报价。没有批量端点, 每次一只;官方明确不建议持续轮询, 额度按分钟计。
|
|
2
|
+
import { MARKET_META, normalizeQuote, StockError } from '../market-model.mjs'
|
|
3
|
+
const DEFAULT_ENDPOINTS = { quotes: 'https://finnhub.io/api/v1/quote' }
|
|
4
|
+
const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
|
|
5
|
+
// 免费档只开放 /quote: K线与盘口都标 Premium Access Required, 所以本适配器只声明报价能力。
|
|
6
|
+
const PROBE_SECURITY = 'AAPL'
|
|
7
|
+
// 无效代码由来源返回全 0 字段而非 404, 现价 0 即视为无此证券
|
|
8
|
+
const EMPTY_PRICE = 0
|
|
9
|
+
const MINUTE_MS = 60 * 1000
|
|
10
|
+
async function getJson(ctx, url) {
|
|
11
|
+
let response
|
|
12
|
+
try {
|
|
13
|
+
response = await ctx.fetch(url, { headers: { 'User-Agent': 'Mozilla/5.0' }, signal: ctx.signal, redirect: 'error' })
|
|
14
|
+
} catch (e) {
|
|
15
|
+
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
16
|
+
if (e instanceof StockError) throw e
|
|
17
|
+
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
18
|
+
}
|
|
19
|
+
if (response.status === 401 || response.status === 403) throw new StockError('AUTH', '来源拒绝了该凭据', 401)
|
|
20
|
+
if (response.status === 429) throw new StockError('RATE_LIMIT', '来源限流', 429, { retryAfterMs: MINUTE_MS })
|
|
21
|
+
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
22
|
+
return response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
|
|
23
|
+
}
|
|
24
|
+
export const finnhub = {
|
|
25
|
+
descriptor: { adapterId: 'finnhub', capabilities: ['quotes'], markets: ['XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 1, credential: 'DSH_STOCK_FINNHUB_TOKEN', description: 'Finnhub:需配置凭据,美股实时报价,免费档不含K线,单只一请求', endpointKeys: [{ key: 'quotes', label: '实时报价' }] },
|
|
26
|
+
async probe(request, ctx) {
|
|
27
|
+
const security = { id: `${request.market}:equity:${PROBE_SECURITY}`, exchange: request.market, code: PROBE_SECURITY }
|
|
28
|
+
const result = await this.quotes({ ...request, securities: [security] }, ctx)
|
|
29
|
+
if (!result.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
30
|
+
return { status: 'ready', capability: 'quotes', market: request.market, instrument: 'equity' }
|
|
31
|
+
},
|
|
32
|
+
async quotes(request, ctx) {
|
|
33
|
+
const token = ctx.credential(), items = [], errors = []
|
|
34
|
+
for (const security of request.securities) {
|
|
35
|
+
const body = await getJson(ctx, `${endpointOf(ctx, 'quotes')}?symbol=${encodeURIComponent(security.code)}&token=${encodeURIComponent(token)}`)
|
|
36
|
+
if (!Number.isFinite(body?.c) || body.c === EMPTY_PRICE) {
|
|
37
|
+
errors.push({ securityId: security.id, code: 'NO_DATA', message: '来源未返回此证券报价' })
|
|
38
|
+
continue
|
|
39
|
+
}
|
|
40
|
+
// t 是最后一笔成交的 Unix 秒。延迟交给 collector 按时差派生: 盘后拉取时差本来就大,
|
|
41
|
+
// 适配器硬声明实时等于替来源撒谎。
|
|
42
|
+
items.push(normalizeQuote({
|
|
43
|
+
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'finnhub', providerSymbol: security.code,
|
|
44
|
+
last: body.c, previousClose: body.pc ?? null, open: body.o ?? null, high: body.h ?? null, low: body.l ?? null,
|
|
45
|
+
volume: null, volumeUnit: 'share', amount: null, amountUnit: MARKET_META[security.exchange]?.currency || 'USD',
|
|
46
|
+
quoteAt: Number.isFinite(body.t) && body.t > 0 ? new Date(body.t * 1000).toISOString() : null,
|
|
47
|
+
timestampKind: 'trade',
|
|
48
|
+
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
49
|
+
}))
|
|
50
|
+
}
|
|
51
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors }
|
|
52
|
+
},
|
|
53
|
+
}
|
|
@@ -37,7 +37,7 @@ async function query(capability, params, ctx) {
|
|
|
37
37
|
}
|
|
38
38
|
function symbol(security) { return `${security.code}.${SUFFIX[security.exchange]}` }
|
|
39
39
|
export const tushare = {
|
|
40
|
-
descriptor: { adapterId: 'tushare', capabilities: ['quotes', 'catalog', 'calendar'], markets: ['XSHG', 'XSHE'], instruments: ['equity'], maxQuoteBatch: 20, credential: '
|
|
40
|
+
descriptor: { adapterId: 'tushare', capabilities: ['quotes', 'catalog', 'calendar'], markets: ['XSHG', 'XSHE'], instruments: ['equity'], maxQuoteBatch: 20, credential: 'DSH_STOCK_TUSHARE_TOKEN', description: 'Tushare Pro:需配置凭据,沪深目录/日历/行情,有SLA' },
|
|
41
41
|
async catalog(request, ctx) {
|
|
42
42
|
let rows = await query('catalog', { exchange: EXCHANGE[request.market], list_status: 'L' }, ctx)
|
|
43
43
|
let complete = rows.length < 6000
|
package/src/routes.mjs
CHANGED
|
@@ -25,6 +25,7 @@ export function registerRoutes(webServer, app) {
|
|
|
25
25
|
preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
|
|
26
26
|
configuration: ['POST', input => { operationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
|
|
27
27
|
'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
|
|
28
|
+
credential: ['POST', input => app.credential(input)],
|
|
28
29
|
'catalog-sync': ['POST', input => app.sync(input)],
|
|
29
30
|
'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
|
|
30
31
|
refresh: ['POST', (input, signal) => app.refresh(input, signal)],
|
package/src/schemas.mjs
CHANGED
|
@@ -10,15 +10,27 @@ export const marksSchema = z.array(markSchema).max(12).default([]).superRefine((
|
|
|
10
10
|
if (new Set(list.map(mark => `${mark.kind}:${mark.price}`)).size !== list.length) ctx.addIssue({ code: 'custom', message: '同类型的价格不能重复' })
|
|
11
11
|
})
|
|
12
12
|
const rate = z.number().int().positive().max(100000)
|
|
13
|
+
// 每票可同时归属的分组上限: 标签是视图视角, 超过这个数量就该换一种组织方式
|
|
14
|
+
export const MAX_TAGS = 8
|
|
15
|
+
// 标签名即分组身份: 允许 1-12 字, 不允许首尾空白与控制字符(它们会让同名标签在界面上看起来一样)。
|
|
16
|
+
// C0/C1/DEL 之外还挡零宽与双向控制符: 它们不占宽度却能让两个不同的标签在 chips 与 tab 上完全同形
|
|
17
|
+
const TAG_CHARS_SOURCE = '\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u202a-\\u202e'
|
|
18
|
+
const TAG_CHARS = new RegExp(`[${TAG_CHARS_SOURCE}]`), TAG_CHARS_ALL = new RegExp(`[${TAG_CHARS_SOURCE}]`, 'g')
|
|
19
|
+
// 旧版校验只挡 C0, 存量 group 里可能存在零宽/双向字符: 迁移必须先剥掉再判定, 否则一条旧记录会让插件整体不激活
|
|
20
|
+
export const stripTagChars = value => value.replace(TAG_CHARS_ALL, '')
|
|
21
|
+
export const tagName = z.string().refine(s => {
|
|
22
|
+
const trimmed = s.trim()
|
|
23
|
+
return trimmed !== '' && trimmed === s && [...trimmed].length <= 12 && !TAG_CHARS.test(trimmed)
|
|
24
|
+
}, '标签名需为 1-12 字, 不含首尾空白与控制字符')
|
|
13
25
|
export const capability = z.enum(['quotes', 'catalog', 'search', 'calendar', 'kline'])
|
|
14
26
|
export const marketSchema = z.enum(Object.keys(MARKET_META))
|
|
15
27
|
export const providerSchema = z.strictObject({
|
|
16
|
-
id, adapterId: id, enabled: z.boolean(),
|
|
28
|
+
id, adapterId: id, enabled: z.boolean(), credentialRef: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).nullable(), quotaGroup: id,
|
|
17
29
|
budget: z.strictObject({ requestsPerMinute: rate.nullable(), dailyRequestLimit: rate.nullable(), billingUnit: z.enum(['request', 'symbol']), symbolCreditsPerMinute: rate.nullable(), capabilityLimits: z.partialRecord(capability, rate) }),
|
|
18
30
|
endpoints: z.record(z.string().url()).optional(),
|
|
19
31
|
// 上游出口代理(反代/正向代理统一走 URL): http(s)://[user:pass@]host:port, 凭据在 userinfo
|
|
20
32
|
proxy: z.string().url().refine(v => v.startsWith('http://') || v.startsWith('https://'), '代理仅支持 http(s) URL').optional(),
|
|
21
|
-
}).refine(p => p.
|
|
33
|
+
}).refine(p => p.credentialRef !== null || p.budget.requestsPerMinute !== null, '免凭据来源必须声明保守预算')
|
|
22
34
|
export const routeSchema = z.strictObject({
|
|
23
35
|
id, capability, market: marketSchema, instrument: z.literal('equity'), primaryInstanceId: id,
|
|
24
36
|
fallbackInstanceIds: z.array(id).max(1), failoverMode: z.enum(['off', 'network']), maxDelaySeconds: z.number().nonnegative().nullable(), acceptUnknownDelay: z.boolean(),
|
|
@@ -47,7 +59,7 @@ export function parseConfiguration(value) {
|
|
|
47
59
|
if (providerIds.has(p.id)) fail('DUPLICATE_PROVIDER', '数据源实例名称重复', 422)
|
|
48
60
|
providerIds.add(p.id)
|
|
49
61
|
if (p.budget.billingUnit === 'symbol' && p.budget.symbolCreditsPerMinute === null) fail('INVALID_BUDGET', '按证券计费必须提供证券额度', 422)
|
|
50
|
-
const same = config.providers.filter(other => other.adapterId === p.adapterId && other.
|
|
62
|
+
const same = config.providers.filter(other => other.adapterId === p.adapterId && other.credentialRef === p.credentialRef)
|
|
51
63
|
if (same.some(other => other.quotaGroup !== p.quotaGroup)) fail('INVALID_BUDGET', '同账号引用必须共享额度组', 422)
|
|
52
64
|
}
|
|
53
65
|
const routeIds = new Set()
|
|
@@ -62,22 +74,62 @@ export function parseConfiguration(value) {
|
|
|
62
74
|
}
|
|
63
75
|
return config
|
|
64
76
|
}
|
|
65
|
-
export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), watchlist: z.object({ order: z.array(z.string()).max(100), items: z.record(z.string(), securitySchema.safeExtend({ alias: z.string(), pinned: z.boolean(), marks: marksSchema,
|
|
77
|
+
export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), watchlist: z.object({ order: z.array(z.string()).max(100), items: z.record(z.string(), securitySchema.safeExtend({ alias: z.string(), pinned: z.boolean(), marks: marksSchema, tags: z.array(tagName).max(MAX_TAGS).refine(list => new Set(list).size === list.length, '标签不能重复').default([]) })) }), preferences: preferencesSchema, providers: z.array(providerSchema), routes: z.array(routeSchema), operations: z.array(z.object({ id: z.uuid(), hash: z.string(), at: z.number(), result: z.object({ revision: z.number() }).passthrough(), action: z.string(), payload: z.unknown() })).max(256) }).superRefine((control, ctx) => {
|
|
66
78
|
const w = control.watchlist
|
|
67
79
|
if (new Set(w.order).size !== w.order.length || w.order.length !== Object.keys(w.items).length || w.order.some(id => w.items[id]?.id !== id)) ctx.addIssue({ code: 'custom', message: '自选序列与证券不一致' })
|
|
68
80
|
let unpinned = false
|
|
69
81
|
for (const id of w.order) { if (!w.items[id]?.pinned) unpinned = true; else if (unpinned) ctx.addIssue({ code: 'custom', message: '置顶序列混乱' }) }
|
|
70
82
|
try { parseConfiguration({ providers: control.providers, routes: control.routes }) } catch { ctx.addIssue({ code: 'custom', message: '来源配置不一致' }) }
|
|
71
83
|
})
|
|
72
|
-
|
|
84
|
+
// 存量记录归一: 数据源实例的凭据字段曾叫 credentialEnv(本来也只存引用名), 更名 credentialRef 后
|
|
85
|
+
// 旧记录要能在数据域打开时通过校验并就地改成新字段 —— 这次校验发生在 storageDomain.open,
|
|
86
|
+
// 早于插件应用层的任何迁移代码, 迁移写在这一层之外等于永远跑不到。
|
|
87
|
+
// 新旧字段并存时以新字段为准; 非对象条目原样交给 schema 去拒绝, 不在这里抛
|
|
88
|
+
const normalizeProvider = provider => {
|
|
89
|
+
if (!provider || typeof provider !== 'object' || !('credentialEnv' in provider)) return provider
|
|
90
|
+
const { credentialEnv, ...rest } = provider
|
|
91
|
+
return { ...rest, credentialRef: 'credentialRef' in rest ? rest.credentialRef : credentialEnv ?? null }
|
|
92
|
+
}
|
|
93
|
+
const normalizeCredentialField = root => {
|
|
94
|
+
if (!root || typeof root !== 'object' || !Array.isArray(root.providers)) return root
|
|
95
|
+
if (!root.providers.some(p => p && typeof p === 'object' && 'credentialEnv' in p)) return root
|
|
96
|
+
return { ...root, providers: root.providers.map(normalizeProvider) }
|
|
97
|
+
}
|
|
98
|
+
// 分组从单值 group 改为多标签 tags。与凭据改名同理, 归一必须在数据域 schema 上做,
|
|
99
|
+
// 否则存量记录通不过 storageDomain.open 的校验, 插件整体起不来。非字符串 group 也搬进 tags,
|
|
100
|
+
// 交给 tagName 校验报错, 不静默丢弃。
|
|
101
|
+
// 空分组说明用户没手工组织过: 按市场回填默认标签, 否则升级后所有存量票都落进未分组。
|
|
102
|
+
// 旧写路径会 trim, 但手工或外部写入可能带空白; 不 trim 会让一条旧记录直接锁死整个插件。
|
|
103
|
+
// tags 已存在时无论形态都原样保留: 让 schema 报错, 而不是用 group 静默覆盖用户标签。
|
|
104
|
+
const normalizeWatchlistTags = root => {
|
|
105
|
+
const items = root?.watchlist?.items
|
|
106
|
+
if (!items || typeof items !== 'object' || Array.isArray(items)) return root
|
|
107
|
+
if (!Object.values(items).some(item => item && typeof item === 'object' && 'group' in item)) return root
|
|
108
|
+
const next = Object.fromEntries(Object.entries(items).map(([id, item]) => {
|
|
109
|
+
if (!item || typeof item !== 'object' || !('group' in item)) return [id, item]
|
|
110
|
+
const { group, ...rest } = item
|
|
111
|
+
if ('tags' in rest) return [id, rest]
|
|
112
|
+
const marketTag = MARKET_META[rest.exchange]?.tag
|
|
113
|
+
if (typeof group !== 'string') return [id, { ...rest, tags: [group] }]
|
|
114
|
+
const text = stripTagChars(group).trim()
|
|
115
|
+
return [id, { ...rest, tags: text ? [text] : marketTag ? [marketTag] : [] }]
|
|
116
|
+
}))
|
|
117
|
+
return { ...root, watchlist: { ...root.watchlist, items: next } }
|
|
118
|
+
}
|
|
119
|
+
const normalizeStoredControl = root => normalizeWatchlistTags(normalizeCredentialField(root))
|
|
120
|
+
export const storedControlSchema = z.preprocess(normalizeStoredControl, controlSchema)
|
|
121
|
+
// 存储只有一条记录: 自选与路由。K 线/目录/日历都是可重建的派生数据, 只放内存 ——
|
|
122
|
+
// 把它们塞进同一个文件曾把文件撑到 3.3 MB, 每次改自选都要整体重写, 写坏一次全没。
|
|
123
|
+
// 旧文件同名同版本, 打开时只取声明过的 control 表, 缓存表被忽略, 下次写入自然缩到十几 KB。
|
|
124
|
+
export const domainSpec = { name: 'stock_assistant', version: 1, layout: 'single', tables: { control: { valueSchema: storedControlSchema } } }
|
|
73
125
|
// 推荐配置:四个免凭据源,东财做八市场主力,其余按实测最强能力分派备份——公开源无SLA,能覆盖的市场都串上备源。
|
|
74
126
|
export const defaultConfig = () => {
|
|
75
127
|
const budget = (requestsPerMinute, capabilityLimits = {}) => ({ requestsPerMinute, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits })
|
|
76
128
|
const providers = [
|
|
77
|
-
{ id: 'em-default', adapterId: 'eastmoney', enabled: true,
|
|
78
|
-
{ id: 'sn-backup', adapterId: 'sina', enabled: true,
|
|
79
|
-
{ id: 'tx-backup', adapterId: 'tencent', enabled: true,
|
|
80
|
-
{ id: 'xq-backup', adapterId: 'xueqiu', enabled: true,
|
|
129
|
+
{ id: 'em-default', adapterId: 'eastmoney', enabled: true, credentialRef: null, quotaGroup: 'free-quote', budget: budget(60, { kline: 30 }) },
|
|
130
|
+
{ id: 'sn-backup', adapterId: 'sina', enabled: true, credentialRef: null, quotaGroup: 'free-list', budget: budget(120, { catalog: 60 }) },
|
|
131
|
+
{ id: 'tx-backup', adapterId: 'tencent', enabled: true, credentialRef: null, quotaGroup: 'free-backup', budget: budget(60, { kline: 20 }) },
|
|
132
|
+
{ id: 'xq-backup', adapterId: 'xueqiu', enabled: true, credentialRef: null, quotaGroup: 'free-xq', budget: budget(60) },
|
|
81
133
|
]
|
|
82
134
|
// 备用源只在探针可验证的组合上声明: 腾讯美股K线需先由搜索建立代码映射, 探针期必然不可用
|
|
83
135
|
const klineBackup = new Set(['XSHG', 'XSHE', 'XHKG'])
|
package/src/service.mjs
CHANGED
|
@@ -1,17 +1,26 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
|
-
import { fail, parseSecurityId } from './market-model.mjs'
|
|
3
|
-
import { securitySchema, marksSchema } from './schemas.mjs'
|
|
2
|
+
import { fail, parseSecurityId, MARKET_META } from './market-model.mjs'
|
|
3
|
+
import { securitySchema, marksSchema, tagName, MAX_TAGS } from './schemas.mjs'
|
|
4
4
|
// 自选身份八市场: parseSecurityId 是唯一事实源(市场/代码形态随 MARKET_META)
|
|
5
5
|
const securityId = z.string().refine(v => { try { parseSecurityId(v); return true } catch { return false } })
|
|
6
|
+
// 标签输入先归一(trim/去空/去重), 再按存储规则校验: 空白条目等于没填, 不因输入框残留空格就拒绝整次操作
|
|
7
|
+
const tagValue = z.string().transform(value => value.trim()).refine(value => tagName.safeParse(value).success, '标签名需为 1-12 字, 不含控制字符')
|
|
8
|
+
const tagList = z.array(z.string()).transform(list => [...new Set(list.map(value => value.trim()).filter(Boolean))]).superRefine((list, ctx) => {
|
|
9
|
+
if (list.length > MAX_TAGS) ctx.addIssue({ code: 'custom', message: `每只最多 ${MAX_TAGS} 个标签` })
|
|
10
|
+
for (const tag of list) {
|
|
11
|
+
const result = tagName.safeParse(tag)
|
|
12
|
+
if (!result.success) ctx.addIssue({ code: 'custom', message: result.error.issues[0].message })
|
|
13
|
+
}
|
|
14
|
+
})
|
|
6
15
|
const payloads = {
|
|
7
16
|
add: z.strictObject({ securityId }), remove: z.strictObject({ securityId }),
|
|
8
17
|
restore: z.strictObject({ removeOperationId: z.uuid() }),
|
|
9
18
|
alias: z.strictObject({ securityId, alias: z.string().refine(s => [...s].length <= 30) }),
|
|
10
19
|
marks: z.strictObject({ securityId, marks: marksSchema }),
|
|
11
|
-
//
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
20
|
+
// 标签整组替换: 与 marks 同一语义, 协议面只有一个操作, 不出现半更新的中间态
|
|
21
|
+
tags: z.strictObject({ securityId, tags: tagList }),
|
|
22
|
+
tagRename: z.strictObject({ from: tagValue, to: tagValue }),
|
|
23
|
+
tagRemove: z.strictObject({ tag: tagValue }),
|
|
15
24
|
pin: z.strictObject({ securityId, pinned: z.boolean() }),
|
|
16
25
|
move: z.strictObject({ securityId, beforeId: securityId.nullable() }),
|
|
17
26
|
// 拖拽排序: 提交完整显示序, 前端算好顺序一次落库, 避免逐行 move 的中间态
|
|
@@ -40,7 +49,8 @@ export function createWatchlistService(state, resolveSecurity, now = Date.now) {
|
|
|
40
49
|
if (w.order.length >= 100) fail('LIMIT_REACHED', '最多添加100只自选', 422)
|
|
41
50
|
const security = resolveSecurity(p.securityId)
|
|
42
51
|
if (!security || !securitySchema.safeParse(security).success) fail('CANDIDATE_EXPIRED', '候选已过期,请重新搜索', 409)
|
|
43
|
-
|
|
52
|
+
// 默认按市场分组: 标签由市场元数据生成, 用户可再改可删
|
|
53
|
+
w.items[p.securityId] = { ...security, alias: '', pinned: false, marks: [], tags: [MARKET_META[security.exchange].tag] }; w.order.push(p.securityId)
|
|
44
54
|
} else if (operation.action === 'restore') {
|
|
45
55
|
const deleted = control.operations.find(o => o.id === p.removeOperationId && o.action === 'remove')
|
|
46
56
|
const restore = deleted?.result.restore
|
|
@@ -53,9 +63,21 @@ export function createWatchlistService(state, resolveSecurity, now = Date.now) {
|
|
|
53
63
|
const after = w.order.indexOf(restore.previousId) + 1; w.order.splice(after, 0, restored.id)
|
|
54
64
|
} else if (restore.nextId && same(restore.nextId)) insert(restored.id, restore.nextId)
|
|
55
65
|
else insert(restored.id, restored.pinned ? regionEnd(true) : null)
|
|
56
|
-
} else if (operation.action === '
|
|
57
|
-
|
|
58
|
-
|
|
66
|
+
} else if (operation.action === 'tags') {
|
|
67
|
+
if (!w.items[p.securityId]) fail('NOT_FOUND', '证券已被移除', 404)
|
|
68
|
+
w.items[p.securityId].tags = p.tags
|
|
69
|
+
}
|
|
70
|
+
// 标签是名称身份: 重命名即批量替换, 目标名已存在时合并去重而不是制造重复
|
|
71
|
+
else if (operation.action === 'tagRename') {
|
|
72
|
+
const holders = w.order.filter(id => w.items[id].tags.includes(p.from))
|
|
73
|
+
if (!holders.length) fail('NOT_FOUND', '标签不存在', 404)
|
|
74
|
+
for (const id of holders) w.items[id].tags = [...new Set(w.items[id].tags.map(tag => tag === p.from ? p.to : tag))]
|
|
75
|
+
}
|
|
76
|
+
else if (operation.action === 'tagRemove') {
|
|
77
|
+
const holders = w.order.filter(id => w.items[id].tags.includes(p.tag))
|
|
78
|
+
if (!holders.length) fail('NOT_FOUND', '标签不存在', 404)
|
|
79
|
+
for (const id of holders) w.items[id].tags = w.items[id].tags.filter(tag => tag !== p.tag)
|
|
80
|
+
}
|
|
59
81
|
else {
|
|
60
82
|
if (!item) fail('NOT_FOUND', '证券已被移除', 404)
|
|
61
83
|
if (operation.action === 'remove') {
|
package/src/state.mjs
CHANGED
|
@@ -1,19 +1,24 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
2
|
import { domainSpec, initialControl, controlSchema } from './schemas.mjs'
|
|
3
|
+
import { createMemoryCache } from './memory-cache.mjs'
|
|
3
4
|
import { fail } from './market-model.mjs'
|
|
4
5
|
const DAY = 24 * 60 * 60 * 1000
|
|
6
|
+
// 目录/日历条数很少, 给独立小池: 与 K 线共用一个淘汰池时会被几十节 K 线挤掉, 挤掉后又要重新拉目录
|
|
7
|
+
const CATALOG_CACHE_LIMIT = 64, KLINE_CACHE_LIMIT = 512
|
|
5
8
|
export const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex')
|
|
6
9
|
export async function openState(storageDomain, changed = () => {}, now = Date.now) {
|
|
10
|
+
// 只有控制记录落盘; 派生数据放内存, 所以打开失败只可能是这一个文件
|
|
7
11
|
const domain = await storageDomain.open(domainSpec)
|
|
8
|
-
const table = domain.table('control')
|
|
12
|
+
const table = domain.table('control')
|
|
9
13
|
try {
|
|
14
|
+
// 存量字段改名的归一发生在数据域的 valueSchema 上(storageDomain.open 阶段), 这里读到的已是新格式
|
|
10
15
|
if (!table.get('root')) await table.put('root', initialControl())
|
|
11
|
-
|
|
12
|
-
|
|
16
|
+
} catch (e) { await Promise.allSettled([domain.close()]); throw e }
|
|
17
|
+
const cache = createMemoryCache({ limit: CATALOG_CACHE_LIMIT }), klineCache = createMemoryCache({ limit: KLINE_CACHE_LIMIT })
|
|
13
18
|
let tail = Promise.resolve(), stopped = false
|
|
14
19
|
return {
|
|
15
20
|
get: () => structuredClone(table.get('root')),
|
|
16
|
-
cache,
|
|
21
|
+
cache, klineCache,
|
|
17
22
|
replay(operation) {
|
|
18
23
|
const prior = table.get('root').operations.find(o => o.id === operation.operationId && now() - o.at < DAY)
|
|
19
24
|
if (!prior) return null
|
|
@@ -51,6 +56,10 @@ export async function openState(storageDomain, changed = () => {}, now = Date.no
|
|
|
51
56
|
}
|
|
52
57
|
const job = tail.then(run); tail = job.catch(() => {}); return job
|
|
53
58
|
},
|
|
54
|
-
async close() {
|
|
59
|
+
async close() {
|
|
60
|
+
stopped = true
|
|
61
|
+
await tail
|
|
62
|
+
await domain.close()
|
|
63
|
+
},
|
|
55
64
|
}
|
|
56
65
|
}
|