summaryrefslogtreecommitdiffhomepage
path: root/packages/journal-sink/src/journal-sink.ts
blob: 072a0132c4a51a79d4435c4e1ec8d1ffdfc78c55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import { closeSync, fsyncSync, openSync, renameSync, statSync, writeSync } from "node:fs";
import type { LogRecord, LogSink } from "@dispatch/kernel";

// --- Pure core (no I/O) ---

/**
 * Serialize a LogRecord to exactly one NDJSON line (record JSON + newline).
 * Pure function — no I/O, no side effects.
 */
export function serialize(record: LogRecord): string {
  return `${JSON.stringify(record)}\n`;
}

// --- Imperative shell (fs edge) ---

/** Injectable fs operations — confined to the edge. */
export interface FsOps {
  readonly open: (path: string) => number;
  readonly write: (fd: number, data: string) => void;
  readonly close: (fd: number) => void;
  readonly rename: (oldPath: string, newPath: string) => void;
  readonly statSize: (path: string) => number;
  readonly fsync: (fd: number) => void;
}

/** Clock injection for fsync interval. */
export interface ClockOps {
  readonly now: () => number;
}

export interface JournalSinkOpts {
  readonly path: string;
  readonly maxBytes?: number;
  readonly fsync?: "periodic" | "none";
  readonly fs?: FsOps;
  readonly clock?: ClockOps;
}

const DEFAULT_MAX_BYTES = 50 * 1024 * 1024; // 50 MB
const FSYNC_INTERVAL_MS = 5_000; // 5 seconds

/**
 * Create a LogSink that durably appends each record to the journal file
 * as one NDJSON line. Fail-safe: write errors drop + warn, never throw.
 * Rotates when file exceeds maxBytes (rename → .1, reopen fresh).
 */
export function createJournalSink(opts: JournalSinkOpts): LogSink {
  const filePath = opts.path;
  const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
  const syncMode = opts.fsync ?? "periodic";
  const fs = opts.fs ?? createDefaultFsOps();
  const clock = opts.clock ?? { now: () => Date.now() };

  const NO_FD = -1;
  let fd: number;
  let bytesWritten: number;
  try {
    fd = fs.open(filePath);
    bytesWritten = fs.statSize(filePath);
  } catch {
    fd = NO_FD;
    bytesWritten = 0;
  }
  let lastFsyncAt = clock.now();

  function tryOpen(): boolean {
    if (fd !== NO_FD) return true;
    try {
      fd = fs.open(filePath);
      bytesWritten = 0;
      return true;
    } catch {
      return false;
    }
  }

  function rotate(): void {
    if (fd !== NO_FD) {
      try {
        fs.close(fd);
      } catch {
        // Ignore close errors during rotation.
      }
    }
    const rotatedPath = `${filePath}.1`;
    try {
      fs.rename(filePath, rotatedPath);
    } catch {
      // If rename fails, just truncate by reopening.
    }
    try {
      fd = fs.open(filePath);
    } catch {
      fd = NO_FD;
    }
    bytesWritten = 0;
  }

  function maybeFsync(): void {
    if (syncMode !== "periodic" || fd === NO_FD) return;
    const now = clock.now();
    if (now - lastFsyncAt >= FSYNC_INTERVAL_MS) {
      try {
        fs.fsync(fd);
      } catch {
        // Swallow — fail-safe.
      }
      lastFsyncAt = now;
    }
  }

  const sink: LogSink = {
    emit(record: LogRecord): void {
      try {
        if (!tryOpen()) {
          console.warn("[journal-sink] cannot open journal, dropping record");
          return;
        }

        const line = serialize(record);
        const lineBytes = Buffer.byteLength(line, "utf8");

        if (bytesWritten + lineBytes > maxBytes) {
          rotate();
          if (fd === NO_FD) {
            console.warn("[journal-sink] rotation failed, dropping record");
            return;
          }
        }

        fs.write(fd, line);
        bytesWritten += lineBytes;
        maybeFsync();
      } catch (err) {
        // Fail-safe: drop + warn, never throw to the caller (D3/D7).
        console.warn("[journal-sink] write failed, dropping record:", err);
      }
    },
  };

  return sink;
}

// --- Default fs ops (real Bun/Node I/O) ---

function createDefaultFsOps(): FsOps {
  return {
    open(path: string): number {
      return openSync(path, "a");
    },
    write(fd: number, data: string): void {
      writeSync(fd, data);
    },
    close(fd: number): void {
      closeSync(fd);
    },
    rename(oldPath: string, newPath: string): void {
      renameSync(oldPath, newPath);
    },
    statSize(path: string): number {
      try {
        return statSync(path).size;
      } catch {
        return 0;
      }
    },
    fsync(fd: number): void {
      fsyncSync(fd);
    },
  };
}