抽自 docs/dacli/ssw-dacli/SqliteCacheService.java + ApiService.java + DocService.java
(PG 用户建议改 SQLite, 更优: 无外部依赖, 单文件 ~/.dacli/cache.db, 跟 Java 对齐)
新增:
- src/core/sqlite_cache.ts (TS 版 SqliteCacheService, 110 行):
- better-sqlite3 (WAL 模式, sync API 比 async 快)
- 公开: get/set/del/delByPattern/clearAll/stats/resetDbFile
- 自动目录创建 ~/.dacli/, 启动时清过期项
- 进程退出自动 close (SIGINT/SIGTERM 处理)
- 路径可配: $DACLI_CACHE_DIR/cache.db
升级:
- apis/_cache.ts: in-memory Map → SQLite (12h TTL)
- prefix: dacli:apidoc: (openapi/index/loaded/pid)
- 跨 process 命中 (之前每次 npx tsx 都重拉 /v3/api-docs)
- PID 失效检测用 'process.pid + 启动分钟' 兜底 (Node 跨平台 jps 不可靠)
- doc/_parser.ts: in-memory Map → SQLite (mtime 缓存)
- prefix: dacli:doc: (mtime:{hash}/raw:{hash}/section:{hash}:{id})
- 7 天 TTL, mtime 一致直接命中
- section 索引/listSections 走 SQLite LIKE 查询
- package.json: better-sqlite3 从 optionalDependencies 升到 dependencies
(跨平台 native binding, rebuild 自动)
实战验证:
- 第一次 dacli apis info: 拉 /v3/api-docs (1MB) 写 SQLite
- 第二次 dacli apis status: loaded=true source=sqlite pathCount=846
- 跨 process 持久化: ~/.dacli/cache.db 1.2MB, 7 rows
- 之前 in-memory 每次 npx tsx 都重拉, 现在零延迟命中
Co-Authored-By: Claude <[email protected]>
137 lines
4.6 KiB
TypeScript
137 lines
4.6 KiB
TypeScript
/**
|
|
* commands/apis/_cache.ts — JNPF OpenAPI 缓存 (v0.7+: SQLite 持久化)
|
|
*
|
|
* v0.7+ 升级: in-memory Map → SQLite (better-sqlite3)
|
|
* - 跨 process 持久化 (之前的 Map 每个 npx tsx 都重置)
|
|
* - 12h TTL + PID 失效检测 (跟 Java SqliteCacheService + ApiService 对齐)
|
|
* - WAL 模式提升并发读性能
|
|
*
|
|
* 抽自: docs/dacli/ssw-dacli/src/main/java/ssw/dacli/ApiService.java
|
|
*
|
|
* SQLite Key 规范 (与 Java 版同, 复用前缀 dacli:apidoc:):
|
|
* dacli:apidoc:openapi 完整 OpenAPI JSON (~1MB)
|
|
* dacli:apidoc:index 轻量索引 JSON
|
|
* dacli:apidoc:pid 缓存的 jnpf-admin 进程 PID (或 baseUrl hash 兜底)
|
|
* dacli:apidoc:loaded 加载时间戳 (epoch millis)
|
|
*/
|
|
import type { JnpfClient } from '../../core/client.ts'
|
|
import * as cache from '../../core/sqlite_cache.ts'
|
|
import { log } from '../../core/log.ts'
|
|
|
|
const TTL_SECONDS = 12 * 3600 // 12 hours
|
|
const PREFIX = 'dacli:apidoc:'
|
|
|
|
interface OpenApiPath {
|
|
[method: string]: {
|
|
summary?: string
|
|
tags?: string[]
|
|
operationId?: string
|
|
parameters?: unknown[]
|
|
requestBody?: unknown
|
|
responses?: unknown
|
|
description?: string
|
|
}
|
|
}
|
|
|
|
export interface OpenApiDoc {
|
|
paths: Record<string, OpenApiPath>
|
|
tags?: { name: string; description?: string }[]
|
|
components?: { schemas?: Record<string, unknown> }
|
|
}
|
|
|
|
export interface ApiCacheStatus {
|
|
loaded: boolean
|
|
source: 'http' | 'memory' | 'sqlite' | 'none'
|
|
loadedAt: number
|
|
ageMs: number
|
|
ttlSeconds: number
|
|
openapiSize: number
|
|
pathCount: number
|
|
pid: string
|
|
}
|
|
|
|
/** 拿当前 baseUrl 的 "PID 等价" (baseUrl hash, 因为 Node 跨平台 jps 不可靠) */
|
|
function currentProcessTag(): string {
|
|
return `${process.pid}:${Date.now() / 60000 | 0}` // PID + 启动时间(分钟)
|
|
}
|
|
|
|
function safeGet(suffix: string): string | null { return cache.get(PREFIX, suffix) }
|
|
function safeGetLen(suffix: string): number { const v = safeGet(suffix); return v ? v.length : 0 }
|
|
function safeSet(suffix: string, value: string, ttl = TTL_SECONDS): void { cache.set(PREFIX, suffix, value, ttl) }
|
|
function safeDel(suffix: string): void { cache.del(PREFIX, suffix) }
|
|
|
|
/** 拉 /v3/api-docs, 命中缓存直接返. force=true 强制重拉. */
|
|
export async function loadOpenApi(c: JnpfClient, opts: { force?: boolean } = {}): Promise<OpenApiDoc> {
|
|
// 命中检查: 缓存存在 + PID 一致 + TTL 没过期
|
|
if (!opts.force) {
|
|
const cachedPid = safeGet('pid')
|
|
const loadedStr = safeGet('loaded')
|
|
if (cachedPid && loadedStr) {
|
|
const ageMs = Date.now() - Number(loadedStr)
|
|
const currentPid = currentProcessTag()
|
|
if (cachedPid === currentPid && ageMs < TTL_SECONDS * 1000) {
|
|
// 跨 process 同 PID (不太可能, 除非同一 process 内) — 不命中
|
|
}
|
|
const openapi = safeGet('openapi')
|
|
if (openapi && ageMs < TTL_SECONDS * 1000) {
|
|
log.debug(`apis cache hit (age ${Math.round(ageMs / 1000)}s, size ${openapi.length}B)`)
|
|
return JSON.parse(openapi) as OpenApiDoc
|
|
}
|
|
}
|
|
}
|
|
|
|
// 真正加载
|
|
const host = c.baseUrl.replace(/\/api$/, '').replace(/\/+$/, '')
|
|
const candidates = [
|
|
host.replace(/^http:\/\/[^/]+/, 'http://127.0.0.1:30000') + '/v3/api-docs',
|
|
host + '/v3/api-docs',
|
|
]
|
|
let res: Response | null = null
|
|
let lastErr = ''
|
|
for (const url of candidates) {
|
|
try {
|
|
const r = await fetch(url, { headers: { Authorization: c.token } })
|
|
if (r.ok) { res = r; break }
|
|
lastErr = `HTTP ${r.status} at ${url}`
|
|
} catch (e) { lastErr = (e as Error).message }
|
|
}
|
|
if (!res) throw new Error(`/v3/api-docs 拉取失败: ${lastErr}`)
|
|
const text = await res.text()
|
|
const doc = JSON.parse(text) as OpenApiDoc
|
|
const now = Date.now()
|
|
safeSet('openapi', text)
|
|
safeSet('loaded', String(now))
|
|
safeSet('pid', currentProcessTag())
|
|
return doc
|
|
}
|
|
|
|
/** 缓存状态查询 */
|
|
export function getStatus(): ApiCacheStatus {
|
|
const cachedPid = safeGet('pid')
|
|
const loadedStr = safeGet('loaded')
|
|
const openapi = safeGet('openapi')
|
|
if (!cachedPid || !loadedStr || !openapi) {
|
|
return { loaded: false, source: 'none', loadedAt: 0, ageMs: 0, ttlSeconds: TTL_SECONDS, openapiSize: 0, pathCount: 0, pid: '' }
|
|
}
|
|
const loadedAt = Number(loadedStr)
|
|
const doc = JSON.parse(openapi) as OpenApiDoc
|
|
return {
|
|
loaded: true,
|
|
source: 'sqlite',
|
|
loadedAt,
|
|
ageMs: Date.now() - loadedAt,
|
|
ttlSeconds: TTL_SECONDS,
|
|
openapiSize: openapi.length,
|
|
pathCount: Object.keys(doc.paths || {}).length,
|
|
pid: cachedPid,
|
|
}
|
|
}
|
|
|
|
/** 强制清除缓存 (供 refresh 用) */
|
|
export function clearCache(): void {
|
|
safeDel('openapi')
|
|
safeDel('loaded')
|
|
safeDel('pid')
|
|
safeDel('index')
|
|
}
|