~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
213 lines · 7.1 KB Raw History
//! The last encoded full-repo CARs, keyed by repo and commit CID. A full
//! getRepo is the costliest read a PDS answers, and relays, backfillers and
//! mirrors ask for the same repo again and again between writes; while the
//! head commit is unchanged its export is the same bytes, so they are built
//! once and served from here until the repo moves on or the space is needed.
//!
//! Entries are reference counted: a reader streaming one keeps it alive
//! after it is replaced or evicted.

const std = @import("std");

pub const Entry = struct {
    did: []u8,
    commit_cid: []u8,
    bytes: []u8,
    refs: usize = 1,
    last_used: u64 = 0,

    pub fn release(self: *Entry) void {
        if (@atomicRmw(usize, &self.refs, .Sub, 1, .acq_rel) == 1) destroy(self);
    }

    fn retain(self: *Entry) void {
        _ = @atomicRmw(usize, &self.refs, .Add, 1, .monotonic);
    }
};

const allocator = std.heap.smp_allocator;
const max_entries = 8;

var lock: std.atomic.Value(bool) = .init(false);
var entries: [max_entries]?*Entry = @splat(null);
var held_bytes: usize = 0;
var clock: u64 = 0;
var hits: std.atomic.Value(usize) = .init(0);
var misses: std.atomic.Value(usize) = .init(0);

fn acquireLock() void {
    while (lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
}

fn releaseLock() void {
    lock.store(false, .release);
}

/// The cached CAR for this repo at this commit, retained for the caller, who
/// releases it when done writing.
pub fn acquire(did: []const u8, commit_cid: []const u8) ?*Entry {
    acquireLock();
    defer releaseLock();
    for (entries) |slot| {
        const entry = slot orelse continue;
        if (std.mem.eql(u8, entry.did, did) and std.mem.eql(u8, entry.commit_cid, commit_cid)) {
            clock += 1;
            entry.last_used = clock;
            entry.retain();
            _ = hits.fetchAdd(1, .monotonic);
            return entry;
        }
    }
    _ = misses.fetchAdd(1, .monotonic);
    return null;
}

/// Takes `bytes` (allocated with `bytesAllocator`) as this repo's export at
/// `commit_cid` and returns it retained for the caller. A repo keeps one
/// entry: its older commit's export is dropped. Older entries of other repos
/// are evicted to stay within `budget`; an export larger than the budget is
/// not kept, but is still returned for the caller to send.
pub fn put(did: []const u8, commit_cid: []const u8, bytes: []u8, budget: usize) !*Entry {
    const entry = try allocator.create(Entry);
    errdefer allocator.destroy(entry);
    const did_copy = try allocator.dupe(u8, did);
    errdefer allocator.free(did_copy);
    const cid_copy = try allocator.dupe(u8, commit_cid);
    entry.* = .{ .did = did_copy, .commit_cid = cid_copy, .bytes = bytes };
    if (bytes.len > budget) return entry;

    acquireLock();
    defer releaseLock();
    for (&entries) |*slot| {
        const old = slot.* orelse continue;
        if (std.mem.eql(u8, old.did, did)) dropLocked(slot);
    }
    while (held_bytes + bytes.len > budget or freeSlotLocked() == null) {
        dropLocked(oldestSlotLocked() orelse break);
    }
    const slot = freeSlotLocked() orelse return entry;
    clock += 1;
    entry.last_used = clock;
    entry.retain();
    slot.* = entry;
    held_bytes += bytes.len;
    return entry;
}

/// Drops every cached export of this repo, for an account that is deleted.
pub fn forget(did: []const u8) void {
    acquireLock();
    defer releaseLock();
    for (&entries) |*slot| {
        const old = slot.* orelse continue;
        if (std.mem.eql(u8, old.did, did)) dropLocked(slot);
    }
}

pub fn bytesAllocator() std.mem.Allocator {
    return allocator;
}

pub const Stats = struct { entries: usize, bytes: usize, hits: usize, misses: usize };

pub fn stats() Stats {
    acquireLock();
    defer releaseLock();
    var count: usize = 0;
    for (entries) |slot| {
        if (slot != null) count += 1;
    }
    return .{ .entries = count, .bytes = held_bytes, .hits = hits.load(.monotonic), .misses = misses.load(.monotonic) };
}

fn freeSlotLocked() ?*?*Entry {
    for (&entries) |*slot| {
        if (slot.* == null) return slot;
    }
    return null;
}

fn oldestSlotLocked() ?*?*Entry {
    var oldest: ?*?*Entry = null;
    for (&entries) |*slot| {
        const entry = slot.* orelse continue;
        if (oldest == null or entry.last_used < oldest.?.*.?.last_used) oldest = slot;
    }
    return oldest;
}

fn dropLocked(slot: *?*Entry) void {
    const entry = slot.*.?;
    slot.* = null;
    held_bytes -= entry.bytes.len;
    entry.release();
}

fn destroy(entry: *Entry) void {
    allocator.free(entry.bytes);
    allocator.free(entry.commit_cid);
    allocator.free(entry.did);
    allocator.destroy(entry);
}

fn resetForTest() void {
    for (&entries) |*slot| {
        if (slot.* != null) dropLocked(slot);
    }
    hits.store(0, .monotonic);
    misses.store(0, .monotonic);
}

fn testBytes(len: usize) ![]u8 {
    const bytes = try allocator.alloc(u8, len);
    @memset(bytes, 0xca);
    return bytes;
}

test "a repo's export is served until its commit changes" {
    resetForTest();
    defer resetForTest();

    try std.testing.expect(acquire("did:plc:a", "bafyone") == null);
    const first = try put("did:plc:a", "bafyone", try testBytes(10), 100);
    first.release();
    const hit = acquire("did:plc:a", "bafyone") orelse return error.TestUnexpectedResult;
    try std.testing.expectEqual(@as(usize, 10), hit.bytes.len);
    try std.testing.expect(acquire("did:plc:a", "bafytwo") == null);

    // A newer commit replaces the old export; a reader still writing the
    // old bytes keeps them until it is done.
    (try put("did:plc:a", "bafytwo", try testBytes(20), 100)).release();
    try std.testing.expectEqual(@as(usize, 10), hit.bytes.len);
    hit.release();
    try std.testing.expect(acquire("did:plc:a", "bafyone") == null);
    try std.testing.expectEqual(Stats{ .entries = 1, .bytes = 20, .hits = 1, .misses = 3 }, stats());
}

test "the byte budget evicts the least recently used repo" {
    resetForTest();
    defer resetForTest();

    (try put("did:plc:a", "bafya", try testBytes(40), 100)).release();
    (try put("did:plc:b", "bafyb", try testBytes(40), 100)).release();
    acquire("did:plc:a", "bafya").?.release();
    (try put("did:plc:c", "bafyc", try testBytes(40), 100)).release();
    try std.testing.expect(acquire("did:plc:b", "bafyb") == null);
    acquire("did:plc:a", "bafya").?.release();
    acquire("did:plc:c", "bafyc").?.release();

    // Too large to keep, but still handed back to send.
    const big = try put("did:plc:d", "bafyd", try testBytes(101), 100);
    try std.testing.expectEqual(@as(usize, 101), big.bytes.len);
    big.release();
    try std.testing.expect(acquire("did:plc:d", "bafyd") == null);
    try std.testing.expectEqual(@as(usize, 80), stats().bytes);

    forget("did:plc:a");
    try std.testing.expect(acquire("did:plc:a", "bafya") == null);
    try std.testing.expectEqual(@as(usize, 40), stats().bytes);

    // A zero budget keeps nothing.
    (try put("did:plc:e", "bafye", try testBytes(1), 0)).release();
    try std.testing.expect(acquire("did:plc:e", "bafye") == null);
}