Skip to content
zit Artifact [e9a4bfd3ad]
Login

Artifact [e9a4bfd3ad]

Artifact e9a4bfd3ad84c81aa8fe2ad922bdb36169f2dcb32c4ae552822dd17230cd71d7:


//! Pushed deltas waiting for a basis this store does not hold yet.
//!
//! A pusher may send `file HASH DELTASRC SIZE` before the server has
//! DELTASRC. Fossil stores such a delta against a phantom source and
//! completes it when the source lands (xfer.c, D. Richard Hipp). A zit store
//! holds no phantoms, so the delta is kept here instead, in a file beside the
//! store, and applied by the request that brings its basis.
//!
//! Nothing here is trusted. Every record carries a checksum, so a torn or
//! damaged one is skipped, and the artifact a delta reconstructs is verified
//! against its name before it is stored, as any received artifact is. Losing
//! the file costs a pusher the round trips it saved and nothing else: the
//! server asks again for what it no longer has.
//!
//! This file does no I/O. The server loads the bytes before a request and
//! writes `merged` back after it, under the store's writer lock.
const std = @import("std");
const Crc32 = @import("../store/crc32.zig").Crc32;

/// The most bytes the spool file may hold. Past it a delta is not kept and
/// the server asks for its target again.
pub const bytes_max_default: usize = 32 << 20;

/// How long a delta waits for its basis. After that it is discarded and its
/// target is asked for again, so a basis that never comes cannot hold a
/// target back for good.
pub const ttl_s: i64 = 24 * 60 * 60;

/// The most reconstructed bytes one request takes from the spool. A small
/// delta can stand for a large artifact, and a long chain of them would
/// otherwise be rebuilt in memory at once.
pub const apply_bytes_max_default: usize = 256 << 20;

pub const magic = "zit-delta-spool 1\n";

/// A record: payload length and CRC-32 of the payload, both little-endian,
/// then the payload: stamp (i64 seconds), the three name lengths, the names,
/// and the delta as the rest.
const record_header_len = 8;
const payload_fixed_len = 8 + 1 + 1 + 2;

pub const Entry = struct {
    hash: []const u8,
    src: []const u8,
    delta: []const u8,
    state: State = .kept,

    pub const State = enum { kept, added, removed };

    pub fn live(self: Entry) bool {
        return self.state != .removed;
    }
};

pub const DeltaSpool = struct {
    arena: std.heap.ArenaAllocator,
    now_s: i64,
    /// Whose deltas this request may apply. A delta is judged by the push
    /// rules when it is applied, so it is applied only for the pusher who
    /// sent it; the front's login when there is one, else empty.
    owner: []const u8,
    bytes_max: usize = bytes_max_default,
    apply_bytes_max: usize = apply_bytes_max_default,
    entries: std.ArrayListUnmanaged(Entry) = .empty,
    by_target: std.StringHashMapUnmanaged(u32) = .empty,
    /// Targets of the deltas, any owner's, that outlived `ttl_s`. Asking for
    /// an artifact is not owner's business; applying a delta is.
    expired: std.ArrayListUnmanaged([]const u8) = .empty,
    /// Bytes the file holds after this request, counted against `bytes_max`.
    size: usize = magic.len,
    /// Whether the file read differs from what `merged` would write for an
    /// unchanged spool: a damaged or expired record is worth rewriting away.
    stale: bool = false,
    verdict: Verdict = .untouched,
    /// The request may write, so it read the spool and asked for what the
    /// spool gave up on. Only such a request rewrites the file: a rewrite
    /// drops the expired deltas, and their targets must have been asked for.
    engaged: bool = false,

    pub const Verdict = enum {
        /// The request failed before it was judged.
        untouched,
        /// The request was refused after the spool supplied artifacts to it.
        /// What it supplied was judged and is not offered again; what the
        /// request would have added is not kept.
        refused,
        committed,
    };

    pub fn init(gpa: std.mem.Allocator, now_s: i64, owner: []const u8) DeltaSpool {
        return .{ .arena = std.heap.ArenaAllocator.init(gpa), .now_s = now_s, .owner = owner };
    }

    pub fn deinit(self: *DeltaSpool) void {
        self.arena.deinit();
        self.* = undefined;
    }

    /// Read a spool file. Anything that does not parse is passed over.
    pub fn load(self: *DeltaSpool, file: []const u8) error{OutOfMemory}!void {
        const a = self.arena.allocator();
        var it = Records.init(file);
        while (it.next()) |r| {
            if (expiredAt(r.stamp, self.now_s)) {
                self.stale = true;
                try self.expired.append(a, try a.dupe(u8, r.hash));
                continue;
            }
            self.size += r.raw.len;
            if (!std.mem.eql(u8, r.owner, self.owner)) continue;
            const gop = try self.by_target.getOrPut(a, r.hash);
            if (gop.found_existing) {
                // A later record for the same target replaces the earlier.
                self.size -= r.raw.len;
                self.stale = true;
                continue;
            }
            const e: Entry = .{ .hash = try a.dupe(u8, r.hash), .src = try a.dupe(u8, r.src), .delta = try a.dupe(u8, r.delta) };
            gop.key_ptr.* = e.hash;
            gop.value_ptr.* = @intCast(self.entries.items.len);
            try self.entries.append(a, e);
        }
        if (it.damaged or (file.len != 0 and !it.recognised)) self.stale = true;
    }

    /// Whether a delta for `hash` is waiting here.
    pub fn contains(self: *const DeltaSpool, hash: []const u8) bool {
        const i = self.by_target.get(hash) orelse return false;
        return self.entries.items[i].live();
    }

    /// Keep a delta. False when it does not fit, and the caller falls back.
    pub fn put(self: *DeltaSpool, hash: []const u8, src: []const u8, delta: []const u8) error{OutOfMemory}!bool {
        if (!validName(hash) or !validName(src)) return false;
        if (self.owner.len > std.math.maxInt(u16)) return false;
        const len = recordLen(hash, src, self.owner, delta);
        if (self.by_target.get(hash)) |i| {
            const old = &self.entries.items[i];
            if (old.live()) {
                if (std.mem.eql(u8, old.src, src) and std.mem.eql(u8, old.delta, delta)) return true;
                self.remove(i);
            }
        }
        if (len > self.bytes_max or self.size > self.bytes_max - len) return false;
        const a = self.arena.allocator();
        const e: Entry = .{ .hash = try a.dupe(u8, hash), .src = try a.dupe(u8, src), .delta = try a.dupe(u8, delta), .state = .added };
        try self.by_target.put(a, e.hash, @intCast(self.entries.items.len));
        try self.entries.append(a, e);
        self.size += len;
        return true;
    }

    pub fn remove(self: *DeltaSpool, index: u32) void {
        const e = &self.entries.items[index];
        if (!e.live()) return;
        self.size -= recordLen(e.hash, e.src, self.owner, e.delta);
        e.state = .removed;
    }

    /// Whether the file needs writing after this request.
    pub fn dirty(self: *const DeltaSpool) bool {
        if (!self.engaged or self.verdict == .untouched) return false;
        if (self.stale) return true;
        for (self.entries.items) |e| switch (e.state) {
            .kept => {},
            .removed => return true,
            .added => if (self.verdict == .committed) return true,
        };
        return false;
    }

    /// The file to write: `disk` as it is now, less what this request took or
    /// replaced and what has expired, plus what this request added. `disk` is
    /// read again under the writer lock, so a record another writer added
    /// since `load` is kept. Caller owns the result.
    pub fn merged(self: *const DeltaSpool, gpa: std.mem.Allocator, disk: []const u8) error{OutOfMemory}![]u8 {
        var out: std.ArrayListUnmanaged(u8) = .empty;
        errdefer out.deinit(gpa);
        try out.appendSlice(gpa, magic);
        var seen: std.StringHashMapUnmanaged(void) = .empty;
        defer seen.deinit(gpa);
        var it = Records.init(disk);
        while (it.next()) |r| {
            if (expiredAt(r.stamp, self.now_s)) continue;
            if (std.mem.eql(u8, r.owner, self.owner)) {
                if (self.by_target.get(r.hash)) |i| if (self.entries.items[i].state != .kept) continue;
                const gop = try seen.getOrPut(gpa, r.hash);
                if (gop.found_existing) continue;
            }
            if (out.items.len + r.raw.len > self.bytes_max) continue;
            try out.appendSlice(gpa, r.raw);
        }
        if (self.verdict == .committed) for (self.entries.items) |e| {
            if (e.state != .added) continue;
            const len = recordLen(e.hash, e.src, self.owner, e.delta);
            if (out.items.len + len > self.bytes_max) continue;
            try appendRecord(gpa, &out, self.now_s, e.hash, e.src, self.owner, e.delta);
        };
        return out.toOwnedSlice(gpa);
    }
};

fn expiredAt(stamp: i64, now_s: i64) bool {
    // A stamp ahead of the clock is as untrustworthy as an old one: a clock
    // stepped back must not make a delta wait forever.
    return now_s -| stamp > ttl_s or stamp -| now_s > ttl_s;
}

fn validName(name: []const u8) bool {
    if (name.len != 40 and name.len != 64) return false;
    for (name) |c| switch (c) {
        '0'...'9', 'a'...'f' => {},
        else => return false,
    };
    return true;
}

fn recordLen(hash: []const u8, src: []const u8, owner: []const u8, delta: []const u8) usize {
    return record_header_len + payload_fixed_len + hash.len + src.len + owner.len + delta.len;
}

fn appendRecord(
    gpa: std.mem.Allocator,
    out: *std.ArrayListUnmanaged(u8),
    stamp: i64,
    hash: []const u8,
    src: []const u8,
    owner: []const u8,
    delta: []const u8,
) error{OutOfMemory}!void {
    const len = recordLen(hash, src, owner, delta);
    try out.ensureUnusedCapacity(gpa, len);
    const start = out.items.len;
    var word: [8]u8 = undefined;
    out.appendNTimesAssumeCapacity(0, record_header_len);
    std.mem.writeInt(i64, &word, stamp, .little);
    out.appendSliceAssumeCapacity(&word);
    out.appendAssumeCapacity(@intCast(hash.len));
    out.appendAssumeCapacity(@intCast(src.len));
    std.mem.writeInt(u16, word[0..2], @intCast(owner.len), .little);
    out.appendSliceAssumeCapacity(word[0..2]);
    out.appendSliceAssumeCapacity(hash);
    out.appendSliceAssumeCapacity(src);
    out.appendSliceAssumeCapacity(owner);
    out.appendSliceAssumeCapacity(delta);
    const payload = out.items[start + record_header_len ..];
    std.mem.writeInt(u32, out.items[start..][0..4], @intCast(payload.len), .little);
    std.mem.writeInt(u32, out.items[start + 4 ..][0..4], Crc32.hash(payload), .little);
}

/// Walks the records of a spool file, passing over what does not check.
const Records = struct {
    file: []const u8,
    at: usize,
    recognised: bool,
    damaged: bool = false,

    const Record = struct {
        raw: []const u8,
        stamp: i64,
        hash: []const u8,
        src: []const u8,
        owner: []const u8,
        delta: []const u8,
    };

    fn init(file: []const u8) Records {
        const ok = std.mem.startsWith(u8, file, magic);
        return .{ .file = file, .at = if (ok) magic.len else file.len, .recognised = ok };
    }

    fn next(self: *Records) ?Record {
        while (self.at < self.file.len) {
            const rest = self.file[self.at..];
            // A length that runs past the end is a torn tail, or a damaged
            // length: either way nothing after it can be framed.
            if (rest.len < record_header_len) break;
            const len: usize = std.mem.readInt(u32, rest[0..4], .little);
            if (len < payload_fixed_len or len > rest.len - record_header_len) break;
            const raw = rest[0 .. record_header_len + len];
            self.at += raw.len;
            const payload = raw[record_header_len..];
            if (Crc32.hash(payload) != std.mem.readInt(u32, rest[4..8], .little)) {
                self.damaged = true;
                continue;
            }
            const hash_len: usize = payload[8];
            const src_len: usize = payload[9];
            const owner_len: usize = std.mem.readInt(u16, payload[10..12], .little);
            const names = payload[payload_fixed_len..];
            if (hash_len + src_len + owner_len > names.len) {
                self.damaged = true;
                continue;
            }
            const r: Record = .{
                .raw = raw,
                .stamp = std.mem.readInt(i64, payload[0..8], .little),
                .hash = names[0..hash_len],
                .src = names[hash_len..][0..src_len],
                .owner = names[hash_len + src_len ..][0..owner_len],
                .delta = names[hash_len + src_len + owner_len ..],
            };
            if (!validName(r.hash) or !validName(r.src)) {
                self.damaged = true;
                continue;
            }
            return r;
        }
        if (self.at < self.file.len) {
            self.damaged = true;
            self.at = self.file.len;
        }
        return null;
    }
};

const testing = std.testing;
const repeat = @import("../repeat.zig").repeat;
const name_a = repeat("a", 64);
const name_b = repeat("b", 64);
const name_c = repeat("c", 64);
const name_d = repeat("d", 64);

/// A spool that accepted `puts` and was committed, as the file it writes.
fn fileOf(gpa: std.mem.Allocator, now_s: i64, owner: []const u8, puts: []const [3][]const u8) ![]u8 {
    var s = DeltaSpool.init(gpa, now_s, owner);
    defer s.deinit();
    for (puts) |p| try testing.expect(try s.put(p[0], p[1], p[2]));
    s.engaged = true;
    s.verdict = .committed;
    return s.merged(gpa, "");
}

test "spool: what one request keeps the next one reads back" {
    const gpa = testing.allocator;
    const file = try fileOf(gpa, 1000, "", &.{ .{ name_b, name_a, "delta-ab" }, .{ name_c, name_b, "delta-bc" } });
    defer gpa.free(file);

    var s = DeltaSpool.init(gpa, 1001, "");
    defer s.deinit();
    try s.load(file);
    try testing.expectEqual(@as(usize, 2), s.entries.items.len);
    try testing.expect(s.contains(name_b) and s.contains(name_c));
    try testing.expectEqualStrings("delta-bc", s.entries.items[s.by_target.get(name_c).?].delta);
    try testing.expectEqualStrings(name_b, s.entries.items[s.by_target.get(name_c).?].src);
    try testing.expectEqual(file.len, s.size);
    try testing.expect(!s.dirty());
}

test "spool: a damaged record is passed over and the ones around it survive" {
    const gpa = testing.allocator;
    const file = try fileOf(gpa, 1000, "", &.{ .{ name_b, name_a, "first" }, .{ name_c, name_b, "second" }, .{ name_d, name_c, "third" } });
    defer gpa.free(file);
    // One byte of the middle record's delta.
    const at = std.mem.indexOf(u8, file, "second").?;
    file[at] ^= 0x40;

    var s = DeltaSpool.init(gpa, 1000, "");
    defer s.deinit();
    try s.load(file);
    try testing.expect(s.contains(name_b));
    try testing.expect(!s.contains(name_c));
    try testing.expect(s.contains(name_d));
    // The rewrite drops the damage.
    s.engaged = true;
    s.verdict = .committed;
    try testing.expect(s.dirty());
    const healed = try s.merged(gpa, file);
    defer gpa.free(healed);
    try testing.expect(healed.len < file.len);
    var again = DeltaSpool.init(gpa, 1000, "");
    defer again.deinit();
    try again.load(healed);
    try testing.expectEqual(@as(usize, 2), again.entries.items.len);
    try testing.expect(!again.stale);
}

test "spool: a torn tail, a wrong header and an empty file all read as what is whole" {
    const gpa = testing.allocator;
    const file = try fileOf(gpa, 1000, "", &.{ .{ name_b, name_a, "first" }, .{ name_c, name_b, "second" } });
    defer gpa.free(file);
    {
        var s = DeltaSpool.init(gpa, 1000, "");
        defer s.deinit();
        try s.load(file[0 .. file.len - 3]);
        try testing.expect(s.contains(name_b));
        try testing.expect(!s.contains(name_c));
        try testing.expect(s.stale);
    }
    {
        var s = DeltaSpool.init(gpa, 1000, "");
        defer s.deinit();
        try s.load(file[1..]);
        try testing.expectEqual(@as(usize, 0), s.entries.items.len);
        try testing.expect(s.stale);
    }
    {
        var s = DeltaSpool.init(gpa, 1000, "");
        defer s.deinit();
        try s.load("");
        try testing.expectEqual(@as(usize, 0), s.entries.items.len);
        try testing.expect(!s.stale);
    }
    // Every prefix and every single-byte flip parses without a fault.
    for (0..file.len) |n| {
        var s = DeltaSpool.init(gpa, 1000, "");
        defer s.deinit();
        try s.load(file[0..n]);
        const copy = try gpa.dupe(u8, file);
        defer gpa.free(copy);
        copy[n] ^= 0xff;
        var t = DeltaSpool.init(gpa, 1000, "");
        defer t.deinit();
        try t.load(copy);
    }
}

test "spool: past the cap a delta is refused and the spool is unchanged" {
    const gpa = testing.allocator;
    var s = DeltaSpool.init(gpa, 1000, "");
    defer s.deinit();
    const one = recordLen(name_b, name_a, "", "12345678");
    s.bytes_max = magic.len + one + one / 2;
    try testing.expect(try s.put(name_b, name_a, "12345678"));
    try testing.expect(!try s.put(name_c, name_b, "12345678"));
    try testing.expect(!s.contains(name_c));
    // The same delta again is already kept, and a removal makes room.
    try testing.expect(try s.put(name_b, name_a, "12345678"));
    s.remove(s.by_target.get(name_b).?);
    try testing.expect(try s.put(name_c, name_b, "12345678"));
    // A name that is not a hash is never kept.
    try testing.expect(!try s.put("not-a-hash", name_a, "x"));
}

test "spool: a delta past its time is dropped and its target reported" {
    const gpa = testing.allocator;
    const file = try fileOf(gpa, 1000, "", &.{.{ name_b, name_a, "old" }});
    defer gpa.free(file);
    for ([_]i64{ 1000 + ttl_s + 1, 1000 - ttl_s - 1 }) |now| {
        var s = DeltaSpool.init(gpa, now, "");
        defer s.deinit();
        try s.load(file);
        try testing.expect(!s.contains(name_b));
        try testing.expectEqual(@as(usize, 1), s.expired.items.len);
        try testing.expectEqualStrings(name_b, s.expired.items[0]);
        s.engaged = true;
        s.verdict = .committed;
        const rewritten = try s.merged(gpa, file);
        defer gpa.free(rewritten);
        try testing.expectEqualStrings(magic, rewritten);
    }
    var s = DeltaSpool.init(gpa, 1000 + ttl_s, "");
    defer s.deinit();
    try s.load(file);
    try testing.expect(s.contains(name_b));
}

test "spool: one pusher's deltas are not another's, and both survive a rewrite" {
    const gpa = testing.allocator;
    const jan = try fileOf(gpa, 1000, "jan", &.{.{ name_b, name_a, "jan's" }});
    defer gpa.free(jan);

    var s = DeltaSpool.init(gpa, 1000, "piet");
    defer s.deinit();
    try s.load(jan);
    try testing.expect(!s.contains(name_b));
    try testing.expectEqual(jan.len, s.size);
    try testing.expect(try s.put(name_b, name_a, "piet's"));
    s.engaged = true;
    s.verdict = .committed;
    const both = try s.merged(gpa, jan);
    defer gpa.free(both);

    for ([_][2][]const u8{ .{ "jan", "jan's" }, .{ "piet", "piet's" } }) |who| {
        var r = DeltaSpool.init(gpa, 1000, who[0]);
        defer r.deinit();
        try r.load(both);
        try testing.expectEqual(@as(usize, 1), r.entries.items.len);
        try testing.expectEqualStrings(who[1], r.entries.items[0].delta);
    }
}

test "spool: a rewrite keeps what another writer added since the load, and a refused request adds nothing" {
    const gpa = testing.allocator;
    const before = try fileOf(gpa, 1000, "", &.{.{ name_b, name_a, "ab" }});
    defer gpa.free(before);
    const during = try fileOf(gpa, 1000, "", &.{ .{ name_b, name_a, "ab" }, .{ name_d, name_c, "cd" } });
    defer gpa.free(during);

    var s = DeltaSpool.init(gpa, 1000, "");
    defer s.deinit();
    try s.load(before);
    s.remove(s.by_target.get(name_b).?);
    try testing.expect(try s.put(name_c, name_b, "bc"));

    s.engaged = true;
    s.verdict = .refused;
    try testing.expect(s.dirty());
    const refused = try s.merged(gpa, during);
    defer gpa.free(refused);
    var r = DeltaSpool.init(gpa, 1000, "");
    defer r.deinit();
    try r.load(refused);
    try testing.expect(!r.contains(name_b) and !r.contains(name_c) and r.contains(name_d));

    s.engaged = true;
    s.verdict = .committed;
    const committed = try s.merged(gpa, during);
    defer gpa.free(committed);
    var c = DeltaSpool.init(gpa, 1000, "");
    defer c.deinit();
    try c.load(committed);
    try testing.expect(!c.contains(name_b) and c.contains(name_c) and c.contains(name_d));

    s.verdict = .untouched;
    try testing.expect(!s.dirty());
}