feat(dacli): storage/* 模块 wrapCommand 迁移 (info/test/use, 5 exit 收口)

info 从旧 finally+printCommandEnd 升级 (无 appCode 跳过 L3, DacliError throw 被 wrapCommand catch).
test 批量连通测试用 ctx.partial (fail>0). use 纯 yml 无 appCode, process.exit → ctx.fail/success.
storage/ 模块 process.exit 归零.

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
sswandClaude committed 2026-07-21 21:05:16 +08:00
1 parent 2a1fd000a6
commit 2795d7f2db
3 files changed
+169 -143

No files matched your search

+42 -49
View File
@@ -5,7 +5,7 @@ import { Command } from 'commander'
import { readStorageConfig, defaultYmlPath, maskPlatform } from './_helpers.ts'
import { log, printJson } from '../../core/log.ts'
import { installHelpHook } from '../../core/help.ts'
import { setupOutputFilter, addOutputOptions, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘 (无 appCode, 跳过 L3 落盘, 仅 L1 summary)
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤 (无 appCode, 跳过 L3); v2.2+ wrapCommand 收口 5c
import { DacliError } from '../../core/types.ts'
interface InfoOpts {
@@ -26,57 +26,50 @@ export function buildStorageInfoCommand(): Command {
.action(async (platform: string, opts: InfoOpts) => {
// 输出过滤: 默认静默
setupOutputFilter(opts)
const startTime = Date.now()
let cmdError: string | undefined
let cmdSummary: Record<string, unknown> = { platform }
try {
const ymlPath = opts.yml || defaultYmlPath(opts.profile)
const cfg = readStorageConfig(ymlPath)
const found = cfg.platforms.find((p) => p.name === platform)
if (!found) {
const avail = cfg.platforms.map((p) => p.name).join(', ') || '(无)'
throw new DacliError(`platform '${platform}' 不在 yml 中, 可用: ${avail}`)
}
const masked = maskPlatform(found)
cmdSummary = {
platform,
type: found.type,
isDefault: found.name === cfg.defaultPlatform,
yml: ymlPath,
}
if (opts.json) {
printJson({
yml: ymlPath,
await wrapCommand({
command: 'storage info',
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
const ymlPath = opts.yml || defaultYmlPath(opts.profile)
const cfg = readStorageConfig(ymlPath)
const found = cfg.platforms.find((p) => p.name === platform)
if (!found) {
const avail = cfg.platforms.map((p) => p.name).join(', ') || '(无)'
throw new DacliError(`platform '${platform}' 不在 yml 中, 可用: ${avail}`)
}
const masked = maskPlatform(found)
const cmdSummary = {
platform,
type: found.type,
isDefault: found.name === cfg.defaultPlatform,
platform: masked,
})
return
yml: ymlPath,
}
if (opts.json) {
printJson({
yml: ymlPath,
isDefault: found.name === cfg.defaultPlatform,
platform: masked,
})
return ctx.success(cmdSummary)
}
log.info(`platform: ${found.name} type: ${found.type} active: ${found.name === cfg.defaultPlatform ? '✓' : '✗'}`)
log.info(`yml-path: ${found.ymlPath}`)
console.log('')
const maxKeyLen = Math.max(...Object.keys(masked.raw).map((k) => k.length))
for (const [k, v] of Object.entries(masked.raw)) {
const key = k.padEnd(maxKeyLen + 2)
console.log(` ${key} ${JSON.stringify(v)}`)
}
ctx.success(cmdSummary)
} catch (e) {
ctx.fail(`storage info 失败: ${(e as Error).message?.slice(0, 200)}`, { platform })
}
log.info(`platform: ${found.name} type: ${found.type} active: ${found.name === cfg.defaultPlatform ? '✓' : '✗'}`)
log.info(`yml-path: ${found.ymlPath}`)
console.log('')
const maxKeyLen = Math.max(...Object.keys(masked.raw).map((k) => k.length))
for (const [k, v] of Object.entries(masked.raw)) {
const key = k.padEnd(maxKeyLen + 2)
console.log(` ${key} ${JSON.stringify(v)}`)
}
} catch (e) {
cmdError = (e as Error).message?.slice(0, 200)
log.error(`storage info 失败: ${cmdError}`)
} finally {
// v2.1+ (2026-07-21): 输出 CommandLog (无 appCode, 跳过 L3 落盘, 仅 L1 summary)
printCommandEnd({
command: 'storage info',
result: cmdError ? 'failure' : 'success',
error: cmdError,
summary: cmdSummary,
duration_ms: Date.now() - startTime,
verbose: opts.verbose,
json: opts.json,
})
if (cmdError) process.exit(1)
}
})
})
installHelpHook(cmd, {
purpose: '显示某 platform 的详细配置 (access-key / secret-key 等敏感字段自动脱敏)',
+82 -63
View File
@@ -15,12 +15,15 @@ import { readStorageConfig, defaultYmlPath } from './_helpers.ts'
import { log, printJson } from '../../core/log.ts'
import { installHelpHook } from '../../core/help.ts'
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤; v2.2+ wrapCommand 收口 5c
interface TestOpts {
profile?: string
yml?: string
type?: string
json?: boolean
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
verbose?: boolean
}
export function buildStorageTestCommand(): Command {
@@ -30,75 +33,91 @@ export function buildStorageTestCommand(): Command {
.option('--profile <p>', 'spring profile (默认 dev)', 'dev')
.option('--yml <path>', '显式 yml 路径')
.option('--type <t>', '只测某 type, 如 aliyun-oss/minio (默认全测启用的)')
.option('--json', '原始 JSON 输出', false)
addOutputOptions(cmd)
.action(async (platform: string | undefined, opts: TestOpts) => {
const ymlPath = opts.yml || defaultYmlPath(opts.profile)
const cfg = readStorageConfig(ymlPath)
setupOutputFilter(opts)
const c = await JnpfClient.fromToken()
const targets = platform
? cfg.platforms.filter((p) => p.name === platform)
: cfg.platforms.filter((p) =>
opts.type ? p.type === opts.type : p.enableStorage,
)
if (targets.length === 0) {
const enhanced = enhanceFromBackend('未找到匹配 platform 配置', 'platform', { entity: 'storage' })
log.error(` ${formatErrorLine(enhanced, { step: 0, stepName: '配置检查' })}`)
process.exit(2)
}
const results: Array<{ platform: string; type: string; ok: boolean; msg: string; ms: number }> = []
for (const p of targets) {
// JNPF Uploader 端点的 {type} 路径参数是任意标识 (database 用 'database' / avatar 用 'avatar')
// 这里用 platform type 名, 后端按 default-platform 走对应后端
const testType = p.type
const t0 = Date.now()
await wrapCommand({
command: 'storage test',
appCode: c.appCode,
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
const tmpDir = mkdtempSync(join(tmpdir(), 'dacli-storage-'))
const testFile = join(tmpDir, 'dacli-storage-test.txt')
writeFileSync(testFile, `dacli storage test ${new Date().toISOString()}\n`, 'utf-8')
const buf = readFileSync(testFile)
const blob = new Blob([buf], { type: 'text/plain' })
const fd = new FormData()
fd.append('file', blob, 'dacli-storage-test.txt')
const url = `${c.baseUrl}/file/Uploader/${encodeURIComponent(testType)}`
const res = await fetch(url, {
method: 'POST',
headers: {
Authorization: c.token,
'App-Code': c.appCode,
},
body: fd,
})
unlinkSync(testFile)
rmdirSync(tmpDir)
const text = await res.text()
let parsed: any = null
try { parsed = JSON.parse(text) } catch { /* 留空 */ }
const ms = Date.now() - t0
if (res.ok && (parsed?.code === 200 || parsed === null)) {
results.push({ platform: p.name, type: p.type, ok: true, msg: `upload ok (${res.status})`, ms })
log.info(`✓ ${p.name} (${p.type}) ${ms}ms`)
} else {
const msg = parsed?.msg || text.slice(0, 200) || `HTTP ${res.status}`
results.push({ platform: p.name, type: p.type, ok: false, msg, ms })
log.error(`✗ ${p.name} (${p.type}) ${msg}`)
const ymlPath = opts.yml || defaultYmlPath(opts.profile)
const cfg = readStorageConfig(ymlPath)
const targets = platform
? cfg.platforms.filter((p) => p.name === platform)
: cfg.platforms.filter((p) =>
opts.type ? p.type === opts.type : p.enableStorage,
)
if (targets.length === 0) {
const enhanced = enhanceFromBackend('未找到匹配 platform 配置', 'platform', { entity: 'storage' })
log.error(` ${formatErrorLine(enhanced, { step: 0, stepName: '配置检查' })}`)
return ctx.fail('未找到匹配 platform 配置', { platform, type: opts.type })
}
const results: Array<{ platform: string; type: string; ok: boolean; msg: string; ms: number }> = []
for (const p of targets) {
// JNPF Uploader 端点的 {type} 路径参数是任意标识 (database 用 'database' / avatar 用 'avatar')
// 这里用 platform type 名, 后端按 default-platform 走对应后端
const testType = p.type
const t0 = Date.now()
try {
const tmpDir = mkdtempSync(join(tmpdir(), 'dacli-storage-'))
const testFile = join(tmpDir, 'dacli-storage-test.txt')
writeFileSync(testFile, `dacli storage test ${new Date().toISOString()}\n`, 'utf-8')
const buf = readFileSync(testFile)
const blob = new Blob([buf], { type: 'text/plain' })
const fd = new FormData()
fd.append('file', blob, 'dacli-storage-test.txt')
const url = `${c.baseUrl}/file/Uploader/${encodeURIComponent(testType)}`
const res = await fetch(url, {
method: 'POST',
headers: {
Authorization: c.token,
'App-Code': c.appCode,
},
body: fd,
})
unlinkSync(testFile)
rmdirSync(tmpDir)
const text = await res.text()
let parsed: any = null
try { parsed = JSON.parse(text) } catch { /* 留空 */ }
const ms = Date.now() - t0
if (res.ok && (parsed?.code === 200 || parsed === null)) {
results.push({ platform: p.name, type: p.type, ok: true, msg: `upload ok (${res.status})`, ms })
log.info(`✓ ${p.name} (${p.type}) ${ms}ms`)
} else {
const msg = parsed?.msg || text.slice(0, 200) || `HTTP ${res.status}`
results.push({ platform: p.name, type: p.type, ok: false, msg, ms })
log.error(`✗ ${p.name} (${p.type}) ${msg}`)
}
} catch (e) {
const ms = Date.now() - t0
const msg = (e as Error).message
results.push({ platform: p.name, type: p.type, ok: false, msg, ms })
log.error(`✗ ${p.name} (${p.type}) ${msg}`)
}
}
if (opts.json) {
printJson({ yml: ymlPath, results })
}
const fail = results.filter((r) => !r.ok).length
const summary = { total: results.length, failed: fail }
if (fail > 0) {
log.error(`共 ${results.length} 个, ${fail} 个失败`)
return ctx.partial(`${fail}/${results.length} 个 platform 连通测试失败`, summary)
}
log.info(`共 ${results.length} 个全部通过`)
ctx.success(summary)
} catch (e) {
const ms = Date.now() - t0
const msg = (e as Error).message
results.push({ platform: p.name, type: p.type, ok: false, msg, ms })
log.error(`✗ ${p.name} (${p.type}) ${msg}`)
ctx.fail(`storage test 失败: ${(e as Error).message?.slice(0, 200)}`)
}
}
if (opts.json) {
printJson({ yml: ymlPath, results })
return
}
const fail = results.filter((r) => !r.ok).length
if (fail > 0) {
log.error(`共 ${results.length} 个, ${fail} 个失败`)
process.exit(1)
}
log.info(`共 ${results.length} 个全部通过`)
})
})
installHelpHook(cmd, {
purpose: '测试存储后端连通性 — 走 JNPF /api/file/Uploader/{type} 上传 1KB 测试文件',
+45 -31
View File
@@ -10,12 +10,16 @@ import { Command } from 'commander'
import { readStorageConfig, defaultYmlPath, writeDefaultPlatform, backupYml } from './_helpers.ts'
import { log } from '../../core/log.ts'
import { installHelpHook } from '../../core/help.ts'
import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_filter.ts' // v2.1+ 输出过滤 (无 appCode, 跳过 L3); v2.2+ wrapCommand 收口 5c
interface UseOpts {
profile?: string
yml?: string
/** --no-backup 触发, commander 会把 flag 反向解析到 opts.backup = false */
backup?: boolean
json?: boolean
/** v2.1+ (2026-07-21): --verbose, addOutputOptions 注入 */
verbose?: boolean
}
export function buildStorageUseCommand(): Command {
@@ -25,38 +29,48 @@ export function buildStorageUseCommand(): Command {
.option('--profile <p>', 'spring profile (默认 dev)', 'dev')
.option('--yml <path>', '显式 yml 路径')
.option('--no-backup', '跳过备份 (不推荐)')
addOutputOptions(cmd)
.action(async (platform: string, opts: UseOpts) => {
const ymlPath = opts.yml || defaultYmlPath(opts.profile)
const cfg = readStorageConfig(ymlPath)
if (cfg.defaultPlatform === platform) {
log.info(`已是 default-platform = ${platform}, 无需切换`)
return
}
const found = cfg.platforms.find((p) => p.name === platform)
if (!found) {
const avail = cfg.platforms.map((p) => `${p.name} (${p.type})`).join(', ') || '(无)'
log.error(`platform '${platform}' 不在 yml 中, 可用: ${avail}`)
process.exit(2)
}
if (!found.enableStorage) {
log.warn(`platform '${platform}' (${found.type}) enable-storage=false, 切换后可能上传失败`)
log.warn(` 建议先用 \`dacli storage test ${platform}\` 验证连通性`)
}
if (opts.backup !== false) {
const bak = backupYml(ymlPath)
log.info(`✓ 已备份: ${bak}`)
}
try {
writeDefaultPlatform(ymlPath, platform)
log.info(`✓ ${ymlPath}: default-platform: ${cfg.defaultPlatform} → ${platform}`)
log.info('')
log.info('请手动重启 JNPF 生效:')
log.info(' dacli app init --restart # 自动 kill + nohup + 健康检查 + 重登')
log.info(' # 或: pkill -f jnpf-admin && nohup java -jar ... &')
} catch (e) {
log.error(`写 yml 失败: ${(e as Error).message}`)
process.exit(1)
}
setupOutputFilter(opts)
await wrapCommand({
command: 'storage use',
startTime: Date.now(),
verbose: opts.verbose,
json: opts.json,
fixes: [],
}, async (ctx) => {
try {
const ymlPath = opts.yml || defaultYmlPath(opts.profile)
const cfg = readStorageConfig(ymlPath)
if (cfg.defaultPlatform === platform) {
log.info(`已是 default-platform = ${platform}, 无需切换`)
return ctx.success({ platform, changed: false })
}
const found = cfg.platforms.find((p) => p.name === platform)
if (!found) {
const avail = cfg.platforms.map((p) => `${p.name} (${p.type})`).join(', ') || '(无)'
return ctx.fail(`platform '${platform}' 不在 yml 中, 可用: ${avail}`, { platform })
}
if (!found.enableStorage) {
log.warn(`platform '${platform}' (${found.type}) enable-storage=false, 切换后可能上传失败`)
log.warn(` 建议先用 \`dacli storage test ${platform}\` 验证连通性`)
}
if (opts.backup !== false) {
const bak = backupYml(ymlPath)
log.info(`✓ 已备份: ${bak}`)
}
writeDefaultPlatform(ymlPath, platform)
log.info(`✓ ${ymlPath}: default-platform: ${cfg.defaultPlatform} → ${platform}`)
log.info('')
log.info('请手动重启 JNPF 生效:')
log.info(' dacli app init --restart # 自动 kill + nohup + 健康检查 + 重登')
log.info(' # 或: pkill -f jnpf-admin && nohup java -jar ... &')
ctx.success({ platform, changed: true, from: cfg.defaultPlatform })
} catch (e) {
ctx.fail(`storage use 失败: ${(e as Error).message?.slice(0, 200)}`, { platform })
}
})
})
installHelpHook(cmd, {
purpose: '切换 file-storage.default-platform — 改 yml + 备份 + 提示手动重启',