Something went wrong. Try again.
A Zig library for Bluesky activity and feed analytics, built on Zat.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657const std = @import("std");
pub const Publication = enum { create, replace };
pub fn save(io: std.Io, allocator: std.mem.Allocator, dir: std.Io.Dir, path: []const u8, value: anytype, publication: Publication) !void { const bytes = try std.json.Stringify.valueAlloc(allocator, value, .{ .whitespace = .indent_2 }); defer allocator.free(bytes); var staged = try dir.createFileAtomic(io, path, .{ .permissions = .fromMode(0o600), .replace = publication == .replace }); defer staged.deinit(io); try staged.file.writeStreamingAll(io, bytes); try staged.file.sync(io); switch (publication) { .create => try staged.link(io), .replace => try staged.replace(io), } const directory: std.Io.File = .{ .handle = staged.dir.handle, .flags = .{ .nonblocking = false } }; try directory.sync(io);}
test "exclusive publication preserves existing checkpoint and replace publishes complete JSON" { const io = std.testing.io; const a = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try save(io, a, tmp.dir, "checkpoint.json", .{ .page = 1 }, .create); try std.testing.expectError(error.PathAlreadyExists, save(io, a, tmp.dir, "checkpoint.json", .{ .page = 2 }, .create)); const old = try tmp.dir.readFileAlloc(io, "checkpoint.json", a, .limited(1024)); defer a.free(old); const old_json = try std.json.parseFromSlice(struct { page: usize }, a, old, .{}); defer old_json.deinit(); try std.testing.expectEqual(@as(usize, 1), old_json.value.page); try save(io, a, tmp.dir, "checkpoint.json", .{ .page = 2 }, .replace); const new = try tmp.dir.readFileAlloc(io, "checkpoint.json", a, .limited(1024)); defer a.free(new); const new_json = try std.json.parseFromSlice(struct { page: usize }, a, new, .{}); defer new_json.deinit(); try std.testing.expectEqual(@as(usize, 2), new_json.value.page);}
test "abandoning a staged write leaves published checkpoint readable" { const io = std.testing.io; const a = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try save(io, a, tmp.dir, "checkpoint.json", .{ .page = 1 }, .create); { var staged = try tmp.dir.createFileAtomic(io, "checkpoint.json", .{ .replace = true }); defer staged.deinit(io); try staged.file.writeStreamingAll(io, "{broken"); } const bytes = try tmp.dir.readFileAlloc(io, "checkpoint.json", a, .limited(1024)); defer a.free(bytes); const parsed = try std.json.parseFromSlice(struct { page: usize }, a, bytes, .{}); defer parsed.deinit(); try std.testing.expectEqual(@as(usize, 1), parsed.value.page);}