Something went wrong. Try again.
Classic Unix mailbox files for Zig 0.16: an iterator to read, a predicate to delete, an atomic rewrite for every change.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A mailbox file: the locking, and the atomic rewrite that changing one//! needs.//!//! Everything above this works on bytes and streams. This is the layer that//! knows there is a file, and it exists for the two things that only a file//! has: other processes looking at the same one, and the possibility of being//! interrupted halfway through writing it.//!//! # How a change is made//!//! Never in place. A change writes a whole new mailbox into an unnamed//! temporary file beside the old one and renames it over the top, so the file//! at that path is either entirely the old mailbox or entirely the new one and//! never a mixture. An interrupted rewrite costs the work and nothing else.//!//! `append` is the same operation with a predicate that keeps everything,//! which is why adding one message to a mailbox costs a copy of the mailbox.//! That is a real price and it is paid deliberately: the alternative, seeking//! to the end and writing, leaves a half-written message behind when it fails.//!//! # What the locking does and does not protect against//!//! The lock is `flock`, taken shared to read and exclusive to change, and it//! is released the moment the operation ends — and if the process dies, by the//! kernel.//!//! Against another program using this library, that is enough. Against a//! delivery agent appending to the same file it is not, and cannot be made so,//! because the rename that makes the change atomic also makes the old file//! nameless: a delivery written to it after the rename lands in a file that no//! longer has a path, and is lost when the last handle closes. This is not a//! defect in the locking, it is what rewrite-and-rename means, and it is why//! the classic mbox tools rewrite in place and risk the other failure instead.//!//! What follows from it: this library is for mailboxes nothing else is//! delivering into — an archive, an export, a spool that has been moved aside//! — and it is not a delivery agent. The handle and the lock are reopened//! after every rewrite, so operations through *this* library stay correct//! whatever else is happening.//!//! Ownership is the other thing a rename cannot carry: a new file belongs to//! whoever made it. The permissions are copied across deliberately, because a//! mailbox that came back world-readable would be a disclosure; the owning//! user and group cannot be without privileges this has no business having.
const std = @import("std");const Io = std.Io;const Dir = Io.Dir;const File = Io.File;const Allocator = std.mem.Allocator;const testing = std.testing;
const From = @import("From.zig");const Reader = @import("Reader.zig");const Writer = @import("Writer.zig");const filter = @import("filter.zig");const variant = @import("variant.zig");const Variant = variant.Variant;
const Mailbox = @This();
/// What a pass over the mailbox did. The same type `filter` reports.pub const Stats = filter.Stats;
/// The smallest buffer `iterate` will work with, re-exported here because this/// is where a caller is standing when it has to size one.pub const min_buffer = Reader.min_buffer;
pub const Options = struct { variant: Variant = .mboxrd,
/// Take an advisory lock: shared while reading, exclusive while changing, /// released as soon as the operation is over. /// /// Turning it off is for a caller who has its own locking, or who knows it /// is the only thing that can reach the file — a mailbox in a directory it /// made itself, say. Read the note at the top of this file for what the /// lock is worth even when it is on. lock: bool = true,
max_message_bytes: usize = 64 * 1024 * 1024, trust_content_length: bool = true,
/// The permissions a rewritten mailbox is given, or null for the ones the /// file already had. /// /// Null is almost always right. A rewrite makes a new file, and a new file /// is made with whatever the process's umask says rather than with what /// the mailbox had, so without copying them across a `0600` spool comes /// back readable by anyone. permissions: ?File.Permissions = null,
/// The buffer each side of a rewrite gets. How big it is, is the whole of /// the throughput. buffer_size: usize = 64 * 1024,
fn readerOptions(self: Options) Reader.Options { return .{ .variant = self.variant, .max_message_bytes = self.max_message_bytes, .trust_content_length = self.trust_content_length, }; }};
pub const OpenError = File.OpenError || File.LockError || error{ /// The path did not fit `Dir.max_path_bytes`. NameTooLong,};
/// How many times an operation will reopen a mailbox that was replaced out/// from under it before giving up. Each turn of that loop needs another/// process to have completed a whole rewrite, so reaching this means/// something is rewriting the mailbox in a loop rather than that the machine/// is busy.const max_relock_attempts = 32;
pub const LockError = File.LockError || File.OpenError || File.StatError || Dir.StatFileError || error{ /// The file at this path kept being replaced, so no lock could be taken /// on the file that was actually the mailbox. MailboxKeptChanging,};
pub const RewriteError = OpenError || LockError || filter.Error || Dir.CreateFileAtomicError || File.Atomic.ReplaceError || File.StatError || File.Writer.EndError || File.Reader.SeekError;
/// The directory the mailbox is in, which is also where the temporary file for/// a rewrite is made: a rename is only atomic within one filesystem, and the/// same directory is the only place guaranteed to be on one.dir: Dir,file: File,/// Held inline rather than borrowed, because a rewrite needs the path again/// long after `open` returned and a borrowed one would quietly make the caller/// responsible for keeping it alive that long.path_buffer: [Dir.max_path_bytes]u8,path_len: usize,options: Options,/// Whether a lock is currently held, so that `close` does not unlock a file/// that was never locked.locked: bool,
/// Opens an existing mailbox.pub fn open(parent: Dir, io: Io, sub_path: []const u8, options: Options) OpenError!Mailbox { if (sub_path.len > Dir.max_path_bytes) return error.NameTooLong; const file = try parent.openFile(io, sub_path, .{ .mode = .read_only }); var self: Mailbox = .{ .dir = parent, .file = file, .path_buffer = undefined, .path_len = sub_path.len, .options = options, .locked = false, }; @memcpy(self.path_buffer[0..sub_path.len], sub_path); return self;}
/// Opens a mailbox, making an empty one if there is nothing there.////// An empty file is a mailbox with no messages in it, so there is nothing to/// write into a new one.pub fn create(parent: Dir, io: Io, sub_path: []const u8, options: Options) OpenError!Mailbox { if (parent.openFile(io, sub_path, .{ .mode = .read_only })) |file| { file.close(io); } else |err| switch (err) { error.FileNotFound => { const made = try parent.createFile(io, sub_path, .{ .truncate = false }); made.close(io); }, else => |e| return e, } return open(parent, io, sub_path, options);}
pub fn close(self: *Mailbox, io: Io) void { self.unlock(io); self.file.close(io); self.* = undefined;}
/// The path this mailbox was opened at, relative to `dir`.pub fn path(self: *const Mailbox) []const u8 { return self.path_buffer[0..self.path_len];}
fn lock(self: *Mailbox, io: Io, mode: File.Lock) File.LockError!void { if (!self.options.lock) return; std.debug.assert(!self.locked); try self.file.lock(io, mode); self.locked = true;}
/// Takes the lock, and makes sure it is a lock on the file that is actually at/// this path.////// A rewrite -- this library's, in another process, or any other tool's --/// puts a new file at the path and leaves the old one nameless. A handle/// opened before that still reads the old one, and a lock held on it guards/// nothing, so both have to be renewed. Checking *after* taking the lock is/// what makes it a check rather than a guess: once the lock is held on the/// file at the path, no other holder of that lock can replace it.fn lockFresh(self: *Mailbox, io: Io, mode: File.Lock) LockError!void { for (0..max_relock_attempts) |_| { try self.lock(io, mode); const held = (try self.file.stat(io)).inode; const named = (try self.dir.statFile(io, self.path(), .{})).inode; if (held == named) return;
// Somebody replaced the mailbox. Let go of the file that used to be // it and take hold of the one that is. self.unlock(io); const fresh = try self.dir.openFile(io, self.path(), .{ .mode = .read_only }); self.file.close(io); self.file = fresh; } return error.MailboxKeptChanging;}
fn unlock(self: *Mailbox, io: Io) void { if (!self.locked) return; self.file.unlock(io); self.locked = false;}
// -- reading -----------------------------------------------------------------
/// Reads the mailbox from the beginning.////// `buffer` is the read buffer and must be at least `Reader.min_buffer`; how/// big it is beyond that, is the throughput. It has to outlive the iterator.////// The shared lock is held until `deinit`, so an iterator is not something to/// keep open while doing something else.pub fn iterate(self: *Mailbox, gpa: Allocator, io: Io, buffer: []u8) LockError!Iterator { std.debug.assert(buffer.len >= Reader.min_buffer); try self.lockFresh(io, .shared); return .{ .mailbox = self, .io = io, .file_reader = self.file.reader(io, buffer), .reader = .init(gpa, undefined, self.options.readerOptions()), .attached = false, };}
pub const Iterator = struct { mailbox: *Mailbox, io: Io, file_reader: File.Reader, reader: Reader, /// Whether `reader.input` has been pointed at `file_reader.interface` yet. /// /// It cannot be done in `iterate`, because that returns the iterator by /// value and the pointer would be to the copy left behind. Doing it on /// first use means it is taken once the iterator is wherever the caller /// put it, which is the address it will keep. attached: bool,
pub fn next(self: *Iterator) Reader.Error!?Reader.Entry { if (!self.attached) { self.attached = true; self.reader.input = &self.file_reader.interface; } return self.reader.next(); }
pub fn deinit(self: *Iterator) void { self.reader.deinit(); self.mailbox.unlock(self.io); self.* = undefined; }};
// -- changing ----------------------------------------------------------------
/// Adds one message to the end of the mailbox.////// A copy of the whole mailbox, because that is what makes it atomic. See the/// note at the top of this file.pub fn append( self: *Mailbox, gpa: Allocator, io: Io, from: From, message: []const u8,) RewriteError!Stats { return self.rewrite(gpa, io, {}, filter.keepAll, .{ .from = from, .message = message });}
/// Rewrites the mailbox, keeping the messages `keep` returns true for.////// The predicate is asked about every message before anything is written, and/// it may read the message it is deciding about: `Entry.parse` and/// `Entry.headers` fail only by running out of memory, which is exactly the/// latitude the predicate has.pub fn filterMessages( self: *Mailbox, gpa: Allocator, io: Io, context: anytype, comptime keep: fn (@TypeOf(context), Reader.Entry) Allocator.Error!bool,) RewriteError!Stats { return self.rewrite(gpa, io, context, keep, null);}
/// A message to write after everything the predicate kept.const Extra = struct { from: From, message: []const u8,};
fn rewrite( self: *Mailbox, gpa: Allocator, io: Io, context: anytype, comptime keep: fn (@TypeOf(context), Reader.Entry) Allocator.Error!bool, extra: ?Extra,) RewriteError!Stats { try self.lockFresh(io, .exclusive); // Unlocked explicitly further down, once it is known which file the lock // is even on; this catches the paths that leave early. errdefer self.unlock(io);
// Before the new file is made, so that it is made with them rather than // corrected afterwards -- there is no window in which the replacement is // readable by anyone the original was not. const permissions = self.options.permissions orelse (try self.file.stat(io)).permissions;
const buffers = try gpa.alloc(u8, self.options.buffer_size * 2); defer gpa.free(buffers); const read_buffer = buffers[0..self.options.buffer_size]; const write_buffer = buffers[self.options.buffer_size..];
var atomic = try self.dir.createFileAtomic(io, self.path(), .{ .permissions = permissions, // Not optional: `File.Atomic.replace` asserts on it, because whether // the temporary can be an unnamed file depends on how it will be // materialised. .replace = true, }); // Always, even when it worked: the doc comment on `deinit` says so, and // on the failing path it is what deletes the temporary. defer atomic.deinit(io);
var file_reader = self.file.reader(io, read_buffer); try file_reader.seekTo(0); var file_writer = atomic.file.writer(io, write_buffer);
const stats = try filter.copy( gpa, &file_reader.interface, &file_writer.interface, self.options.readerOptions(), context, keep, );
var total = stats; if (extra) |one| { var mbox: Writer = .init(&file_writer.interface, .{ .variant = self.options.variant }); try mbox.append(one.from, one.message); total.kept += 1; total.bytes_kept += one.message.len; }
// `end` rather than `flush`: the temporary is a fresh file, but saying so // is what makes the length right whichever mode the writer picked. try file_writer.end(); try atomic.replace(io);
// The lock and the handle are now on an inode with no name: the rename // put a different file at this path. Everything after this would be // reading a file nobody can reach, so both are replaced. self.unlock(io); self.file.close(io); self.file = try self.dir.openFile(io, self.path(), .{ .mode = .read_only });
return total;}
// -- tests -------------------------------------------------------------------//// What this layer does to a real file is `tests/e2e.zig`; these are the parts// that need no directory.
test "options carry through to the reader" { const options: Options = .{ .variant = .mboxcl2, .max_message_bytes = 99, .trust_content_length = false, }; const derived = options.readerOptions(); try testing.expectEqual(Variant.mboxcl2, derived.variant); try testing.expectEqual(@as(usize, 99), derived.max_message_bytes); try testing.expectEqual(false, derived.trust_content_length);}
test "a path too long to hold is refused rather than truncated" { const long = "x" ** (Dir.max_path_bytes + 1); try testing.expectError(error.NameTooLong, open(.cwd(), testing.io, long, .{}));}