Files
SnowLuma/packages/core/tests/log-file-transport.test.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

160 lines
5.3 KiB
TypeScript

// Tests for the file transport that backs the SnowLuma logger.
// Each test gets its own tmp dir and a fresh FileTransport so env / state
// from one test never bleeds into another.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { FileTransport } from '@snowluma/common/log-file-transport';
let tmpDir: string;
const ENV_KEYS = [
'SNOWLUMA_LOG_FILE',
'SNOWLUMA_LOG_DIR',
'SNOWLUMA_LOG_MAX_MB',
'SNOWLUMA_LOG_RETAIN_DAYS',
] as const;
const savedEnv: Record<string, string | undefined> = {};
function setEnv(env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>): void {
for (const [k, v] of Object.entries(env)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
}
function listLogFiles(dir: string): string[] {
return fs.readdirSync(dir).filter((f) => f.endsWith('.log')).sort();
}
beforeEach(() => {
for (const k of ENV_KEYS) savedEnv[k] = process.env[k];
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-log-'));
setEnv({
SNOWLUMA_LOG_DIR: tmpDir,
SNOWLUMA_LOG_FILE: '1',
SNOWLUMA_LOG_MAX_MB: '1',
SNOWLUMA_LOG_RETAIN_DAYS: '7',
});
});
afterEach(() => {
for (const k of ENV_KEYS) {
if (savedEnv[k] === undefined) delete process.env[k];
else process.env[k] = savedEnv[k];
}
fs.rmSync(tmpDir, { recursive: true, force: true });
vi.useRealTimers();
});
describe('FileTransport', () => {
it('creates today\'s file and writes a single line', async () => {
const t = new FileTransport();
t.write('hello world');
await t.close();
const files = listLogFiles(tmpDir);
expect(files).toHaveLength(1);
expect(files[0]).toMatch(/^snowluma-\d{4}-\d{2}-\d{2}\.log$/);
expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8')).toBe('hello world\n');
});
it('strips ANSI color escapes and ASCII control chars before writing', async () => {
const t = new FileTransport();
t.write('\x1b[36mINFO\x1b[0m \x07[Bridge] msg');
await t.close();
const [file] = listLogFiles(tmpDir);
expect(fs.readFileSync(path.join(tmpDir, file!), 'utf8')).toBe('INFO [Bridge] msg\n');
});
it('rolls into a .1 file when the current file exceeds the size cap', async () => {
// 1MB cap from beforeEach. Write ~2 MB to force a single rotation.
const t = new FileTransport();
const oneKB = 'x'.repeat(1023); // +1 byte newline = 1024
for (let i = 0; i < 2048; i++) t.write(oneKB);
await t.close();
const files = listLogFiles(tmpDir);
expect(files.length).toBeGreaterThanOrEqual(2);
const base = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.log$/.test(f));
const split = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.1\.log$/.test(f));
expect(base).toBeDefined();
expect(split).toBeDefined();
});
it('opens a new file when the day rolls over mid-process', async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0));
const t = new FileTransport();
t.write('day-one line');
vi.setSystemTime(new Date(2026, 4, 19, 0, 0, 1));
t.write('day-two line');
await t.close();
const files = listLogFiles(tmpDir);
expect(files).toContain('snowluma-2026-05-18.log');
expect(files).toContain('snowluma-2026-05-19.log');
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8'))
.toContain('day-one line');
expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8'))
.toContain('day-two line');
});
it('deletes files older than the retention window on startup', async () => {
const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log');
fs.writeFileSync(stalePath, 'stale\n');
const t = new FileTransport();
t.write('fresh');
await t.close();
expect(fs.existsSync(stalePath)).toBe(false);
});
it('keeps files inside the retention window', async () => {
const recent = new Date();
recent.setDate(recent.getDate() - 2);
const recentName = `snowluma-${recent.getFullYear()}-${String(recent.getMonth() + 1).padStart(2, '0')}-${String(recent.getDate()).padStart(2, '0')}.log`;
const recentPath = path.join(tmpDir, recentName);
fs.writeFileSync(recentPath, 'recent\n');
const t = new FileTransport();
await t.close();
expect(fs.existsSync(recentPath)).toBe(true);
});
it('SNOWLUMA_LOG_FILE=0 suppresses all file output', async () => {
setEnv({ SNOWLUMA_LOG_FILE: '0' });
const t = new FileTransport();
t.write('should not be written');
await t.close();
expect(t.isDisabled).toBe(true);
expect(listLogFiles(tmpDir)).toHaveLength(0);
});
it('appends to the existing today file across restarts', async () => {
const a = new FileTransport();
a.write('before restart');
await a.close();
const b = new FileTransport();
b.write('after restart');
await b.close();
const files = listLogFiles(tmpDir);
expect(files).toHaveLength(1);
expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8'))
.toBe('before restart\nafter restart\n');
});
it('exposes the current file path while open', () => {
const t = new FileTransport();
t.write('x');
expect(t.currentPath).not.toBeNull();
expect(t.currentPath!).toMatch(/snowluma-\d{4}-\d{2}-\d{2}\.log$/);
});
});