@zxlll/dsh-integration-env 0.0.0-stage → 0.1.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/lib/nacos.js ADDED
@@ -0,0 +1,561 @@
1
+ /**
2
+ * Nacos 只读连接器:`fetch` + `AbortSignal.timeout`,不依赖第三方 SDK。
3
+ *
4
+ * `baseUrl` 已含 `/nacos` 上下文路径,因此直接拼 `/v1/...`、`/v3/...`(契约 §7.2)。
5
+ * accessToken 进程内缓存,按 tokenTtl 过期;token 失效时失效缓存并重登一次。
6
+ *
7
+ * 版本兼容(实测 Nacos 3.0.3):
8
+ * - 2.x,以及打开了 `nacos.core.api.compatibility.console.enabled=true` 的 3.x,走 v1 接口;
9
+ * - 纯 3.x 上 v1 控制台接口返回 HTTP 410(提示迁移),业务接口实际落在 **`/v3/admin/*`**。
10
+ * 部分文档写的是 `/v3/console/*`,但该部署上 `/v3/console/*` 一律 404,
11
+ * 因此每个动作都按 v1 → v3 console → v3 admin 依次尝试,谁能用用谁。
12
+ * - 3.x 的 v3 接口把业务数据包在 `{ code, message, data }` 里,且**业务失败时 HTTP 仍是 200**
13
+ * (配置不存在 = `code:20004`),所以必须校验 `code`,绝不能拿响应体当数据返回。
14
+ */
15
+ const DEFAULT_TIMEOUT_MS = 8000
16
+ const DEFAULT_TOKEN_TTL_SECONDS = 18000
17
+ const DEFAULT_PAGE_NO = 1
18
+ const DEFAULT_PAGE_SIZE = 20
19
+ const MAX_PAGE_SIZE = 200
20
+ const DEFAULT_GROUP = 'DEFAULT_GROUP'
21
+ /** Nacos 3.x 业务码:资源不存在(此时 HTTP 仍为 200)。 */
22
+ const CODE_RESOURCE_NOT_FOUND = 20004
23
+
24
+ /** baseUrl + username → `{ token, expiresAt }`。 */
25
+ const TOKEN_CACHE = new Map()
26
+
27
+ function userError(code, message) {
28
+ const error = new Error(message)
29
+ error.code = code
30
+ return error
31
+ }
32
+
33
+ function isPlainObject(value) {
34
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
35
+ }
36
+
37
+ /** 去掉末尾斜杠,并在缺少协议时补 http://。 */
38
+ export function normalizeBaseUrl(value) {
39
+ let url = String(value ?? '').trim()
40
+ if (!url) return ''
41
+ url = url.replace(/\/+$/, '')
42
+ if (!/^https?:\/\//i.test(url)) url = `http://${url}`
43
+ return url
44
+ }
45
+
46
+ /** fetch 包装:统一超时与中文错误。 */
47
+ async function doFetch(url, options = {}) {
48
+ try {
49
+ return await fetch(url, { ...options, signal: AbortSignal.timeout(DEFAULT_TIMEOUT_MS) })
50
+ } catch (error) {
51
+ if (error?.name === 'TimeoutError' || error?.name === 'AbortError') {
52
+ throw userError('connection-failed', `请求 Nacos 超时(${DEFAULT_TIMEOUT_MS}ms):${url}。请检查地址与网络。`)
53
+ }
54
+ throw userError('connection-failed', `无法连接 Nacos(${url}):${error?.message ?? String(error)}。请检查地址与网络。`)
55
+ }
56
+ }
57
+
58
+ /**
59
+ * 把一次失败的 HTTP 响应归类,决定「换下一个候选路径」还是「立刻上报」。
60
+ * - `auth`:登录/权限问题,换路径没用,立即抛。
61
+ * - `not-found`:接口可用但资源不存在(配置/服务没有),继续试别的版本路径确认。
62
+ * - `deprecated`:410,接口在这个版本已废弃。
63
+ * - `unsupported`:404 且不像业务错误,说明该部署没有这个版本的接口。
64
+ * - `other`:其它(5xx、参数错误等),继续试。
65
+ */
66
+ function classifyHttpFailure(status, text) {
67
+ if (status === 401) return 'auth'
68
+ if (status === 403) return 'auth'
69
+ if (status === 404) {
70
+ // Spring 的「没有这个路由」:说明该部署没有这个版本的接口。
71
+ if (/No endpoint|No message available|Whitelabel/i.test(text)) return 'unsupported'
72
+ // 业务层的「不存在」:v1 的 get_config 返回纯文本,v3 用 code:20004 / code:30000 + not found 描述。
73
+ if (/config data not exist|resource not found|"code"\s*:\s*20004/i.test(text)) return 'not-found'
74
+ if (/"code"\s*:\s*\d+/.test(text) && /not\s*found|not\s*exist|不存在/i.test(text)) return 'not-found'
75
+ return 'unsupported'
76
+ }
77
+ if (status === 410) return 'deprecated'
78
+ if (status === 405 || status === 501) return 'unsupported'
79
+ return 'other'
80
+ }
81
+
82
+ /** 把失败响应翻成中文说明(带状态码、路径与响应体前 500 字符)。 */
83
+ function describeFailure(status, text, label, path, kind) {
84
+ const body = text.slice(0, 500) || '(空响应)'
85
+ const where = path ? `${path} ` : ''
86
+ // 403 authorization failed:登录是成功的,是这个账号没有该资源的权限,必须提示去授权。
87
+ if (status === 403 && /authorization failed/i.test(text)) {
88
+ return `Nacos ${label}失败:登录已通过,但该账号没有 ${where}的权限(HTTP 403 authorization failed)。`
89
+ + '请在 Nacos 控制台的「权限控制」里给该用户/角色授予对应命名空间的读权限,或改用管理员账号。'
90
+ + `原始响应:${body}`
91
+ }
92
+ // 401 / 403 User not found:没带 token 或 token 失效。
93
+ if (status === 401 || (status === 403 && /User not found/i.test(text))) {
94
+ return `Nacos ${label}失败:鉴权未通过(HTTP ${status} ${where}),请检查用户名和密码。原始响应:${body}`
95
+ }
96
+ // 404 + 业务码:资源(配置/服务/实例)不存在,而不是接口不存在。
97
+ if (kind === 'not-found') {
98
+ return `Nacos ${label}失败:目标资源不存在(HTTP ${status} ${where})。原始响应:${body}`
99
+ }
100
+ // 410 Gone:Nacos 3.x 已废弃该 v1 接口,响应体会给出建议路径。
101
+ if (status === 410) {
102
+ const suggestion = /use API\(s\)\s*`([^`]+)`/i.exec(text)
103
+ const hint = suggestion
104
+ ? ` 服务端建议改用:${suggestion[1].replace('${contextPath:nacos}', '')};若该路径返回 404,说明这个部署把接口放在 /v3/admin/* 下。`
105
+ : ' 该接口在当前 Nacos 版本已废弃。'
106
+ return `Nacos ${label}失败:接口已废弃(HTTP 410 ${where})。${hint}原始响应:${body}`
107
+ }
108
+ if (status === 404) {
109
+ return `Nacos ${label}失败:该部署没有这个接口(HTTP 404 ${where})。原始响应:${body}`
110
+ }
111
+ return `Nacos ${label}失败(HTTP ${status} ${where}):${body}`
112
+ }
113
+
114
+ /** 构造带分类信息的 HTTP 失败错误,供 requestFirst 决定是否继续下一个候选。 */
115
+ function httpFailure(status, text, label, path) {
116
+ const kind = classifyHttpFailure(status, text)
117
+ const error = userError(
118
+ kind === 'not-found' ? 'not-found' : 'connection-failed',
119
+ describeFailure(status, text, label, path, kind),
120
+ )
121
+ error.status = status
122
+ error.nacosFailure = { kind, retryNext: kind !== 'auth' }
123
+ return error
124
+ }
125
+
126
+ /** 读响应体文本;超时/中断翻成中文错误。 */
127
+ async function readBodyText(response, label) {
128
+ try {
129
+ return await response.text()
130
+ } catch (error) {
131
+ if (error?.name === 'TimeoutError' || error?.name === 'AbortError') {
132
+ throw userError('connection-failed', `读取 Nacos ${label}响应超时(${DEFAULT_TIMEOUT_MS}ms)。`)
133
+ }
134
+ throw userError('connection-failed', `读取 Nacos ${label}响应失败:${error?.message ?? String(error)}`)
135
+ }
136
+ }
137
+
138
+ /** 解析响应体:JSON 优先,失败时当纯文本(v1 的 get_config 直接返回配置正文)。 */
139
+ function parseBody(text) {
140
+ if (!text) return { text: '', data: null }
141
+ try {
142
+ return { text, data: JSON.parse(text) }
143
+ } catch {
144
+ return { text, data: text }
145
+ }
146
+ }
147
+
148
+ /**
149
+ * token 缓存键。必须含密码:用户改了密码后,旧 token 不该继续被复用
150
+ * (否则会一直拿旧凭据成功,让人误以为改密码没生效)。
151
+ */
152
+ function tokenCacheKey(baseUrl, username, password) {
153
+ return `${baseUrl}\u0000${username}\u0000${password}`
154
+ }
155
+
156
+ /**
157
+ * 发一次登录请求。Nacos 的登录接口只接受 **表单编码**(`application/x-www-form-urlencoded`),
158
+ * 传 JSON 会报 "Required parameter 'username' is not present",因此这里用 URLSearchParams。
159
+ */
160
+ async function postLoginForm(baseUrl, path, username, password) {
161
+ const response = await doFetch(`${baseUrl}${path}`, {
162
+ method: 'POST',
163
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
164
+ body: new URLSearchParams({ username, password }).toString(),
165
+ })
166
+ const text = await readBodyText(response, '登录')
167
+ if (!response.ok) throw httpFailure(response.status, text, '登录', path)
168
+ return parseBody(text).data
169
+ }
170
+
171
+ /** 登录并缓存 token;force=true 时忽略缓存。 */
172
+ async function login(baseUrl, username, password, force = false) {
173
+ const cacheKey = tokenCacheKey(baseUrl, username, password)
174
+ if (!force) {
175
+ const cached = TOKEN_CACHE.get(cacheKey)
176
+ if (cached && cached.expiresAt > Date.now()) return cached.token
177
+ }
178
+ // Nacos 1.x/2.x 用 /v1/auth/login;3.x 起用户登录改到 /v1/auth/users/login。
179
+ // 先试前者,拿不到 accessToken 再试后者;两个都不行时抛第一个错误(更贴近真实原因)。
180
+ let data = null
181
+ let firstError = null
182
+ try {
183
+ data = await postLoginForm(baseUrl, '/v1/auth/login', username, password)
184
+ } catch (error) {
185
+ firstError = error
186
+ }
187
+ if (!data || typeof data !== 'object' || !data.accessToken) {
188
+ try {
189
+ data = await postLoginForm(baseUrl, '/v1/auth/users/login', username, password)
190
+ } catch (error) {
191
+ throw firstError ?? error
192
+ }
193
+ }
194
+ const token = data && typeof data === 'object' ? data.accessToken : undefined
195
+ if (!token) {
196
+ throw userError('connection-failed', 'Nacos 登录失败:响应里没有 accessToken,请检查用户名和密码。')
197
+ }
198
+ const ttl = Number(data.tokenTtl) > 0 ? Number(data.tokenTtl) : DEFAULT_TOKEN_TTL_SECONDS
199
+ TOKEN_CACHE.set(cacheKey, {
200
+ token: String(token),
201
+ // 提前 60s 过期,避免临界失效。
202
+ expiresAt: Date.now() + Math.max(60, ttl - 60) * 1000,
203
+ })
204
+ return String(token)
205
+ }
206
+
207
+ /**
208
+ * 带 token 的 GET/POST。username/password 任一非空时先登录。
209
+ * 「token 失效」时清缓存重登一次;「403 权限不足」重登没用,直接按失败上报。
210
+ */
211
+ async function nacosRequest(config, path, params = {}, options = {}) {
212
+ const baseUrl = normalizeBaseUrl(config.baseUrl)
213
+ if (!baseUrl) throw userError('bad-request', '实例缺少 Nacos 服务地址(baseUrl),请先在面板里补全。')
214
+ const username = String(config.username ?? '')
215
+ const password = String(config.password ?? '')
216
+ const hasCredentials = Boolean(username || password)
217
+ const label = options.label ?? '请求'
218
+
219
+ const buildUrl = (token) => {
220
+ const url = new URL(`${baseUrl}${path}`)
221
+ for (const [key, value] of Object.entries(params)) {
222
+ if (value === undefined || value === null || value === '') continue
223
+ url.searchParams.set(key, String(value))
224
+ }
225
+ if (token) url.searchParams.set('accessToken', token)
226
+ return url
227
+ }
228
+
229
+ const run = async (token) => {
230
+ const response = await doFetch(buildUrl(token), {
231
+ method: options.method ?? 'GET',
232
+ ...(options.body === undefined ? {} : {
233
+ headers: { 'content-type': 'application/json' },
234
+ body: JSON.stringify(options.body),
235
+ }),
236
+ })
237
+ return { response, text: await readBodyText(response, label) }
238
+ }
239
+
240
+ let token = hasCredentials ? await login(baseUrl, username, password) : ''
241
+ let outcome = await run(token)
242
+ const { status, text } = { status: outcome.response.status, text: outcome.text }
243
+ // 只有「token 无效/User not found」才值得重登;纯授权不足重登没用。
244
+ const tokenProblem = status === 401 || (status === 403 && !/authorization failed/i.test(text))
245
+ if (hasCredentials && tokenProblem) {
246
+ TOKEN_CACHE.delete(tokenCacheKey(baseUrl, username, password))
247
+ token = await login(baseUrl, username, password, true)
248
+ outcome = await run(token)
249
+ }
250
+ if (!outcome.response.ok) {
251
+ throw httpFailure(outcome.response.status, outcome.text, label, path)
252
+ }
253
+ return { baseUrl, path, ...parseBody(outcome.text) }
254
+ }
255
+
256
+ /**
257
+ * 解包 3.x 的 `{ code, message, data }` 信封,并**校验业务码**。
258
+ * 关键:3.x 业务失败也返回 HTTP 200,不校验 code 就会把错误当数据返回(历史 bug)。
259
+ * 2.x 没有 `code` 字段,原样返回。
260
+ */
261
+ function unwrapPayload(data, label, path) {
262
+ if (!isPlainObject(data) || typeof data.code !== 'number') return data
263
+ if (data.code === 0) return data.data
264
+ const message = String(data.message ?? '').trim() || `业务码 ${data.code}`
265
+ const notFound = data.code === CODE_RESOURCE_NOT_FOUND
266
+ const isAuth = /forbidden|authoriz|auth failed|token/i.test(message)
267
+ const error = userError(
268
+ notFound ? 'not-found' : 'connection-failed',
269
+ notFound
270
+ ? `Nacos ${label}失败:${path} 返回「resource not found」(业务码 ${CODE_RESOURCE_NOT_FOUND})。`
271
+ : `Nacos ${label}失败:${path} 返回业务码 ${data.code}(${message})。`,
272
+ )
273
+ error.nacosCode = data.code
274
+ error.nacosFailure = { kind: notFound ? 'not-found' : isAuth ? 'auth' : 'other', retryNext: !isAuth }
275
+ throw error
276
+ }
277
+
278
+ function requiredString(value, message) {
279
+ const text = String(value ?? '').trim()
280
+ if (!text) throw userError('bad-request', message)
281
+ return text
282
+ }
283
+
284
+ function pageNoOf(value) {
285
+ const number = Number(value)
286
+ return Number.isFinite(number) && number > 0 ? Math.trunc(number) : DEFAULT_PAGE_NO
287
+ }
288
+
289
+ function pageSizeOf(value) {
290
+ const number = Number(value)
291
+ if (!Number.isFinite(number)) return DEFAULT_PAGE_SIZE
292
+ return Math.min(MAX_PAGE_SIZE, Math.max(1, Math.trunc(number)))
293
+ }
294
+
295
+ /**
296
+ * 依次尝试多个 `{ path, params }` 候选(兼容 Nacos 2.x 的 v1 与 3.x 的 v3 路径)。
297
+ * `options.parse(data, ctx)` 可以抛错(例如业务码校验),其 `nacosFailure.retryNext` 决定是否继续下一候选。
298
+ * 全部失败时优先抛「资源不存在」,其次「410 废弃」,最后才是第一个错误,并在末尾列出已尝试的路径。
299
+ */
300
+ async function requestFirst(config, candidates, label, options = {}) {
301
+ const attempted = []
302
+ let firstError = null
303
+ let deprecatedError = null
304
+ let notFoundError = null
305
+ for (const candidate of candidates) {
306
+ attempted.push(candidate.path)
307
+ try {
308
+ const result = await nacosRequest(config, candidate.path, candidate.params ?? {}, { label })
309
+ if (!options.parse) return result
310
+ return { ...result, parsed: await options.parse(result, candidate) }
311
+ } catch (error) {
312
+ if (!firstError) firstError = error
313
+ const kind = error?.nacosFailure?.kind
314
+ // 鉴权/权限问题换路径也没用。
315
+ if (kind === 'auth') throw error
316
+ if (kind === 'not-found') {
317
+ notFoundError = error
318
+ continue
319
+ }
320
+ if (kind === 'deprecated') deprecatedError = error
321
+ }
322
+ }
323
+ const failure = notFoundError ?? deprecatedError ?? firstError
324
+ const suffix = attempted.length > 1 ? `(已尝试:${attempted.join('、')})` : ''
325
+ const error = userError(failure?.code ?? 'connection-failed', `${failure?.message ?? `Nacos ${label}失败。`}${suffix}`)
326
+ error.nacosFailure = failure?.nacosFailure
327
+ throw error
328
+ }
329
+
330
+ /** 从解包后的载荷里取配置正文;取不到就报错,绝不把响应信封当正文返回。 */
331
+ function pickConfigContent(payload, path) {
332
+ if (typeof payload === 'string') return payload
333
+ if (isPlainObject(payload)) {
334
+ for (const key of ['content', 'configInfo', 'configValue']) {
335
+ const value = payload[key]
336
+ if (typeof value === 'string') return value
337
+ }
338
+ }
339
+ throw userError(
340
+ 'connection-failed',
341
+ `Nacos 读取配置失败:${path} 的响应里没有 content 字段,无法识别响应结构。`,
342
+ )
343
+ }
344
+
345
+ /** get_config 的候选路径:v1(2.x / 3.x 兼容模式)→ v3 client → v3 admin。 */
346
+ function fetchConfig(config, dataId, group, namespace) {
347
+ return requestFirst(config, [
348
+ { path: '/v1/cs/configs', params: { dataId, group, tenant: namespace } },
349
+ { path: '/v3/client/cs/config', params: { dataId, groupName: group, namespaceId: namespace } },
350
+ { path: '/v3/admin/cs/config', params: { dataId, groupName: group, namespaceId: namespace } },
351
+ ], '读取配置', {
352
+ parse: (result) => ({
353
+ content: pickConfigContent(unwrapPayload(result.data, '读取配置', result.path), result.path),
354
+ path: result.path,
355
+ }),
356
+ })
357
+ }
358
+
359
+ /**
360
+ * 分组回退策略:只有「调用方没有显式传 group」时才允许回退到 DEFAULT_GROUP。
361
+ * 实例的 group 最常见的填错方式就是填成命名空间名,而配置几乎都在 DEFAULT_GROUP 下。
362
+ * 显式传了 group 就不许悄悄换分组——那是调用方的意图,答非所问比报错更糟。
363
+ */
364
+ function groupFallbackInfo(config, payload, namespace) {
365
+ const explicit = String(payload.group ?? '').trim()
366
+ const configured = String(config.group ?? '').trim() || DEFAULT_GROUP
367
+ const group = explicit || configured
368
+ const canFallback = !explicit && group !== DEFAULT_GROUP
369
+ return { group, canFallback, namespace }
370
+ }
371
+
372
+ function groupFallbackWarning(config, group) {
373
+ return `实例「${config?.name ?? ''}」配置的分组是「${group}」,但该分组下没有目标资源;`
374
+ + '已自动改用 DEFAULT_GROUP 读到结果。这通常是把命名空间名填成了分组,'
375
+ + '建议到右侧「集成环境」把分组改回 DEFAULT_GROUP。'
376
+ }
377
+
378
+ /**
379
+ * 连接器统一入口:`run(instance, payload)` → 结果对象;失败抛 Error。
380
+ * @param payload - `{ action, dataId?, group?, namespace?, serviceName?, pageNo?, pageSize? }`。
381
+ */
382
+ export async function runNacos(instance, payload = {}) {
383
+ const config = instance?.config ?? {}
384
+ const baseUrl = normalizeBaseUrl(config.baseUrl)
385
+ if (!baseUrl) throw userError('bad-request', `实例「${instance?.name ?? ''}」缺少 Nacos 服务地址,请先在面板里补全。`)
386
+ const action = String(payload.action ?? '')
387
+ const defaultGroup = String(payload.group ?? config.group ?? '').trim() || DEFAULT_GROUP
388
+ const defaultNamespace = String(payload.namespace ?? config.namespace ?? '').trim()
389
+
390
+ switch (action) {
391
+ case 'get_config': {
392
+ const dataId = requiredString(payload.dataId, 'get_config 动作需要 dataId 参数。')
393
+ const { group, canFallback, namespace } = groupFallbackInfo(config, payload, defaultNamespace)
394
+ const attempt = async (targetGroup) => fetchConfig(config, dataId, targetGroup, namespace)
395
+ let found
396
+ try {
397
+ found = await attempt(group)
398
+ } catch (error) {
399
+ if (error?.code !== 'not-found') throw error
400
+ // 诊断增强:分组填成了命名空间名时,同一 dataId 往往能在 DEFAULT_GROUP 下读到。
401
+ const fallback = canFallback ? await attempt(DEFAULT_GROUP).catch(() => null) : null
402
+ if (fallback) {
403
+ return {
404
+ action,
405
+ dataId,
406
+ group: DEFAULT_GROUP,
407
+ requestedGroup: group,
408
+ namespace,
409
+ content: fallback.parsed.content,
410
+ path: fallback.parsed.path,
411
+ warning: groupFallbackWarning(config, group),
412
+ }
413
+ }
414
+ if (group !== DEFAULT_GROUP && !canFallback) {
415
+ throw userError(
416
+ 'not-found',
417
+ `Nacos 配置 ${dataId} 在分组「${group}」下不存在(命名空间=${namespace || 'public'})。`
418
+ + '这是调用时显式指定的分组,因此没有自动改用别的分组。'
419
+ + `请确认分组是否正确;多数配置在 DEFAULT_GROUP 下(可显式传 group=DEFAULT_GROUP 重试)。`,
420
+ )
421
+ }
422
+ throw userError(
423
+ 'not-found',
424
+ `Nacos 配置 ${dataId} 不存在(分组=${group},命名空间=${namespace || 'public'})。`
425
+ + '请核对 dataId 是否写全(含 .yml/.properties 后缀)、分组是否为 DEFAULT_GROUP、命名空间是否正确。',
426
+ )
427
+ }
428
+ return {
429
+ action,
430
+ dataId,
431
+ group,
432
+ namespace,
433
+ content: found.parsed.content,
434
+ path: found.parsed.path,
435
+ }
436
+ }
437
+ case 'list_namespaces': {
438
+ const result = await requestFirst(config, [
439
+ { path: '/v1/console/namespaces' },
440
+ { path: '/v3/console/core/namespace/list' },
441
+ { path: '/v3/admin/core/namespace/list' },
442
+ ], '读取命名空间', {
443
+ parse: (r) => {
444
+ const data = unwrapPayload(r.data, '读取命名空间', r.path)
445
+ return Array.isArray(data)
446
+ ? data
447
+ : Array.isArray(data?.namespace)
448
+ ? data.namespace
449
+ : Array.isArray(data?.namespaceList)
450
+ ? data.namespaceList
451
+ : []
452
+ },
453
+ })
454
+ return { action, namespaces: result.parsed }
455
+ }
456
+ case 'list_services': {
457
+ const pageNo = pageNoOf(payload.pageNo)
458
+ const pageSize = pageSizeOf(payload.pageSize)
459
+ const namespaceId = defaultNamespace
460
+ const result = await requestFirst(config, [
461
+ { path: '/v1/ns/service/list', params: { pageNo, pageSize, namespaceId } },
462
+ { path: '/v3/console/ns/service/list', params: { pageNo, pageSize, namespaceId } },
463
+ { path: '/v3/admin/ns/service/list', params: { pageNo, pageSize, namespaceId } },
464
+ ], '读取服务列表', {
465
+ parse: (r) => unwrapPayload(r.data, '读取服务列表', r.path),
466
+ })
467
+ const data = result.parsed
468
+ const services = Array.isArray(data)
469
+ ? data
470
+ : Array.isArray(data?.doms)
471
+ ? data.doms
472
+ : Array.isArray(data?.services)
473
+ ? data.services
474
+ : Array.isArray(data?.pageItems)
475
+ ? data.pageItems
476
+ : []
477
+ const count = Number(data?.count ?? data?.totalCount)
478
+ return {
479
+ action,
480
+ pageNo,
481
+ pageSize,
482
+ namespaceId,
483
+ count: Number.isFinite(count) ? count : services.length,
484
+ services,
485
+ }
486
+ }
487
+ case 'list_instances': {
488
+ const serviceName = requiredString(payload.serviceName, 'list_instances 动作需要 serviceName 参数。')
489
+ const { group: groupName, canFallback, namespace: namespaceId } = groupFallbackInfo(config, payload, defaultNamespace)
490
+ const hostsOf = (data) => (Array.isArray(data?.hosts)
491
+ ? data.hosts
492
+ : Array.isArray(data?.instances)
493
+ ? data.instances
494
+ : Array.isArray(data?.pageItems)
495
+ ? data.pageItems
496
+ : Array.isArray(data)
497
+ ? data
498
+ : [])
499
+ const query = async (group) => hostsOf((await requestFirst(config, [
500
+ { path: '/v1/ns/catalog/instances', params: { serviceName, groupName: group, namespaceId } },
501
+ {
502
+ path: '/v3/console/ns/instance/list',
503
+ params: { serviceName, groupName: group, namespaceId, pageNo: 1, pageSize: MAX_PAGE_SIZE },
504
+ },
505
+ {
506
+ path: '/v3/admin/ns/instance/list',
507
+ params: { serviceName, groupName: group, namespaceId, pageNo: 1, pageSize: MAX_PAGE_SIZE },
508
+ },
509
+ ], '读取服务实例', { parse: (r) => unwrapPayload(r.data, '读取服务实例', r.path) })).parsed)
510
+
511
+ let hosts
512
+ try {
513
+ hosts = await query(groupName)
514
+ } catch (error) {
515
+ if (error?.code !== 'not-found') throw error
516
+ // 诊断增强:分组填成了命名空间名时,服务往往注册在 DEFAULT_GROUP 下。
517
+ const fallback = canFallback ? await query(DEFAULT_GROUP).catch(() => null) : null
518
+ if (fallback && fallback.length > 0) {
519
+ return {
520
+ action,
521
+ serviceName,
522
+ groupName: DEFAULT_GROUP,
523
+ requestedGroup: groupName,
524
+ namespaceId,
525
+ hosts: fallback,
526
+ warning: groupFallbackWarning(config, groupName),
527
+ }
528
+ }
529
+ throw userError(
530
+ 'not-found',
531
+ `Nacos 服务 ${serviceName} 不存在(分组=${groupName},命名空间=${namespaceId || 'public'})。`
532
+ + '请先用 list_services 确认服务名与分组。',
533
+ )
534
+ }
535
+ return { action, serviceName, groupName, namespaceId, hosts }
536
+ }
537
+ case 'login_only': {
538
+ // 只验证「账号能不能登录」,不碰任何控制台/数据接口(供连通测试用)。
539
+ const username = String(config.username ?? '')
540
+ const password = String(config.password ?? '')
541
+ if (!username && !password) return { action, authenticated: false }
542
+ await login(baseUrl, username, password)
543
+ return { action, authenticated: true }
544
+ }
545
+ case 'server_info': {
546
+ const result = await requestFirst(config, [
547
+ { path: '/v1/console/server/state' },
548
+ { path: '/v3/console/server/state' },
549
+ { path: '/v3/admin/core/state' },
550
+ ], '读取服务状态', {
551
+ parse: (r) => unwrapPayload(r.data, '读取服务状态', r.path),
552
+ })
553
+ return { action, state: result.parsed }
554
+ }
555
+ default:
556
+ throw userError(
557
+ 'bad-request',
558
+ `未知的 nacos 动作「${action}」,可用:get_config / list_namespaces / list_services / list_instances / server_info。`,
559
+ )
560
+ }
561
+ }
package/lib/probe.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 连通性探测:TCP 建连延迟 + 超时,供 mongodb / mqtt 这类 v1 只做端口探测的 kind 使用。
3
+ * 另外导出 withTimeout,供 index.js 的实例测试统一加超时。
4
+ */
5
+ import net from 'node:net'
6
+
7
+ /** 给任意 promise 加超时;超时抛中文 Error。 */
8
+ export function withTimeout(promise, timeoutMs, message) {
9
+ let timer
10
+ const timeout = new Promise((_resolve, reject) => {
11
+ timer = setTimeout(() => {
12
+ const error = new Error(message)
13
+ error.code = 'connection-failed'
14
+ reject(error)
15
+ }, timeoutMs)
16
+ if (typeof timer.unref === 'function') timer.unref()
17
+ })
18
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer))
19
+ }
20
+
21
+ /** 把网络错误翻成中文(探测场景尽量短)。 */
22
+ function describeNetError(error, host, port) {
23
+ switch (error?.code) {
24
+ case 'ECONNREFUSED':
25
+ return `连接被拒绝(${host}:${port},端口未监听)`
26
+ case 'ENOTFOUND':
27
+ case 'EAI_AGAIN':
28
+ return `无法解析主机「${host}」`
29
+ case 'ECONNRESET':
30
+ return `连接被重置(${host}:${port})`
31
+ case 'ETIMEDOUT':
32
+ return `连接超时(${host}:${port})`
33
+ default:
34
+ return `${host}:${port} 连接失败:${error?.message ?? String(error)}`
35
+ }
36
+ }
37
+
38
+ /**
39
+ * 探测 host:port 是否可建连。
40
+ * @returns `{ ok, latencyMs, error }`,永不 reject。
41
+ */
42
+ export function tcpProbe(host, port, timeoutMs = 2000) {
43
+ return new Promise((resolve) => {
44
+ const startedAt = Date.now()
45
+ let settled = false
46
+ const socket = net.createConnection({ host, port })
47
+ socket.setNoDelay?.(true)
48
+
49
+ let timer = null
50
+ const finish = (result) => {
51
+ if (settled) return
52
+ settled = true
53
+ if (timer) clearTimeout(timer)
54
+ try {
55
+ socket.destroy()
56
+ } catch {
57
+ // 忽略销毁异常。
58
+ }
59
+ resolve(result)
60
+ }
61
+
62
+ timer = setTimeout(() => {
63
+ finish({ ok: false, latencyMs: timeoutMs, error: `连接超时(${timeoutMs}ms):${host}:${port}` })
64
+ }, timeoutMs)
65
+ if (typeof timer.unref === 'function') timer.unref()
66
+
67
+ socket.once('connect', () => {
68
+ finish({ ok: true, latencyMs: Date.now() - startedAt, error: null })
69
+ })
70
+ socket.once('error', (error) => {
71
+ finish({ ok: false, latencyMs: Date.now() - startedAt, error: describeNetError(error, host, port) })
72
+ })
73
+ })
74
+ }