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

zat.dev/zds

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

0
0
162 lines · 7.0 KB Raw History
//! Keeps a copy of every blob in an S3-compatible bucket when
//! ZDS_BLOB_MIRROR_BUCKET is set. The blobstore on disk stays the primary
//! copy and serves every read; the bucket is what a lost or restored volume
//! fetches missing blobs back from (blobstore.restoreFromMirror).
//!
//! One background thread does all the bucket writes. Each round it first
//! carries out the deletions blobstore.delete left behind, then uploads the
//! next batch of blobs whose row still says `storage = 'disk'` and marks
//! them `'s3'`. Existing blobs are all `'disk'`, so turning the mirror on
//! backfills them in row order. Nothing on the request path waits for the
//! bucket: an upload is acknowledged once it is on disk, so the newest blobs
//! are only on the volume until the next round.
const std = @import("std");
const zat = @import("zat");
const Io = std.Io;
const log = @import("../core/log.zig");
const blobstore = @import("blobstore.zig");
const s3 = @import("s3.zig");
const store = @import("store.zig");

const batch_size = 32;
const idle_seconds = 30;
/// Once caught up, rounds only look past the last blob they saw. A full
/// pass from the first row, which retries blobs that failed and any row
/// that reused an old rowid, runs this often.
const rescan_seconds = 3600;
const backoff_seconds = 60;
/// Consecutive failures before a round gives up and backs off, so an
/// unreachable bucket is not hammered, while one bad blob does not hold up
/// the rest.
const failures_before_backoff = 3;

var started = std.atomic.Value(bool).init(false);

pub fn start() void {
    if (blobstore.mirror() == null) return;
    if (started.cmpxchgStrong(false, true, .acq_rel, .acquire) != null) return;
    const thread = std.Thread.spawn(.{}, run, .{}) catch |err| {
        started.store(false, .release);
        log.err("blob mirror spawn failed err={s}\n", .{@errorName(err)});
        return;
    };
    thread.detach();
}

fn run() void {
    const io = store.currentIo();
    var transport = zat.HttpTransport.init(io, std.heap.page_allocator);
    defer transport.deinit();
    const client: s3.Client = .{ .config = blobstore.mirror().?, .transport = &transport, .now = nowSeconds };
    var cursor: i64 = 0;
    var last_rescan = nowSeconds();
    if (store.blobMirrorCounts()) |counts| {
        log.info("blob mirror started mirrored={d} pending={d}\n", .{ counts.mirrored, counts.pending });
    } else |_| {}
    while (true) {
        var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
        const round = runRound(arena.allocator(), client, &cursor) catch |err| blk: {
            log.err("blob mirror round failed err={s}\n", .{@errorName(err)});
            break :blk Round{ .backoff = true };
        };
        arena.deinit();
        if (round.uploaded > 0 or round.deleted > 0 or round.failed > 0) {
            log.info("blob mirror uploaded={d} bytes={d} deleted={d} failed={d}\n", .{ round.uploaded, round.bytes, round.deleted, round.failed });
        }
        if (round.caught_up and nowSeconds() - last_rescan >= rescan_seconds) {
            cursor = 0;
            last_rescan = nowSeconds();
        }
        const pause: i64 = if (round.backoff) backoff_seconds else if (round.caught_up) idle_seconds else 0;
        if (pause > 0) io.sleep(Io.Duration.fromSeconds(pause), .awake) catch {};
    }
}

fn nowSeconds() i64 {
    return @intCast(@divTrunc(Io.Timestamp.now(store.currentIo(), .real).nanoseconds, std.time.ns_per_s));
}

pub const Round = struct {
    uploaded: usize = 0,
    bytes: usize = 0,
    deleted: usize = 0,
    failed: usize = 0,
    /// no blobs past the cursor are left to copy.
    caught_up: bool = false,
    backoff: bool = false,
};

/// One round of deletions and uploads. Public for the tests.
pub fn runRound(allocator: std.mem.Allocator, client: s3.Client, cursor: *i64) !Round {
    var round: Round = .{};
    var consecutive_failures: usize = 0;
    // where the current run of failures began, to come back to after a
    // backoff: a run of failures is more likely the bucket than the blobs.
    var streak_start: i64 = cursor.*;

    for (try blobstore.pendingDeletes(allocator, batch_size)) |pending| {
        // The same blob uploaded again since: content-addressed, so the
        // bucket's copy is the live one now and stays.
        if (!try store.blobExists(pending.did, pending.cid)) {
            const key = try blobstore.mirrorKey(allocator, pending.did, pending.cid);
            client.delete(allocator, key) catch |err| {
                log.err("blob mirror delete failed did={s} cid={s} err={s}\n", .{ pending.did, pending.cid, @errorName(err) });
                round.failed += 1;
                round.backoff = true;
                return round;
            };
            round.deleted += 1;
        }
        blobstore.clearPendingDelete(allocator, pending.did, pending.cid);
    }

    const blobs = try store.blobsToMirror(allocator, cursor.*, batch_size);
    if (blobs.len < batch_size) round.caught_up = true;
    for (blobs) |blob| {
        const before = cursor.*;
        cursor.* = blob.rowid;
        const bytes = uploadOne(client, blob) catch |err| {
            log.err("blob mirror upload failed did={s} cid={s} err={s}\n", .{ blob.did, blob.cid, @errorName(err) });
            round.failed += 1;
            if (consecutive_failures == 0) streak_start = before;
            consecutive_failures += 1;
            if (consecutive_failures >= failures_before_backoff) {
                cursor.* = streak_start;
                round.backoff = true;
                round.caught_up = false;
                return round;
            }
            continue;
        };
        consecutive_failures = 0;
        if (bytes) |n| {
            round.uploaded += 1;
            round.bytes += n;
        }
    }
    return round;
}

/// Uploads one blob and marks it mirrored. Null when the blob was deleted
/// meanwhile, in which case its fresh copy is removed again.
fn uploadOne(client: s3.Client, blob: store.BlobToMirror) !?usize {
    // a blob can be as large as the upload limit, so it gets its own arena
    // that is gone before the next one is read.
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const digest = try blobstore.sha256OfCid(allocator, blob.cid);
    const data = try blobstore.getLocal(allocator, blob.did, blob.cid, blob.size + 1);
    if (data.len != blob.size) return error.BlobSizeMismatch;
    var actual: [32]u8 = undefined;
    std.crypto.hash.sha2.Sha256.hash(data, &actual, .{});
    if (!std.mem.eql(u8, &actual, &digest)) return error.BlobDigestMismatch;
    const key = try blobstore.mirrorKey(allocator, blob.did, blob.cid);
    try client.put(allocator, key, data, &std.fmt.bytesToHex(digest, .lower));
    if (try store.markBlobMirrored(blob.did, blob.cid)) return data.len;
    client.delete(allocator, key) catch |err| {
        log.err("blob mirror cleanup failed did={s} cid={s} err={s}\n", .{ blob.did, blob.cid, @errorName(err) });
    };
    return null;
}