Skip to content
zit Artifact [034c190cb3]
Login

Artifact [034c190cb3]

Artifact 034c190cb33ff54cf9d14a0fd3e16de3f01f1b25086ba0cd5abcc2065bf386d6:


//! Opening a store: for append under its one writer lock, the seam every
//! writer passes through, and for a lock-free read. Kept free of the CLI so
//! the library core (and what links it) opens stores without the verb layer.

const std = @import("std");
const storelock = @import("../store/storelock.zig");
const checkout = @import("../worktree/checkout.zig");
const import_transaction = @import("../store/import_transaction.zig");
const logstore = @import("../store/logstore.zig");
const storage = @import("../store/storage.zig");
const repocache = @import("../repo/repocache.zig");

/// The store's file name beside its checkout record.
const repo_marker: []const u8 = ".zit";

/// Open the store for appending, under the store's one write lock.
///
/// Every writer to `.zit` passes through here so that two appenders
/// serialize instead of tearing the log. The lock is `.zit.lock` beside the
/// store, taken by exclusive create (`storelock`), and it is taken BEFORE the
/// store is opened, so the caller's `stat` reads an end no other writer can
/// move. A second writer waits for it, says after a second what it is waiting
/// for, and gives up after `storelock.default_wait_ms` naming the holder.
/// Readers take no lock at all (`verify` documents that promise), so a writer
/// never blocks them and they never block a writer.
///
/// Two rules this imposes on callers. `close` the handle as soon as the
/// append has committed: holding it across later, store-free work (a push,
/// an advisory) extends the exclusion for no reason. And no flow may open a
/// second handle while it still holds one; that is refused at once as
/// `error.StoreLocked` rather than waited on.
///
/// A generation REWRITE (`pack`, `shun --force`) takes the same lock around
/// its final check and rename (`lockStoreWriter`), so no append can land in
/// the generation it is about to replace.
pub fn openStoreAppend(io: std.Io, root_dir: std.Io.Dir) (std.Io.File.OpenError || StoreLocationError || StoreLockError)!StoreAppend {
    var lock = try lockStoreWriter(io, root_dir);
    errdefer lock.release(io);
    return .{ .file = try openStoreFile(io, root_dir), .lock = lock };
}

/// The store file under `root_dir`, resolved through a checkout's store
/// pointer, opened for read and write: the one write-mode open of the store,
/// reached only through `openStoreAppend`, after the lock.
fn openStoreFile(io: std.Io, root_dir: std.Io.Dir) (std.Io.File.OpenError || StoreLocationError)!std.Io.File {
    if (try storeDirOf(io, root_dir)) |store| {
        var store_dir = store;
        defer store_dir.close(io);
        return store_dir.openFile(io, repo_marker, .{ .mode = .read_write });
    }
    return root_dir.openFile(io, repo_marker, .{ .mode = .read_write });
}

/// `LogStore.open` for a caller that holds the writer lock, adopting the
/// store's persisted scan index when it still describes the file the lock now
/// covers, so the open costs what was appended since the index rather than
/// one header read per frame already there. The index is adopted exactly as
/// a reader adopts it (an appended tail is walked); what makes the handle
/// writable is that the lock is held and the adopted end is the file's end.
/// Anything else -- no index, a stale or damaged one, a torn tail only the
/// scanning open repairs -- takes the scanning open, and sets `scanned`.
pub fn openLogForAppend(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, sf: storage.StorageFile, scanned: ?*bool) logstore.OpenError!logstore.LogStore {
    adopt: {
        sf.refreshEnd() catch break :adopt;
        var resolved = checkout.storeDirOf(io, dir) catch null;
        defer if (resolved) |*r| r.close(io);
        const idx = repocache.mapLogIndex(io, resolved orelse dir) orelse break :adopt;
        var extended = false;
        // `adoptIndex` takes `idx` on every path.
        var log = (logstore.LogStore.adoptIndex(gpa, sf, idx, &extended) catch |e| switch (e) {
            error.OutOfMemory => return error.OutOfMemory,
            else => break :adopt,
        }) orelse break :adopt;
        const size = sf.size() catch {
            log.deinit(gpa);
            break :adopt;
        };
        if (log.end != size) {
            log.deinit(gpa);
            break :adopt;
        }
        log.writable = true;
        return log;
    }
    if (scanned) |s| s.* = true;
    return logstore.LogStore.open(gpa, sf, 0);
}

/// The store opened for appending, and the writer lock that makes that safe.
pub const StoreAppend = struct {
    file: std.Io.File,
    lock: storelock.Lock,

    /// Closes the store, then releases the lock.
    pub fn close(self: *StoreAppend, io: std.Io) void {
        self.file.close(io);
        self.lock.release(io);
    }
};

/// Why the writer lock was not taken. `StoreBusy`: another process held it
/// past the wait, and stderr already says who and what to do, so a caller
/// adds nothing. `StoreLocked`: anything else, which the caller reports.
pub const StoreLockError = error{ StoreBusy, StoreLocked, StoreLockAmbiguous, ImportRecoveryRequired };

/// Take the store's writer lock, resolved through the checkout to the store's
/// own directory, so every worktree of one store shares one lock. Waiting and
/// giving-up notices go to stderr: several writers have no other stream.
pub fn lockStoreWriter(io: std.Io, root_dir: std.Io.Dir) (StoreLocationError || StoreLockError)!storelock.Lock {
    var lock = try lockStoreRecovery(io, root_dir);
    errdefer lock.release(io);
    const resolved = try storeDirOf(io, root_dir);
    defer if (resolved) |dir| dir.close(io);
    import_transaction.requireIdle(io, resolved orelse root_dir) catch |err| {
        if (err == error.ImportRecoveryRequired) return error.ImportRecoveryRequired;
        return error.StoreLocked;
    };
    return lock;
}

/// Only explicit source-free import recovery may bypass the pending fence.
pub fn lockStoreRecovery(io: std.Io, root_dir: std.Io.Dir) (StoreLocationError || StoreLockError)!storelock.Lock {
    var notice_buf: [512]u8 = undefined;
    // Streaming, as main's own stderr is: a positional writer starts at
    // offset 0 and overwrites what the verb has already written to a
    // redirected stderr.
    var notices: std.Io.File.Writer = .initStreaming(.stderr(), io, &notice_buf);
    defer notices.interface.flush() catch {};
    if (try storeDirOf(io, root_dir)) |store| {
        var store_dir = store;
        defer store_dir.close(io);
        return storelock.acquire(io, store_dir, storelock.writer_lock_name, storelock.default_wait_ms, &notices.interface) catch |e|
            lockError(e);
    }
    return storelock.acquire(io, root_dir, storelock.writer_lock_name, storelock.default_wait_ms, &notices.interface) catch |e|
        lockError(e);
}

fn lockError(e: storelock.AcquireError) StoreLockError {
    return switch (e) {
        error.Busy => error.StoreBusy,
        error.Ambiguous => error.StoreLockAmbiguous,
        error.HeldByThisProcess, error.Io => error.StoreLocked,
    };
}

test "lockStoreWriter: only a holder that outlasted the wait is StoreBusy" {
    // StoreBusy tells callers the notice is already on stderr, so it must
    // mean exactly the case that wrote one.
    try std.testing.expectEqual(error.StoreBusy, lockError(error.Busy));
    try std.testing.expectEqual(error.StoreLocked, lockError(error.HeldByThisProcess));
    try std.testing.expectEqual(error.StoreLocked, lockError(error.Io));
}

pub const StoreLocationError = error{ Storage, Corrupt };

/// Where this checkout's store lives; see `checkout.storeDirOf`.
pub fn storeDirOf(io: std.Io, root_dir: std.Io.Dir) StoreLocationError!?std.Io.Dir {
    return checkout.storeDirOf(io, root_dir);
}

/// Open the store read-only, resolved through the checkout the same way the
/// append path resolves it. Readers take no lock (verify's promise).
pub fn openStoreRead(io: std.Io, root_dir: std.Io.Dir) !import_transaction.Snapshot {
    const resolved = try storeDirOf(io, root_dir);
    defer if (resolved) |dir| dir.close(io);
    return import_transaction.capture(io, resolved orelse root_dir);
}

/// A fresh store `.zit` in `dir` holding `bodies`, named by their SHA3-256,
/// with its scan index stored beside it when `index` is set.
fn seedIndexedStore(io: std.Io, dir: std.Io.Dir, bodies: []const []const u8, index: bool) !void {
    const gpa = std.testing.allocator;
    const file = try dir.createFile(io, repo_marker, .{ .read = true, .truncate = true });
    defer file.close(io);
    var fs = storage.FileStorage.init(io, file, 0);
    var log = try logstore.LogStore.open(gpa, fs.storageFile(), 0);
    defer log.deinit(gpa);
    for (bodies) |b| {
        const name = testName(b);
        _ = try log.put(&name, b);
    }
    try log.commit();
    if (index) {
        const blob = try log.serializeIndex(gpa);
        defer gpa.free(blob);
        repocache.storeLogIndex(io, dir, blob);
    }
}

fn testName(body: []const u8) [32]u8 {
    var d: [32]u8 = undefined;
    std.crypto.hash.sha3.Sha3_256.hash(body, &d, .{});
    return d;
}

/// Append `bodies` to `dir`'s store without touching its index, returning
/// the span the last one took.
fn appendBodies(io: std.Io, dir: std.Io.Dir, bodies: []const []const u8) !u64 {
    var sa = try openStoreAppend(io, dir);
    defer sa.close(io);
    const st = try sa.file.stat(io);
    var fs = storage.FileStorage.init(io, sa.file, st.size);
    var log = try logstore.LogStore.open(std.testing.allocator, fs.storageFile(), 0);
    defer log.deinit(std.testing.allocator);
    var before = log.size();
    for (bodies) |b| {
        before = log.size();
        const name = testName(b);
        _ = try log.put(&name, b);
    }
    try log.commit();
    return log.size() - before;
}

fn truncateBy(io: std.Io, dir: std.Io.Dir, n: u64) !void {
    var sa = try openStoreAppend(io, dir);
    defer sa.close(io);
    const st = try sa.file.stat(io);
    try sa.file.setLength(io, st.size - n);
}

/// What a writer open of `dir`'s store leaves behind, and what it reads: the
/// file's length after the open, the handle's end, and which names it holds.
const OpenedShape = struct { file_len: u64, end: u64, count: usize, holds: u64 };

fn openedShape(io: std.Io, dir: std.Io.Dir, names: []const []const u8, via_append_open: bool, scanned: ?*bool) !OpenedShape {
    const gpa = std.testing.allocator;
    var sa = try openStoreAppend(io, dir);
    defer sa.close(io);
    const file = sa.file;
    const st = try file.stat(io);
    var fs = storage.FileStorage.init(io, file, st.size);
    var log = if (via_append_open)
        try openLogForAppend(gpa, io, dir, fs.storageFile(), scanned)
    else
        try logstore.LogStore.open(gpa, fs.storageFile(), 0);
    defer log.deinit(gpa);
    std.debug.assert(names.len <= 64);
    var holds: u64 = 0;
    for (names, 0..) |b, i| {
        const name = testName(b);
        if (log.lookup(&name) != null) holds |= @as(u64, 1) << @intCast(i);
    }
    // The handle must take a further append at its end and keep it.
    const extra = testName("appended after the open");
    _ = try log.put(&extra, "appended after the open");
    try log.commit();
    const after = try file.stat(io);
    return .{ .file_len = after.size, .end = log.end, .count = log.entryCount(), .holds = holds };
}

test "openLogForAppend: a torn tail under a valid index is repaired as the full scan repairs it" {
    const io = std.testing.io;
    const bodies = [_][]const u8{ "alpha", "bravo", "charlie", "delta" };
    // The torn frame sits right at the index's end, or past an intact frame
    // appended after the index was taken; it is torn in its payload trailer,
    // or so early that not even its fixed header landed.
    for ([_]bool{ false, true }) |grown| for ([_]bool{ false, true }) |header_torn| {
        var shapes: [2]OpenedShape = undefined;
        for (&shapes, [_]bool{ false, true }) |*shape, via_append_open| {
            var tmp = std.testing.tmpDir(.{});
            defer tmp.cleanup();
            try seedIndexedStore(io, tmp.dir, bodies[0..2], true);
            const torn = if (grown) bodies[2..4] else bodies[3..4];
            const span = try appendBodies(io, tmp.dir, torn);
            try truncateBy(io, tmp.dir, if (header_torn) span - 10 else 3);
            var scanned = false;
            shape.* = try openedShape(io, tmp.dir, &bodies, via_append_open, &scanned);
            if (via_append_open) try std.testing.expect(scanned);
        }
        try std.testing.expectEqual(shapes[0], shapes[1]);
        const expect_holds: u64 = if (grown) 0b0111 else 0b0011;
        try std.testing.expectEqual(expect_holds, shapes[1].holds);
    };
}

test "openLogForAppend: an index keyed to a different prefix is refused and the log is scanned" {
    const io = std.testing.io;
    // Same frame count and lengths, so every offset the stale index records
    // still lands on a frame boundary; only the last frame's header differs.
    const old = [_][]const u8{ "alpha", "bravo", "charlie" };
    const new = [_][]const u8{ "alpha", "bravo", "CHARLIE" };
    // A rewritten generation: different frames and a different length.
    const packed_gen = [_][]const u8{ "bravo", "echo" };
    const names = [_][]const u8{ "alpha", "bravo", "charlie", "CHARLIE", "echo" };
    for ([_][]const []const u8{ &new, &packed_gen }) |replacement| {
        var shapes: [2]OpenedShape = undefined;
        for (&shapes, [_]bool{ false, true }) |*shape, via_append_open| {
            var tmp = std.testing.tmpDir(.{});
            defer tmp.cleanup();
            try seedIndexedStore(io, tmp.dir, &old, true);
            try seedIndexedStore(io, tmp.dir, replacement, false);
            var scanned = false;
            shape.* = try openedShape(io, tmp.dir, &names, via_append_open, &scanned);
            if (via_append_open) try std.testing.expect(scanned);
        }
        try std.testing.expectEqual(shapes[0], shapes[1]);
        try std.testing.expect(shapes[1].holds & 0b00100 == 0); // nothing from the stale index
    }
}

test "openLogForAppend: a current index is adopted without a scan" {
    const io = std.testing.io;
    const bodies = [_][]const u8{ "alpha", "bravo", "charlie" };
    var shapes: [2]OpenedShape = undefined;
    for (&shapes, [_]bool{ false, true }) |*shape, via_append_open| {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        try seedIndexedStore(io, tmp.dir, &bodies, true);
        var scanned = false;
        shape.* = try openedShape(io, tmp.dir, &bodies, via_append_open, &scanned);
        if (via_append_open) try std.testing.expect(!scanned);
    }
    try std.testing.expectEqual(shapes[0], shapes[1]);
}