Files
SnowLuma/packages/common/src/log-file-transport.ts
T
DrSmoothl 46b302f738 refactor(common): extract leaf utilities into @snowluma/common package
Phase 1 of the 4-package split called out in RoadMap #3. Moves the
"infrastructure" leaves — files with zero business dependencies that
@snowluma/bridge, @snowluma/core, and @snowluma/onebot all consume —
into a dedicated workspace package. Mirrors what #4 (proto-defs)
did for wire-protobuf definitions.

Why
---
- Cleaner layering: these were never bridge- or onebot-specific.
  Logger / hex codec / runtime config sit at the bottom of every
  module's import graph; giving them their own package makes that
  graph readable and prevents future leaks the other direction.
- Sets up #3's bridge + onebot extractions: those need a clean leaf
  to depend on. Without this, every cross-package import would have
  to re-export through core, which defeats the split.
- Mirrors @snowluma/proto-defs layout — per-file subpath exports
  (`@snowluma/common/logger`, `@snowluma/common/hex`, …) keep import
  sites unambiguous and let bundlers tree-shake aggressively.

Layout
------
Moved (via `git mv` — history preserved):
  packages/core/src/utils/logger.ts             → @snowluma/common/logger
  packages/core/src/utils/hex.ts                → @snowluma/common/hex
  packages/core/src/utils/log-file-transport.ts → @snowluma/common/log-file-transport
  packages/core/src/utils/log-summary.ts        → @snowluma/common/log-summary
  packages/core/src/protocol/packet-sender.ts   → @snowluma/common/packet-sender
  packages/core/src/protocol/types.ts           → @snowluma/common/protocol-types
  packages/core/src/common/runtime.ts           → @snowluma/common/runtime

Not moved (deferred to Phase 2): `packages/core/src/utils/event-format.ts`
— it has reverse imports on `bridge/events`, `bridge/identity-service`,
`onebot/message-store`, `onebot/types`. It moves into @snowluma/bridge
in Phase 2, with the MessageStore parameter decoupled via a structural
type so bridge doesn't end up depending on onebot.

Changes
-------
- New package `packages/common/` (package.json, tsconfig.json — no
  src/index.ts barrel, callers use the subpath exports directly to
  avoid pulling in `node:fs` when only the hex codec is needed).
- 7 `.ts` files moved via `git mv`.
- 50+ import sites rewritten via sed across `packages/core/src` and
  `packages/core/tests`. Old shapes (`../utils/logger`,
  `../../protocol/types`, `./common/runtime`, `../src/utils/hex`)
  all collapse to `@snowluma/common/<sub>`.
- `@snowluma/core` depends on `@snowluma/common` (workspace:*).
- `packages/core/src/{protocol,common}/` directories removed (empty).

Verification
------------
- core typecheck: clean
- common typecheck: clean
- Full workspace `pnpm -r typecheck`: all 9 projects clean
- core test suite: 552 passed / 552 total (pre-existing
  websocket-darwin-arm64.node addon failure unchanged — same baseline
  as the previous refactor commits)
- Vite build with stubbed native binary: clean (143 modules, 2.84 MB
  bundle, 224 KB gzip — same size envelope as before)

Note: `utils/event-format.ts` is the only file remaining under the
old `utils/` namespace. It moves into @snowluma/bridge alongside the
events / identity-service / packet-pipeline trio in Phase 2.
2026-05-21 08:27:05 +08:00

275 lines
7.5 KiB
TypeScript

import fs from 'node:fs';
import path from 'node:path';
const DEFAULT_DIR = 'logs';
const DEFAULT_MAX_MB = 50;
const DEFAULT_RETAIN_DAYS = 7;
const FILE_PREFIX = 'snowluma-';
const FILE_SUFFIX = '.log';
const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/;
// eslint-disable-next-line no-control-regex
const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit
// multi-line records (stack traces), ESC is stripped through ANSI_RE.
// eslint-disable-next-line no-control-regex
const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g;
function parsePositiveInt(v: string | undefined, dflt: number): number {
if (!v) return dflt;
const n = Number.parseInt(v, 10);
return Number.isFinite(n) && n > 0 ? n : dflt;
}
function todayString(d: Date = new Date()): string {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return `${y}-${m}-${day}`;
}
function dateOf(s: string): Date {
const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10));
return new Date(y!, m! - 1, d!);
}
function stripAnsi(line: string): string {
return line.replace(ANSI_RE, '').replace(CTRL_RE, '');
}
interface OpenFile {
stream: fs.WriteStream;
bytes: number;
date: string;
splitIndex: number;
path: string;
}
/**
* Owns one output directory: keeps at most one open WriteStream, handles
* daily rollover, per-file size cap, and retention cleanup. The shared
* top-level dir uses one of these; each per-UIN sub-dir gets its own.
*/
class FileWriter {
private disabled = false;
private file: OpenFile | null = null;
constructor(
private readonly dir: string,
private readonly maxBytes: number,
private readonly retainDays: number,
) {
try {
fs.mkdirSync(dir, { recursive: true });
} catch (err) {
this.disabled = true;
console.error(
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
);
return;
}
this.cleanup();
}
get isDisabled(): boolean {
return this.disabled;
}
get currentPath(): string | null {
return this.file?.path ?? null;
}
write(data: string, bytes: number): void {
if (this.disabled) return;
const today = todayString();
this.ensureForToday(today);
if (!this.file) return;
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
this.rotateBySize();
if (!this.file) return;
}
this.file.stream.write(data);
this.file.bytes += bytes;
}
close(): Promise<void> {
const f = this.file;
this.file = null;
if (!f) return Promise.resolve();
return new Promise((resolve) => {
try {
f.stream.end(() => resolve());
} catch {
resolve();
}
});
}
private ensureForToday(today: string): void {
if (this.file && this.file.date === today) return;
if (this.file) {
try {
this.file.stream.end();
} catch {
/* ignore */
}
this.file = null;
this.cleanup();
}
// Resume from the highest existing split index for today (so two
// process starts on the same day share files / don't clobber).
let idx = 0;
while (fs.existsSync(this.pathFor(today, idx + 1))) idx++;
this.file = this.openFile(today, idx);
}
private rotateBySize(): void {
if (!this.file) return;
const date = this.file.date;
try {
this.file.stream.end();
} catch {
/* ignore */
}
let next = this.file.splitIndex + 1;
while (fs.existsSync(this.pathFor(date, next))) next++;
this.file = this.openFile(date, next);
}
private openFile(date: string, splitIndex: number): OpenFile | null {
const p = this.pathFor(date, splitIndex);
try {
let bytes = 0;
try {
bytes = fs.statSync(p).size;
} catch {
/* file doesn't exist yet */
}
const stream = fs.createWriteStream(p, { flags: 'a' });
stream.on('error', (err) => {
console.error(`[logger] file write error on ${p}: ${err.message}`);
});
return { stream, bytes, date, splitIndex, path: p };
} catch (err) {
console.error(
`[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`,
);
return null;
}
}
private pathFor(date: string, splitIndex: number): string {
const tail = splitIndex > 0 ? `.${splitIndex}` : '';
return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`);
}
private cleanup(): void {
let entries: string[];
try {
entries = fs.readdirSync(this.dir);
} catch {
return;
}
const retainMs = this.retainDays * 24 * 60 * 60 * 1000;
const cutoff = Date.now() - retainMs;
for (const name of entries) {
const m = FILE_RE.exec(name);
if (!m) continue;
const dateStr = m[1]!;
if (dateOf(dateStr).getTime() < cutoff) {
try {
fs.unlinkSync(path.join(this.dir, name));
} catch {
/* ignore */
}
}
}
}
}
export class FileTransport {
private readonly dir: string;
private readonly maxBytes: number;
private readonly retainDays: number;
private readonly enabled: boolean;
private readonly perUinEnabled: boolean;
private shared: FileWriter | null = null;
private perUin = new Map<number, FileWriter>();
constructor() {
this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR;
this.maxBytes =
parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024;
this.retainDays = parsePositiveInt(
process.env.SNOWLUMA_LOG_RETAIN_DAYS,
DEFAULT_RETAIN_DAYS,
);
this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0';
this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0';
if (this.enabled) {
const w = new FileWriter(this.dir, this.maxBytes, this.retainDays);
this.shared = w.isDisabled ? null : w;
}
}
/** True when no file output will happen (env disable or init failure). */
get isDisabled(): boolean {
return !this.shared;
}
/** Current shared-file path (or null if disabled / not yet opened). */
get currentPath(): string | null {
return this.shared?.currentPath ?? null;
}
/** Path of the per-UIN file for the given UIN, if open. */
perUinPath(uin: number): string | null {
return this.perUin.get(uin)?.currentPath ?? null;
}
write(line: string, uin?: number): void {
if (!this.shared) return;
const data = stripAnsi(line) + '\n';
const bytes = Buffer.byteLength(data, 'utf8');
this.shared.write(data, bytes);
if (uin !== undefined && this.perUinEnabled) {
let w = this.perUin.get(uin);
if (!w) {
w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays);
if (w.isDisabled) return;
this.perUin.set(uin, w);
}
w.write(data, bytes);
}
}
async close(): Promise<void> {
const closes: Promise<void>[] = [];
if (this.shared) closes.push(this.shared.close());
for (const w of this.perUin.values()) closes.push(w.close());
this.shared = null;
this.perUin.clear();
await Promise.all(closes);
}
}
let singleton: FileTransport | null = null;
export function getFileTransport(): FileTransport {
if (!singleton) singleton = new FileTransport();
return singleton;
}
/** Reset state between tests. Closes all active file handles. */
export async function _resetFileTransportForTesting(): Promise<void> {
if (singleton) await singleton.close();
singleton = null;
}