@mzzsfy/dsh-stock-assistant 0.8.0 → 0.8.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/CHANGELOG.md +13 -1
- package/README.md +10 -0
- package/package.json +1 -1
- package/src/application.mjs +400 -400
- package/src/catalog.mjs +193 -193
- package/src/client.js +2646 -2642
- package/src/collector.mjs +265 -265
- package/src/executor.mjs +149 -148
- package/src/index.js +45 -45
- package/src/provider-router.mjs +2 -1
- package/src/providers/eastmoney.mjs +226 -217
- package/src/providers/tencent.mjs +168 -168
- package/src/providers/tushare.mjs +92 -92
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +5 -1
package/src/executor.mjs
CHANGED
|
@@ -1,148 +1,149 @@
|
|
|
1
|
-
import { StockError, fail } from './market-model.mjs'
|
|
2
|
-
// 每实例上游请求环形日志容量: 概览"最近请求"展示面
|
|
3
|
-
const REQUEST_LOG_LIMIT = 20
|
|
4
|
-
export function createExecutor({ registry, budget, env = process.env, resolveCredential = async ref => env[ref], fetch: fetchImpl = globalThis.fetch, proxyFetch = null, now = Date.now, timers = globalThis, usSymbols = new Map(), proxyFactory = null, tickPeriodMs = () => 0, tickCapabilities = ['quotes', 'kline', 'trend'] }) {
|
|
5
|
-
const queues = new Map(), controllers = new Set(), starts = new Map()
|
|
6
|
-
const requestLogs = new Map(), proxies = new Map()
|
|
7
|
-
let stopped = false, running = 0
|
|
8
|
-
// probe 标记只给后台探测用: 界面上的"最近请求"只该反映用户请求
|
|
9
|
-
const record = (instanceId, url, status, startedAt, probe = false) => {
|
|
10
|
-
const log = requestLogs.get(instanceId) || []
|
|
11
|
-
log.unshift({ at: now(), url: String(url), status, ms: Math.max(0, now() - startedAt), ...(probe ? { probe: true } : {}) })
|
|
12
|
-
if (log.length > REQUEST_LOG_LIMIT) log.length = REQUEST_LOG_LIMIT
|
|
13
|
-
requestLogs.set(instanceId, log)
|
|
14
|
-
}
|
|
15
|
-
// 实例代理 dispatcher: 按代理 URL 惰性创建缓存(多实例共享同代理不重复建); proxyFactory 由宿主注入(undici ProxyAgent)
|
|
16
|
-
// dispatcher 是 undici 的私有契约, Node 内置 fetch 与 userland undici 版本错位时会直接 502:
|
|
17
|
-
// 配了代理就必须用同一份 undici.fetch 发请求; 任一组件缺失都明确报错, 不能静默直连泄露真实出口
|
|
18
|
-
const dispatcherFor = proxy => {
|
|
19
|
-
if (!proxy) return null
|
|
20
|
-
if (typeof proxyFactory !== 'function' || typeof proxyFetch !== 'function') fail('NETWORK', '代理出口不可用:缺少 undici 运行依赖', 502)
|
|
21
|
-
if (!proxies.has(proxy)) {
|
|
22
|
-
let dispatcher
|
|
23
|
-
try { dispatcher = proxyFactory(proxy) } catch (e) { fail('NETWORK', `代理出口不可用:${e.message}`, 502) }
|
|
24
|
-
if (!dispatcher) fail('NETWORK', '代理出口不可用:dispatcher 创建失败', 502)
|
|
25
|
-
proxies.set(proxy, dispatcher)
|
|
26
|
-
}
|
|
27
|
-
return proxies.get(proxy)
|
|
28
|
-
}
|
|
29
|
-
// 代理账号密码只从宿主凭据/环境变量取, 运行时注入 URL; 配置与快照里永远只有 proxyCredentialRef 引用
|
|
30
|
-
const proxyUrlOf = async instance => {
|
|
31
|
-
if (!instance.proxy) return null
|
|
32
|
-
if (!instance.proxyCredentialRef) return instance.proxy
|
|
33
|
-
const secret = await resolveCredential(instance.proxyCredentialRef)
|
|
34
|
-
if (!secret) fail('AUTH', '未配置代理凭据', 422)
|
|
35
|
-
const url = new URL(instance.proxy), separator = secret.indexOf(':')
|
|
36
|
-
url.username = separator < 0 ? secret : secret.slice(0, separator)
|
|
37
|
-
url.password = separator < 0 ? '' : secret.slice(separator + 1)
|
|
38
|
-
return url.toString()
|
|
39
|
-
}
|
|
40
|
-
// 组内节拍等待:上取整加裕度。setTimeout 对非整数 ms 向下取整且唤醒有抖动,
|
|
41
|
-
// 直接 setTimeout(gap) 会在 now-starts<间隔 时醒来,预算层同源时钟误判 RATE_LIMIT
|
|
42
|
-
// (CI 双架构高发竞态);唤醒后 now-starts>=间隔 恒成立,预算门恒过。
|
|
43
|
-
const THROTTLE_SLACK_MS = 5
|
|
44
|
-
const throttleDelay = gap => Math.ceil(gap) + THROTTLE_SLACK_MS
|
|
45
|
-
const waitFor = (ms, signal) => new Promise((resolve, reject) => {
|
|
46
|
-
const abort = () => { timers.clearTimeout(id); reject(new StockError('CANCELLED', '请求已取消', 503)) }
|
|
47
|
-
const id = timers.setTimeout(() => { signal.removeEventListener('abort', abort); resolve() }, ms)
|
|
48
|
-
signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort()
|
|
49
|
-
})
|
|
50
|
-
// 兜底节拍: 每个数据源实例一拍最多发一轮请求, 相邻两拍的启用时刻间隔不小于 tickPeriodMs。
|
|
51
|
-
// 一拍内允许多个请求连续发出(报价分批/分时/详情 K 线本来就是一拍的事), 所以只看拍的开拍时刻;
|
|
52
|
-
// 拍的前半段算同一拍, 后半段才封到下一拍 —— 否则同一拍的第二个请求会被推开整整一个周期。
|
|
53
|
-
// 探针与目录同步是一次性动作, 不受节拍约束(否则首次同步会被拖成每页等一个周期)。
|
|
54
|
-
const tickOpenedAt = new Map()
|
|
55
|
-
const tickDelay = (instance, capability, options) => {
|
|
56
|
-
if (options.probe || !tickCapabilities.includes(capability)) return 0
|
|
57
|
-
const period = tickPeriodMs()
|
|
58
|
-
if (!(period > 0)) return 0
|
|
59
|
-
const opened = tickOpenedAt.get(instance.id), at = now()
|
|
60
|
-
if (opened === undefined || at - opened >= period) { tickOpenedAt.set(instance.id, at); return 0 }
|
|
61
|
-
return at - opened > period / 2 ? opened + period - at : 0
|
|
62
|
-
}
|
|
63
|
-
const slots = []
|
|
64
|
-
async function acquire(signal) {
|
|
65
|
-
if (running < 2) { running++; return }
|
|
66
|
-
await new Promise((resolve, reject) => {
|
|
67
|
-
const slot = { resolve: () => { signal.removeEventListener('abort', abort); resolve() } }
|
|
68
|
-
const abort = () => { const i = slots.indexOf(slot); if (i >= 0) slots.splice(i, 1); reject(new StockError('CANCELLED', '请求已取消', 503)) }
|
|
69
|
-
slots.push(slot); signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort()
|
|
70
|
-
})
|
|
71
|
-
}
|
|
72
|
-
function release() { if (slots.length) slots.shift().resolve(); else running-- }
|
|
73
|
-
return {
|
|
74
|
-
run(instance, capability, request, options = {}) {
|
|
75
|
-
const group = options.probe ? `${instance.quotaGroup}#probe` : instance.quotaGroup
|
|
76
|
-
const previous = queues.get(group) || Promise.resolve()
|
|
77
|
-
const job = previous.catch(() => {}).then(async () => {
|
|
78
|
-
if (stopped || options.signal?.aborted) fail('CANCELLED', '请求已取消', 503)
|
|
79
|
-
const controller = new AbortController(); controllers.add(controller)
|
|
80
|
-
const abort = () => controller.abort(options.signal?.reason)
|
|
81
|
-
options.signal?.addEventListener('abort', abort, { once: true })
|
|
82
|
-
let timeout, acquired = false
|
|
83
|
-
const startedAt = now()
|
|
84
|
-
try {
|
|
85
|
-
// 闸门放在实际发请求之前, 与 1 秒防连打一起构成两次等待: 先等节拍, 再等组内间隔。
|
|
86
|
-
// 等完再判一次: 等待期间别的请求可能已经开了新拍, 这里要跟着新拍走
|
|
87
|
-
for (let tick = tickDelay(instance, capability, options); tick; tick = tickDelay(instance, capability, options)) await waitFor(throttleDelay(tick), controller.signal)
|
|
88
|
-
const gap = Math.max(0, (starts.get(instance.quotaGroup) ?? -Infinity) + (instance.budget?.requestsPerMinute === null ? 10 * 1000 : 1000) - now())
|
|
89
|
-
if (gap) await waitFor(throttleDelay(gap), controller.signal)
|
|
90
|
-
await acquire(controller.signal); acquired = true
|
|
91
|
-
starts.set(instance.quotaGroup, now())
|
|
92
|
-
const adapter = registry.get(instance.adapterId), method = options.probe ? 'probe' : capability
|
|
93
|
-
if (typeof adapter[method] !== 'function') fail('UNSUPPORTED_CAPABILITY', '来源不支持该能力', 422)
|
|
94
|
-
let used = false
|
|
95
|
-
// 凭据每次操作解析一次, 不跨操作缓存: 存储层改了密钥, 下一次请求就生效, 不必重启插件。
|
|
96
|
-
// 解析在超时计时之前完成——读本地存储不该占用上游的 8 秒预算。
|
|
97
|
-
const secret = instance.credentialRef === null ? undefined : await resolveCredential(instance.credentialRef)
|
|
98
|
-
if (instance.credentialRef !== null && !secret) fail('AUTH', '未配置凭据', 422)
|
|
99
|
-
const proxyUrl = await proxyUrlOf(instance)
|
|
100
|
-
// 超时计时覆盖整个能力调用;分页适配器每次网络活动重置计时,空闲超过窗口才判超时。
|
|
101
|
-
const armTimeout = () => { timers.clearTimeout(timeout); timeout = timers.setTimeout(() => controller.abort(new StockError('TIMEOUT', '来源请求超时', 504, { retryable: true })), 8 * 1000) }
|
|
102
|
-
armTimeout()
|
|
103
|
-
const ctx = { now, signal: controller.signal, usSymbols, endpoints: instance.endpoints || null, credential: () => secret,
|
|
104
|
-
fetch: async (...args) => {
|
|
105
|
-
if (used) {
|
|
106
|
-
const gap = Math.max(0, starts.get(instance.quotaGroup) + (instance.budget?.requestsPerMinute === null ? 10 * 1000 : 1000) - now())
|
|
107
|
-
if (gap) await waitFor(throttleDelay(gap), controller.signal)
|
|
108
|
-
}
|
|
109
|
-
if (controller.signal.aborted) fail('CANCELLED', '请求已取消', 503)
|
|
110
|
-
armTimeout()
|
|
111
|
-
budget.reserve(instance, capability, request.securities?.length || 1, !!options.periodic, !!options.probe); used = true; starts.set(instance.quotaGroup, now())
|
|
112
|
-
const dispatcher = dispatcherFor(proxyUrl)
|
|
113
|
-
const response = await (dispatcher ? proxyFetch : fetchImpl)(args[0], { ...(args[1] || {}), ...(dispatcher ? { dispatcher } : {}) })
|
|
114
|
-
armTimeout()
|
|
115
|
-
return response
|
|
116
|
-
} }
|
|
117
|
-
// 免凭据实例(credentialRef=null)解析结果恒为空, 上述守卫不触发。
|
|
118
|
-
const work = Promise.resolve(adapter[method]({ ...request, providerInstanceId: instance.id, capability }, ctx))
|
|
119
|
-
const result = await new Promise((resolve, reject) => {
|
|
120
|
-
const aborted = () => reject(controller.signal.reason instanceof StockError ? controller.signal.reason : new StockError('CANCELLED', '请求已取消', 503))
|
|
121
|
-
controller.signal.addEventListener('abort', aborted, { once: true })
|
|
122
|
-
work.then(resolve, reject).finally(() => controller.signal.removeEventListener('abort', aborted))
|
|
123
|
-
if (controller.signal.aborted) aborted()
|
|
124
|
-
})
|
|
125
|
-
if (!used) budget.reserve(instance, capability, request.securities?.length || 1, !!options.periodic, !!options.probe)
|
|
126
|
-
record(instance.id, `${options.probe ? 'probe' : capability} ${instance.adapterId}`, 'ok', startedAt, !!options.probe)
|
|
127
|
-
return result
|
|
128
|
-
} catch (e) {
|
|
129
|
-
const code = e instanceof StockError ? e.code : 'NETWORK'
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
if (
|
|
133
|
-
if (e
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
}
|
|
1
|
+
import { StockError, fail } from './market-model.mjs'
|
|
2
|
+
// 每实例上游请求环形日志容量: 概览"最近请求"展示面
|
|
3
|
+
const REQUEST_LOG_LIMIT = 20
|
|
4
|
+
export function createExecutor({ registry, budget, env = process.env, resolveCredential = async ref => env[ref], fetch: fetchImpl = globalThis.fetch, proxyFetch = null, now = Date.now, timers = globalThis, usSymbols = new Map(), proxyFactory = null, tickPeriodMs = () => 0, tickCapabilities = ['quotes', 'kline', 'trend'] }) {
|
|
5
|
+
const queues = new Map(), controllers = new Set(), starts = new Map()
|
|
6
|
+
const requestLogs = new Map(), proxies = new Map()
|
|
7
|
+
let stopped = false, running = 0
|
|
8
|
+
// probe 标记只给后台探测用: 界面上的"最近请求"只该反映用户请求
|
|
9
|
+
const record = (instanceId, url, status, startedAt, probe = false, message = null) => {
|
|
10
|
+
const log = requestLogs.get(instanceId) || []
|
|
11
|
+
log.unshift({ at: now(), url: String(url), status, ms: Math.max(0, now() - startedAt), ...(message ? { message } : {}), ...(probe ? { probe: true } : {}) })
|
|
12
|
+
if (log.length > REQUEST_LOG_LIMIT) log.length = REQUEST_LOG_LIMIT
|
|
13
|
+
requestLogs.set(instanceId, log)
|
|
14
|
+
}
|
|
15
|
+
// 实例代理 dispatcher: 按代理 URL 惰性创建缓存(多实例共享同代理不重复建); proxyFactory 由宿主注入(undici ProxyAgent)
|
|
16
|
+
// dispatcher 是 undici 的私有契约, Node 内置 fetch 与 userland undici 版本错位时会直接 502:
|
|
17
|
+
// 配了代理就必须用同一份 undici.fetch 发请求; 任一组件缺失都明确报错, 不能静默直连泄露真实出口
|
|
18
|
+
const dispatcherFor = proxy => {
|
|
19
|
+
if (!proxy) return null
|
|
20
|
+
if (typeof proxyFactory !== 'function' || typeof proxyFetch !== 'function') fail('NETWORK', '代理出口不可用:缺少 undici 运行依赖', 502)
|
|
21
|
+
if (!proxies.has(proxy)) {
|
|
22
|
+
let dispatcher
|
|
23
|
+
try { dispatcher = proxyFactory(proxy) } catch (e) { fail('NETWORK', `代理出口不可用:${e.message}`, 502) }
|
|
24
|
+
if (!dispatcher) fail('NETWORK', '代理出口不可用:dispatcher 创建失败', 502)
|
|
25
|
+
proxies.set(proxy, dispatcher)
|
|
26
|
+
}
|
|
27
|
+
return proxies.get(proxy)
|
|
28
|
+
}
|
|
29
|
+
// 代理账号密码只从宿主凭据/环境变量取, 运行时注入 URL; 配置与快照里永远只有 proxyCredentialRef 引用
|
|
30
|
+
const proxyUrlOf = async instance => {
|
|
31
|
+
if (!instance.proxy) return null
|
|
32
|
+
if (!instance.proxyCredentialRef) return instance.proxy
|
|
33
|
+
const secret = await resolveCredential(instance.proxyCredentialRef)
|
|
34
|
+
if (!secret) fail('AUTH', '未配置代理凭据', 422)
|
|
35
|
+
const url = new URL(instance.proxy), separator = secret.indexOf(':')
|
|
36
|
+
url.username = separator < 0 ? secret : secret.slice(0, separator)
|
|
37
|
+
url.password = separator < 0 ? '' : secret.slice(separator + 1)
|
|
38
|
+
return url.toString()
|
|
39
|
+
}
|
|
40
|
+
// 组内节拍等待:上取整加裕度。setTimeout 对非整数 ms 向下取整且唤醒有抖动,
|
|
41
|
+
// 直接 setTimeout(gap) 会在 now-starts<间隔 时醒来,预算层同源时钟误判 RATE_LIMIT
|
|
42
|
+
// (CI 双架构高发竞态);唤醒后 now-starts>=间隔 恒成立,预算门恒过。
|
|
43
|
+
const THROTTLE_SLACK_MS = 5
|
|
44
|
+
const throttleDelay = gap => Math.ceil(gap) + THROTTLE_SLACK_MS
|
|
45
|
+
const waitFor = (ms, signal) => new Promise((resolve, reject) => {
|
|
46
|
+
const abort = () => { timers.clearTimeout(id); reject(new StockError('CANCELLED', '请求已取消', 503)) }
|
|
47
|
+
const id = timers.setTimeout(() => { signal.removeEventListener('abort', abort); resolve() }, ms)
|
|
48
|
+
signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort()
|
|
49
|
+
})
|
|
50
|
+
// 兜底节拍: 每个数据源实例一拍最多发一轮请求, 相邻两拍的启用时刻间隔不小于 tickPeriodMs。
|
|
51
|
+
// 一拍内允许多个请求连续发出(报价分批/分时/详情 K 线本来就是一拍的事), 所以只看拍的开拍时刻;
|
|
52
|
+
// 拍的前半段算同一拍, 后半段才封到下一拍 —— 否则同一拍的第二个请求会被推开整整一个周期。
|
|
53
|
+
// 探针与目录同步是一次性动作, 不受节拍约束(否则首次同步会被拖成每页等一个周期)。
|
|
54
|
+
const tickOpenedAt = new Map()
|
|
55
|
+
const tickDelay = (instance, capability, options) => {
|
|
56
|
+
if (options.probe || !tickCapabilities.includes(capability)) return 0
|
|
57
|
+
const period = tickPeriodMs()
|
|
58
|
+
if (!(period > 0)) return 0
|
|
59
|
+
const opened = tickOpenedAt.get(instance.id), at = now()
|
|
60
|
+
if (opened === undefined || at - opened >= period) { tickOpenedAt.set(instance.id, at); return 0 }
|
|
61
|
+
return at - opened > period / 2 ? opened + period - at : 0
|
|
62
|
+
}
|
|
63
|
+
const slots = []
|
|
64
|
+
async function acquire(signal) {
|
|
65
|
+
if (running < 2) { running++; return }
|
|
66
|
+
await new Promise((resolve, reject) => {
|
|
67
|
+
const slot = { resolve: () => { signal.removeEventListener('abort', abort); resolve() } }
|
|
68
|
+
const abort = () => { const i = slots.indexOf(slot); if (i >= 0) slots.splice(i, 1); reject(new StockError('CANCELLED', '请求已取消', 503)) }
|
|
69
|
+
slots.push(slot); signal.addEventListener('abort', abort, { once: true }); if (signal.aborted) abort()
|
|
70
|
+
})
|
|
71
|
+
}
|
|
72
|
+
function release() { if (slots.length) slots.shift().resolve(); else running-- }
|
|
73
|
+
return {
|
|
74
|
+
run(instance, capability, request, options = {}) {
|
|
75
|
+
const group = options.probe ? `${instance.quotaGroup}#probe` : instance.quotaGroup
|
|
76
|
+
const previous = queues.get(group) || Promise.resolve()
|
|
77
|
+
const job = previous.catch(() => {}).then(async () => {
|
|
78
|
+
if (stopped || options.signal?.aborted) fail('CANCELLED', '请求已取消', 503)
|
|
79
|
+
const controller = new AbortController(); controllers.add(controller)
|
|
80
|
+
const abort = () => controller.abort(options.signal?.reason)
|
|
81
|
+
options.signal?.addEventListener('abort', abort, { once: true })
|
|
82
|
+
let timeout, acquired = false
|
|
83
|
+
const startedAt = now()
|
|
84
|
+
try {
|
|
85
|
+
// 闸门放在实际发请求之前, 与 1 秒防连打一起构成两次等待: 先等节拍, 再等组内间隔。
|
|
86
|
+
// 等完再判一次: 等待期间别的请求可能已经开了新拍, 这里要跟着新拍走
|
|
87
|
+
for (let tick = tickDelay(instance, capability, options); tick; tick = tickDelay(instance, capability, options)) await waitFor(throttleDelay(tick), controller.signal)
|
|
88
|
+
const gap = Math.max(0, (starts.get(instance.quotaGroup) ?? -Infinity) + (instance.budget?.requestsPerMinute === null ? 10 * 1000 : 1000) - now())
|
|
89
|
+
if (gap) await waitFor(throttleDelay(gap), controller.signal)
|
|
90
|
+
await acquire(controller.signal); acquired = true
|
|
91
|
+
starts.set(instance.quotaGroup, now())
|
|
92
|
+
const adapter = registry.get(instance.adapterId), method = options.probe ? 'probe' : capability
|
|
93
|
+
if (typeof adapter[method] !== 'function') fail('UNSUPPORTED_CAPABILITY', '来源不支持该能力', 422)
|
|
94
|
+
let used = false
|
|
95
|
+
// 凭据每次操作解析一次, 不跨操作缓存: 存储层改了密钥, 下一次请求就生效, 不必重启插件。
|
|
96
|
+
// 解析在超时计时之前完成——读本地存储不该占用上游的 8 秒预算。
|
|
97
|
+
const secret = instance.credentialRef === null ? undefined : await resolveCredential(instance.credentialRef)
|
|
98
|
+
if (instance.credentialRef !== null && !secret) fail('AUTH', '未配置凭据', 422)
|
|
99
|
+
const proxyUrl = await proxyUrlOf(instance)
|
|
100
|
+
// 超时计时覆盖整个能力调用;分页适配器每次网络活动重置计时,空闲超过窗口才判超时。
|
|
101
|
+
const armTimeout = () => { timers.clearTimeout(timeout); timeout = timers.setTimeout(() => controller.abort(new StockError('TIMEOUT', '来源请求超时', 504, { retryable: true })), 8 * 1000) }
|
|
102
|
+
armTimeout()
|
|
103
|
+
const ctx = { now, signal: controller.signal, usSymbols, endpoints: instance.endpoints || null, credential: () => secret,
|
|
104
|
+
fetch: async (...args) => {
|
|
105
|
+
if (used) {
|
|
106
|
+
const gap = Math.max(0, starts.get(instance.quotaGroup) + (instance.budget?.requestsPerMinute === null ? 10 * 1000 : 1000) - now())
|
|
107
|
+
if (gap) await waitFor(throttleDelay(gap), controller.signal)
|
|
108
|
+
}
|
|
109
|
+
if (controller.signal.aborted) fail('CANCELLED', '请求已取消', 503)
|
|
110
|
+
armTimeout()
|
|
111
|
+
budget.reserve(instance, capability, request.securities?.length || 1, !!options.periodic, !!options.probe); used = true; starts.set(instance.quotaGroup, now())
|
|
112
|
+
const dispatcher = dispatcherFor(proxyUrl)
|
|
113
|
+
const response = await (dispatcher ? proxyFetch : fetchImpl)(args[0], { ...(args[1] || {}), ...(dispatcher ? { dispatcher } : {}) })
|
|
114
|
+
armTimeout()
|
|
115
|
+
return response
|
|
116
|
+
} }
|
|
117
|
+
// 免凭据实例(credentialRef=null)解析结果恒为空, 上述守卫不触发。
|
|
118
|
+
const work = Promise.resolve(adapter[method]({ ...request, providerInstanceId: instance.id, capability }, ctx))
|
|
119
|
+
const result = await new Promise((resolve, reject) => {
|
|
120
|
+
const aborted = () => reject(controller.signal.reason instanceof StockError ? controller.signal.reason : new StockError('CANCELLED', '请求已取消', 503))
|
|
121
|
+
controller.signal.addEventListener('abort', aborted, { once: true })
|
|
122
|
+
work.then(resolve, reject).finally(() => controller.signal.removeEventListener('abort', aborted))
|
|
123
|
+
if (controller.signal.aborted) aborted()
|
|
124
|
+
})
|
|
125
|
+
if (!used) budget.reserve(instance, capability, request.securities?.length || 1, !!options.periodic, !!options.probe)
|
|
126
|
+
record(instance.id, `${options.probe ? 'probe' : capability} ${instance.adapterId}`, 'ok', startedAt, !!options.probe)
|
|
127
|
+
return result
|
|
128
|
+
} catch (e) {
|
|
129
|
+
const code = e instanceof StockError ? e.code : 'NETWORK'
|
|
130
|
+
// 原因文案由适配器给出: 界面照着念, 不必猜是网络坏了还是被要求过人机验证
|
|
131
|
+
record(instance.id, `${options.probe ? 'probe' : capability} ${instance.adapterId}`, code, startedAt, !!options.probe, e?.message ?? null)
|
|
132
|
+
if (controller.signal.aborted && controller.signal.reason?.code === 'TIMEOUT') throw controller.signal.reason
|
|
133
|
+
if (e.code === 'RATE_LIMIT' && !options.probe) budget.block?.(instance, e.retryAfterMs || 60 * 1000)
|
|
134
|
+
if (e instanceof StockError) throw e
|
|
135
|
+
throw new StockError('NETWORK', '数据源请求失败', 502, { retryable: true })
|
|
136
|
+
} finally {
|
|
137
|
+
timers.clearTimeout(timeout); controllers.delete(controller); options.signal?.removeEventListener('abort', abort); if (acquired) release()
|
|
138
|
+
}
|
|
139
|
+
})
|
|
140
|
+
queues.set(group, job)
|
|
141
|
+
job.catch(() => {}).finally(() => { if (queues.get(group) === job) queues.delete(group) })
|
|
142
|
+
return job
|
|
143
|
+
},
|
|
144
|
+
recentRequests: instanceId => [...(requestLogs.get(instanceId) || [])],
|
|
145
|
+
// 有没有活干: 后台探测靠它避让, 不与用户请求抢并发槽和组链
|
|
146
|
+
idle: () => running === 0 && queues.size === 0,
|
|
147
|
+
dispose() { stopped = true; for (const c of controllers) c.abort(); controllers.clear() },
|
|
148
|
+
}
|
|
149
|
+
}
|
package/src/index.js
CHANGED
|
@@ -1,45 +1,45 @@
|
|
|
1
|
-
export const name = 'dsh-stock-assistant'
|
|
2
|
-
export const inject = ['webServer', 'storageDomain', 'credentials']
|
|
3
|
-
import { setupCommonTools, createChangeNotifier } from '@mzzsfy/dsh-common-tools/host'
|
|
4
|
-
import { createApplication } from './application.mjs'
|
|
5
|
-
import { registerRoutes } from './routes.mjs'
|
|
6
|
-
import { serveVendor, VENDOR_PREFIX, vendorReadable } from './serve-vendor.mjs'
|
|
7
|
-
import { withHostGate } from './route-gate.mjs'
|
|
8
|
-
export async function apply(ctx) {
|
|
9
|
-
if (typeof ctx.webServer?.register !== 'function' || typeof ctx.webServer?.registerUpgrade !== 'function' || typeof ctx.storageDomain?.open !== 'function') {
|
|
10
|
-
ctx.logger?.warn?.('股票工具已禁用:缺少webServer或storageDomain能力')
|
|
11
|
-
return
|
|
12
|
-
}
|
|
13
|
-
let disposed = false, application, stopRoutes, unsubscribe, notifier, bus
|
|
14
|
-
ctx.effect(() => () => {
|
|
15
|
-
disposed = true; stopRoutes?.(); unsubscribe?.(); notifier?.dispose()
|
|
16
|
-
return application?.close()
|
|
17
|
-
}, 'stock-assistant lifecycle')
|
|
18
|
-
try {
|
|
19
|
-
// vendor 可读性预判定先于应用构建: vendorAvailable=false 随快照下发→client 直接降级数字详情
|
|
20
|
-
let vendorAvailable = true
|
|
21
|
-
try { vendorAvailable = vendorReadable() } catch { vendorAvailable = false }
|
|
22
|
-
// 凭据服务由宿主提供; 接口不全时应用层会整体退回进程环境变量, 不因此拒绝启动
|
|
23
|
-
application = await createApplication({ storageDomain: ctx.storageDomain, credentials: ctx.credentials ?? null, publish: () => notifier?.refresh(), vendorAvailable })
|
|
24
|
-
if (disposed) { await application.close(); return }
|
|
25
|
-
bus = setupCommonTools(ctx)
|
|
26
|
-
notifier = createChangeNotifier(() => bus.publish({ type: 'invalidate', serverEpoch: application.snapshot().serverEpoch, snapshotSeq: application.snapshot().snapshotSeq }))
|
|
27
|
-
unsubscribe = bus.subscribe(message => { if (message?.type === 'watch-demand') application.demand(message) })
|
|
28
|
-
stopRoutes = registerRoutes(ctx.webServer, application, ctx)
|
|
29
|
-
// vendor 路由与业务路由同规: 必须登记 effect disposer(禁用/热重载时注销), 且首行回问宿主闸门。
|
|
30
|
-
// 注册异常仅告警: client ensureLwc 失败同样走降级路径。
|
|
31
|
-
ctx.effect(() => {
|
|
32
|
-
try { return ctx.webServer.register({ kind: 'prefix', path: VENDOR_PREFIX, handler: withHostGate(ctx, serveVendor) }) } catch (e) { ctx.logger?.warn?.('图表组件路由注册失败,详情将降级为数字详情'); return () => {} }
|
|
33
|
-
}, 'stock-assistant vendor route')
|
|
34
|
-
} catch (e) {
|
|
35
|
-
// 失败原因先落日志再清理: 清理自身抛错不能盖掉原始原因。
|
|
36
|
-
// 数据域的 invalid-record 只有表/键有用, 记录值不能进日志。
|
|
37
|
-
const location = e?.detail?.table === undefined ? '' : `,记录 ${e.detail.table}/${e.detail.key}`
|
|
38
|
-
const reason = e && typeof e === 'object' ? `${e.code ? `${e.code}: ` : ''}${e.message || String(e)}${location}` : String(e)
|
|
39
|
-
ctx.logger?.warn?.(`股票工具未激活:独立数据域或依赖初始化失败 (${reason})`)
|
|
40
|
-
// 逐步清理: 任一步抛错都不能跳过关闭应用, 否则数据域占位留在宿主里, 重载只会一直 already-open
|
|
41
|
-
for (const step of [() => stopRoutes?.(), () => unsubscribe?.(), () => notifier?.dispose(), () => application?.close()]) {
|
|
42
|
-
try { await step() } catch (cleanupError) { ctx.logger?.warn?.(`股票工具清理失败: ${cleanupError?.message || cleanupError}`) }
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
}
|
|
1
|
+
export const name = 'dsh-stock-assistant'
|
|
2
|
+
export const inject = ['webServer', 'storageDomain', 'credentials']
|
|
3
|
+
import { setupCommonTools, createChangeNotifier } from '@mzzsfy/dsh-common-tools/host'
|
|
4
|
+
import { createApplication } from './application.mjs'
|
|
5
|
+
import { registerRoutes } from './routes.mjs'
|
|
6
|
+
import { serveVendor, VENDOR_PREFIX, vendorReadable } from './serve-vendor.mjs'
|
|
7
|
+
import { withHostGate } from './route-gate.mjs'
|
|
8
|
+
export async function apply(ctx) {
|
|
9
|
+
if (typeof ctx.webServer?.register !== 'function' || typeof ctx.webServer?.registerUpgrade !== 'function' || typeof ctx.storageDomain?.open !== 'function') {
|
|
10
|
+
ctx.logger?.warn?.('股票工具已禁用:缺少webServer或storageDomain能力')
|
|
11
|
+
return
|
|
12
|
+
}
|
|
13
|
+
let disposed = false, application, stopRoutes, unsubscribe, notifier, bus
|
|
14
|
+
ctx.effect(() => () => {
|
|
15
|
+
disposed = true; stopRoutes?.(); unsubscribe?.(); notifier?.dispose()
|
|
16
|
+
return application?.close()
|
|
17
|
+
}, 'stock-assistant lifecycle')
|
|
18
|
+
try {
|
|
19
|
+
// vendor 可读性预判定先于应用构建: vendorAvailable=false 随快照下发→client 直接降级数字详情
|
|
20
|
+
let vendorAvailable = true
|
|
21
|
+
try { vendorAvailable = vendorReadable() } catch { vendorAvailable = false }
|
|
22
|
+
// 凭据服务由宿主提供; 接口不全时应用层会整体退回进程环境变量, 不因此拒绝启动
|
|
23
|
+
application = await createApplication({ storageDomain: ctx.storageDomain, credentials: ctx.credentials ?? null, publish: () => notifier?.refresh(), vendorAvailable })
|
|
24
|
+
if (disposed) { await application.close(); return }
|
|
25
|
+
bus = setupCommonTools(ctx)
|
|
26
|
+
notifier = createChangeNotifier(() => bus.publish({ type: 'invalidate', serverEpoch: application.snapshot().serverEpoch, snapshotSeq: application.snapshot().snapshotSeq }))
|
|
27
|
+
unsubscribe = bus.subscribe(message => { if (message?.type === 'watch-demand') application.demand(message) })
|
|
28
|
+
stopRoutes = registerRoutes(ctx.webServer, application, ctx)
|
|
29
|
+
// vendor 路由与业务路由同规: 必须登记 effect disposer(禁用/热重载时注销), 且首行回问宿主闸门。
|
|
30
|
+
// 注册异常仅告警: client ensureLwc 失败同样走降级路径。
|
|
31
|
+
ctx.effect(() => {
|
|
32
|
+
try { return ctx.webServer.register({ kind: 'prefix', path: VENDOR_PREFIX, handler: withHostGate(ctx, serveVendor) }) } catch (e) { ctx.logger?.warn?.('图表组件路由注册失败,详情将降级为数字详情'); return () => {} }
|
|
33
|
+
}, 'stock-assistant vendor route')
|
|
34
|
+
} catch (e) {
|
|
35
|
+
// 失败原因先落日志再清理: 清理自身抛错不能盖掉原始原因。
|
|
36
|
+
// 数据域的 invalid-record 只有表/键有用, 记录值不能进日志。
|
|
37
|
+
const location = e?.detail?.table === undefined ? '' : `,记录 ${e.detail.table}/${e.detail.key}`
|
|
38
|
+
const reason = e && typeof e === 'object' ? `${e.code ? `${e.code}: ` : ''}${e.message || String(e)}${location}` : String(e)
|
|
39
|
+
ctx.logger?.warn?.(`股票工具未激活:独立数据域或依赖初始化失败 (${reason})`)
|
|
40
|
+
// 逐步清理: 任一步抛错都不能跳过关闭应用, 否则数据域占位留在宿主里, 重载只会一直 already-open
|
|
41
|
+
for (const step of [() => stopRoutes?.(), () => unsubscribe?.(), () => notifier?.dispose(), () => application?.close()]) {
|
|
42
|
+
try { await step() } catch (cleanupError) { ctx.logger?.warn?.(`股票工具清理失败: ${cleanupError?.message || cleanupError}`) }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/provider-router.mjs
CHANGED
|
@@ -4,7 +4,8 @@ export const RECOVERY_PROBE_MS = 5 * 60 * 1000
|
|
|
4
4
|
// 探测退避上限: 一个实例连续探不通时, 间隔按倍数涨到这么久就不再涨
|
|
5
5
|
export const PROBE_BACKOFF_MAX_MS = 60 * 60 * 1000
|
|
6
6
|
// 触发降级的错误码: 别的错误码说明问题不在网络上, 换源也没用
|
|
7
|
-
|
|
7
|
+
// 人机验证也是端起端落: 过验证码就好, 与网络故障一样按轮计次, 攒满三轮切到备源
|
|
8
|
+
export const TRANSIENT_CODES = ['NETWORK', 'TIMEOUT', 'CHALLENGE']
|
|
8
9
|
export function createRouter(getConfig, now = Date.now, changed = () => {}) {
|
|
9
10
|
const states = new Map()
|
|
10
11
|
// 主源与备用源构成一个环: 顺序即优先级, 降级沿环往下走一格, 走到头回到主源
|