const std = @import("std"); const zat = @import("zat"); const log = @import("../core/log.zig"); const s3 = @import("s3.zig"); const Io = std.Io; var blob_io: Io = undefined; var root_path: []const u8 = "dev/blobs"; var initialized = false; /// The bucket that keeps a copy of every blob, when one is configured. The /// files under `root_path` stay the primary copy; see blob_mirror.zig. var mirror_config: ?s3.Config = null; var mirror_prefix: []const u8 = "blobs/"; /// Deletions the mirror still has to make in the bucket, one empty file per /// blob, so they survive a restart. Not a DID, so never an actor directory. const pending_deletes_dir = ".mirror-deletes"; pub fn init(io: Io, path: []const u8) void { blob_io = io; root_path = trimTrailingSlash(path); initialized = true; } pub fn initMirror(config: s3.Config, prefix: []const u8) void { mirror_config = config; mirror_prefix = prefix; } pub fn mirror() ?s3.Config { return mirror_config; } /// `/`: the object that holds a blob's copy. pub fn mirrorKey(allocator: std.mem.Allocator, did: []const u8, cid: []const u8) ![]u8 { return std.fmt.allocPrint(allocator, "{s}{s}/{s}", .{ mirror_prefix, did, cid }); } pub fn put(allocator: std.mem.Allocator, io: Io, did: []const u8, cid: []const u8, data: []const u8) !void { const temp_path = try stage(allocator, io, did, cid, data); errdefer discard(temp_path); try promote(allocator, temp_path, did, cid); } pub fn stage(allocator: std.mem.Allocator, io: Io, did: []const u8, cid: []const u8, data: []const u8) ![]const u8 { try requireInitialized(); const dir_path = try actorDirPath(allocator, did); try mkdirPath(allocator, dir_path); const path = try blobPath(allocator, did, cid); return writeTempFileC(allocator, io, path, data); } pub const StagedUpload = struct { temp_path: []const u8, digest: [std.crypto.hash.sha2.Sha256.digest_length]u8, size: usize, }; pub fn stageUpload( allocator: std.mem.Allocator, io: Io, did: []const u8, reader: *std.Io.Reader, expected_size: usize, max_size: usize, ) !StagedUpload { if (expected_size > max_size) return error.BlobTooLarge; try requireInitialized(); const dir_path = try actorDirPath(allocator, did); try mkdirPath(allocator, dir_path); const temp_path = try uniqueTempPath(allocator, io, dir_path); const temp_path_z = try allocator.dupeSentinel(u8, temp_path, 0); errdefer Io.Dir.cwd().deleteFile(io, temp_path) catch {}; const file = std.c.fopen(temp_path_z.ptr, "wb") orelse return error.OpenBlobFailed; var closed = false; defer { if (!closed) _ = std.c.fclose(file); } const Sha256 = std.crypto.hash.sha2.Sha256; var hasher = Sha256.init(.{}); var size: usize = 0; var buf: [64 * 1024]u8 = undefined; while (size < expected_size) { const read_len = @min(buf.len, expected_size - size); reader.readSliceAll(buf[0..read_len]) catch return error.IncompleteBlob; const chunk = buf[0..read_len]; if (std.c.fwrite(chunk.ptr, 1, chunk.len, file) != chunk.len) return error.WriteBlobFailed; hasher.update(chunk); size += chunk.len; } if (std.c.fclose(file) != 0) return error.WriteBlobFailed; closed = true; var digest: [Sha256.digest_length]u8 = undefined; hasher.final(&digest); return .{ .temp_path = temp_path, .digest = digest, .size = size }; } pub fn promote(allocator: std.mem.Allocator, temp_path: []const u8, did: []const u8, cid: []const u8) !void { try requireInitialized(); const path = try blobPath(allocator, did, cid); try Io.Dir.cwd().rename(temp_path, Io.Dir.cwd(), path, blob_io); } pub fn discard(temp_path: []const u8) void { Io.Dir.cwd().deleteFile(blob_io, temp_path) catch {}; } pub fn get(allocator: std.mem.Allocator, did: []const u8, cid: []const u8, limit: usize) ![]u8 { try requireInitialized(); const path = try blobPath(allocator, did, cid); return Io.Dir.cwd().readFileAlloc(blob_io, path, allocator, .limited(limit)) catch |err| switch (err) { error.FileNotFound => { if (!try restoreFromMirror(allocator, did, cid, limit)) return err; return Io.Dir.cwd().readFileAlloc(blob_io, path, allocator, .limited(limit)); }, else => return err, }; } /// Opens a blob to stream it rather than read it whole; close it with /// `file.close(blobstore.fileIo())`. pub fn open(allocator: std.mem.Allocator, did: []const u8, cid: []const u8) !Io.File { try requireInitialized(); const path = try blobPath(allocator, did, cid); return Io.Dir.cwd().openFile(blob_io, path, .{}) catch |err| switch (err) { error.FileNotFound => { if (!try restoreFromMirror(allocator, did, cid, std.math.maxInt(usize))) return err; return Io.Dir.cwd().openFile(blob_io, path, .{}); }, else => return err, }; } /// Reads the file on disk only, never the mirror: what the mirror uploads. pub fn getLocal(allocator: std.mem.Allocator, did: []const u8, cid: []const u8, limit: usize) ![]u8 { try requireInitialized(); const path = try blobPath(allocator, did, cid); return Io.Dir.cwd().readFileAlloc(blob_io, path, allocator, .limited(limit)); } /// A blob that is missing on disk but has a copy in the bucket (a volume /// restored from an older snapshot, or a new one) is fetched back into the /// blobstore. The bytes must hash to the CID before they are kept. Returns /// false when no mirror is configured or the bucket has no such object. fn restoreFromMirror(allocator: std.mem.Allocator, did: []const u8, cid: []const u8, limit: usize) !bool { const config = mirror_config orelse return false; const expected = try sha256OfCid(allocator, cid); const dir_path = try actorDirPath(allocator, did); try mkdirPath(allocator, dir_path); const temp_path = try uniqueTempPath(allocator, blob_io, dir_path); var kept = false; defer if (!kept) Io.Dir.cwd().deleteFile(blob_io, temp_path) catch {}; const file = try Io.Dir.cwd().createFile(blob_io, temp_path, .{}); var file_closed = false; defer if (!file_closed) file.close(blob_io); var file_buf: [64 * 1024]u8 = undefined; var file_writer = file.writer(blob_io, &file_buf); var hash_buf: [64]u8 = undefined; var hashed = file_writer.interface.hashed(std.crypto.hash.sha2.Sha256.init(.{}), &hash_buf); var transport = zat.HttpTransport.init(blob_io, allocator); defer transport.deinit(); const client: s3.Client = .{ .config = config, .transport = &transport, .now = nowSeconds }; const key = try mirrorKey(allocator, did, cid); const size = client.get(allocator, key, &hashed.writer, limit) catch |err| { log.err("blob mirror restore failed did={s} cid={s} err={s}\n", .{ did, cid, @errorName(err) }); return err; } orelse return false; try hashed.writer.flush(); try file_writer.interface.flush(); file.close(blob_io); file_closed = true; var digest: [32]u8 = undefined; hashed.hasher.final(&digest); if (!std.mem.eql(u8, &digest, &expected)) { log.err("blob mirror restore refused did={s} cid={s} reason=digest_mismatch\n", .{ did, cid }); return error.MirrorDigestMismatch; } try Io.Dir.cwd().rename(temp_path, Io.Dir.cwd(), try blobPath(allocator, did, cid), blob_io); kept = true; log.info("blob mirror restored did={s} cid={s} bytes={d}\n", .{ did, cid, size }); return true; } /// The SHA-256 a blob CID names; blobs are always raw sha2-256 CIDs. pub fn sha256OfCid(allocator: std.mem.Allocator, cid: []const u8) ![32]u8 { const parsed = zat.cbor.Cid.fromString(allocator, cid) catch return error.InvalidBlobCid; if (parsed.hashFn() != 0x12) return error.InvalidBlobCid; const digest = parsed.digest() orelse return error.InvalidBlobCid; if (digest.len != 32) return error.InvalidBlobCid; return digest[0..32].*; } fn nowSeconds() i64 { return @intCast(@divTrunc(Io.Timestamp.now(blob_io, .real).nanoseconds, std.time.ns_per_s)); } pub fn fileIo() Io { return blob_io; } pub fn delete(allocator: std.mem.Allocator, did: []const u8, cid: []const u8) !void { try requireInitialized(); const path = try blobPath(allocator, did, cid); Io.Dir.cwd().deleteFile(blob_io, path) catch |err| switch (err) { error.FileNotFound => {}, else => return err, }; // The bucket's copy goes too, but not from here: a deletion runs inside // account deletion and blob collection, so it only leaves a note that // the mirror worker carries out. if (mirror_config != null) try markPendingDelete(allocator, did, cid); } fn pendingDeletePath(allocator: std.mem.Allocator, did: []const u8, cid: []const u8) ![]const u8 { const name = try std.fmt.allocPrint(allocator, "{s}+{s}", .{ did, cid }); return std.fs.path.join(allocator, &.{ root_path, pending_deletes_dir, name }); } fn markPendingDelete(allocator: std.mem.Allocator, did: []const u8, cid: []const u8) !void { const dir_path = try std.fs.path.join(allocator, &.{ root_path, pending_deletes_dir }); try mkdirPath(allocator, dir_path); const temp_path = try writeTempFileC(allocator, blob_io, try pendingDeletePath(allocator, did, cid), ""); errdefer discard(temp_path); try Io.Dir.cwd().rename(temp_path, Io.Dir.cwd(), try pendingDeletePath(allocator, did, cid), blob_io); } pub const PendingDelete = struct { did: []const u8, cid: []const u8 }; /// Up to `limit` deletions the bucket has not seen yet. pub fn pendingDeletes(allocator: std.mem.Allocator, limit: usize) ![]PendingDelete { try requireInitialized(); const dir_path = try std.fs.path.join(allocator, &.{ root_path, pending_deletes_dir }); var dir = Io.Dir.cwd().openDir(blob_io, dir_path, .{ .iterate = true }) catch |err| switch (err) { error.FileNotFound => return &.{}, else => return err, }; defer dir.close(blob_io); var out: std.ArrayList(PendingDelete) = .empty; var it = dir.iterate(); while (out.items.len < limit) { const entry = (try it.next(blob_io)) orelse break; if (entry.kind != .file) continue; const split = std.mem.lastIndexOfScalar(u8, entry.name, '+') orelse continue; if (std.mem.indexOf(u8, entry.name, ".tmp-") != null) continue; try out.append(allocator, .{ .did = try allocator.dupe(u8, entry.name[0..split]), .cid = try allocator.dupe(u8, entry.name[split + 1 ..]), }); } return out.toOwnedSlice(allocator); } pub fn clearPendingDelete(allocator: std.mem.Allocator, did: []const u8, cid: []const u8) void { const path = pendingDeletePath(allocator, did, cid) catch return; Io.Dir.cwd().deleteFile(blob_io, path) catch {}; } pub fn deleteActorDir(allocator: std.mem.Allocator, did: []const u8) void { requireInitialized() catch return; const path = actorDirPath(allocator, did) catch return; Io.Dir.cwd().deleteDir(blob_io, path) catch {}; } fn actorDirPath(allocator: std.mem.Allocator, did: []const u8) ![]const u8 { return std.fs.path.join(allocator, &.{ root_path, did }); } fn blobPath(allocator: std.mem.Allocator, did: []const u8, cid: []const u8) ![]const u8 { return std.fs.path.join(allocator, &.{ root_path, did, cid }); } fn requireInitialized() !void { if (!initialized) return error.BlobstoreNotInitialized; } fn trimTrailingSlash(value: []const u8) []const u8 { if (value.len > 1 and value[value.len - 1] == '/') return value[0 .. value.len - 1]; return value; } fn mkdirPath(allocator: std.mem.Allocator, path: []const u8) !void { var index: usize = 0; while (index < path.len) : (index += 1) { if (path[index] != std.fs.path.sep) continue; if (index == 0) continue; try mkdirOne(allocator, path[0..index]); } try mkdirOne(allocator, path); } fn mkdirOne(allocator: std.mem.Allocator, path: []const u8) !void { const path_z = try allocator.dupeSentinel(u8, path, 0); if (std.c.mkdir(path_z.ptr, 0o755) == 0) return; const err: std.posix.E = @fromBackingInt(@intCast(std.posix.system._errno().*)); if (err == .EXIST) return; return error.CreateDirFailed; } fn writeTempFileC(allocator: std.mem.Allocator, io: Io, path: []const u8, data: []const u8) ![]const u8 { var random_bytes: [8]u8 = undefined; io.random(&random_bytes); const nonce = std.fmt.bytesToHex(random_bytes, .lower); const temp_path = try std.fmt.allocPrint(allocator, "{s}.tmp-{s}", .{ path, &nonce }); const temp_path_z = try allocator.dupeSentinel(u8, temp_path, 0); errdefer Io.Dir.cwd().deleteFile(io, temp_path) catch {}; const file = std.c.fopen(temp_path_z.ptr, "wb") orelse return error.OpenBlobFailed; var closed = false; defer { if (!closed) _ = std.c.fclose(file); } if (data.len > 0 and std.c.fwrite(data.ptr, 1, data.len, file) != data.len) { return error.WriteBlobFailed; } if (std.c.fclose(file) != 0) return error.WriteBlobFailed; closed = true; return temp_path; } fn uniqueTempPath(allocator: std.mem.Allocator, io: Io, dir_path: []const u8) ![]const u8 { var random_bytes: [8]u8 = undefined; io.random(&random_bytes); const nonce = std.fmt.bytesToHex(random_bytes, .lower); return std.fmt.allocPrint(allocator, "{s}/.upload-{s}.tmp", .{ dir_path, &nonce }); } test "disk blobstore writes and reads account blob bytes" { const allocator = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [std.fs.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(std.testing.io, &path_buf); const path = path_buf[0..path_len]; init(std.Options.debug_io, path); var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const a = arena.allocator(); try put(a, std.Options.debug_io, "did:plc:test", "bafytest", "hello blobstore"); const data = try get(a, "did:plc:test", "bafytest", 1024); try std.testing.expectEqualStrings("hello blobstore", data); } test "disk blobstore replaces existing bytes atomically" { const allocator = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [std.fs.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(std.testing.io, &path_buf); const path = path_buf[0..path_len]; init(std.Options.debug_io, path); var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const a = arena.allocator(); try put(a, std.Options.debug_io, "did:plc:test", "bafytest", "first"); try put(a, std.Options.debug_io, "did:plc:test", "bafytest", "second"); const data = try get(a, "did:plc:test", "bafytest", 1024); try std.testing.expectEqualStrings("second", data); } test "streamed blob upload enforces its size limit" { const allocator = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [std.fs.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(std.testing.io, &path_buf); init(std.Options.debug_io, path_buf[0..path_len]); var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); var reader: std.Io.Reader = .fixed("too large"); try std.testing.expectError( error.BlobTooLarge, stageUpload(arena.allocator(), std.Options.debug_io, "did:plc:test", &reader, 9, 3), ); } test "with a mirror, a deletion leaves a note until the mirror clears it" { const allocator = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [std.fs.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(std.testing.io, &path_buf); init(std.Options.debug_io, path_buf[0..path_len]); initMirror(.{ .endpoint = "https://fly.storage.tigris.dev", .bucket = "zds-test", .region = "auto", .access_key_id = "id", .secret_access_key = "secret", }, "blobs/"); defer mirror_config = null; var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const a = arena.allocator(); const did = "did:plc:mirrortest"; const cid = "bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku"; try std.testing.expectEqualStrings("blobs/did:plc:mirrortest/" ++ cid, try mirrorKey(a, did, cid)); try put(a, std.Options.debug_io, did, cid, "hello"); try std.testing.expectEqual(@as(usize, 0), (try pendingDeletes(a, 10)).len); try delete(a, did, cid); const pending = try pendingDeletes(a, 10); try std.testing.expectEqual(@as(usize, 1), pending.len); try std.testing.expectEqualStrings(did, pending[0].did); try std.testing.expectEqualStrings(cid, pending[0].cid); clearPendingDelete(a, did, cid); try std.testing.expectEqual(@as(usize, 0), (try pendingDeletes(a, 10)).len); } test "blob CIDs give back the SHA-256 they name" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); // sha256("hello") const digest = try sha256OfCid(arena.allocator(), "bafkreibm6jg3ux5qumhcn2b3flc3tyu6dmlb4xa7u5bf44yegnrjhc4yeq"); try std.testing.expectEqualStrings( "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", &std.fmt.bytesToHex(digest, .lower), ); try std.testing.expectError(error.InvalidBlobCid, sha256OfCid(arena.allocator(), "not-a-cid")); }