@mzzsfy/dsh-stock-assistant 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +447 -0
- package/README.md +23 -19
- package/package.json +9 -6
- package/src/application.mjs +400 -266
- package/src/catalog.mjs +193 -168
- package/src/client.js +2642 -2358
- package/src/collector.mjs +265 -171
- package/src/executor.mjs +148 -113
- package/src/index.js +6 -2
- package/src/kline-cache.mjs +6 -7
- package/src/market-model.mjs +88 -16
- package/src/provider-registry.mjs +5 -1
- package/src/provider-router.mjs +75 -9
- package/src/providers/eastmoney.mjs +26 -54
- package/src/providers/sina.mjs +3 -1
- package/src/providers/tencent.mjs +51 -5
- package/src/recovery.mjs +64 -0
- package/src/route-gate.mjs +85 -29
- package/src/routes.mjs +68 -68
- package/src/schemas.mjs +126 -19
- package/src/state.mjs +9 -5
- package/src/ticks.mjs +45 -0
- package/src/trend-cache.mjs +26 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +211 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// 东财公开行情接口适配器:quotes/catalog/search/kline。非官方端点,无SLA;延迟未知,f124为来源秒级时间戳。
|
|
2
|
-
import { normalizeQuote, makeSecurity, securityId, StockError, MARKET_META, sharesFromLots } from '../market-model.mjs'
|
|
2
|
+
import { normalizeQuote, makeSecurity, securityId, StockError, MARKET_META, sharesFromLots, zonedUnixSeconds } from '../market-model.mjs'
|
|
3
3
|
// 官方默认端点表(key 供 instance.endpoints 覆盖, 反代/镜像场景由 ctx.endpoints 提供同名 key)
|
|
4
4
|
const DEFAULT_ENDPOINTS = {
|
|
5
5
|
quotes: 'https://push2.eastmoney.com/api/qt/ulist.np/get',
|
|
@@ -47,7 +47,7 @@ async function getJson(ctx, url) {
|
|
|
47
47
|
return response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
|
|
48
48
|
}
|
|
49
49
|
export const eastmoney = {
|
|
50
|
-
descriptor: { adapterId: 'eastmoney', capabilities: ['quotes', 'catalog', 'search', 'kline'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '东方财富公开接口:免凭据,八市场目录,行情/K
|
|
50
|
+
descriptor: { adapterId: 'eastmoney', capabilities: ['quotes', 'catalog', 'search', 'kline', 'trend'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS', 'XJPX', 'XKRX', 'XLON'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '东方财富公开接口:免凭据,八市场目录,行情/K线/分时/搜索,非官方无SLA', endpointKeys: [{ key: 'quotes', label: '行情批量' }, { key: 'list', label: '证券目录' }, { key: 'search', label: '搜索联想' }, { key: 'kline', label: 'K线历史' }, { key: 'trend', label: '分时' }] },
|
|
51
51
|
async probe(request, ctx) {
|
|
52
52
|
if (request.capability === 'catalog' || request.capability === 'search') {
|
|
53
53
|
// 探针词按市场用代表证券代码(茅台/平安只对沪深有效, 其他市场返回 0 项会误判 denied)。
|
|
@@ -55,12 +55,16 @@ export const eastmoney = {
|
|
|
55
55
|
if (!result.items.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
56
56
|
return { status: 'ready', capability: request.capability, market: request.market, instrument: 'equity' }
|
|
57
57
|
}
|
|
58
|
-
// kline 探针直接拉代表证券 3 根日K(实测列义/端点全链),quotes 探针沿用行情行。
|
|
59
|
-
|
|
58
|
+
// kline 探针直接拉代表证券 3 根日K(实测列义/端点全链), trend 探针拉当日分时, quotes 探针沿用行情行。
|
|
59
|
+
// 各能力必须探各自的上游端点: 拿行情接口冒充分时, 「分时就绪」只会是假阳性
|
|
60
|
+
if (request.capability === 'kline' || request.capability === 'trend') {
|
|
61
|
+
const capability = request.capability
|
|
60
62
|
const code = PROBE_SECURITY[request.market] || '000001'
|
|
61
|
-
const result = await this
|
|
63
|
+
const result = await this[capability](capability === 'kline'
|
|
64
|
+
? { ...request, securityId: `${request.market}:equity:${code}`, code, period: '1d', adjust: 'qfq', limit: 3 }
|
|
65
|
+
: { ...request, securityId: `${request.market}:equity:${code}`, code, period: 'trend', limit: 50 }, ctx)
|
|
62
66
|
if (!result.candles.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
63
|
-
return { status: 'ready', capability
|
|
67
|
+
return { status: 'ready', capability, market: request.market, instrument: 'equity' }
|
|
64
68
|
}
|
|
65
69
|
// 美股前缀的逐个试探已收敛进 quotes,探针只需一次结果,避免探针与真实取价走两套路径
|
|
66
70
|
const security = request.securities?.[0] || { exchange: request.market, code: PROBE_SECURITY[request.market] || '000001' }
|
|
@@ -152,22 +156,22 @@ export const eastmoney = {
|
|
|
152
156
|
secidOf(request, ctx) {
|
|
153
157
|
return secidFor({ exchange: request.market, code: request.code }, ctx)
|
|
154
158
|
},
|
|
159
|
+
// 美股默认前缀猜错时经搜索联想解析真实 MktNum, 重试一次并缓存映射; K线与分时共用同一条兜底
|
|
160
|
+
async withUsFallback(request, ctx, buildUrl, hasData, label) {
|
|
161
|
+
let body = await getJson(ctx, buildUrl(this.secidOf(request, ctx)))
|
|
162
|
+
if (hasData(body)) return body
|
|
163
|
+
if (!isUSExchange(request.market)) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
|
|
164
|
+
const resolved = await this.resolveUsSecid(request, ctx)
|
|
165
|
+
if (!resolved) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
|
|
166
|
+
ctx.usSymbols?.set(`US:${request.code}`, resolved)
|
|
167
|
+
body = await getJson(ctx, buildUrl(`${resolved.mktNum}.${request.code}`))
|
|
168
|
+
if (!hasData(body)) throw new StockError('NO_DATA', `来源未返回此证券${label}`, 422)
|
|
169
|
+
return body
|
|
170
|
+
},
|
|
155
171
|
async kline(request, ctx) {
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const
|
|
159
|
-
const body = await getJson(ctx, url)
|
|
160
|
-
if (!body?.data?.klines) {
|
|
161
|
-
if (request.market !== 'XNAS' && request.market !== 'XNYS') throw new StockError('NO_DATA', '来源未返回此证券K线', 422)
|
|
162
|
-
// 美股默认前缀猜错: 经搜索联想解析真实 MktNum, 重试一次;仍失败 NO_DATA。
|
|
163
|
-
const resolved = await this.resolveUsSecid(request, ctx)
|
|
164
|
-
if (!resolved) throw new StockError('NO_DATA', '来源未返回此证券K线', 422)
|
|
165
|
-
ctx.usSymbols?.set(`US:${request.code}`, resolved)
|
|
166
|
-
const retryUrl = url.replace(`secid=${secid}`, `secid=${resolved.mktNum}.${request.code}`)
|
|
167
|
-
const retryBody = await getJson(ctx, retryUrl)
|
|
168
|
-
if (!retryBody?.data?.klines) throw new StockError('NO_DATA', '来源未返回此证券K线', 422)
|
|
169
|
-
return buildKlineResponse(request, retryBody.data, ctx)
|
|
170
|
-
}
|
|
172
|
+
const klt = KLT[request.period]
|
|
173
|
+
if (!klt) throw new StockError('INVALID_PARAM', '东财 K 线只支持日/周/月,分时请走分时能力', 400)
|
|
174
|
+
const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'kline')}?secid=${secid}&fields1=f1,f2,f3&fields2=${KLINE_FIELDS}&klt=${klt}&fqt=1&end=20500101&lmt=${request.limit}`, body => !!body?.data?.klines, 'K线')
|
|
171
175
|
return buildKlineResponse(request, body.data, ctx)
|
|
172
176
|
},
|
|
173
177
|
async resolveUsSecid(request, ctx) {
|
|
@@ -177,10 +181,7 @@ export const eastmoney = {
|
|
|
177
181
|
return row ? { mktNum: row.MktNum, jys: row.JYS || null, at: ctx.now() } : null
|
|
178
182
|
},
|
|
179
183
|
async trend(request, ctx) {
|
|
180
|
-
const
|
|
181
|
-
const url = `${endpointOf(ctx, 'trend')}?secid=${secid}&fields1=f1,f2,f3,f4,f5,f6,f7,f8&fields2=${TREND_FIELDS}&iscr=0&ndays=1`
|
|
182
|
-
const body = await getJson(ctx, url)
|
|
183
|
-
if (!body?.data?.trends) throw new StockError('NO_DATA', '来源未返回此证券分时', 422)
|
|
184
|
+
const body = await this.withUsFallback(request, ctx, secid => `${endpointOf(ctx, 'trend')}?secid=${secid}&fields1=f1,f2,f3,f4,f5,f6,f7,f8&fields2=${TREND_FIELDS}&iscr=0&ndays=1`, body => !!body?.data?.trends, '分时')
|
|
184
185
|
// 东财分时的时间戳一律按北京时间给出(八市场实测: 日股 08:00 对应东京 09:00 开盘, 英股 16:00 对应伦敦 08:00),
|
|
185
186
|
// 不是市场本地时间; 之前按市场时区解释, 日韩英的横轴整体偏了几小时。
|
|
186
187
|
const candles = body.data.trends.map(row => {
|
|
@@ -199,35 +200,6 @@ export const eastmoney = {
|
|
|
199
200
|
function num_or_null(v) { const n = parseFloat(v); return Number.isFinite(n) ? n : null }
|
|
200
201
|
|
|
201
202
|
|
|
202
|
-
// 时区格式化器按来源时区复用:分时逐行换算时,新建 formatter 的成本主导解析
|
|
203
|
-
const ZONE_FORMATTERS = new Map()
|
|
204
|
-
|
|
205
|
-
function zoneFormatter(timeZone) {
|
|
206
|
-
let formatter = ZONE_FORMATTERS.get(timeZone)
|
|
207
|
-
if (formatter === undefined) {
|
|
208
|
-
formatter = new Intl.DateTimeFormat('en-US', {
|
|
209
|
-
timeZone, hour12: false,
|
|
210
|
-
year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
|
|
211
|
-
})
|
|
212
|
-
ZONE_FORMATTERS.set(timeZone, formatter)
|
|
213
|
-
}
|
|
214
|
-
return formatter
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// 把指定时区的"YYYY-MM-DD HH:MM"换算成 Unix 秒, 时刻属于哪个时区由调用方给定;
|
|
218
|
-
// 无时区元数据或格式不符时返回 null, 调用方回退自造时间轴
|
|
219
|
-
function zonedUnixSeconds(stamp, timeZone) {
|
|
220
|
-
const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/.exec(stamp)
|
|
221
|
-
if (!match || !timeZone) return null
|
|
222
|
-
const [, y, mo, d, hh, mm] = match.map(Number)
|
|
223
|
-
const localAsUtc = Date.UTC(y, mo - 1, d, hh, mm)
|
|
224
|
-
const parts = zoneFormatter(timeZone).formatToParts(new Date(localAsUtc))
|
|
225
|
-
const rendered = Object.fromEntries(parts.map((part) => [part.type, part.value]))
|
|
226
|
-
const asUtc = Date.UTC(Number(rendered.year), Number(rendered.month) - 1, Number(rendered.day),
|
|
227
|
-
Number(rendered.hour) % 24, Number(rendered.minute), Number(rendered.second))
|
|
228
|
-
return Math.floor((localAsUtc - (asUtc - localAsUtc)) / 1000)
|
|
229
|
-
}
|
|
230
|
-
|
|
231
203
|
// klines CSV → 合同响应: 逐行解析/升序/重复拒绝; complete 由 dktotal 与请求量判定(源截断标志)。
|
|
232
204
|
function buildKlineResponse(request, data, ctx) {
|
|
233
205
|
const candles = []
|
package/src/providers/sina.mjs
CHANGED
|
@@ -102,10 +102,12 @@ export const sina = {
|
|
|
102
102
|
if (!match) continue
|
|
103
103
|
const providerSymbol = match[1], security = symbols.get(providerSymbol)
|
|
104
104
|
if (!security) continue
|
|
105
|
+
// 停牌/无值行来源返回空串: 不记 seen, 由 errors 记 NO_DATA; 不拖垮同批其它证券。
|
|
106
|
+
// 只有非空行字段不足才是来源结构异常
|
|
107
|
+
if (match[2].trim() === '') continue
|
|
105
108
|
if (seen.has(providerSymbol)) throw new StockError('BAD_PAYLOAD', '报价身份冲突', 502)
|
|
106
109
|
seen.add(providerSymbol)
|
|
107
110
|
const f = match[2].split(','), kind = kindOf(providerSymbol)
|
|
108
|
-
// 停牌行来源返回空串,按无值处理而不是伪造零价
|
|
109
111
|
if (f.length < MIN_FIELDS[kind]) throw new StockError('BAD_PAYLOAD', '来源字段数量异常', 502)
|
|
110
112
|
const mapped = FIELD_MAP[kind](f)
|
|
111
113
|
items.push(normalizeQuote({
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
// 腾讯公开行情接口适配器:quotes+kline(备源)。非官方端点,无SLA,随时可能失效;延迟未知,行情时间戳为来源快照时间。
|
|
2
|
-
import { normalizeQuote, parseQuoteTime, StockError, MARKET_META, sharesFromLots, amountFromWan } from '../market-model.mjs'
|
|
1
|
+
// 腾讯公开行情接口适配器:quotes+kline+trend(备源)。非官方端点,无SLA,随时可能失效;延迟未知,行情时间戳为来源快照时间。
|
|
2
|
+
import { normalizeQuote, parseQuoteTime, StockError, MARKET_META, sharesFromLots, amountFromWan, zonedUnixSeconds } from '../market-model.mjs'
|
|
3
|
+
// 分时时间戳与东财同一基准: 腾讯给的是北京时间
|
|
4
|
+
const SOURCE_ZONE = 'Asia/Shanghai'
|
|
3
5
|
// 官方默认端点表(key 供 instance.endpoints 覆盖, 反代/镜像场景由 ctx.endpoints 提供同名 key)
|
|
4
6
|
const DEFAULT_ENDPOINTS = {
|
|
5
7
|
quotes: 'https://qt.gtimg.cn/q=',
|
|
6
8
|
kline: 'https://web.ifzq.gtimg.cn/appstock/app/fqkline/get',
|
|
9
|
+
trend: 'https://web.ifzq.gtimg.cn/appstock/app/minute/query?code=',
|
|
7
10
|
}
|
|
8
11
|
const endpointOf = (ctx, key) => ctx.endpoints?.[key] || DEFAULT_ENDPOINTS[key]
|
|
9
12
|
// quotes 与 kline 共用一张前缀表,防双源漂移(design.md 数据结构节)。
|
|
@@ -33,7 +36,7 @@ const quoteStamp = raw => {
|
|
|
33
36
|
}
|
|
34
37
|
|
|
35
38
|
export const tencent = {
|
|
36
|
-
descriptor: { adapterId: 'tencent', capabilities: ['quotes', 'kline'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '
|
|
39
|
+
descriptor: { adapterId: 'tencent', capabilities: ['quotes', 'kline', 'trend'], markets: ['XSHG', 'XSHE', 'XHKG', 'XNAS', 'XNYS'], instruments: ['equity'], maxQuoteBatch: 60, credential: 'none', description: '腾讯公开接口:免凭据,行情/K线/分时备源,非官方无SLA', endpointKeys: [{ key: 'quotes', label: '行情批量' }, { key: 'kline', label: 'K线历史' }, { key: 'trend', label: '分时' }] },
|
|
37
40
|
async probe(request, ctx) {
|
|
38
41
|
// kline 探针直接拉代表证券 3 根日K(quotes 不覆盖港股);quotes 探针沿用代表证券行。
|
|
39
42
|
if (request.capability === 'kline') {
|
|
@@ -43,6 +46,14 @@ export const tencent = {
|
|
|
43
46
|
if (!result.candles.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
44
47
|
return { status: 'ready', capability: 'kline', market: request.market, instrument: 'equity' }
|
|
45
48
|
}
|
|
49
|
+
// 分时探针拉一次代表证券的当日分钟线: 美股没有分钟线, 直接判不支持
|
|
50
|
+
if (request.capability === 'trend') {
|
|
51
|
+
const code = { XSHG: '600519', XSHE: '000001', XHKG: '00700' }[request.market]
|
|
52
|
+
if (!code) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源不提供该市场分时', 422)
|
|
53
|
+
const result = await this.trend({ ...request, securityId: `${request.market}:equity:${code}`, code }, ctx)
|
|
54
|
+
if (!result.candles.length) throw new StockError('NO_DATA', '来源未返回可校验数据,暂不能确认能力就绪', 422)
|
|
55
|
+
return { status: 'ready', capability: 'trend', market: request.market, instrument: 'equity' }
|
|
56
|
+
}
|
|
46
57
|
const PROBE = { XSHG: '600519', XSHE: '000001', XHKG: '00700', XNAS: 'AAPL', XNYS: 'BABA' }
|
|
47
58
|
const security = request.securities?.[0] || { exchange: request.market, code: PROBE[request.market] || '000001' }
|
|
48
59
|
const rows = await this.quotes({ ...request, securities: [security] }, ctx)
|
|
@@ -84,7 +95,6 @@ export const tencent = {
|
|
|
84
95
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), items, errors: request.securities.filter(s => !seen.has(symbolOf(s))).map(s => ({ securityId: s.id, code: 'NO_DATA', message: '来源未返回此证券报价' })) }
|
|
85
96
|
},
|
|
86
97
|
async kline(request, ctx) {
|
|
87
|
-
if (request.period === 'trend') throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源不提供分时数据', 422)
|
|
88
98
|
let symbol = klineSymbolOf(request)
|
|
89
99
|
if (request.market === 'XNAS' || request.market === 'XNYS') {
|
|
90
100
|
const mapped = ctx.usSymbols?.get(`US:${request.code}`)
|
|
@@ -92,7 +102,9 @@ export const tencent = {
|
|
|
92
102
|
if (suffix === undefined) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯来源的美股K线需先经搜索建立代码映射', 422)
|
|
93
103
|
symbol = suffix ? `us${request.code}.${suffix}` : `us${request.code}`
|
|
94
104
|
}
|
|
95
|
-
const
|
|
105
|
+
const period = { '1d': 'day', '1w': 'week', '1M': 'month' }[request.period]
|
|
106
|
+
if (!period) throw new StockError('INVALID_PARAM', '腾讯 K 线只支持日/周/月,分时请走分时能力', 400)
|
|
107
|
+
const param = `${symbol},${period},,,${request.limit},qfq`
|
|
96
108
|
let response
|
|
97
109
|
try {
|
|
98
110
|
response = await ctx.fetch(`${endpointOf(ctx, 'kline')}?param=${param}`, { headers: { Referer: 'https://gu.qq.com/', 'User-Agent': 'Mozilla/5.0' }, signal: ctx.signal, redirect: 'error' })
|
|
@@ -119,4 +131,38 @@ export const tencent = {
|
|
|
119
131
|
const preClose = qt ? num(qt[4]) : null
|
|
120
132
|
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), complete: true, preClose, candles }
|
|
121
133
|
},
|
|
134
|
+
// 分时(备源): minute/query 给当日逐分钟价格/量/额。腾讯的分时没有开高低与均价,
|
|
135
|
+
// 移位填成同一价, 客户端按 OHLC 校验时才不会把每根丢掉。
|
|
136
|
+
async trend(request, ctx) {
|
|
137
|
+
const symbol = klineSymbolOf(request)
|
|
138
|
+
if (!SYMBOL_PREFIX[request.market]) throw new StockError('UNSUPPORTED_CAPABILITY', '腾讯分时只覆盖沪深港', 422)
|
|
139
|
+
let response
|
|
140
|
+
try {
|
|
141
|
+
response = await ctx.fetch(endpointOf(ctx, 'trend') + symbol, { headers: { Referer: 'https://gu.qq.com/', 'User-Agent': 'Mozilla/5.0' }, signal: ctx.signal, redirect: 'error' })
|
|
142
|
+
} catch (e) {
|
|
143
|
+
if (ctx.signal.aborted) throw new StockError('CANCELLED', '请求已取消', 503)
|
|
144
|
+
if (e instanceof StockError) throw e
|
|
145
|
+
throw new StockError('NETWORK', '无法连接行情来源', 502, { retryable: true })
|
|
146
|
+
}
|
|
147
|
+
if (!response.ok) throw new StockError('NETWORK', '来源服务暂不可用', 502, { retryable: true })
|
|
148
|
+
const body = await response.json().catch(() => { throw new StockError('BAD_PAYLOAD', '来源响应不是JSON', 502) })
|
|
149
|
+
const data = body?.data?.[symbol]?.data
|
|
150
|
+
const rows = Array.isArray(data?.data) ? data.data : []
|
|
151
|
+
const day = /^(\d{4})(\d{2})(\d{2})$/.exec(String(data?.date || ''))
|
|
152
|
+
if (!rows.length || !day) throw new StockError('NO_DATA', '来源未返回此证券分时', 422)
|
|
153
|
+
const stamp = `${day[1]}-${day[2]}-${day[3]}`
|
|
154
|
+
const candles = []
|
|
155
|
+
for (const row of rows) {
|
|
156
|
+
const cols = String(row).split(' ')
|
|
157
|
+
// 价格必须是纯数字才收: 上游偶有畸形行, 与其把 NaN 画进图里, 不如少一点
|
|
158
|
+
if (!/^\d{3,4}$/.test(cols[0] || '') || !/^\d+(\.\d+)?$/.test(cols[1] || '')) continue
|
|
159
|
+
const time = `${cols[0].padStart(4, '0').slice(0, 2)}:${cols[0].padStart(4, '0').slice(2)}`
|
|
160
|
+
const price = num(cols[1])
|
|
161
|
+
if (price == null) continue
|
|
162
|
+
candles.push({ time, at: zonedUnixSeconds(`${stamp} ${time}`, SOURCE_ZONE), open: price, close: price, high: price, low: price, volume: sharesFromLots(num(cols[2]), request.market), amount: num(cols[3]), avg: null })
|
|
163
|
+
}
|
|
164
|
+
if (!candles.length) throw new StockError('NO_DATA', '来源分时数据不可解析', 422)
|
|
165
|
+
const qt = Array.isArray(body?.data?.[symbol]?.qt?.[symbol]) ? body.data[symbol].qt[symbol] : null
|
|
166
|
+
return { providerInstanceId: request.providerInstanceId, fetchedAt: ctx.now(), complete: true, preClose: qt ? num(qt[4]) : null, candles }
|
|
167
|
+
},
|
|
122
168
|
}
|
package/src/recovery.mjs
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// 降级后回头试上级: 后台定时跑, 不占用户请求时间, 也不用业务请求去猜上游好坏。
|
|
2
|
+
// 每个适配器自己实现探针(probe), 这里只负责按路由顺序点名、把汇报交给路由器。
|
|
3
|
+
export const RECOVERY_RETRY_MS = 20 * 1000
|
|
4
|
+
export function createRecovery({ getConfig, router, executor }) {
|
|
5
|
+
return async function probeRecovery() {
|
|
6
|
+
// 用户请求在跑时整轮跳过: 探测排在别人的超时后面会把详情页请求推到 10 秒线上
|
|
7
|
+
if (!executor.idle()) return
|
|
8
|
+
for (const route of getConfig().routes) {
|
|
9
|
+
if (route.failoverMode !== 'network') continue
|
|
10
|
+
const epoch = router.selections()[route.id]?.routeEpoch
|
|
11
|
+
if (epoch === undefined) continue
|
|
12
|
+
for (const id of router.recoveryCandidates(route.id)) {
|
|
13
|
+
const instance = getConfig().providers.find(p => p.id === id && p.enabled !== false && p.budget?.requestsPerMinute !== null)
|
|
14
|
+
if (!instance) continue
|
|
15
|
+
let ready = false
|
|
16
|
+
try {
|
|
17
|
+
const result = await executor.run(instance, route.capability, { market: route.market, instrument: route.instrument }, { probe: true })
|
|
18
|
+
// 探针必须由同名能力产出: 适配器拿别的能力冒充时不能当就绪
|
|
19
|
+
ready = result?.status === 'ready' && result.capability === route.capability
|
|
20
|
+
} catch {}
|
|
21
|
+
try { router.recordProbe(route.id, id, ready, epoch) } catch { break }
|
|
22
|
+
if (ready) break
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// 探测节奏跟着面板走: 有人看才探, 没人看就停; 每次重新活跃先立刻探一次, 不用干等一个周期。
|
|
29
|
+
// 上一轮没跑完就跳过这一轮: 探测要逐个实例打上游, 一轮可能比周期还长。
|
|
30
|
+
// 用户请求在跑时短重试, 不占首屏的队列
|
|
31
|
+
export function createRecoveryLoop({ probe, timers, interval, canRun = () => true }) {
|
|
32
|
+
let timer = null, retry = null, running = false, busy = false, stopped = false, inflight = Promise.resolve()
|
|
33
|
+
const run = () => {
|
|
34
|
+
if (stopped || busy) return
|
|
35
|
+
if (!canRun()) {
|
|
36
|
+
if (retry) return
|
|
37
|
+
retry = timers.setTimeout?.(() => { retry = null; run() }, RECOVERY_RETRY_MS) ?? null
|
|
38
|
+
retry?.unref?.()
|
|
39
|
+
return
|
|
40
|
+
}
|
|
41
|
+
busy = true
|
|
42
|
+
inflight = Promise.resolve().then(probe).catch(() => {}).finally(() => { busy = false })
|
|
43
|
+
}
|
|
44
|
+
const stop = () => {
|
|
45
|
+
stopped = true
|
|
46
|
+
if (timer) timers.clearInterval?.(timer)
|
|
47
|
+
if (retry) timers.clearTimeout?.(retry)
|
|
48
|
+
timer = null; retry = null; running = false
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
sync(active) {
|
|
52
|
+
if (active === running) return
|
|
53
|
+
if (!active) return stop()
|
|
54
|
+
stopped = false
|
|
55
|
+
run()
|
|
56
|
+
timer = timers.setInterval?.(run, interval) ?? null
|
|
57
|
+
timer?.unref?.()
|
|
58
|
+
running = true
|
|
59
|
+
},
|
|
60
|
+
// 在飞的那一轮, 关闭时等它收尾
|
|
61
|
+
idle: () => inflight,
|
|
62
|
+
stop,
|
|
63
|
+
}
|
|
64
|
+
}
|
package/src/route-gate.mjs
CHANGED
|
@@ -1,29 +1,85 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 宿主闸门复用。宿主把认证挂在它自己的 `/api` prefix 路由里,而 responder 选择是
|
|
3
|
-
* 「exact 先、最长 prefix 后」——插件注册的 `/api/<pkg>` 更长,先命中,`connection.admit`
|
|
4
|
-
* 从不执行。所以插件路由必须自己回问一次宿主闸门,否则无 cookie 的调用直接进业务面。
|
|
5
|
-
*
|
|
6
|
-
* 服务缺失(非 web 传输、旧宿主)时放行:与原行为一致,不新增自有认证层。
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
export function
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 宿主闸门复用。宿主把认证挂在它自己的 `/api` prefix 路由里,而 responder 选择是
|
|
3
|
+
* 「exact 先、最长 prefix 后」——插件注册的 `/api/<pkg>` 更长,先命中,`connection.admit`
|
|
4
|
+
* 从不执行。所以插件路由必须自己回问一次宿主闸门,否则无 cookie 的调用直接进业务面。
|
|
5
|
+
*
|
|
6
|
+
* 服务缺失(非 web 传输、旧宿主)时放行:与原行为一致,不新增自有认证层。
|
|
7
|
+
* 写路由再叠加 Origin↔Host 同源比对与 JSON content-type 校验(用 withRouteGate):
|
|
8
|
+
* 这是浏览器侧 CSRF 防线,不是身份认证;禁止在此实现 Host 白名单/DNS-rebinding
|
|
9
|
+
* 防线/自有 token。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
function sendGuardJson(res, status, error) {
|
|
13
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
|
|
14
|
+
res.end(JSON.stringify({ error }))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// 宿主闸门返回的拒绝值只有整数 4xx/5xx 可写进 writeHead;null/0/对象/Promise 一律按
|
|
18
|
+
// 默认拒绝码收敛——否则 writeHead 抛 Invalid status code,请求拿不到任何响应。
|
|
19
|
+
const REJECTION_MIN = 400
|
|
20
|
+
const REJECTION_MAX = 599
|
|
21
|
+
const DEFAULT_REJECTION = 403
|
|
22
|
+
const isRejectionCode = (value) => Number.isInteger(value) && value >= REJECTION_MIN && value <= REJECTION_MAX
|
|
23
|
+
|
|
24
|
+
export function rejectUnadmitted(ctx, req, res) {
|
|
25
|
+
let rejection
|
|
26
|
+
try {
|
|
27
|
+
const connection = typeof ctx?.get === 'function' ? ctx.get('connection') : undefined
|
|
28
|
+
rejection = connection?.requestRejection?.(req)
|
|
29
|
+
} catch {
|
|
30
|
+
// 闸门自身异常不放行:宁可拒绝,不把故障当认证通过
|
|
31
|
+
rejection = DEFAULT_REJECTION
|
|
32
|
+
}
|
|
33
|
+
if (rejection === undefined) return false
|
|
34
|
+
const status = isRejectionCode(rejection) ? rejection : DEFAULT_REJECTION
|
|
35
|
+
res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' })
|
|
36
|
+
res.end(status === 401 ? 'unauthorized' : 'forbidden')
|
|
37
|
+
return true
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function withHostGate(ctx, handler) {
|
|
41
|
+
return async (req, res) => {
|
|
42
|
+
if (rejectUnadmitted(ctx, req, res)) return
|
|
43
|
+
await handler(req, res)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Origin 存在即比对 Host(大小写不敏感);缺 Origin 的非浏览器调用不受影响。
|
|
48
|
+
// Origin 非法(无法解析)按跨源拒绝。
|
|
49
|
+
export function rejectCrossOrigin(req, res) {
|
|
50
|
+
const origin = req.headers ? req.headers.origin : undefined
|
|
51
|
+
if (!origin) return false
|
|
52
|
+
const host = req.headers ? req.headers.host : undefined
|
|
53
|
+
let sameOrigin = false
|
|
54
|
+
try {
|
|
55
|
+
sameOrigin = typeof host === 'string' && new URL(origin).host.toLowerCase() === host.toLowerCase()
|
|
56
|
+
} catch {
|
|
57
|
+
sameOrigin = false
|
|
58
|
+
}
|
|
59
|
+
if (sameOrigin) return false
|
|
60
|
+
sendGuardJson(res, 403, '跨源请求被拒绝')
|
|
61
|
+
return true
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 写方法只接受 JSON:跨站表单(enctype=text/plain 等简单请求)无预检,必须显式拒绝。
|
|
65
|
+
// 媒体类型按 essence 精确比较,避免 application/jsonp / text/plain;...application/json 混入。
|
|
66
|
+
export const WRITE_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE'])
|
|
67
|
+
export function rejectNonJson(req, res) {
|
|
68
|
+
const contentType = req.headers ? String(req.headers['content-type'] || '') : ''
|
|
69
|
+
const essence = contentType.split(';', 1)[0].trim().toLowerCase()
|
|
70
|
+
if (essence === 'application/json') return false
|
|
71
|
+
sendGuardJson(res, 400, 'content-type 须为 application/json')
|
|
72
|
+
return true
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 写路由完整闸门:宿主闸门 → 同源 → JSON。GET/HEAD 只过宿主闸门(无写副作用)
|
|
76
|
+
export function withRouteGate(ctx, handler) {
|
|
77
|
+
return async (req, res) => {
|
|
78
|
+
if (rejectUnadmitted(ctx, req, res)) return
|
|
79
|
+
if (WRITE_METHODS.has(String(req.method || '').toUpperCase())) {
|
|
80
|
+
if (rejectCrossOrigin(req, res)) return
|
|
81
|
+
if (rejectNonJson(req, res)) return
|
|
82
|
+
}
|
|
83
|
+
await handler(req, res)
|
|
84
|
+
}
|
|
85
|
+
}
|
package/src/routes.mjs
CHANGED
|
@@ -1,68 +1,68 @@
|
|
|
1
|
-
import { z } from 'zod'
|
|
2
|
-
import { StockError, fail } from './market-model.mjs'
|
|
3
|
-
import {
|
|
4
|
-
const PREFIX = '/api/stock-assistant'
|
|
5
|
-
const operationSchema = z.object({ operationId: z.uuid(), expectedRevision: z.number().int().nonnegative() })
|
|
6
|
-
async function body(req) {
|
|
7
|
-
const chunks = []; let size = 0
|
|
8
|
-
for await (const chunk of req) {
|
|
9
|
-
size += chunk.length
|
|
10
|
-
if (size > 64 * 1024) fail('BODY_TOO_LARGE', '请求内容过大', 413)
|
|
11
|
-
chunks.push(chunk)
|
|
12
|
-
}
|
|
13
|
-
try { return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') }
|
|
14
|
-
catch { fail('INVALID_JSON', '请求必须为JSON') }
|
|
15
|
-
}
|
|
16
|
-
function json(res, status, value) {
|
|
17
|
-
if (res.destroyed || res.writableEnded) return
|
|
18
|
-
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value))
|
|
19
|
-
}
|
|
20
|
-
export function registerRoutes(webServer, app, ctx) {
|
|
21
|
-
const handlers = {
|
|
22
|
-
snapshot: ['GET', () => app.snapshot()],
|
|
23
|
-
search: ['GET', async (input, signal) => await app.search(input.q || '', input.phase === 'remote' ? 'remote' : 'local', signal)],
|
|
24
|
-
browse: ['GET', input => app.browse(input)],
|
|
25
|
-
watchlist: ['POST', input => { operationSchema.parse(input); return app.watchlist(input) }],
|
|
26
|
-
preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
|
|
27
|
-
configuration: ['POST', input => { operationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
|
|
28
|
-
'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
|
|
29
|
-
credential: ['POST', input => app.credential(input)],
|
|
30
|
-
'catalog-sync': ['POST', input => app.sync(input)],
|
|
31
|
-
'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
|
|
32
|
-
refresh: ['POST', (input, signal) => app.refresh(input, signal)],
|
|
33
|
-
kline: ['GET', (input, signal) => app.kline(input, signal)],
|
|
34
|
-
}
|
|
35
|
-
const controllers = new Set(), disposers = []
|
|
36
|
-
let stopped = false
|
|
37
|
-
try {
|
|
38
|
-
for (const [name, [method, action]] of Object.entries(handlers))
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
}
|
|
66
|
-
} catch (e) { for (const dispose of disposers.reverse()) dispose(); throw e }
|
|
67
|
-
return () => { stopped = true; for (const dispose of disposers.reverse()) dispose(); for (const c of controllers) c.abort(); controllers.clear() }
|
|
68
|
-
}
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import { StockError, fail } from './market-model.mjs'
|
|
3
|
+
import { withRouteGate } from './route-gate.mjs'
|
|
4
|
+
const PREFIX = '/api/stock-assistant'
|
|
5
|
+
const operationSchema = z.object({ operationId: z.uuid(), expectedRevision: z.number().int().nonnegative() })
|
|
6
|
+
async function body(req) {
|
|
7
|
+
const chunks = []; let size = 0
|
|
8
|
+
for await (const chunk of req) {
|
|
9
|
+
size += chunk.length
|
|
10
|
+
if (size > 64 * 1024) fail('BODY_TOO_LARGE', '请求内容过大', 413)
|
|
11
|
+
chunks.push(chunk)
|
|
12
|
+
}
|
|
13
|
+
try { return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') }
|
|
14
|
+
catch { fail('INVALID_JSON', '请求必须为JSON') }
|
|
15
|
+
}
|
|
16
|
+
function json(res, status, value) {
|
|
17
|
+
if (res.destroyed || res.writableEnded) return
|
|
18
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value))
|
|
19
|
+
}
|
|
20
|
+
export function registerRoutes(webServer, app, ctx) {
|
|
21
|
+
const handlers = {
|
|
22
|
+
snapshot: ['GET', () => app.snapshot()],
|
|
23
|
+
search: ['GET', async (input, signal) => await app.search(input.q || '', input.phase === 'remote' ? 'remote' : 'local', signal)],
|
|
24
|
+
browse: ['GET', input => app.browse(input)],
|
|
25
|
+
watchlist: ['POST', input => { operationSchema.parse(input); return app.watchlist(input) }],
|
|
26
|
+
preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
|
|
27
|
+
configuration: ['POST', input => { operationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
|
|
28
|
+
'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
|
|
29
|
+
credential: ['POST', input => app.credential(input)],
|
|
30
|
+
'catalog-sync': ['POST', input => app.sync(input)],
|
|
31
|
+
'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
|
|
32
|
+
refresh: ['POST', (input, signal) => app.refresh(input, signal)],
|
|
33
|
+
kline: ['GET', (input, signal) => app.kline(input, signal)],
|
|
34
|
+
}
|
|
35
|
+
const controllers = new Set(), disposers = []
|
|
36
|
+
let stopped = false
|
|
37
|
+
try {
|
|
38
|
+
for (const [name, [method, action]] of Object.entries(handlers)) {
|
|
39
|
+
// 写方法与读方法统一走共享闸门: 宿主闸门恒过; 写方法再叠同源与 JSON content-type。
|
|
40
|
+
// GET 无写副作用, 只回问宿主闸门。
|
|
41
|
+
const handle = async (req, res) => {
|
|
42
|
+
if (stopped) return json(res, 503, { ok: false, error: { code: 'STOPPED', message: '工具已停止' } })
|
|
43
|
+
if (req.method !== method) { res.setHeader('Allow', method); return json(res, 405, { ok: false, error: { code: 'METHOD_NOT_ALLOWED', message: '请求方法不支持' } }) }
|
|
44
|
+
const controller = new AbortController(); controllers.add(controller)
|
|
45
|
+
const onClose = () => { if (!res.writableEnded) controller.abort() }
|
|
46
|
+
res.on('close', onClose)
|
|
47
|
+
const timeout = name === 'provider-check' ? 60 * 1000 : name === 'catalog-sync' ? 120 * 1000 : 10 * 1000
|
|
48
|
+
let timer
|
|
49
|
+
try {
|
|
50
|
+
const input = method === 'GET' ? Object.fromEntries(new URL(req.url, 'http://local').searchParams) : await body(req)
|
|
51
|
+
if (method === 'POST' && (input === null || typeof input !== 'object' || Array.isArray(input))) fail('INVALID_REQUEST', '请求内容必须为JSON对象')
|
|
52
|
+
const data = await Promise.race([
|
|
53
|
+
Promise.resolve(action(input, controller.signal)),
|
|
54
|
+
// 超时错误随 abort reason 一起下发: 即使 abort 监听先被同步派发, 也拿到 TIMEOUT 而不是 CANCELLED
|
|
55
|
+
new Promise((_, reject) => { timer = setTimeout(() => { const error = new StockError('TIMEOUT', '操作超时,请稍后重试', 504); controller.abort(error); reject(error) }, timeout) }),
|
|
56
|
+
new Promise((_, reject) => controller.signal.addEventListener('abort', () => reject(controller.signal.reason instanceof StockError ? controller.signal.reason : new StockError('CANCELLED', '操作已取消', stopped ? 503 : 504)), { once: true })),
|
|
57
|
+
])
|
|
58
|
+
json(res, 200, { ok: true, data })
|
|
59
|
+
} catch (e) {
|
|
60
|
+
const error = e instanceof StockError ? e : new StockError('INVALID_REQUEST', e instanceof z.ZodError ? '请求参数格式错误' : '股票工具请求失败', e instanceof z.ZodError ? 400 : 500)
|
|
61
|
+
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
|
+
} finally { clearTimeout(timer); controllers.delete(controller); res.removeListener('close', onClose) }
|
|
63
|
+
}
|
|
64
|
+
disposers.push(webServer.register({ kind: 'exact', path: `${PREFIX}/${name}`, handler: withRouteGate(ctx, handle) }))
|
|
65
|
+
}
|
|
66
|
+
} catch (e) { for (const dispose of disposers.reverse()) dispose(); throw e }
|
|
67
|
+
return () => { stopped = true; for (const dispose of disposers.reverse()) dispose(); for (const c of controllers) c.abort(); controllers.clear() }
|
|
68
|
+
}
|