@mzzsfy/dsh-stock-assistant 0.9.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/CHANGELOG.md +117 -4
- package/README.md +24 -18
- package/package.json +1 -1
- package/src/application.mjs +377 -123
- package/src/budget.mjs +16 -15
- package/src/catalog.mjs +145 -93
- package/src/client.js +1067 -380
- package/src/client.js~RF25ea9e49.TMP +3301 -0
- package/src/collector.mjs +171 -93
- package/src/executor.mjs +212 -60
- package/src/index.js +5 -3
- package/src/kline-cache.mjs +10 -13
- package/src/market-model.mjs +35 -8
- package/src/memory-cache.mjs +5 -1
- package/src/provider-router.mjs +13 -7
- package/src/providers/eastmoney.mjs +128 -57
- package/src/providers/sina.mjs +63 -41
- package/src/providers/tencent.mjs +19 -5
- package/src/providers/tushare.mjs +11 -2
- package/src/providers/us-markets.mjs +4 -0
- package/src/providers/xueqiu.mjs +68 -27
- package/src/recovery.mjs +29 -14
- package/src/routes.mjs +18 -5
- package/src/schemas.mjs +15 -22
- package/src/state.mjs +17 -2
- package/src/trend-cache.mjs +114 -12
- package/src/us-symbols.mjs +30 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +239 -13
package/src/providers/xueqiu.mjs
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
// 雪球公开行情接口适配器:quotes(沪深港美)。
|
|
2
2
|
// 与新浪/东财的差别:同一请求可混装多市场,且额外给出换手率/振幅/市值/总股本。
|
|
3
3
|
// 接口需要 xq_a_token cookie,匿名访问首页即可拿到,本适配器惰性获取并按 TTL 缓存。
|
|
4
|
-
import { normalizeQuote,
|
|
4
|
+
import { normalizeQuote, numberOrNull, StockError } from '../market-model.mjs'
|
|
5
5
|
const ENDPOINT = 'https://stock.xueqiu.com/v5/stock/batch/quote.json'
|
|
6
|
-
const HOME = 'https://xueqiu.com/'
|
|
6
|
+
const HOME = 'https://www.xueqiu.com/'
|
|
7
7
|
const HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' }
|
|
8
|
-
// cookie 有效期远长于一次会话, 缓存到进程内并按 TTL 刷新, 避免每个请求都先访问首页
|
|
9
8
|
const TOKEN_TTL = 30 * 60 * 1000
|
|
10
|
-
|
|
9
|
+
// 出口与其传输生命周期绑定,避免在直连和代理之间混用匿名凭据。
|
|
10
|
+
const tokenByEgress = new WeakMap()
|
|
11
|
+
const tokenRejected = response => response.status === 400 || response.status === 401
|
|
12
|
+
const cancelled = () => new StockError('CANCELLED', '请求已取消', 503)
|
|
11
13
|
// 沪深用大写市场前缀, 港股与美股直接用代码本身(实测 HK00700 返回空, 00700 才有数据)
|
|
12
14
|
const symbolOf = security => (security.exchange === 'XSHG' ? 'SH' : security.exchange === 'XSHE' ? 'SZ' : '') + security.code
|
|
13
15
|
const PROBE_SECURITY = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
|
|
14
|
-
const quote = value => { const n = Number(value); return Number.isFinite(n) ? n.toFixed(2) : null }
|
|
15
16
|
|
|
16
17
|
export const xueqiu = {
|
|
17
18
|
descriptor: { adapterId: 'xueqiu', capabilities: ['quotes'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '雪球公开接口:免凭据(匿名 token),沪深港美行情,可混装多市场,额外提供换手率与市值' },
|
|
@@ -24,20 +25,27 @@ export const xueqiu = {
|
|
|
24
25
|
},
|
|
25
26
|
async quotes(request, ctx) {
|
|
26
27
|
const symbols = new Map(request.securities.map(s => [symbolOf(s), s]))
|
|
28
|
+
const key = ctx.egressKey ?? ctx.fetch
|
|
29
|
+
const requestQuotes = token => ctx.fetch(`${ENDPOINT}?symbol=${[...symbols.keys()].join(',')}`, { headers: { ...HEADERS, Cookie: token.value, Referer: HOME }, signal: ctx.signal, redirect: 'error' })
|
|
27
30
|
let response
|
|
28
31
|
try {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
if (response
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
let token = await tokenOf(ctx, key)
|
|
33
|
+
response = await requestQuotes(token)
|
|
34
|
+
if (tokenRejected(response)) {
|
|
35
|
+
response.body?.cancel().catch(() => {})
|
|
36
|
+
token = await tokenOf(ctx, key, token)
|
|
37
|
+
response = await requestQuotes(token)
|
|
38
|
+
if (tokenRejected(response) && tokenByEgress.get(key)?.token === token) tokenByEgress.delete(key)
|
|
34
39
|
}
|
|
35
40
|
} catch (e) {
|
|
36
|
-
if (ctx.signal.aborted) throw
|
|
41
|
+
if (ctx.signal.aborted) throw cancelled()
|
|
37
42
|
if (e instanceof StockError) throw e
|
|
38
43
|
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
39
44
|
}
|
|
40
|
-
if (!response.ok)
|
|
45
|
+
if (!response.ok) {
|
|
46
|
+
response.body?.cancel().catch(() => {})
|
|
47
|
+
throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
48
|
+
}
|
|
41
49
|
const body = await response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
|
|
42
50
|
const items = body?.data?.items
|
|
43
51
|
if (!Array.isArray(items)) throw new StockError('BAD_PAYLOAD', '来源字段结构异常', 502)
|
|
@@ -50,32 +58,65 @@ export const xueqiu = {
|
|
|
50
58
|
if (seen.has(security.id)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
|
|
51
59
|
seen.add(security.id)
|
|
52
60
|
// 雪球 volume 统一是股, amount 统一是元; 时间戳是毫秒 Unix
|
|
61
|
+
const volume = numberOrNull(row.volume), amount = numberOrNull(row.amount), marketCapital = numberOrNull(row.market_capital), stamp = numberOrNull(row.timestamp)
|
|
53
62
|
result.push(normalizeQuote({
|
|
54
63
|
securityId: security.id, providerInstanceId: request.providerInstanceId, adapterId: 'xueqiu', providerSymbol: row.symbol,
|
|
55
|
-
last:
|
|
56
|
-
volume:
|
|
57
|
-
amount:
|
|
58
|
-
quoteAt:
|
|
64
|
+
last: row.current, previousClose: row.last_close, open: row.open, high: row.high, low: row.low,
|
|
65
|
+
volume: volume === null ? null : String(Math.round(volume)), volumeUnit: 'share',
|
|
66
|
+
amount: amount === null ? null : String(Math.round(amount)), amountUnit: String(row.currency || ''),
|
|
67
|
+
quoteAt: stamp === null ? null : new Date(stamp).toISOString(), timestampKind: 'trade',
|
|
59
68
|
receivedAt: ctx.now(), delayKind: 'unknown', delaySeconds: null, securityState: 'unknown',
|
|
60
|
-
turnoverRate:
|
|
61
|
-
marketCapital:
|
|
69
|
+
turnoverRate: numberOrNull(row.turnover_rate),
|
|
70
|
+
marketCapital: marketCapital === null ? null : Math.round(marketCapital),
|
|
62
71
|
}))
|
|
63
72
|
}
|
|
64
73
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items: result, errors: request.securities.filter(s => !seen.has(s.id)).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
|
|
65
74
|
},
|
|
66
75
|
}
|
|
67
76
|
|
|
68
|
-
async function
|
|
69
|
-
if (
|
|
77
|
+
async function tokenOf(ctx, key, rejected) {
|
|
78
|
+
if (ctx.signal.aborted) throw cancelled()
|
|
79
|
+
const current = tokenByEgress.get(key)
|
|
80
|
+
if (current?.token !== rejected && current?.token?.until > ctx.now()) return current.token
|
|
81
|
+
if (current?.pending) {
|
|
82
|
+
// 等待者可独立取消,不关闭当前出口上共享的首页请求。
|
|
83
|
+
let onAbort
|
|
84
|
+
const aborted = new Promise((_, reject) => { onAbort = () => reject(cancelled()) })
|
|
85
|
+
ctx.signal.addEventListener('abort', onAbort, { once: true })
|
|
86
|
+
try {
|
|
87
|
+
return await Promise.race([current.pending, aborted])
|
|
88
|
+
} catch (error) {
|
|
89
|
+
// 本地配额和生命周期属于发起者,不属于出口。
|
|
90
|
+
if (ctx.signal.aborted || !(error.local || ['CANCELLED', 'RATE_LIMIT', 'BUDGET_UNKNOWN'].includes(error.code))) throw error
|
|
91
|
+
return tokenOf(ctx, key, rejected)
|
|
92
|
+
} finally {
|
|
93
|
+
ctx.signal.removeEventListener('abort', onAbort)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const pending = fetchToken(ctx)
|
|
97
|
+
tokenByEgress.set(key, { pending })
|
|
98
|
+
try {
|
|
99
|
+
const token = await pending
|
|
100
|
+
tokenByEgress.set(key, { token })
|
|
101
|
+
return token
|
|
102
|
+
} catch (error) {
|
|
103
|
+
tokenByEgress.delete(key)
|
|
104
|
+
throw error
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function fetchToken(ctx) {
|
|
70
109
|
let response
|
|
71
|
-
try {
|
|
110
|
+
try {
|
|
111
|
+
response = await ctx.fetch(HOME, { headers: HEADERS, signal: ctx.signal, redirect: 'follow' })
|
|
112
|
+
} catch (error) {
|
|
72
113
|
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
73
|
-
|
|
74
|
-
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
114
|
+
throw error
|
|
75
115
|
}
|
|
76
|
-
|
|
77
|
-
|
|
116
|
+
response.body?.cancel().catch(() => {})
|
|
117
|
+
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
118
|
+
const cookies = response.headers?.getSetCookie?.() ?? []
|
|
119
|
+
const value = cookies.map(cookie => cookie.split(';', 1)[0].trim()).find(cookie => /^xq_a_token=[^\s;]+$/.test(cookie))
|
|
78
120
|
if (!value) throw new StockError('BAD_PAYLOAD', '来源未返回访问令牌', 502)
|
|
79
|
-
|
|
80
|
-
return value
|
|
121
|
+
return { value, until: ctx.now() + TOKEN_TTL }
|
|
81
122
|
}
|
package/src/recovery.mjs
CHANGED
|
@@ -1,23 +1,34 @@
|
|
|
1
1
|
// 降级后回头试上级: 后台定时跑, 不占用户请求时间, 也不用业务请求去猜上游好坏。
|
|
2
2
|
// 每个适配器自己实现探针(probe), 这里只负责按路由顺序点名、把汇报交给路由器。
|
|
3
|
+
import { StockError } from './market-model.mjs'
|
|
4
|
+
|
|
3
5
|
export const RECOVERY_RETRY_MS = 20 * 1000
|
|
4
|
-
export function createRecovery({ getConfig, router, executor }) {
|
|
5
|
-
return async function probeRecovery() {
|
|
6
|
-
//
|
|
7
|
-
if (!executor.idle()) return
|
|
8
|
-
|
|
6
|
+
export function createRecovery({ getConfig, router, executor, canProbe = () => true, onError = () => {}, deadlineOf = () => undefined }) {
|
|
7
|
+
return async function probeRecovery(signal) {
|
|
8
|
+
// 用户请求在跑时整轮跳过。
|
|
9
|
+
if (signal?.aborted || !executor.idle()) return
|
|
10
|
+
const { routes, routingRevision } = getConfig()
|
|
11
|
+
for (const route of routes) {
|
|
9
12
|
if (route.failoverMode !== 'network') continue
|
|
10
13
|
const epoch = router.selections()[route.id]?.routeEpoch
|
|
11
14
|
if (epoch === undefined) continue
|
|
12
15
|
for (const id of router.recoveryCandidates(route.id)) {
|
|
16
|
+
if (signal?.aborted) return
|
|
13
17
|
const instance = getConfig().providers.find(p => p.id === id && p.enabled !== false && p.budget?.requestsPerMinute !== null)
|
|
14
|
-
if (!instance) continue
|
|
15
|
-
let ready = false
|
|
18
|
+
if (!instance || !canProbe(route, instance, routingRevision)) continue
|
|
19
|
+
let ready = false, failure
|
|
20
|
+
const current = () => getConfig().routingRevision === routingRevision && router.selections()[route.id]?.routeEpoch === epoch
|
|
16
21
|
try {
|
|
17
|
-
const result = await executor.run(instance, route.capability, { market: route.market, instrument: route.instrument }, { probe: true
|
|
18
|
-
|
|
22
|
+
const result = await executor.run(instance, route.capability, { market: route.market, instrument: route.instrument }, { probe: true, signal, deadline: deadlineOf(), beforeDispatch: () => {
|
|
23
|
+
if (!current() || !canProbe(route, instance, routingRevision)) throw new StockError('CANCELLED', '回探目标已变化', 503, { local: true })
|
|
24
|
+
} })
|
|
25
|
+
// 探针必须由同名能力产出。
|
|
19
26
|
ready = result?.status === 'ready' && result.capability === route.capability
|
|
20
|
-
} catch {}
|
|
27
|
+
} catch (e) { failure = e }
|
|
28
|
+
if (signal?.aborted || getConfig().routingRevision !== routingRevision) return
|
|
29
|
+
if (!current()) break
|
|
30
|
+
if (failure?.local || failure?.code === 'CANCELLED') continue
|
|
31
|
+
if (failure) onError(route, instance, failure, routingRevision)
|
|
21
32
|
try { router.recordProbe(route.id, id, ready, epoch) } catch { break }
|
|
22
33
|
if (ready) break
|
|
23
34
|
}
|
|
@@ -29,20 +40,24 @@ export function createRecovery({ getConfig, router, executor }) {
|
|
|
29
40
|
// 上一轮没跑完就跳过这一轮: 探测要逐个实例打上游, 一轮可能比周期还长。
|
|
30
41
|
// 用户请求在跑时短重试, 不占首屏的队列
|
|
31
42
|
export function createRecoveryLoop({ probe, timers, interval, canRun = () => true }) {
|
|
32
|
-
let timer = null, retry = null, running = false,
|
|
43
|
+
let timer = null, retry = null, running = false, stopped = false, controller = null, inflight = Promise.resolve()
|
|
33
44
|
const run = () => {
|
|
34
|
-
if (stopped ||
|
|
45
|
+
if (stopped || controller) return
|
|
35
46
|
if (!canRun()) {
|
|
36
47
|
if (retry) return
|
|
37
48
|
retry = timers.setTimeout?.(() => { retry = null; run() }, RECOVERY_RETRY_MS) ?? null
|
|
38
49
|
retry?.unref?.()
|
|
39
50
|
return
|
|
40
51
|
}
|
|
41
|
-
|
|
42
|
-
inflight = Promise.resolve().then(probe).catch(() => {}).finally(() => {
|
|
52
|
+
const attempt = controller = new AbortController()
|
|
53
|
+
inflight = Promise.resolve().then(() => probe(attempt.signal)).catch(() => {}).finally(() => {
|
|
54
|
+
if (controller === attempt) controller = null
|
|
55
|
+
if (!stopped && attempt.signal.aborted) run()
|
|
56
|
+
})
|
|
43
57
|
}
|
|
44
58
|
const stop = () => {
|
|
45
59
|
stopped = true
|
|
60
|
+
controller?.abort()
|
|
46
61
|
if (timer) timers.clearInterval?.(timer)
|
|
47
62
|
if (retry) timers.clearTimeout?.(retry)
|
|
48
63
|
timer = null; retry = null; running = false
|
package/src/routes.mjs
CHANGED
|
@@ -2,7 +2,13 @@ import { z } from 'zod'
|
|
|
2
2
|
import { StockError, fail } from './market-model.mjs'
|
|
3
3
|
import { withRouteGate } from './route-gate.mjs'
|
|
4
4
|
const PREFIX = '/api/stock-assistant'
|
|
5
|
+
// catalog-sync 分页抓全量目录: 单独预算; 探针与其余路由都由应用层推导(见 application.providerCheckTimeoutMs / routeTimeoutMs),
|
|
6
|
+
// 应用层给不出时退回这里的兜底值
|
|
7
|
+
const PROVIDER_CHECK_TIMEOUT_MS = 60 * 1000, CATALOG_SYNC_TIMEOUT_MS = 120 * 1000, DEFAULT_ROUTE_TIMEOUT_MS = 10 * 1000
|
|
5
8
|
const operationSchema = z.object({ operationId: z.uuid(), expectedRevision: z.number().int().nonnegative() })
|
|
9
|
+
const expectedServerEpoch = z.uuid().optional()
|
|
10
|
+
const configurationOperationSchema = operationSchema.extend({ expectedServerEpoch })
|
|
11
|
+
const credentialVersionsSchema = z.object({ expectedServerEpoch, expectedRoutingRevision: z.number().int().nonnegative().optional() })
|
|
6
12
|
async function body(req) {
|
|
7
13
|
const chunks = []; let size = 0
|
|
8
14
|
for await (const chunk of req) {
|
|
@@ -21,13 +27,13 @@ export function registerRoutes(webServer, app, ctx) {
|
|
|
21
27
|
const handlers = {
|
|
22
28
|
snapshot: ['GET', () => app.snapshot()],
|
|
23
29
|
search: ['GET', async (input, signal) => await app.search(input.q || '', input.phase === 'remote' ? 'remote' : 'local', signal)],
|
|
24
|
-
browse: ['GET', input => app.browse(input)],
|
|
30
|
+
browse: ['GET', (input, signal) => app.browse(input, signal)],
|
|
25
31
|
watchlist: ['POST', input => { operationSchema.parse(input); return app.watchlist(input) }],
|
|
26
32
|
preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
|
|
27
|
-
configuration: ['POST', input => {
|
|
33
|
+
configuration: ['POST', input => { configurationOperationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
|
|
28
34
|
'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
|
|
29
|
-
credential: ['POST', input => app.credential(input)],
|
|
30
|
-
'catalog-sync': ['POST', input => app.sync(input)],
|
|
35
|
+
credential: ['POST', input => { credentialVersionsSchema.parse(input); return app.credential(input) }],
|
|
36
|
+
'catalog-sync': ['POST', (input, signal) => app.sync(input, signal)],
|
|
31
37
|
'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
|
|
32
38
|
refresh: ['POST', (input, signal) => app.refresh(input, signal)],
|
|
33
39
|
kline: ['GET', (input, signal) => app.kline(input, signal)],
|
|
@@ -44,11 +50,15 @@ export function registerRoutes(webServer, app, ctx) {
|
|
|
44
50
|
const controller = new AbortController(); controllers.add(controller)
|
|
45
51
|
const onClose = () => { if (!res.writableEnded) controller.abort() }
|
|
46
52
|
res.on('close', onClose)
|
|
47
|
-
const timeout = name === 'provider-check' ? 60 * 1000 : name === 'catalog-sync' ? 120 * 1000 : 10 * 1000
|
|
48
53
|
let timer
|
|
49
54
|
try {
|
|
50
55
|
const input = method === 'GET' ? Object.fromEntries(new URL(req.url, 'http://local').searchParams) : await body(req)
|
|
51
56
|
if (method === 'POST' && (input === null || typeof input !== 'object' || Array.isArray(input))) fail('INVALID_REQUEST', '请求内容必须为JSON对象')
|
|
57
|
+
// 应用层没给或给了非数值时退回默认预算: 传进 setTimeout 的必须是有限正数。
|
|
58
|
+
// 取值放进 try: 这里抛错也必须有响应写出, 否则请求悬挂到客户端超时。
|
|
59
|
+
// 探针的预算要按待测目标数算, 所以必须等输入解析完再取
|
|
60
|
+
const derived = name === 'provider-check' ? app.providerCheckTimeoutMs?.(input) : app.routeTimeoutMs?.()
|
|
61
|
+
const timeout = name === 'catalog-sync' ? CATALOG_SYNC_TIMEOUT_MS : Number.isFinite(derived) && derived > 0 ? derived : name === 'provider-check' ? PROVIDER_CHECK_TIMEOUT_MS : DEFAULT_ROUTE_TIMEOUT_MS
|
|
52
62
|
const data = await Promise.race([
|
|
53
63
|
Promise.resolve(action(input, controller.signal)),
|
|
54
64
|
// 超时错误随 abort reason 一起下发: 即使 abort 监听先被同步派发, 也拿到 TIMEOUT 而不是 CANCELLED
|
|
@@ -58,6 +68,9 @@ export function registerRoutes(webServer, app, ctx) {
|
|
|
58
68
|
json(res, 200, { ok: true, data })
|
|
59
69
|
} catch (e) {
|
|
60
70
|
const error = e instanceof StockError ? e : new StockError('INVALID_REQUEST', e instanceof z.ZodError ? '请求参数格式错误' : '股票工具请求失败', e instanceof z.ZodError ? 400 : 500)
|
|
71
|
+
// 服务端失败必须有痕迹: 只记路由与错误码, 不记文案(文案可能带上游地址与凭据形态)。
|
|
72
|
+
// 客户端关页/切详情触发的取消不是故障, 记成 5xx 只会让日志看起来一直在报错
|
|
73
|
+
if (error.status >= 500 && error.code !== 'CANCELLED') ctx?.logger?.warn?.(`股票助手请求失败: ${name} ${error.code} (${error.status})`)
|
|
61
74
|
json(res, error.status, { ok: false, error: { code: error.code, message: error.message, retryable: error.retryable, retryAfterMs: error.retryAfterMs }, ...(error.details === undefined ? {} : { details: error.details }), ...(error.revision === undefined ? {} : { revision: error.revision }), ...(e.snapshot ? { snapshot: e.snapshot } : {}) })
|
|
62
75
|
} finally { clearTimeout(timer); controllers.delete(controller); res.removeListener('close', onClose) }
|
|
63
76
|
}
|
package/src/schemas.mjs
CHANGED
|
@@ -58,7 +58,7 @@ export const klineQuerySchema = z.strictObject({
|
|
|
58
58
|
securityId: z.string().regex(/^[\w]+:equity:[\w.]{1,15}$/),
|
|
59
59
|
period: z.enum(['trend', '1d', '1w', '1M']),
|
|
60
60
|
limit: z.coerce.number().int().min(20).max(1000).default(250),
|
|
61
|
-
//
|
|
61
|
+
// 日、周、月 K 线可强制跳过缓存;分时仍遵守共享刷新窗口。
|
|
62
62
|
force: z.enum(['0', '1']).optional(),
|
|
63
63
|
})
|
|
64
64
|
// 手动刷新的证券参数: 自选 id 字符串或客户端持有的完整身份(浏览/搜索 peek)。形状在这里定死,
|
|
@@ -69,7 +69,11 @@ const refreshSecuritySchema = z.union([
|
|
|
69
69
|
return parts.length === 3 && parts[1] === 'equity' && MARKET_META[parts[0]] !== undefined && /^[\w.]{1,15}$/.test(parts[2])
|
|
70
70
|
}, '证券标识无效'),
|
|
71
71
|
z.object({ id: z.string().min(1).max(64), exchange: marketSchema, code: z.string().min(1).max(20), officialName: z.string().min(1).max(100).optional() })
|
|
72
|
-
|
|
72
|
+
// 代码形状必须与市场一致: 否则 makeSecurity 抛普通 Error, 路由层会把它折叠成 500 而不是 400
|
|
73
|
+
.superRefine((value, ctx) => {
|
|
74
|
+
if (value.id !== `${value.exchange}:equity:${value.code}`) ctx.addIssue({ code: 'custom', message: '证券身份不一致' })
|
|
75
|
+
if (!MARKET_META[value.exchange]?.codePattern.test(value.code)) ctx.addIssue({ code: 'custom', message: '证券代码与市场不符' })
|
|
76
|
+
}),
|
|
73
77
|
])
|
|
74
78
|
export const refreshSecuritiesSchema = z.array(refreshSecuritySchema).max(100)
|
|
75
79
|
// 路由上限: 八市场 × 全部能力, 全开也要装得下
|
|
@@ -117,7 +121,7 @@ export function parseConfiguration(value) {
|
|
|
117
121
|
}
|
|
118
122
|
// 分时路由的迁移版本: 存量库只补一次(补缺失路由 + 给单源分时登记备源), 用户随后删掉分时路由不该在下次启动被复活
|
|
119
123
|
export const TREND_ROUTE_MIGRATION = 2
|
|
120
|
-
export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), routeMigration: z.number().int().nonnegative().default(0), 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()
|
|
124
|
+
export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), routeMigration: z.number().int().nonnegative().default(0), 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() })).max(256) }).superRefine((control, ctx) => {
|
|
121
125
|
const w = control.watchlist
|
|
122
126
|
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: '自选序列与证券不一致' })
|
|
123
127
|
let unpinned = false
|
|
@@ -171,25 +175,16 @@ const normalizeCredentialField = root => {
|
|
|
171
175
|
const providers = root.providers.map(p => { const next = normalizeProvider(p); if (next !== p) changed = true; return next })
|
|
172
176
|
return changed ? { ...root, providers } : root
|
|
173
177
|
}
|
|
174
|
-
//
|
|
175
|
-
//
|
|
178
|
+
// 幂等台账曾经存过一份完整的配置副本(含代理/端点明文): 现在只留幂等键与结果,
|
|
179
|
+
// 读入时把存量条目里的 payload 丢掉。丢弃必须发生在归一化里, 否则明文会留在盘上直到下一次无关写入。
|
|
176
180
|
const normalizeOperations = root => {
|
|
177
181
|
if (!Array.isArray(root?.operations)) return root
|
|
178
182
|
let changed = false
|
|
179
183
|
const operations = root.operations.map(operation => {
|
|
180
|
-
|
|
181
|
-
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return operation
|
|
182
|
-
let next = payload
|
|
183
|
-
if (Array.isArray(payload.providers)) {
|
|
184
|
-
let providersChanged = false
|
|
185
|
-
const providers = payload.providers.map(p => { const candidate = normalizeProvider(p); if (candidate !== p) providersChanged = true; return candidate })
|
|
186
|
-
if (providersChanged) next = { ...next, providers }
|
|
187
|
-
}
|
|
188
|
-
const endpoints = normalizeEndpointMap(next.endpoints)
|
|
189
|
-
if (endpoints !== next.endpoints) next = { ...next, endpoints }
|
|
190
|
-
if (next === payload) return operation
|
|
184
|
+
if (!operation || typeof operation !== 'object' || !('payload' in operation)) return operation
|
|
191
185
|
changed = true
|
|
192
|
-
|
|
186
|
+
const { payload, ...rest } = operation
|
|
187
|
+
return rest
|
|
193
188
|
})
|
|
194
189
|
return changed ? { ...root, operations } : root
|
|
195
190
|
}
|
|
@@ -229,7 +224,7 @@ export const storedControlSchema = z.preprocess(normalizeStoredControl, controlS
|
|
|
229
224
|
// 把它们塞进同一个文件曾把文件撑到 3.3 MB, 每次改自选都要整体重写, 写坏一次全没。
|
|
230
225
|
// 旧文件同名同版本, 打开时只取声明过的 control 表, 缓存表被忽略, 下次写入自然缩到十几 KB。
|
|
231
226
|
export const domainSpec = { name: 'stock_assistant', version: 1, layout: 'single', tables: { control: { valueSchema: storedControlSchema } } }
|
|
232
|
-
//
|
|
227
|
+
// 推荐配置由四个免凭据源组成,沪深目录走新浪,其他能力以东财为主。
|
|
233
228
|
export const defaultConfig = () => {
|
|
234
229
|
const budget = (requestsPerMinute, capabilityLimits = {}) => ({ requestsPerMinute, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits })
|
|
235
230
|
const providers = [
|
|
@@ -241,14 +236,12 @@ export const defaultConfig = () => {
|
|
|
241
236
|
]
|
|
242
237
|
// 备用源只在探针可验证的组合上声明: 腾讯美股K线需先由搜索建立代码映射, 探针期必然不可用
|
|
243
238
|
const klineBackup = new Set(['XSHG', 'XSHE', 'XHKG'])
|
|
244
|
-
|
|
245
|
-
const catalogCovered = new Set(['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'])
|
|
239
|
+
const sinaCatalogMarkets = new Set(['XSHG', 'XSHE'])
|
|
246
240
|
// 报价备源按市场派: 沪深港走新浪(免cookie、单位已是股), 美股走雪球(时间戳是UTC毫秒, 与东财同口径)
|
|
247
241
|
const quoteBackupOf = market => (market === 'XNAS' || market === 'XNYS' ? 'xq-backup' : ['XSHG', 'XSHE', 'XHKG'].includes(market) ? 'sn-backup' : null)
|
|
248
242
|
const route = (market, capability, primary, fallback = null) => ({ id: `${market.toLowerCase()}-${capability}`, capability, market, instrument: 'equity', primaryInstanceId: primary, fallbackInstanceIds: fallback ? [fallback] : [], failoverMode: fallback ? 'network' : 'off', maxDelaySeconds: null, acceptUnknownDelay: true })
|
|
249
243
|
const routes = ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'].flatMap(market => [
|
|
250
|
-
|
|
251
|
-
...(catalogCovered.has(market) ? [route(market, 'catalog', 'em-default')] : []),
|
|
244
|
+
route(market, 'catalog', sinaCatalogMarkets.has(market) ? 'sn-backup' : 'em-default'),
|
|
252
245
|
route(market, 'search', 'em-default'),
|
|
253
246
|
route(market, 'quotes', 'em-default', quoteBackupOf(market)),
|
|
254
247
|
route(market, 'kline', 'em-default', klineBackup.has(market) ? 'tx-backup' : null),
|
package/src/state.mjs
CHANGED
|
@@ -20,8 +20,23 @@ export async function openState(storageDomain, changed = () => {}, now = Date.no
|
|
|
20
20
|
} catch (e) { await Promise.allSettled([domain.close()]); throw e }
|
|
21
21
|
const cache = createMemoryCache({ limit: CATALOG_CACHE_LIMIT }), klineCache = createMemoryCache({ limit: KLINE_CACHE_LIMIT }), trendCache = createMemoryCache({ limit: TREND_CACHE_LIMIT })
|
|
22
22
|
let tail = Promise.resolve(), stopped = false
|
|
23
|
+
// 读侧按版本记忆化: 控制记录只在 mutate 里整体替换, 同一版本读出来的内容恒定,
|
|
24
|
+
// 每次深拷贝会把"每标的取一次配置"的热路径变成每秒数毫秒的开销。
|
|
25
|
+
// 返回的对象深冻结: 读侧原地改会在严格模式下直接抛错, 而不是悄悄污染共享快照。
|
|
26
|
+
const deepFreeze = value => {
|
|
27
|
+
if (value && typeof value === 'object') { for (const child of Object.values(value)) deepFreeze(child); Object.freeze(value) }
|
|
28
|
+
return value
|
|
29
|
+
}
|
|
30
|
+
// 缓存键同时看两个版本: 路由换代也会改变读到的语义, 只认 revision 会漏掉只改路由版本的写入
|
|
31
|
+
const versionOf = root => `${root.revision}:${root.routingRevision}`
|
|
32
|
+
let snapshot = null, snapshotVersion = ''
|
|
33
|
+
const current = () => {
|
|
34
|
+
const root = table.get('root'), version = versionOf(root)
|
|
35
|
+
if (version !== snapshotVersion) { snapshot = deepFreeze(structuredClone(root)); snapshotVersion = version }
|
|
36
|
+
return snapshot
|
|
37
|
+
}
|
|
23
38
|
return {
|
|
24
|
-
get: () =>
|
|
39
|
+
get: () => current(),
|
|
25
40
|
cache, klineCache, trendCache,
|
|
26
41
|
replay(operation) {
|
|
27
42
|
const prior = table.get('root').operations.find(o => o.id === operation.operationId && now() - o.at < DAY)
|
|
@@ -44,7 +59,7 @@ export async function openState(storageDomain, changed = () => {}, now = Date.no
|
|
|
44
59
|
next.revision = current.revision + 1
|
|
45
60
|
const result = { revision: next.revision, unchanged: false, ...(next.operationResult || {}) }
|
|
46
61
|
delete next.operationResult
|
|
47
|
-
next.operations = [...current.operations.filter(o => now() - o.at < DAY), { id: operation.operationId, hash, at: now(), result, action: operation.action
|
|
62
|
+
next.operations = [...current.operations.filter(o => now() - o.at < DAY), { id: operation.operationId, hash, at: now(), result, action: operation.action }].slice(-256)
|
|
48
63
|
try { controlSchema.parse(next) } catch (e) { fail('INVARIANT_VIOLATION', '写入结果违反内部不变式', 500, { cause: e }) }
|
|
49
64
|
try {
|
|
50
65
|
await table.update('root', stored => {
|
package/src/trend-cache.mjs
CHANGED
|
@@ -1,26 +1,128 @@
|
|
|
1
|
-
import { marketDate } from './market-model.mjs'
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
const
|
|
6
|
-
|
|
1
|
+
import { marketDate, StockError } from './market-model.mjs'
|
|
2
|
+
// 数据日期取最后一根分时的时间,避免把盘前收到的上个交易日数据当成当天数据。
|
|
3
|
+
const windowKeyOf = ({ market, code, limit, routeKey = '' }) => `trend:${market}:${code}:${limit}:${routeKey}`
|
|
4
|
+
// 离线缓存不按路由代次拆分: 当天真实分时换源后仍是同一只股票的有效兜底
|
|
5
|
+
const cacheKeyOf = ({ market, code, limit }) => `trend:${market}:${code}:${limit}`
|
|
6
|
+
const TREND_INTERVAL_MS = 60 * 1000
|
|
7
|
+
const MAX_WINDOWS = 1024
|
|
8
|
+
const cancelled = () => new StockError('CANCELLED', '分时请求已取消', 503)
|
|
9
|
+
const cooling = retryAfterMs => new StockError('RATE_LIMIT', '分时尚未到刷新时间', 429, { retryable: true, retryAfterMs })
|
|
10
|
+
export function trendSessionDate(market, payload) {
|
|
11
|
+
const at = payload?.candles?.at(-1)?.at
|
|
7
12
|
return Number.isFinite(at) ? marketDate(market, at * 1000) : null
|
|
8
13
|
}
|
|
9
14
|
export function createTrendCache({ table, now = Date.now }) {
|
|
15
|
+
const flights = new Map(), windows = new Map(), sourceCooldowns = new Map()
|
|
16
|
+
let cooldownRevision = null
|
|
17
|
+
const cooldownsFor = routingRevision => {
|
|
18
|
+
if (cooldownRevision !== routingRevision) { sourceCooldowns.clear(); cooldownRevision = routingRevision }
|
|
19
|
+
return sourceCooldowns
|
|
20
|
+
}
|
|
21
|
+
const wait = async (flight, signal) => {
|
|
22
|
+
flight.waiters++
|
|
23
|
+
const sharedSignal = flight.controller.signal
|
|
24
|
+
const waitingSignal = signal ? AbortSignal.any([signal, sharedSignal]) : sharedSignal
|
|
25
|
+
let onAbort
|
|
26
|
+
try {
|
|
27
|
+
return await Promise.race([flight.promise, new Promise((_, reject) => {
|
|
28
|
+
onAbort = () => reject(cancelled())
|
|
29
|
+
waitingSignal.addEventListener('abort', onAbort, { once: true })
|
|
30
|
+
if (waitingSignal.aborted) onAbort()
|
|
31
|
+
})])
|
|
32
|
+
} finally {
|
|
33
|
+
waitingSignal.removeEventListener('abort', onAbort)
|
|
34
|
+
if (--flight.waiters === 0 && !flight.settled) flight.controller.abort(cancelled())
|
|
35
|
+
}
|
|
36
|
+
}
|
|
10
37
|
return {
|
|
38
|
+
sourceWait(routingRevision, instanceId) {
|
|
39
|
+
const cooldowns = cooldownsFor(routingRevision)
|
|
40
|
+
const remaining = (cooldowns.get(instanceId) ?? 0) - now()
|
|
41
|
+
if (remaining <= 0) cooldowns.delete(instanceId)
|
|
42
|
+
return Math.max(0, remaining)
|
|
43
|
+
},
|
|
44
|
+
coolSource(routingRevision, instanceId, delay) {
|
|
45
|
+
const cooldowns = cooldownsFor(routingRevision)
|
|
46
|
+
const until = now() + (delay > 0 ? delay : TREND_INTERVAL_MS)
|
|
47
|
+
cooldowns.set(instanceId, Math.max(cooldowns.get(instanceId) ?? 0, until))
|
|
48
|
+
},
|
|
49
|
+
async fetch(key, signal, fetchTrend) {
|
|
50
|
+
if (signal?.aborted) throw cancelled()
|
|
51
|
+
const day = marketDate(key.market, now())
|
|
52
|
+
let id = `${windowKeyOf(key)}:${day}`
|
|
53
|
+
const currentFlight = flights.get(id)
|
|
54
|
+
if (currentFlight && !currentFlight.controller.signal.aborted) return wait(currentFlight, signal)
|
|
55
|
+
const at = now(), previous = windows.get(id)
|
|
56
|
+
if (previous?.nextAt > at) {
|
|
57
|
+
if (previous.error) {
|
|
58
|
+
if (previous.error.code === 'CANCELLED') throw cooling(previous.nextAt - at)
|
|
59
|
+
const { code, message, status, retryable, routeEpoch } = previous.error
|
|
60
|
+
throw new StockError(code, message, status, { retryable, routeEpoch, retryAfterMs: previous.nextAt - at })
|
|
61
|
+
}
|
|
62
|
+
if (previous.result) return previous.result
|
|
63
|
+
throw cooling(previous.nextAt - at)
|
|
64
|
+
}
|
|
65
|
+
for (const [windowId, window] of windows) {
|
|
66
|
+
if (window.nextAt <= at && !flights.has(windowId)) windows.delete(windowId)
|
|
67
|
+
}
|
|
68
|
+
if (windows.size >= MAX_WINDOWS && !previous) throw cooling(TREND_INTERVAL_MS)
|
|
69
|
+
const window = { nextAt: at + TREND_INTERVAL_MS }, controller = new AbortController()
|
|
70
|
+
windows.set(id, window)
|
|
71
|
+
const flight = { controller, waiters: 0, settled: false, promise: null }
|
|
72
|
+
flights.set(id, flight)
|
|
73
|
+
// 本轮触发切源时,备源已经由同一轮尝试。把在飞与冷却移到新选择,避免换代马上重复回源。
|
|
74
|
+
const moveTo = nextKey => {
|
|
75
|
+
if (flights.get(id) !== flight) return
|
|
76
|
+
const nextId = `${windowKeyOf(nextKey)}:${day}`
|
|
77
|
+
// 目标键已有另一轮在飞或冷却: 让那一轮保持原样, 本轮的窗口留在旧键
|
|
78
|
+
if (flights.has(nextId) || windows.has(nextId)) return
|
|
79
|
+
flights.delete(id)
|
|
80
|
+
windows.delete(id)
|
|
81
|
+
id = nextId
|
|
82
|
+
flights.set(id, flight)
|
|
83
|
+
windows.set(id, window)
|
|
84
|
+
}
|
|
85
|
+
flight.promise = Promise.resolve().then(async () => {
|
|
86
|
+
try {
|
|
87
|
+
if (controller.signal.aborted) throw cancelled()
|
|
88
|
+
const result = await fetchTrend(controller.signal, moveTo)
|
|
89
|
+
if (controller.signal.aborted) throw cancelled()
|
|
90
|
+
// 空响应只占刷新窗口。非空结果(含盘前上一交易日)可在同一窗口内复用;
|
|
91
|
+
// 只有属于当天的完整真分时才写离线表。
|
|
92
|
+
if (!result.candles?.length || (!result.offline && result.complete !== false)) window.result = result
|
|
93
|
+
return result
|
|
94
|
+
} catch (error) {
|
|
95
|
+
window.error = error
|
|
96
|
+
if (error.retryAfterMs > 0) window.nextAt = Math.max(window.nextAt, now() + error.retryAfterMs)
|
|
97
|
+
throw error
|
|
98
|
+
} finally {
|
|
99
|
+
// 执行器排队和同轮补救也耗时,从整轮收尾算下一次刷新时间。
|
|
100
|
+
window.nextAt = Math.max(window.nextAt, now() + TREND_INTERVAL_MS)
|
|
101
|
+
flight.settled = true
|
|
102
|
+
if (flights.get(id) === flight) flights.delete(id)
|
|
103
|
+
}
|
|
104
|
+
})
|
|
105
|
+
return wait(flight, signal)
|
|
106
|
+
},
|
|
107
|
+
dispose() {
|
|
108
|
+
for (const flight of flights.values()) flight.controller.abort(cancelled())
|
|
109
|
+
flights.clear()
|
|
110
|
+
windows.clear()
|
|
111
|
+
sourceCooldowns.clear()
|
|
112
|
+
},
|
|
11
113
|
async get(key) {
|
|
12
|
-
const raw =
|
|
13
|
-
//
|
|
114
|
+
const id = cacheKeyOf(key), raw = table.get(id)
|
|
115
|
+
// 对内存表连续检查和删除,避免在两步间清掉后来写入的当日条目。
|
|
14
116
|
const stale = !raw || raw.kind !== 'trend' || !raw.payload?.candles?.length || raw.sessionDate !== marketDate(key.market, now())
|
|
15
117
|
if (!stale) return raw
|
|
16
|
-
if (raw) await table.delete(
|
|
118
|
+
if (raw) await table.delete(id).catch(() => {})
|
|
17
119
|
return null
|
|
18
120
|
},
|
|
19
121
|
// 空结果(上游成功但没数据)和兜底结果都不写: 缓存只存"完整的一次真分时"
|
|
20
122
|
async put(key, result) {
|
|
21
|
-
const sessionDate =
|
|
22
|
-
if (!sessionDate || result.complete === false || result.offline) return
|
|
23
|
-
await table.put(
|
|
123
|
+
const sessionDate = trendSessionDate(key.market, result)
|
|
124
|
+
if (!sessionDate || result.complete === false || result.offline || sessionDate !== marketDate(key.market, now())) return
|
|
125
|
+
await table.put(cacheKeyOf(key), { kind: 'trend', sessionDate, cachedAt: now(), payload: result }).catch(() => {})
|
|
24
126
|
},
|
|
25
127
|
}
|
|
26
128
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// 美股代码 → 交易所标识(mktNum/JYS)的映射: 上游只在部分接口给出, 下游拼 secid 与后缀时要用。
|
|
2
|
+
// 写入方是适配器(ctx.usSymbols), 没有自然的回收点, 所以上限与过期都由容器自己保证。
|
|
3
|
+
// 必须保持 Map 接口: 适配器只用 get/set, 测试里大量注入裸 Map。
|
|
4
|
+
export const US_SYMBOL_LIMIT = 500
|
|
5
|
+
export const US_SYMBOL_TTL = 24 * 60 * 60 * 1000
|
|
6
|
+
|
|
7
|
+
class UsSymbols extends Map {
|
|
8
|
+
constructor({ now, limit, ttl }) {
|
|
9
|
+
super()
|
|
10
|
+
this.now = now
|
|
11
|
+
this.limit = limit
|
|
12
|
+
this.ttl = ttl
|
|
13
|
+
}
|
|
14
|
+
get(key) {
|
|
15
|
+
const entry = super.get(key)
|
|
16
|
+
if (entry === undefined) return undefined
|
|
17
|
+
// 过期的映射等于没有: 留着只会让拼错 secid 的请求打到一个早就换过的市场
|
|
18
|
+
if (this.now() - entry.at > this.ttl) { this.delete(key); return undefined }
|
|
19
|
+
return entry
|
|
20
|
+
}
|
|
21
|
+
// 写入即移到尾部: Map 的迭代序就是淘汰序, 不重排会让最活跃的映射停在头部先被淘汰
|
|
22
|
+
set(key, value) {
|
|
23
|
+
this.delete(key)
|
|
24
|
+
super.set(key, value)
|
|
25
|
+
while (this.size > this.limit) this.delete(this.keys().next().value)
|
|
26
|
+
return this
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const createUsSymbols = ({ now = Date.now, limit = US_SYMBOL_LIMIT, ttl = US_SYMBOL_TTL } = {}) => new UsSymbols({ now, limit, ttl })
|