@cmach_socket/opencode-qq-bot 0.3.4 → 0.6.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/src/instance.ts CHANGED
@@ -1,14 +1,18 @@
1
1
  /**
2
- * Cross-reload singleton registry.
2
+ * 进程内单实例注册表。
3
3
  *
4
- * OpenCode may load a plugin again without invoking the previous instance's
5
- * cleanup, which would leave duplicate WebSocket connections and duplicate
6
- * message handlers behind. The registry lives on globalThis so it survives
7
- * module reloads within the same server process.
4
+ * 同一台机器上只允许一个插件实例:OpenCode 可能为不同项目目录加载插件,
5
+ * 新实例会接管旧实例并让旧实例整体卸载,避免同时存在多条 NapCat 连接
6
+ * 与重复的消息处理。注册表挂在 globalThis 上,模块重载后依然有效。
7
+ *
8
+ * 槽位绑定到机器人固定的工作目录:只有同一目录的实例才能互相接管,
9
+ * 否则会话上下文会落在不同项目里。
8
10
  */
9
11
 
10
12
  export interface PluginInstance {
11
13
  dispose?: () => Promise<void>
14
+ /** 实例来源描述,仅用于日志。 */
15
+ label?: string
12
16
  }
13
17
 
14
18
  export interface InstanceLease {
@@ -18,8 +22,16 @@ export interface InstanceLease {
18
22
  release(): void
19
23
  }
20
24
 
25
+ export interface InstanceClaim {
26
+ /** 同一工作目录下被接管的旧实例。 */
27
+ previous?: PluginInstance
28
+ /** 槽位已被其它工作目录占用时给出该目录,调用方应停止运行。 */
29
+ occupied?: string
30
+ lease: InstanceLease
31
+ }
32
+
21
33
  interface Host {
22
- active?: { key: string; instance: PluginInstance }
34
+ active?: { directory: string; instance: PluginInstance }
23
35
  }
24
36
 
25
37
  const HOST_KEY = "__opencodeQQBotHost__"
@@ -34,20 +46,21 @@ function host(): Host {
34
46
  }
35
47
 
36
48
  /**
37
- * Claims the singleton slot for `key` and returns any previous instance with
38
- * the same key so the caller can dispose it. Instances with different keys
39
- * (for example another project) are left untouched.
49
+ * 占用进程内唯一的实例槽位。
50
+ *
51
+ * @param directory 机器人固定服务的工作目录。
52
+ * @param label 实例来源描述,通常是项目目录与 NapCat 地址,仅用于日志。
40
53
  */
41
- export function claimInstance(key: string): {
42
- previous: PluginInstance | undefined
43
- lease: InstanceLease
44
- } {
54
+ export function claimInstance(directory: string, label: string): InstanceClaim {
45
55
  const state = host()
46
- const previous = state.active?.key === key ? state.active.instance : undefined
47
- const instance: PluginInstance = {}
48
- state.active = { key, instance }
56
+ const active = state.active
57
+ if (active && active.directory !== directory) {
58
+ return { occupied: active.directory, lease: { setDispose() {}, release() {} } }
59
+ }
60
+ const instance: PluginInstance = { label }
61
+ state.active = { directory, instance }
49
62
  return {
50
- previous,
63
+ previous: active?.instance,
51
64
  lease: {
52
65
  setDispose(dispose) {
53
66
  instance.dispose = dispose
@@ -0,0 +1,222 @@
1
+ import type { Plugin } from "@opencode/plugin"
2
+ import type { QQBotConfig } from "./config"
3
+ import type { Logger } from "./logger"
4
+
5
+ /** 插件存储里保存保活会话 ID 的键。 */
6
+ export const KEEP_ALIVE_SESSION_KEY = "keepalive-session"
7
+ /** 会话标记:用来找回已经建好的保活会话。 */
8
+ export const KEEP_ALIVE_SESSION_MARKER = "qqKeepAliveSession"
9
+ /** 保活会话标题。 */
10
+ export const KEEP_ALIVE_TITLE = "QQ 保活"
11
+
12
+ type SessionListCursor = NonNullable<Parameters<Plugin.Context["session"]["list"]>[0]>["cursor"]
13
+
14
+ /**
15
+ * 保活心跳:让 OpenCode 不要因为长时间没有会话活动而卸载插件。
16
+ *
17
+ * OpenCode 按 location 统计会话活动,默认空闲 60 分钟后卸载该 location 的服务,
18
+ * 插件随之被卸载,NapCat 连接断开后机器人就不再响应。
19
+ * 写回一次会话元数据会发布 durable 的 `session.metadata.updated` 事件,
20
+ * 事件带着插件所在 location,于是该 location 的空闲计时被重置。
21
+ */
22
+ export class KeepAlive {
23
+ private timer: ReturnType<typeof setInterval> | undefined
24
+ private sessionID: string | undefined
25
+ private creating: Promise<string> | undefined
26
+ private stopped = false
27
+
28
+ constructor(
29
+ private readonly ctx: Plugin.Context,
30
+ private readonly config: QQBotConfig,
31
+ private readonly logger: Logger,
32
+ ) {}
33
+
34
+ /** 启动保活心跳。 */
35
+ start(): void {
36
+ if (this.timer || !this.config.keepAlive.enabled) return
37
+ void this.ping()
38
+ this.timer = setInterval(() => {
39
+ void this.ping()
40
+ }, this.config.keepAlive.seconds * 1000)
41
+ const handle = this.timer as { unref?: () => void }
42
+ handle.unref?.()
43
+ }
44
+
45
+ /**
46
+ * 停止保活心跳,并删掉保活会话。
47
+ *
48
+ * 会话只服务于保活,插件卸载后留着它只会在项目目录里留下垃圾,
49
+ * 所以卸载时顺手删掉,存储里的记录也一起清掉。
50
+ */
51
+ async dispose(): Promise<void> {
52
+ this.stopped = true
53
+ if (this.timer) clearInterval(this.timer)
54
+ this.timer = undefined
55
+ const sessionID = this.sessionID
56
+ this.sessionID = undefined
57
+ if (!sessionID) return
58
+ try {
59
+ await this.ctx.session.remove({ sessionID })
60
+ this.logger.info(`保活会话 ${sessionID} 已删除`)
61
+ } catch (error) {
62
+ this.logger.warn("删除保活会话失败", error)
63
+ }
64
+ await this.clearStoredSession(sessionID)
65
+ }
66
+
67
+ /**
68
+ * 写回一次会话元数据,刷新 location 的空闲计时。
69
+ *
70
+ * 元数据是整体替换的,所以先读出当前值再原样写回。
71
+ */
72
+ async ping(): Promise<void> {
73
+ if (this.stopped) return
74
+ let sessionID: string
75
+ try {
76
+ sessionID = await this.ensureSession()
77
+ } catch (error) {
78
+ this.logger.warn("保活心跳失败:取不到保活会话", error)
79
+ return
80
+ }
81
+ if (this.stopped) return
82
+
83
+ let metadata: NonNullable<Parameters<Plugin.Context["session"]["update"]>[0]["metadata"]>
84
+ try {
85
+ const info = await this.ctx.session.get({ sessionID })
86
+ metadata = info?.metadata ?? { [KEEP_ALIVE_SESSION_MARKER]: true }
87
+ } catch (error) {
88
+ // 会话已经被删除:丢掉缓存,下一次心跳重建一个。
89
+ this.logger.warn("保活会话已失效,将重建", error)
90
+ this.sessionID = undefined
91
+ return
92
+ }
93
+
94
+ try {
95
+ await this.ctx.session.update({ sessionID, metadata })
96
+ this.logger.debug(`保活心跳已刷新会话 ${sessionID}`)
97
+ } catch (error) {
98
+ this.logger.warn("保活心跳失败", error)
99
+ }
100
+ }
101
+
102
+ /** 取得(必要时创建)保活会话;并发调用串行执行,避免重复建会话。 */
103
+ private async ensureSession(): Promise<string> {
104
+ if (this.sessionID) return this.sessionID
105
+ this.creating ??= this.resolveSession().finally(() => {
106
+ this.creating = undefined
107
+ })
108
+ return this.creating
109
+ }
110
+
111
+ private async resolveSession(): Promise<string> {
112
+ const stored = await this.readStoredSession()
113
+ if (stored) {
114
+ this.sessionID = stored
115
+ await this.ensureArchived(stored)
116
+ return stored
117
+ }
118
+ const found = await this.findKeepAliveSession()
119
+ if (found) {
120
+ this.sessionID = found
121
+ await this.writeStoredSession(found)
122
+ await this.ensureArchived(found)
123
+ this.logger.info(`复用保活会话 ${found}`)
124
+ return found
125
+ }
126
+ const created = await this.ctx.session.create({
127
+ title: KEEP_ALIVE_TITLE,
128
+ metadata: { [KEEP_ALIVE_SESSION_MARKER]: true },
129
+ })
130
+ this.sessionID = created.id
131
+ await this.writeStoredSession(created.id)
132
+ await this.ensureArchived(created.id)
133
+ this.logger.info(`新建保活会话 ${created.id}`)
134
+ return created.id
135
+ }
136
+
137
+ /**
138
+ * 归档保活会话,让它不出现在会话列表里。
139
+ *
140
+ * 上游的插件接口目前只处理 title/metadata/permissions,archived 会被忽略,
141
+ * 所以调用之后要再读一次,确认到底有没有归档成功。
142
+ */
143
+ private async ensureArchived(sessionID: string): Promise<void> {
144
+ try {
145
+ await this.ctx.session.update({ sessionID, archived: true })
146
+ } catch (error) {
147
+ this.logger.debug("归档保活会话失败", error)
148
+ return
149
+ }
150
+ try {
151
+ const info = await this.ctx.session.get({ sessionID })
152
+ if (info?.time?.archived !== undefined) {
153
+ this.logger.info(`保活会话 ${sessionID} 已归档`)
154
+ } else {
155
+ this.logger.info(`上游未支持归档保活会话 ${sessionID},它会显示在会话列表里`)
156
+ }
157
+ } catch (error) {
158
+ this.logger.debug("确认保活会话归档状态失败", error)
159
+ }
160
+ }
161
+
162
+ /** 读取上次保存的保活会话;会话已经不存在或属于别的目录时返回 undefined。 */
163
+ private async readStoredSession(): Promise<string | undefined> {
164
+ try {
165
+ const stored = await this.ctx.storage.get(KEEP_ALIVE_SESSION_KEY)
166
+ if (typeof stored !== "string" || stored.length === 0) return undefined
167
+ const info = await this.ctx.session.get({ sessionID: stored })
168
+ // 插件存储是机器级共享的,别的目录留下的会话不能拿来用。
169
+ if (info?.location?.directory !== this.ctx.location.directory) {
170
+ this.logger.debug(`存储里的保活会话 ${stored} 不在当前目录,忽略`)
171
+ return undefined
172
+ }
173
+ return stored
174
+ } catch (error) {
175
+ this.logger.debug("读取保活会话失败,将新建会话", error)
176
+ return undefined
177
+ }
178
+ }
179
+
180
+ /** 查找带保活标记的历史会话。 */
181
+ private async findKeepAliveSession(): Promise<string | undefined> {
182
+ let cursor: SessionListCursor | undefined
183
+ try {
184
+ for (let page = 0; page < 5; page += 1) {
185
+ const result = await this.ctx.session.list({
186
+ directory: this.ctx.location.directory,
187
+ limit: 100,
188
+ order: "desc",
189
+ ...(cursor ? { cursor } : {}),
190
+ })
191
+ const hit = result.data.find(
192
+ (session) => session.metadata?.[KEEP_ALIVE_SESSION_MARKER] === true,
193
+ )
194
+ if (hit) return hit.id
195
+ cursor = result.cursor.next ?? undefined
196
+ if (!cursor) break
197
+ }
198
+ } catch (error) {
199
+ this.logger.warn("查找保活会话失败", error)
200
+ }
201
+ return undefined
202
+ }
203
+
204
+ private async writeStoredSession(sessionID: string): Promise<void> {
205
+ try {
206
+ await this.ctx.storage.set(KEEP_ALIVE_SESSION_KEY, sessionID)
207
+ } catch (error) {
208
+ this.logger.warn("保存保活会话失败", error)
209
+ }
210
+ }
211
+
212
+ /** 清掉存储里的会话记录;记录已经被别的项目改写时不动它。 */
213
+ private async clearStoredSession(sessionID: string): Promise<void> {
214
+ try {
215
+ const stored = await this.ctx.storage.get(KEEP_ALIVE_SESSION_KEY)
216
+ if (stored !== sessionID) return
217
+ await this.ctx.storage.remove(KEEP_ALIVE_SESSION_KEY)
218
+ } catch (error) {
219
+ this.logger.warn("清除保活会话记录失败", error)
220
+ }
221
+ }
222
+ }
package/src/logger.ts CHANGED
@@ -1,7 +1,19 @@
1
- export type LogLevel = "debug" | "info" | "warn" | "error"
1
+ import { fsyncSync, mkdirSync } from "node:fs"
2
+ import { homedir } from "node:os"
3
+ import { isAbsolute, join } from "node:path"
4
+ import { inspect } from "node:util"
5
+ import winston from "winston"
6
+ import DailyRotateFile from "winston-daily-rotate-file"
7
+ import { maskSecrets } from "./sensitive"
2
8
 
3
- const LEVEL_ORDER: Record<LogLevel, number> = { debug: 10, info: 20, warn: 30, error: 40 }
9
+ /** 日志级别。 */
10
+ export type LogLevel = "debug" | "info" | "warn" | "error"
4
11
 
12
+ /**
13
+ * 日志器。
14
+ *
15
+ * 只有级别和消息,附加信息用 `...meta` 传,调用点与旧的 console 实现一致。
16
+ */
5
17
  export interface Logger {
6
18
  debug(message: string, ...meta: unknown[]): void
7
19
  info(message: string, ...meta: unknown[]): void
@@ -9,22 +21,266 @@ export interface Logger {
9
21
  error(message: string, ...meta: unknown[]): void
10
22
  }
11
23
 
12
- /** 创建带前缀的日志器,插件运行在 OpenCode 服务端,直接写 stdout/stderr。 */
13
- export function createLogger(prefix: string, level: LogLevel = "info"): Logger {
14
- const threshold = LEVEL_ORDER[level]
15
- const write = (lvl: LogLevel, stream: "log" | "error", message: string, meta: unknown[]) => {
16
- if (LEVEL_ORDER[lvl] < threshold) return
17
- const stamp = new Date().toISOString()
18
- const line = `[${stamp}] ${lvl.toUpperCase()} ${prefix} ${message}`
19
- const details = meta.filter((entry) => entry !== undefined)
20
- if (details.length > 0) console[stream](line, ...details)
21
- else console[stream](line)
24
+ /** 日志器选项。 */
25
+ export interface LoggerOptions {
26
+ /** 最低输出级别,默认 info。 */
27
+ level?: LogLevel
28
+ /** 是否写日志文件,默认 true。 */
29
+ file?: boolean
30
+ /** 日志目录,空表示用 XDG 状态目录。 */
31
+ dir?: string
32
+ /** 单个日志文件的大小上限,默认 5m。 */
33
+ maxSize?: string
34
+ /** 保留的历史日志份数,默认 5。 */
35
+ maxFiles?: number
36
+ /** 已知凭证明文,日志里会被额外打码。 */
37
+ knownSecrets?: string[]
38
+ }
39
+
40
+ /** winston 存放最终输出的符号键。 */
41
+ const MESSAGE = Symbol.for("message")
42
+
43
+ /** 默认的单文件大小上限。 */
44
+ const DEFAULT_MAX_SIZE = "5m"
45
+ /** 默认保留的日志份数。 */
46
+ const DEFAULT_MAX_FILES = 5
47
+ /** 日志文件名模板,%DATE% 会替换成当天日期。 */
48
+ const FILE_NAME = "qq-bot-%DATE%.log"
49
+ /** meta 最多递归几层,再深就原样留下。 */
50
+ const MAX_META_DEPTH = 4
51
+ /** 关闭日志时最多等多久(毫秒),避免卸载卡死。 */
52
+ const CLOSE_TIMEOUT_MS = 2000
53
+
54
+ /** 写文件的那一路传输。 */
55
+ interface FileTransport {
56
+ transport: DailyRotateFile
57
+ /** 当前打开的文件描述符,轮转后会更新。 */
58
+ fd?: number
59
+ }
60
+
61
+ /** 已创建的日志器,插件卸载时按实例关闭。 */
62
+ interface LoggerHandle {
63
+ api: Logger
64
+ logger: winston.Logger
65
+ files: FileTransport[]
66
+ }
67
+
68
+ const handles = new Set<LoggerHandle>()
69
+
70
+ /**
71
+ * 默认日志目录。
72
+ *
73
+ * 优先用 `$XDG_STATE_HOME/opencode-qq-bot/logs`,没设置就用
74
+ * `~/.local/state/opencode-qq-bot/logs`。
75
+ */
76
+ export function defaultLogDir(): string {
77
+ const stateHome = process.env.XDG_STATE_HOME?.trim()
78
+ const base = stateHome && isAbsolute(stateHome) ? stateHome : join(homedir(), ".local", "state")
79
+ return join(base, "opencode-qq-bot", "logs")
80
+ }
81
+
82
+ /** 判断是不是普通对象;Date、Map 之类的原样留下。 */
83
+ function isPlainObject(value: object): boolean {
84
+ const proto = Object.getPrototypeOf(value)
85
+ return proto === Object.prototype || proto === null
86
+ }
87
+
88
+ /**
89
+ * 规整 meta 里的值。
90
+ *
91
+ * Error 变成 `{name, message, stack}`,栈压成一行,避免日志文件里出现多行;
92
+ * 普通对象与数组递归处理,别的类型原样保留。
93
+ */
94
+ function normalizeValue(value: unknown, depth: number): unknown {
95
+ if (value instanceof Error) {
96
+ return {
97
+ name: value.name,
98
+ message: value.message,
99
+ stack: value.stack ? value.stack.replace(/\s*\n\s*/g, " ") : undefined,
100
+ }
22
101
  }
102
+ if (depth >= MAX_META_DEPTH) return value
103
+ if (Array.isArray(value)) return value.map((entry) => normalizeValue(entry, depth + 1))
104
+ if (value && typeof value === "object" && isPlainObject(value)) {
105
+ const result: Record<string, unknown> = {}
106
+ for (const [key, entry] of Object.entries(value)) {
107
+ result[key] = normalizeValue(entry, depth + 1)
108
+ }
109
+ return result
110
+ }
111
+ return value
112
+ }
113
+
114
+ /** 规整 meta 列表,去掉 undefined。 */
115
+ function normalizeMeta(entries: unknown[]): unknown[] {
116
+ const result: unknown[] = []
117
+ for (const entry of entries) {
118
+ if (entry === undefined) continue
119
+ result.push(normalizeValue(entry, 0))
120
+ }
121
+ return result
122
+ }
123
+
124
+ /**
125
+ * 打码格式:把最终序列化出来的那一行里的凭证换成占位符。
126
+ *
127
+ * 放在管道最后,console 与文件两条输出用的是同一套规则。
128
+ */
129
+ function maskFormat(knownSecrets: string[]): winston.Logform.Format {
130
+ return winston.format((info) => {
131
+ const line = info[MESSAGE]
132
+ if (typeof line === "string") {
133
+ info[MESSAGE] = maskSecrets(line, { knownSecrets })
134
+ }
135
+ return info
136
+ })()
137
+ }
138
+
139
+ /**
140
+ * 控制台格式:保持旧的 `[时间] 级别 前缀 消息` 样式,附加信息跟在后面。
141
+ */
142
+ function consoleFormat(prefix: string): winston.Logform.Format {
143
+ return winston.format((info) => {
144
+ const stamp = typeof info.timestamp === "string" ? info.timestamp : new Date().toISOString()
145
+ const level = String(info.level).toUpperCase()
146
+ const message = typeof info.message === "string" ? info.message : inspect(info.message)
147
+ const meta = Array.isArray(info.meta) ? info.meta : []
148
+ const details = meta.map((entry) => inspect(entry, { depth: MAX_META_DEPTH })).join(" ")
149
+ const line = `[${stamp}] ${level} ${prefix} ${message}`
150
+ info[MESSAGE] = details ? `${line} ${details}` : line
151
+ return info
152
+ })()
153
+ }
154
+
155
+ /**
156
+ * 创建一个日志器。
157
+ *
158
+ * 控制台输出保持人类可读的旧格式,同时写一份按天轮转、大小有上限的 JSON 日志文件;
159
+ * 两条输出都会逐行打码,凭证不会落盘。
160
+ *
161
+ * @param prefix 日志前缀,例如 `[qq-bot]`。
162
+ * @param options 级别、目录、轮转参数等;也可以直接传一个级别字符串。
163
+ * @returns 日志器。
164
+ */
165
+ export function createLogger(prefix: string, options: LoggerOptions | LogLevel = {}): Logger {
166
+ const resolved: LoggerOptions = typeof options === "string" ? { level: options } : options
167
+ const level = resolved.level ?? "info"
168
+ const knownSecrets = resolved.knownSecrets ?? []
169
+ const transports: winston.transport[] = []
170
+ const files: FileTransport[] = []
171
+
172
+ transports.push(
173
+ new winston.transports.Console({
174
+ format: winston.format.combine(
175
+ winston.format.errors({ stack: true }),
176
+ consoleFormat(prefix),
177
+ maskFormat(knownSecrets),
178
+ ),
179
+ stderrLevels: ["error"],
180
+ }),
181
+ )
182
+
183
+ if (resolved.file !== false) {
184
+ const dir = resolved.dir?.trim() ? resolved.dir : defaultLogDir()
185
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
186
+ const transport = new DailyRotateFile({
187
+ dirname: dir,
188
+ filename: FILE_NAME,
189
+ datePattern: "YYYY-MM-DD",
190
+ maxSize: resolved.maxSize ?? DEFAULT_MAX_SIZE,
191
+ maxFiles: resolved.maxFiles ?? DEFAULT_MAX_FILES,
192
+ format: winston.format.combine(
193
+ winston.format.errors({ stack: true }),
194
+ winston.format.json(),
195
+ maskFormat(knownSecrets),
196
+ ),
197
+ })
198
+ const entry: FileTransport = { transport }
199
+ transport.logStream.on("open", (fd: number) => {
200
+ entry.fd = fd
201
+ })
202
+ files.push(entry)
203
+ transports.push(transport)
204
+ }
205
+
206
+ const logger = winston.createLogger({
207
+ level,
208
+ format: winston.format((info) => info)(),
209
+ transports,
210
+ exitOnError: false,
211
+ })
212
+
213
+ // 传输出错时不能让进程崩掉,也不能让错误本身带着凭证进日志。
214
+ logger.on("error", (error: Error) => {
215
+ const message = error instanceof Error ? error.message : String(error)
216
+ console.error(`[${prefix}] 日志写入失败:${maskSecrets(message, { knownSecrets })}`)
217
+ })
218
+
219
+ const write = (target: LogLevel, message: string, meta: unknown[]) => {
220
+ const details = normalizeMeta(meta)
221
+ logger.log({
222
+ level: target,
223
+ message,
224
+ ...(details.length > 0 ? { meta: details } : {}),
225
+ timestamp: new Date().toISOString(),
226
+ })
227
+ }
228
+
229
+ const api: Logger = {
230
+ debug: (message, ...meta) => write("debug", message, meta),
231
+ info: (message, ...meta) => write("info", message, meta),
232
+ warn: (message, ...meta) => write("warn", message, meta),
233
+ error: (message, ...meta) => write("error", message, meta),
234
+ }
235
+ handles.add({ api, logger, files })
236
+ return api
237
+ }
238
+
239
+ /** 等传输发出 finish:这时文件流已经把数据交给了操作系统。 */
240
+ function waitFinish(transport: DailyRotateFile): Promise<void> {
241
+ return new Promise<void>((resolve) => {
242
+ const timer = setTimeout(() => resolve(), CLOSE_TIMEOUT_MS)
243
+ timer.unref?.()
244
+ transport.once("finish", () => {
245
+ clearTimeout(timer)
246
+ resolve()
247
+ })
248
+ })
249
+ }
250
+
251
+ /**
252
+ * 关闭指定日志器,等文件传输把缓冲写完;不传时关闭全部。
253
+ *
254
+ * 插件卸载时只关自己的日志器,避免接管实例时误关新实例。
255
+ */
256
+ export async function closeLogger(target?: Logger): Promise<void> {
257
+ const closing = target ? [...handles].filter((handle) => handle.api === target) : [...handles]
258
+ for (const handle of closing) handles.delete(handle)
259
+ await Promise.all(
260
+ closing.map(async (handle) => {
261
+ const waits = handle.files.map((file) => waitFinish(file.transport))
262
+ handle.logger.close()
263
+ await Promise.all(waits)
264
+ }),
265
+ )
266
+ }
23
267
 
24
- return {
25
- debug: (message, ...meta) => write("debug", "log", message, meta),
26
- info: (message, ...meta) => write("info", "log", message, meta),
27
- warn: (message, ...meta) => write("warn", "log", message, meta),
28
- error: (message, ...meta) => write("error", "error", message, meta),
268
+ /**
269
+ * 把指定日志器刷到磁盘;不传时刷新全部。
270
+ *
271
+ * 文件写入是异步的:等一个事件循环,再把内核缓冲 fsync 一次。
272
+ */
273
+ export async function flushLogger(target?: Logger): Promise<void> {
274
+ const targets = target ? [...handles].filter((handle) => handle.api === target) : [...handles]
275
+ for (const handle of targets) {
276
+ for (const file of handle.files) {
277
+ await new Promise<void>((resolve) => setImmediate(resolve))
278
+ if (file.fd === undefined) continue
279
+ try {
280
+ fsyncSync(file.fd)
281
+ } catch {
282
+ // 文件可能刚好被轮转或关闭,忽略。
283
+ }
284
+ }
29
285
  }
30
286
  }