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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
|
//! Optional log redirection.
//!
//! `PANTO_DEBUG != 0` captures `std.log` traffic — most usefully the raw JSON
//! of every provider API request and response — to a per-session file. Writing
//! that to stderr makes the interactive TUI unusable.
//!
//! This module installs a custom `std.Options.logFn` (wired up via
//! `std_options` in `main.zig`). When enabled it routes the entire log stream
//! to a per-session file under
//!
//! ($XDG_DATA_HOME/panto | ~/.local/share/panto)/debug/<session-id>.log
//!
//! and writes nothing to the terminal. Otherwise it delegates to
//! `std.log.defaultLog`.
//!
//! The file is opened with `O_TRUNC`, so each session starts fresh; the file
//! holds exactly one session's logs and never grows across runs. (A *new*
//! session id per invocation already gives a fresh file; truncation guards the
//! resume case where the same id is reused.)
//!
//! The log function may be called from any thread (the `Io.Threaded` worker
//! pool as well as the main loop), so all writes are serialized behind a
//! mutex. Writes go straight to the fd via `std.c.write` — no `Io` handle is
//! needed (and none is available at a `logFn` call site), matching the raw-fd
//! approach already used by `tui_terminal.zig`.
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const panto_home = @import("panto_home.zig");
/// A tiny atomic spinlock serializing writes. `logFn` can be called from any
/// thread but has no `Io` handle, so `Io.Mutex` (which needs one) is out;
/// contention is rare and each critical section is a single bounded write.
var log_lock = std.atomic.Value(bool).init(false);
var capture_enabled = std.atomic.Value(bool).init(false);
fn lockLog() void {
while (log_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) {
std.atomic.spinLoopHint();
}
}
fn unlockLog() void {
log_lock.store(false, .release);
}
/// The open log file descriptor, or -1 before `init` (or if init failed).
var log_fd: std.c.fd_t = -1;
/// Monotonic per-line counter. Wall-clock time needs an `Io` handle (not
/// available at a `logFn` call site), so lines are stamped with a sequence
/// number instead — enough to order events within the session.
var seq: u64 = 0;
/// Buffer backing the per-call `Writer`. Guarded by `log_mutex`.
var writer_buf: [16 * 1024]u8 = undefined;
/// Open the per-session debug log file and arm `logFn` to write to it when
/// `PANTO_DEBUG != 0`. Best-effort: any failure leaves normal logging in place.
///
/// Safe to call once, after the session id is known. `environ_map` is used to
/// resolve the data home; `io` is used only to create the `debug/` directory.
pub fn init(
allocator: Allocator,
io: Io,
environ_map: *const std.process.Environ.Map,
session_id: []const u8,
) void {
const debug = environ_map.get("PANTO_DEBUG") orelse return;
if (debug.len == 0 or std.mem.eql(u8, debug, "0")) return;
var layout = panto_home.resolve(allocator, environ_map) catch return;
defer layout.deinit();
const debug_dir = std.fs.path.join(allocator, &.{ layout.home, "debug" }) catch return;
defer allocator.free(debug_dir);
Io.Dir.cwd().createDirPath(io, debug_dir) catch |err| switch (err) {
error.PathAlreadyExists => {},
else => return,
};
const file_name = std.fmt.allocPrint(allocator, "{s}.log", .{session_id}) catch return;
defer allocator.free(file_name);
const path = std.fs.path.joinZ(allocator, &.{ debug_dir, file_name }) catch return;
defer allocator.free(path);
const flags = std.c.O{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true };
const fd = std.c.open(path.ptr, flags, @as(std.c.mode_t, 0o600));
if (fd < 0) return;
lockLog();
defer unlockLog();
log_fd = fd;
seq = 0;
capture_enabled.store(true, .release);
}
/// Custom `std.Options.logFn`. `PANTO_DEBUG != 0` captures everything to the
/// session file; otherwise use the stderr default.
pub fn logFn(
comptime level: std.log.Level,
comptime scope: @EnumLiteral(),
comptime format: []const u8,
args: anytype,
) void {
if (!capture_enabled.load(.acquire)) {
std.log.defaultLog(level, scope, format, args);
return;
}
lockLog();
defer unlockLog();
const fd = log_fd;
// Before the file is open (early bootstrap), drop the message rather than
// letting it reach the terminal — keeping the TUI pristine is the point.
if (fd < 0) return;
var fw: FdWriter = .{
.fd = fd,
.interface = .{ .vtable = &fd_vtable, .buffer = &writer_buf },
};
const w = &fw.interface;
seq += 1;
w.print("#{d:>6} {s}", .{ seq, level.asText() }) catch {};
if (scope != .default) w.print("({t})", .{scope}) catch {};
w.writeAll(": ") catch {};
w.print(format, args) catch {};
w.writeAll("\n") catch {};
w.flush() catch {};
}
/// A minimal `std.Io.Writer` whose sink is a raw file descriptor. Writes are
/// best-effort (logging must never fault): short writes are looped, `EINTR` is
/// retried, and any other error silently drops the remaining bytes.
const FdWriter = struct {
fd: std.c.fd_t,
interface: std.Io.Writer,
};
const fd_vtable: std.Io.Writer.VTable = .{ .drain = drainFd };
fn drainFd(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize {
const self: *FdWriter = @alignCast(@fieldParentPtr("interface", w));
const fd = self.fd;
// 1. Flush any buffered bytes first (they were logically written already).
if (w.end != 0) {
writeAllFd(fd, w.buffer[0..w.end]);
w.end = 0;
}
// 2. Write each data slice in order; the last is repeated `splat` times.
if (data.len == 0) return 0;
var consumed: usize = 0;
for (data[0 .. data.len - 1]) |slice| {
writeAllFd(fd, slice);
consumed += slice.len;
}
const last = data[data.len - 1];
var i: usize = 0;
while (i < splat) : (i += 1) {
writeAllFd(fd, last);
consumed += last.len;
}
return consumed;
}
fn writeAllFd(fd: std.c.fd_t, bytes: []const u8) void {
var off: usize = 0;
while (off < bytes.len) {
const n = std.c.write(fd, bytes.ptr + off, bytes.len - off);
if (n < 0) {
if (std.posix.errno(n) == .INTR) continue;
return; // best-effort: drop the rest
}
if (n == 0) return;
off += @intCast(n);
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
const testing = std.testing;
test "FdWriter: buffered + splat writes reach the fd intact" {
const path = "/tmp/panto_debug_log_drain_test.txt";
const wr_flags = std.c.O{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true };
const fd = std.c.open(path, wr_flags, @as(std.c.mode_t, 0o600));
try testing.expect(fd >= 0);
{
// A deliberately tiny buffer forces several drains mid-message,
// exercising the buffer-flush path and the splat repetition.
var buf: [8]u8 = undefined;
var fw: FdWriter = .{
.fd = fd,
.interface = .{ .vtable = &fd_vtable, .buffer = &buf },
};
const w = &fw.interface;
try w.print("hello {d} world {s}", .{ 42, "xyz" });
try w.splatBytesAll("ab", 3); // splat: "ababab"
try w.flush();
}
_ = std.c.close(fd);
const rfd = std.c.open(path, std.c.O{ .ACCMODE = .RDONLY }, @as(std.c.mode_t, 0));
try testing.expect(rfd >= 0);
defer _ = std.c.close(rfd);
var rbuf: [128]u8 = undefined;
const n = std.c.read(rfd, &rbuf, rbuf.len);
try testing.expect(n > 0);
try testing.expectEqualStrings("hello 42 world xyzababab", rbuf[0..@intCast(n)]);
}
|