╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const hash = xit.hash; 5 const mrg = xit.merge; 6 const obj = xit.object; 7 const rf = xit.ref; 8 9 pub const User = @import("event/User.zig"); 10 pub const Repo = @import("event/Repo.zig"); 11 pub const Issue = @import("event/Issue.zig"); 12 pub const Discussion = @import("event/Discussion.zig"); 13 pub const Comment = @import("event/Comment.zig"); 14 pub const Attachment = @import("event/Attachment.zig"); 15 16 pub const event_id_size: usize = 16; 17 18 pub const MergePolicy = enum { 19 field_conflicts, 20 target_wins, 21 }; 22 23 // the most bytes an event's serialized form may hold 24 pub const max_event_size: usize = 100 * 1024; 25 26 // the branch haxy events are committed to before being consumed 27 pub const events_ref: rf.Ref = .{ .kind = .head, .name = "haxy/events" }; 28 29 // options + db type for *the admin repo* — the single event store that holds 30 // users, repos, issues, etc. the functions below stay parameterized over 31 // repo_opts because they also operate on individual repos in the repos dir, 32 // which may use different options 33 pub const admin_repo_opts: rp.RepoOpts(.xit) = .{}; 34 pub const AdminDB = rp.Repo(.xit, admin_repo_opts).DB; 35 36 // the xitdb type events are stored in. it only depends on the hash kind, so 37 // this matches the db of any xit repo using that hash kind. 38 pub fn EventDB(comptime hash_kind: hash.HashKind) type { 39 return rp.Repo(.xit, .{ .hash = hash_kind }).DB; 40 } 41 42 // the email between a commit author line's angle brackets, or null 43 pub fn authorEmail(author_line: []const u8) ?[]const u8 { 44 const open_bracket = std.mem.indexOfScalar(u8, author_line, '<') orelse return null; 45 const close_bracket = std.mem.indexOfScalarPos(u8, author_line, open_bracket + 1, '>') orelse return null; 46 return author_line[open_bracket + 1 .. close_bracket]; 47 } 48 49 // build a `T` by copying its fields, by name, out of `source` 50 pub fn project(comptime T: type, source: anytype) T { 51 var result: T = undefined; 52 inline for (std.meta.fields(T)) |field| { 53 @field(result, field.name) = @field(source, field.name); 54 } 55 return result; 56 } 57 58 pub const EventKind = enum { 59 user, 60 repo, 61 issue, 62 discuss, 63 comment, 64 attach, 65 }; 66 67 // every logical event's kind and creation-ordered active/removed id sets 68 pub const event_index_key = "event-id->kind"; 69 pub const active_event_id_set_key = "active-event-id-set"; 70 pub const removed_event_id_set_key = "removed-event-id-set"; 71 72 // a null payload removes the record 73 pub const Event = union(EventKind) { 74 user: ?User, 75 repo: ?Repo, 76 issue: ?Issue, 77 discuss: ?Discussion, 78 comment: ?Comment, 79 attach: ?Attachment, 80 }; 81 82 // a file committed alongside its event, as the one entry in that commit's tree. 83 // it isn't serialized, so nothing about it reaches the commit message. 84 pub const Blob = struct { 85 name: []const u8, 86 size: u64, 87 reader: *std.Io.Reader, 88 }; 89 90 // who a commit is attributed to 91 pub const CommitAuthor = struct { 92 name: []const u8, 93 email: []const u8, 94 }; 95 96 pub const EventWithId = struct { 97 id: [event_id_size * 2]u8, 98 event: Event, 99 timestamp: u64 = 0, // not serialized, because it comes from the commit timestamp 100 author: CommitAuthor, // not serialized, because it goes in the commit author line 101 blob: ?Blob = null, // not serialized, because it goes in the commit tree 102 103 pub fn jsonStringify(self: EventWithId, jw: anytype) !void { 104 try jw.beginObject(); 105 try jw.objectField("id"); 106 try jw.write(self.id); 107 try jw.objectField("kind"); 108 try jw.write(@tagName(self.event)); 109 try jw.objectField("data"); 110 switch (self.event) { 111 inline else => |event_maybe| try jw.write(event_maybe), 112 } 113 try jw.endObject(); 114 } 115 116 fn fromString(arena: *std.heap.ArenaAllocator, message: []const u8) !EventWithId { 117 const JsonEvent = struct { 118 id: [event_id_size * 2]u8, 119 kind: EventKind, 120 data: ?std.json.Value = null, 121 }; 122 const json_event = try std.json.parseFromSliceLeaky(JsonEvent, arena.allocator(), message, .{ .ignore_unknown_fields = true }); 123 return .{ 124 .id = json_event.id, 125 // unused when reading; the author lives in the commit 126 .author = .{ .name = "", .email = "" }, 127 .event = switch (json_event.kind) { 128 .user => .{ 129 .user = if (json_event.data) |value| 130 try std.json.parseFromValueLeaky(User, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 131 else 132 null, 133 }, 134 .repo => .{ 135 .repo = if (json_event.data) |value| 136 try std.json.parseFromValueLeaky(Repo, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 137 else 138 null, 139 }, 140 .issue => .{ 141 .issue = if (json_event.data) |value| 142 try std.json.parseFromValueLeaky(Issue, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 143 else 144 null, 145 }, 146 .discuss => .{ 147 .discuss = if (json_event.data) |value| 148 try std.json.parseFromValueLeaky(Discussion, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 149 else 150 null, 151 }, 152 .comment => .{ 153 .comment = if (json_event.data) |value| 154 try std.json.parseFromValueLeaky(Comment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 155 else 156 null, 157 }, 158 .attach => .{ 159 .attach = if (json_event.data) |value| 160 try std.json.parseFromValueLeaky(Attachment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 161 else 162 null, 163 }, 164 }, 165 }; 166 } 167 168 pub fn randomId(random: std.Random) [event_id_size]u8 { 169 var id_bytes: [event_id_size]u8 = undefined; 170 random.bytes(&id_bytes); 171 return id_bytes; 172 } 173 }; 174 175 // remove an event by emitting a null payload 176 pub fn remove( 177 comptime repo_kind: rp.RepoKind, 178 comptime repo_opts: rp.RepoOpts(repo_kind), 179 io: std.Io, 180 allocator: std.mem.Allocator, 181 repo: *rp.Repo(repo_kind, repo_opts), 182 id: *const [event_id_size]u8, 183 kind: EventKind, 184 author: CommitAuthor, 185 ) !void { 186 const DB = EventDB(repo_opts.hash); 187 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 188 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 189 const moment = (if (event_db_maybe) |*event_db| 190 currentMomentFromDb(repo_opts.hash, event_db.db) 191 else if (repo_kind == .git) 192 return error.EventNotFound 193 else 194 currentMoment(repo_opts, repo)) catch return error.EventNotFound; 195 const kind_map_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return error.EventNotFound; 196 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 197 const stored_kind = (try readEventKind(repo_opts.hash, kind_map, id)) orelse return error.EventNotFound; 198 if (stored_kind != kind) return error.EventNotFound; 199 if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 200 event_db_maybe = null; 201 202 const event: Event = switch (kind) { 203 .user => .{ .user = null }, 204 .repo => .{ .repo = null }, 205 .issue => .{ .issue = null }, 206 .discuss => .{ .discuss = null }, 207 .comment => .{ .comment = null }, 208 .attach => .{ .attach = null }, 209 }; 210 try consume(repo_kind, repo_opts, io, allocator, repo, events_ref, &.{.{ 211 .id = std.fmt.bytesToHex(id.*, .lower), 212 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 213 .author = author, 214 .event = event, 215 }}); 216 } 217 218 // commit `events` (if any) as JSON commit messages on `ref`, then consume the 219 // events on `ref` into the db the repo's views read: the repo's own db for a 220 // xit repo, or the standalone event db next to a git repo. for a xit repo the 221 // commits and the consume run in one transaction. 222 pub fn consume( 223 comptime repo_kind: rp.RepoKind, 224 comptime repo_opts: rp.RepoOpts(repo_kind), 225 io: std.Io, 226 allocator: std.mem.Allocator, 227 repo: *rp.Repo(repo_kind, repo_opts), 228 ref: rf.Ref, 229 events: []const EventWithId, 230 ) !void { 231 var resolved_remote_name: ?[]u8 = null; 232 defer if (resolved_remote_name) |name| allocator.free(name); 233 234 // a branch that only exists on a remote is consumed from its remote-tracking 235 // ref, while commits go on the local branch, continuing from the remote tip 236 // so a cloned repo's local branch stays connected to the server history 237 const resolved_ref: rf.Ref, const first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8 = blk: { 238 if (null != try repo.readRef(io, ref)) break :blk .{ ref, null }; 239 var remotes = try repo.listRemotes(io, allocator); 240 defer remotes.deinit(); 241 for (remotes.sections.keys()) |remote_name| { 242 const remote_ref: rf.Ref = .{ .kind = .{ .remote = remote_name }, .name = ref.name }; 243 if (try repo.readRef(io, remote_ref)) |oid| { 244 if (events.len > 0) break :blk .{ ref, .{oid} }; 245 const name = try allocator.dupe(u8, remote_name); 246 resolved_remote_name = name; 247 break :blk .{ rf.Ref{ .kind = .{ .remote = name }, .name = ref.name }, null }; 248 } 249 } 250 if (events.len > 0) break :blk .{ ref, null }; 251 // the branch is gone (or never existed): drop any db from a previous 252 // sync rather than serving its issues indefinitely 253 if (repo_kind == .git) try LocalEventDB(repo_opts.hash).delete(io, repo.core.repo_dir); 254 return; 255 }; 256 257 switch (repo_kind) { 258 .git => { 259 try commitEvents(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, ref, events, first_parent_oids); 260 261 var event_db = try LocalEventDB(repo_opts.hash).open(io, allocator, repo.core.repo_dir); 262 defer event_db.deinit(io, allocator); 263 264 try event_db.consume(repo_kind, repo_opts, io, allocator, repo, resolved_ref); 265 }, 266 .xit => { 267 const DB = rp.Repo(.xit, repo_opts).DB; 268 const State = rp.Repo(.xit, repo_opts).State; 269 270 const Ctx = struct { 271 core: *rp.Repo(.xit, repo_opts).Core, 272 io: std.Io, 273 allocator: std.mem.Allocator, 274 ref: rf.Ref, 275 events: []const EventWithId, 276 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 277 278 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 279 var moment = try DB.HashMap(.read_write).init(cursor.*); 280 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 281 282 try commitEvents(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.ref, ctx.events, ctx.first_parent_oids); 283 if (!try consumeInTransaction(.xit, repo_opts, state.readOnly(), &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 284 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "event" }); 285 286 // fsync the chunk store, so any chunks written by the 287 // commits are durable before the transaction commits 288 try ctx.core.chunk_store_file.sync(ctx.io); 289 } 290 }; 291 292 try repo.core.db_file.lock(io, .exclusive); 293 defer repo.core.db_file.unlock(io); 294 295 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 296 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 297 .core = &repo.core, 298 .io = io, 299 .allocator = allocator, 300 .ref = resolved_ref, 301 .events = events, 302 .first_parent_oids = first_parent_oids, 303 }) catch |err| switch (err) { 304 error.CancelTransaction => {}, 305 else => |e| return e, 306 }; 307 }, 308 } 309 } 310 311 // merge the remote events ref into the local events ref without touching head, 312 // the index, or the worktree 313 pub fn mergeEvents( 314 comptime repo_kind: rp.RepoKind, 315 comptime repo_opts: rp.RepoOpts(repo_kind), 316 io: std.Io, 317 allocator: std.mem.Allocator, 318 repo: *rp.Repo(repo_kind, repo_opts), 319 remote_ref: rf.Ref, 320 ) !void { 321 switch (repo_kind) { 322 .git => _ = try mergeEventsInTransaction(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, remote_ref), 323 .xit => { 324 const DB = rp.Repo(.xit, repo_opts).DB; 325 const State = rp.Repo(.xit, repo_opts).State; 326 327 const Ctx = struct { 328 core: *rp.Repo(.xit, repo_opts).Core, 329 io: std.Io, 330 allocator: std.mem.Allocator, 331 remote_ref: rf.Ref, 332 333 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 334 var moment = try DB.HashMap(.read_write).init(cursor.*); 335 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 336 if (!try mergeEventsInTransaction(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.remote_ref)) return error.CancelTransaction; 337 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "event" }); 338 try ctx.core.chunk_store_file.sync(ctx.io); 339 } 340 }; 341 342 try repo.core.db_file.lock(io, .exclusive); 343 defer repo.core.db_file.unlock(io); 344 345 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 346 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 347 .core = &repo.core, 348 .io = io, 349 .allocator = allocator, 350 .remote_ref = remote_ref, 351 }) catch |err| switch (err) { 352 error.CancelTransaction => {}, 353 else => |e| return e, 354 }; 355 }, 356 } 357 } 358 359 fn mergeEventsInTransaction( 360 comptime repo_kind: rp.RepoKind, 361 comptime repo_opts: rp.RepoOpts(repo_kind), 362 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 363 io: std.Io, 364 allocator: std.mem.Allocator, 365 remote_ref: rf.Ref, 366 ) !bool { 367 const remote_oid = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = remote_ref })) orelse return false; 368 const local_oid_maybe = try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = events_ref }); 369 370 var ref_path_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 371 const ref_path = try events_ref.toPath(&ref_path_buffer); 372 const local_oid = local_oid_maybe orelse { 373 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 374 return true; 375 }; 376 if (std.mem.eql(u8, &local_oid, &remote_oid)) return false; 377 378 const ancestor_maybe: ?[hash.hexLen(repo_opts.hash)]u8 = mrg.commonAncestor(repo_kind, repo_opts, state.readOnly(), io, allocator, &local_oid, &remote_oid) catch |err| switch (err) { 379 error.NoCommonAncestor => null, 380 else => return err, 381 }; 382 if (ancestor_maybe) |ancestor| { 383 if (std.mem.eql(u8, &ancestor, &remote_oid)) return false; 384 if (std.mem.eql(u8, &ancestor, &local_oid)) { 385 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 386 return true; 387 } 388 } 389 390 const parent_oids = [_][hash.hexLen(repo_opts.hash)]u8{ local_oid, remote_oid }; 391 var tree = try obj.Tree.init(allocator); 392 defer tree.deinit(); 393 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 394 .message = "merge events", 395 .parent_oids = &parent_oids, 396 }, &tree, events_ref); 397 return true; 398 } 399 400 // the file an attach event carries: the one entry in its commit's tree. the 401 // name and oid are allocated in `arena`. 402 fn attachedFile( 403 comptime repo_kind: rp.RepoKind, 404 comptime repo_opts: rp.RepoOpts(repo_kind), 405 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 406 io: std.Io, 407 allocator: std.mem.Allocator, 408 arena: *std.heap.ArenaAllocator, 409 tree_oid: *const [hash.hexLen(repo_opts.hash)]u8, 410 ) !struct { name: []const u8, oid: []const u8 } { 411 var tree_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, tree_oid); 412 defer tree_object.deinit(); 413 414 const entries = switch (tree_object.content) { 415 .tree => |tree| tree.entries, 416 else => return error.InvalidAttachment, 417 }; 418 if (entries.count() != 1) return error.InvalidAttachment; 419 const entry = entries.values()[0]; 420 if (entry.isTree()) return error.InvalidAttachment; 421 const name = entries.keys()[0]; 422 if (!Attachment.nameValid(name)) return error.InvalidAttachment; 423 424 const oid = std.fmt.bytesToHex(entry.oid, .lower); 425 var object_reader = try obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, &oid); 426 defer object_reader.deinit(); 427 if (object_reader.header().kind != .blob) return error.InvalidAttachment; 428 429 return .{ 430 .name = try arena.allocator().dupe(u8, name), 431 .oid = try arena.allocator().dupe(u8, &oid), 432 }; 433 } 434 435 // commit each event as a JSON commit message on `ref` through `state`, so a 436 // xit repo can write them inside an already-open transaction 437 fn commitEvents( 438 comptime repo_kind: rp.RepoKind, 439 comptime repo_opts: rp.RepoOpts(repo_kind), 440 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 441 io: std.Io, 442 allocator: std.mem.Allocator, 443 ref: rf.Ref, 444 events: []const EventWithId, 445 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 446 ) !void { 447 var parent_oids: ?[]const [hash.hexLen(repo_opts.hash)]u8 = if (first_parent_oids) |*oids| oids else null; 448 449 var json: std.Io.Writer.Allocating = .init(allocator); 450 defer json.deinit(); 451 452 for (events) |event| { 453 json.clearRetainingCapacity(); 454 try std.json.Stringify.value(event, .{}, &json.writer); 455 if (json.written().len > max_event_size) return error.EventTooLarge; 456 const author = try std.fmt.allocPrint(allocator, "{s} <{s}>", .{ event.author.name, event.author.email }); 457 defer allocator.free(author); 458 459 // every event gets its own tree, with one entry when it carries a file 460 // and no entries otherwise 461 var tree = try obj.Tree.init(allocator); 462 defer tree.deinit(); 463 if (event.blob) |blob| { 464 var oid_bytes = [_]u8{0} ** hash.byteLen(repo_opts.hash); 465 try obj.writeObject(repo_kind, repo_opts, state, io, blob.reader, .{ .kind = .blob, .size = blob.size }, &oid_bytes); 466 try tree.addBlobEntry(.{ .content = .{ .unix_permission = 0o644, .object_type = .regular_file } }, blob.name, &oid_bytes); 467 } 468 469 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 470 .author = author, 471 .message = json.written(), 472 .timestamp = event.timestamp, 473 .parent_oids = parent_oids, 474 .allow_empty = true, 475 }, &tree, ref); 476 // later events parent on the ref's new tip 477 parent_oids = null; 478 } 479 } 480 481 // serve a receive-pack and consume any events it pushed to the events branch, 482 // all in one transaction: the push and the views derived from it commit 483 // atomically, and a failed consume cancels the push 484 pub fn receivePackAndConsume( 485 comptime repo_opts: rp.RepoOpts(.xit), 486 io: std.Io, 487 allocator: std.mem.Allocator, 488 repo: *rp.Repo(.xit, repo_opts), 489 reader: *std.Io.Reader, 490 writer: *std.Io.Writer, 491 options: xit.net_server_receive_pack.Options, 492 ) !void { 493 const DB = rp.Repo(.xit, repo_opts).DB; 494 const State = rp.Repo(.xit, repo_opts).State; 495 496 const Ctx = struct { 497 core: *rp.Repo(.xit, repo_opts).Core, 498 io: std.Io, 499 allocator: std.mem.Allocator, 500 reader: *std.Io.Reader, 501 writer: *std.Io.Writer, 502 options: xit.net_server_receive_pack.Options, 503 504 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 505 var moment = try DB.HashMap(.read_write).init(cursor.*); 506 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 507 try xit.net_server_receive_pack.run(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.reader, ctx.writer, ctx.options); 508 try xit.undo.writeMessage(repo_opts, state, .push); 509 510 // a repo without an events branch has no events to consume. a 511 // no-op consume must not cancel here, since the push shares the 512 // transaction and must commit regardless. 513 if (null == try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = events_ref })) return; 514 _ = try consumeInTransaction(.xit, repo_opts, state.readOnly(), &ctx.core.db, &moment, ctx.io, ctx.allocator, events_ref); 515 } 516 }; 517 518 try repo.core.db_file.lock(io, .exclusive); 519 defer repo.core.db_file.unlock(io); 520 521 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 522 history.appendContext( 523 .{ .slot = try history.getSlot(-1) }, 524 Ctx{ .core = &repo.core, .io = io, .allocator = allocator, .reader = reader, .writer = writer, .options = options }, 525 ) catch |err| switch (err) { 526 error.CancelTransaction => {}, 527 else => |e| return e, 528 }; 529 530 // pkt-line writes are buffered until the transaction settles, so the 531 // report-status reaches the client only after the push truly committed 532 try writer.flush(); 533 } 534 535 // a standalone event db holding events consumed from a local repo's events 536 // branch. it lives inside the repo dir but is not part of the repo's own data, 537 // so viewing a repo never mutates it. 538 pub fn LocalEventDB(comptime hash_kind: hash.HashKind) type { 539 return struct { 540 file: std.Io.File, 541 buffer: *std.Io.Writer.Allocating, 542 db: *EventDB(hash_kind), 543 544 const db_name = "haxy"; 545 const Self = @This(); 546 547 // open the db in `repo_dir` for writing, creating it if it doesn't exist 548 pub fn open(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !Self { 549 const file = try repo_dir.createFile(io, db_name, .{ .truncate = false, .read = true, .lock = .exclusive }); 550 return fromFile(io, allocator, file); 551 } 552 553 // open the db in `repo_dir` for reading, or null if it doesn't exist 554 pub fn openReadOnly(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !?Self { 555 const file = repo_dir.openFile(io, db_name, .{ .mode = .read_write, .lock = .shared }) catch |err| switch (err) { 556 error.FileNotFound => return null, 557 else => |e| return e, 558 }; 559 return try fromFile(io, allocator, file); 560 } 561 562 // remove the db from `repo_dir`, so a repo whose events branch 563 // disappeared doesn't keep showing stale issues 564 pub fn delete(io: std.Io, repo_dir: std.Io.Dir) !void { 565 repo_dir.deleteFile(io, db_name) catch |err| switch (err) { 566 error.FileNotFound => {}, 567 else => |e| return e, 568 }; 569 } 570 571 fn fromFile(io: std.Io, allocator: std.mem.Allocator, file: std.Io.File) !Self { 572 errdefer file.close(io); 573 574 const buffer = try allocator.create(std.Io.Writer.Allocating); 575 errdefer allocator.destroy(buffer); 576 buffer.* = std.Io.Writer.Allocating.init(allocator); 577 errdefer buffer.deinit(); 578 579 const db = try allocator.create(EventDB(hash_kind)); 580 errdefer allocator.destroy(db); 581 db.* = try EventDB(hash_kind).init(.{ .io = io, .file = file, .buffer = buffer }); 582 583 return .{ .file = file, .buffer = buffer, .db = db }; 584 } 585 586 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 587 self.file.close(io); 588 self.buffer.deinit(); 589 allocator.destroy(self.buffer); 590 allocator.destroy(self.db); 591 } 592 593 // consume the events on `repo`'s `ref` into this db. the db must come 594 // from `open`, whose handle holds the exclusive lock guarding the 595 // transaction. 596 pub fn consume( 597 self: *Self, 598 comptime repo_kind: rp.RepoKind, 599 comptime repo_opts: rp.RepoOpts(repo_kind), 600 io: std.Io, 601 allocator: std.mem.Allocator, 602 repo: *rp.Repo(repo_kind, repo_opts), 603 ref: rf.Ref, 604 ) !void { 605 comptime if (repo_opts.hash != hash_kind) @compileError("the repo must use the db's hash kind"); 606 const DB = EventDB(hash_kind); 607 608 const Ctx = struct { 609 repo: *rp.Repo(repo_kind, repo_opts), 610 db: *DB, 611 io: std.Io, 612 allocator: std.mem.Allocator, 613 ref: rf.Ref, 614 615 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 616 var moment = try DB.HashMap(.read_write).init(cursor.*); 617 var repo_moment = try ctx.repo.core.latestMoment(); 618 const read_state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &ctx.repo.core, .extra = .{ .moment = &repo_moment } }; 619 if (!try consumeInTransaction(repo_kind, repo_opts, read_state, ctx.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 620 } 621 }; 622 623 const history = try DB.ArrayList(.read_write).init(self.db.rootCursor()); 624 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 625 .repo = repo, 626 .db = self.db, 627 .io = io, 628 .allocator = allocator, 629 .ref = ref, 630 }) catch |err| switch (err) { 631 error.CancelTransaction => {}, 632 else => |e| return e, 633 }; 634 } 635 }; 636 } 637 638 // consume the events on `ref` into the db `moment` writes to, returning false 639 // if there was nothing to do. events are read from `read_state`'s repo, which 640 // needn't be the repo backing the db — that's how a local (possibly 641 // git-backed) repo's events land in a standalone db. 642 pub fn consumeInTransaction( 643 comptime repo_kind: rp.RepoKind, 644 comptime repo_opts: rp.RepoOpts(repo_kind), 645 read_state: rp.Repo(repo_kind, repo_opts).State(.read_only), 646 db: *EventDB(repo_opts.hash), 647 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 648 io: std.Io, 649 allocator: std.mem.Allocator, 650 ref: rf.Ref, 651 ) !bool { 652 const DB = EventDB(repo_opts.hash); 653 654 // the last_object_id represents the object id that was last consumed 655 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 656 if (try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id"))) |last_object_id_cursor| { 657 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 658 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 659 last_object_id_maybe = last_object_id_buffer; 660 } 661 662 // the tip was already consumed, so there is nothing to do 663 if (last_object_id_maybe) |*last_object_id| { 664 const tip_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 665 var tip: [hash.byteLen(repo_opts.hash)]u8 = undefined; 666 _ = try std.fmt.hexToBytes(&tip, &tip_hex); 667 if (std.mem.eql(u8, last_object_id, &tip)) return false; 668 } 669 670 // the list with all of haxy's state, including materialized views. 671 // the reason it is a list is so we can keep every previous haxy 672 // state, making it easy to revert to an older state if the user 673 // rebases some of the past commits. 674 const haxy_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, "haxy")); 675 const haxy = try DB.ArrayList(.read_write).init(haxy_cursor); 676 677 // add a new item to the haxy list created above. 678 // we call the item haxy_moments. it is a map of object id to haxy moment. 679 // in other words, it maps each object id to a hash map containing the 680 // state that the database was in when that object id was consumed. 681 var haxy_moments_cursor = try haxy.appendCursor(); 682 // use the previous haxy_moments as the basis for this one if it exists 683 if (try haxy.getCursor(-2)) |last_haxy_moments_cursor| { 684 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 685 } 686 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 687 688 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 689 defer commit_iter.deinit(io, allocator); 690 691 // if there are no events to process, look at the oid at HEAD and update 692 // the last_object_id to point to it. this is important in situations 693 // where we do a merge and then force-push to remove the merge. see the 694 // merge test for an example. 695 if (commit_iter.newest_object_id == null) { 696 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 697 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 698 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 699 700 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 701 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 702 703 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 704 const moment_index = try moment_index_cursor.readUint(); 705 706 try haxy.slice(moment_index + 1); 707 try moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = &head_oid }); 708 return true; 709 } 710 711 // if this branch was rebased and force pushed, we need to detect that and 712 // properly revert the haxy state to the last valid state. we detect this 713 // by simply asking if the last event is a descendent of the last event 714 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 715 if (last_object_id_maybe) |*last_object_id| { 716 var is_rebased = false; 717 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 718 719 _ = mrg.getDescendent( 720 repo_kind, 721 repo_opts, 722 read_state, 723 io, 724 allocator, 725 &std.fmt.bytesToHex(last_object_id, .lower), 726 &std.fmt.bytesToHex(&newest_object_id, .lower), 727 ) catch |err| switch (err) { 728 error.DescendentNotFound => is_rebased = true, 729 else => |e| return e, 730 }; 731 732 if (is_rebased) { 733 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 734 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 735 defer oldest_object.deinit(); 736 737 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 738 switch (parent_oids.len) { 739 0 => { 740 // the branch was rebased all the way to the very beginning. 741 // we have a repo event with no parent, which means it is now 742 // the very first event. all we need to do is set the haxy list 743 // to be empty and make a new haxy_moments map to work with. 744 745 try haxy.slice(0); 746 haxy_moments_cursor = try haxy.appendCursor(); 747 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 748 749 last_object_id_maybe = null; 750 }, 751 1 => { 752 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 753 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 754 755 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 756 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 757 758 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 759 const old_moment_index = try old_moment_index_cursor.readUint(); 760 761 // resize the haxy list so we truncate all the moments that were 762 // created after the parent_oid was consumed 763 try haxy.slice(old_moment_index + 1); 764 765 // make a new haxy moment and set its initial value to the last haxy moment 766 haxy_moments_cursor = try haxy.appendCursor(); 767 const old_haxy_moments_cursor = try haxy.getCursor(old_moment_index) orelse return error.CursorNotFound; 768 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 769 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 770 771 last_object_id_maybe = oid; 772 }, 773 else => return error.UnexpectedParentCount, 774 } 775 } 776 } 777 778 while (try commit_iter.next()) |repo_event_oid| { 779 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 780 defer commit_object.deinit(); 781 782 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 783 784 // create a moment for this object id 785 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 786 787 // if there was a previous object id, set this haxy moment's initial value to it. 788 // this efficiently "clones" the map so we make further modifications based on it. 789 if (parent_oids.len > 0) { 790 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 791 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 792 793 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 794 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 795 } 796 797 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 798 799 // merge changes from every parent after the first parent. the common 800 // ancestor is the baseline, so a later parent only contributes records 801 // it changed relative to the merge base. only the record maps are 802 // merged; every other view is derived from them, and each kind's 803 // `consume` re-derives its own as the winning records are written. 804 if (parent_oids.len > 1) { 805 for (parent_oids[1..]) |*parent_oid| { 806 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 807 _ = try std.fmt.hexToBytes(&oid, parent_oid); 808 809 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 810 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 811 812 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 813 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 814 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 815 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 816 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 817 818 inline for (std.meta.fields(Event)) |field| { 819 const T = @typeInfo(field.type).optional.child; 820 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 821 } 822 } 823 } 824 825 // associate this moment with the index it will first appear at in the haxy list. 826 // this will be important later so we can truncate that list if the user ever 827 // rebases starting at this object id. 828 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy.count() - 1 }); 829 830 // consume the event unless it's a merge commit 831 if (parent_oids.len <= 1) { 832 var arena = std.heap.ArenaAllocator.init(allocator); 833 defer arena.deinit(); 834 835 // read the message from the commit 836 var message: std.ArrayList(u8) = .empty; 837 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 838 839 const event_with_id = try EventWithId.fromString(&arena, message.items); 840 841 // get the id of the current event as bytes 842 var current_event_id: [event_id_size]u8 = undefined; 843 _ = try std.fmt.hexToBytes(&current_event_id, &event_with_id.id); 844 845 // wrap the payload into the record `consume` stores, with its 846 // commit-derived fields; on update, `consume` preserves the 847 // existing record's 848 const created_ts = commit_object.content.commit.metadata.timestamp; 849 switch (event_with_id.event) { 850 .user => |event_maybe| { 851 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_ts = created_ts } else null; 852 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 853 }, 854 .repo => |event_maybe| { 855 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_ts = created_ts } else null; 856 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 857 }, 858 .issue => |event_maybe| { 859 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 860 .event = event, 861 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 862 .created_ts = created_ts, 863 } else null; 864 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 865 }, 866 .discuss => |event_maybe| { 867 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 868 .event = event, 869 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 870 .created_ts = created_ts, 871 } else null; 872 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 873 }, 874 .comment => |event_maybe| { 875 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 876 .event = event, 877 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 878 .created_ts = created_ts, 879 } else null; 880 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 881 }, 882 .attach => |event_maybe| { 883 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 884 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 885 break :blk .{ 886 .event = event, 887 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 888 .created_ts = created_ts, 889 .name = entry.name, 890 .blob_oid = entry.oid, 891 }; 892 } else null; 893 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 894 }, 895 } 896 } 897 898 // the current object id is now the last one 899 last_object_id_maybe = repo_event_oid; 900 901 // prevent any of the data created above from being mutated by future iterations of this loop 902 try db.freeze(); 903 } 904 905 if (last_object_id_maybe) |*last_object_id| { 906 try moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = last_object_id }); 907 } 908 909 return true; 910 } 911 912 // the conflicted records of one kind, keyed by the same order key its id set 913 // uses, so this doubles as the index the conflicts view lists and counts. every 914 // value under an entry is a slot reference to a structure that already exists: 915 // 916 // <order key> -> conflict entry 917 // conflicted-fields the conflicting field names, space separated 918 // base-record the merge base's whole record 919 // their-record the merged-in side's whole record 920 // their-field->oid that side's field name to commit map 921 // 922 // our own value is the live record and our commit is in the kind's oid map, so 923 // neither is repeated here. 924 pub const conflicted_fields_key = "conflicted-fields"; 925 pub const base_record_key = "base-record"; 926 pub const their_record_key = "their-record"; 927 pub const their_field_to_oid_key = "their-field->oid"; 928 929 // record the commit against every field this event changes. a merge passes no 930 // oid, since each field's winner may come from a different side. 931 pub fn writeOid( 932 comptime T: type, 933 comptime DB: type, 934 comptime hash_kind: hash.HashKind, 935 id_to_field_to_oid: DB.HashMap(.read_write), 936 record_key: hash.HashInt(hash_kind), 937 existing_maybe: ?T, 938 event: T, 939 event_oid: ?[]const u8, 940 ) !void { 941 const oid = event_oid orelse return; 942 943 // created only once a field actually changes 944 var field_oids: ?DB.SortedMap(.read_write) = null; 945 946 inline for (std.meta.fields(T)) |field| { 947 const changed = if (existing_maybe) |existing| 948 !fieldEqual(field.type, @field(existing, field.name), @field(event, field.name)) 949 else 950 true; 951 if (changed) { 952 if (field_oids == null) { 953 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 954 } 955 if (field_oids) |map| try map.put(field.name, .{ .bytes = oid }); 956 } 957 } 958 } 959 960 // the whole field list, space separated, is the longest it can get 961 fn conflictedFieldsMaxLen(comptime T: type) usize { 962 var len: usize = 0; 963 for (std.meta.fields(T)) |field| len += field.name.len + 1; 964 return len; 965 } 966 967 // what a three-way merge did with a field 968 const FieldMerge = enum { 969 // the target's value stands, because neither side changed it, both made the 970 // same change, or only the target changed it 971 kept, 972 parent, 973 conflicted, 974 }; 975 976 // three-way merge each field. one only the parent changed takes the parent's 977 // value; one both sides changed differently keeps the target's. a missing 978 // baseline makes every differing field a conflict. 979 fn mergeFields( 980 comptime T: type, 981 baseline_maybe: ?T, 982 target: T, 983 parent: T, 984 outcome: *[std.meta.fields(T).len]FieldMerge, 985 ) T { 986 var merged = target; 987 988 inline for (std.meta.fields(T), 0..) |field, i| { 989 const target_value = @field(target, field.name); 990 const parent_value = @field(parent, field.name); 991 992 if (!fieldEqual(field.type, target_value, parent_value)) { 993 outcome[i] = if (baseline_maybe) |baseline| blk: { 994 const baseline_value = @field(baseline, field.name); 995 if (fieldEqual(field.type, target_value, baseline_value)) { 996 @field(merged, field.name) = parent_value; 997 break :blk .parent; 998 } 999 // only the target changed it 1000 if (fieldEqual(field.type, parent_value, baseline_value)) break :blk .kept; 1001 break :blk .conflicted; 1002 } else .conflicted; 1003 } 1004 } 1005 1006 return merged; 1007 } 1008 1009 // three-way merge of one kind's records from a merge parent. kinds that expose 1010 // conflicts merge field by field; the others take one whole record. the result 1011 // goes through the kind's `consume`, which re-derives the indexes from it. a 1012 // removal carries over unless the other side changed the record, so a merge 1013 // never fails. 1014 pub fn merge( 1015 comptime T: type, 1016 comptime DB: type, 1017 comptime hash_kind: hash.HashKind, 1018 allocator: std.mem.Allocator, 1019 haxy_moment: DB.HashMap(.read_write), 1020 parent_moment: DB.HashMap(.read_only), 1021 baseline_moment: DB.HashMap(.read_only), 1022 ) !void { 1023 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_set_key)) orelse return; 1024 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1025 1026 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1027 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1028 1029 var baseline_records: ?DB.HashMap(.read_only) = null; 1030 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1031 baseline_records = try DB.HashMap(.read_only).init(cursor); 1032 } 1033 1034 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1035 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1036 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1037 switch (comptime T.merge_policy) { 1038 .field_conflicts => { 1039 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1040 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1041 } 1042 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1043 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1044 } 1045 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1046 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1047 } 1048 }, 1049 .target_wins => {}, 1050 } 1051 1052 var arena = std.heap.ArenaAllocator.init(allocator); 1053 defer arena.deinit(); 1054 1055 var iter = try parent_set.iteratorFromIndex(0); 1056 while (try iter.next()) |kv_pair_cursor| { 1057 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1058 const record_key = hash.hashInt(hash_kind, &event_id); 1059 1060 _ = arena.reset(.retain_capacity); 1061 1062 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1063 const parent_slot = parent_record_cursor.slot(); 1064 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1065 1066 // the parent left this record alone 1067 if (baseline_slot) |slot| { 1068 if (slot.eql(parent_slot)) continue; 1069 } 1070 1071 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1072 1073 // re-derived every iteration, since `consume` writes through its own 1074 // handles 1075 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1076 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1077 1078 // a record the target doesn't have arrives wholesale from the parent 1079 var outcome: [std.meta.fields(T).len]FieldMerge = @splat(.parent); 1080 var merged = parent_record; 1081 1082 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1083 // both sides share the change 1084 if (target_record_cursor.slot().eql(parent_slot)) continue; 1085 1086 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1087 1088 var baseline_record: ?T.Record = null; 1089 if (baseline_records) |map| { 1090 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1091 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1092 } 1093 } 1094 1095 switch (comptime T.merge_policy) { 1096 .field_conflicts => { 1097 outcome = @splat(.kept); 1098 merged = target_record; 1099 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1100 1101 // merge the removed state separately from serialized fields. removal 1102 // carries over an unchanged record, while an edit or restoration 1103 // keeps it active. 1104 merged.removed = if (target_record.removed == parent_record.removed) 1105 target_record.removed 1106 else if (baseline_record) |baseline| blk: { 1107 const active = if (!target_record.removed) target_record else parent_record; 1108 if (active.removed != baseline.removed) break :blk false; 1109 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1110 break :blk true; 1111 } else false; 1112 }, 1113 .target_wins => { 1114 // an uncontested parent change carries over. if both sides 1115 // changed the record, the target wins as a whole, except that 1116 // an edit or restoration wins over a removal. 1117 const target_changed = if (baseline_slot) |slot| 1118 !target_record_cursor.slot().eql(slot) 1119 else 1120 true; 1121 merged = if (!target_changed) 1122 parent_record 1123 else if (target_record.removed != parent_record.removed) 1124 if (target_record.removed) parent_record else target_record 1125 else 1126 target_record; 1127 }, 1128 } 1129 } 1130 1131 // the index is unique, so a key the target gave to a different record 1132 // leaves this one out rather than stranding that one behind a name it 1133 // no longer owns 1134 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1135 const index_key = try merged.indexKey(arena.allocator()); 1136 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1137 const name_index = try DB.HashMap(.read_write).init(name_index_cursor); 1138 if (try name_index.getCursor(hash.hashInt(hash_kind, index_key))) |owner_cursor| { 1139 var owner_id: [event_id_size]u8 = undefined; 1140 _ = try owner_cursor.readBytes(&owner_id); 1141 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1142 } 1143 } 1144 1145 // `consume` sets no oids, since each field's winner may come from 1146 // a different side 1147 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1148 1149 switch (comptime T.merge_policy) { 1150 .field_conflicts => {}, 1151 .target_wins => continue, 1152 } 1153 1154 // removed records do not carry field conflicts 1155 if (merged.removed) continue; 1156 1157 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1158 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1159 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1160 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1161 const merged_key = orderKeyDesc(merged.created_ts, &event_id); 1162 1163 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1164 if (parent_id_to_field_to_oid) |map| { 1165 if (try map.getCursor(record_key)) |field_oids_cursor| { 1166 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1167 } 1168 } 1169 // created only once a field actually comes from the parent 1170 var field_oids: ?DB.SortedMap(.read_write) = null; 1171 1172 // the fields both sides changed differently, space separated 1173 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1174 var conflicted_len: usize = 0; 1175 1176 inline for (std.meta.fields(T), 0..) |field, i| { 1177 switch (outcome[i]) { 1178 // the target's value stands, so its oid does too 1179 .kept => {}, 1180 // the parent set this value, so its commit takes the field. a 1181 // parent with no oid took its own value from a merge, leaving 1182 // the field unattributed rather than crediting the target's 1183 // commit for a value it no longer holds. 1184 .parent => { 1185 if (field_oids == null) { 1186 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1187 } 1188 const map = field_oids orelse unreachable; 1189 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1190 if (parent_oid) |oid_cursor| { 1191 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1192 } else { 1193 _ = try map.remove(field.name); 1194 } 1195 }, 1196 .conflicted => { 1197 if (conflicted_len > 0) { 1198 conflicted_fields[conflicted_len] = ' '; 1199 conflicted_len += 1; 1200 } 1201 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1202 conflicted_len += field.name.len; 1203 }, 1204 } 1205 } 1206 1207 if (conflicted_len > 0) { 1208 // each side's whole record is stored by reference, so the view can 1209 // show any of them or take theirs wholesale 1210 _ = try conflicts.remove(&merged_key); 1211 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1212 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1213 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1214 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1215 if (parent_field_oids) |map| { 1216 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1217 } 1218 continue; 1219 } 1220 1221 // created_ts never changes, so the parent keys this record's conflict 1222 // identically, and it carries over when the target has none, unless the 1223 // parent's entry is unchanged from the baseline, meaning the target 1224 // inherited it too and resolving it removed it here. 1225 if (parent_conflicts) |map| { 1226 if (null == try conflicts.getCursor(&merged_key)) { 1227 if (try map.getSlot(&merged_key)) |conflict_slot| { 1228 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1229 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1230 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1231 } 1232 } 1233 } 1234 } 1235 } 1236 1237 pub fn currentMoment( 1238 comptime repo_opts: rp.RepoOpts(.xit), 1239 repo: *rp.Repo(.xit, repo_opts), 1240 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1241 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1242 } 1243 1244 // the oid of the last event commit consumed into `db`, or null before any 1245 // consume completed 1246 fn lastConsumedOid( 1247 comptime hash_kind: hash.HashKind, 1248 db: *EventDB(hash_kind), 1249 ) !?[hash.byteLen(hash_kind)]u8 { 1250 const DB = EventDB(hash_kind); 1251 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1252 const moment_cursor = try history.getCursor(-1) orelse return null; 1253 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1254 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy-last-object-id")) orelse return null; 1255 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1256 _ = try last_object_id_cursor.readBytes(&last_object_id); 1257 return last_object_id; 1258 } 1259 1260 pub fn currentMomentFromDb( 1261 comptime hash_kind: hash.HashKind, 1262 db: *EventDB(hash_kind), 1263 ) !EventDB(hash_kind).HashMap(.read_only) { 1264 const DB = EventDB(hash_kind); 1265 const last_object_id = (try lastConsumedOid(hash_kind, db)) orelse return error.NotFound; 1266 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1267 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1268 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1269 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy")) orelse return error.NotFound; 1270 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 1271 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 1272 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1273 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1274 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1275 } 1276 1277 // build the key for SortedSets sorted by timestamp. the big-endian timestamp 1278 // makes byte order match creation order; the event id breaks ties and keeps 1279 // keys unique within the same timestamp. 1280 pub fn orderKey(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1281 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1282 std.mem.writeInt(u64, key[0..@sizeOf(u64)], timestamp, .big); 1283 @memcpy(key[@sizeOf(u64)..], event_id); 1284 return key; 1285 } 1286 1287 pub fn orderKeyDesc(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1288 return orderKey(std.math.maxInt(u64) - timestamp, event_id); 1289 } 1290 1291 // add or refresh one entry in the global logical-event index. updates and 1292 // removed records preserve created_ts, so the key never moves. 1293 pub fn indexEvent( 1294 comptime DB: type, 1295 comptime hash_kind: hash.HashKind, 1296 haxy_moment: DB.HashMap(.read_write), 1297 event_id: *const [event_id_size]u8, 1298 kind: EventKind, 1299 created_ts: u64, 1300 removed: bool, 1301 ) !void { 1302 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1303 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1304 try kind_map.put(hash.hashInt(hash_kind, event_id), .{ .bytes = @tagName(kind) }); 1305 1306 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1307 const active = try DB.SortedSet(.read_write).init(active_cursor); 1308 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1309 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1310 const order_key = orderKeyDesc(created_ts, event_id); 1311 if (removed) { 1312 _ = try active.remove(&order_key); 1313 try removed_set.put(&order_key); 1314 } else { 1315 _ = try removed_set.remove(&order_key); 1316 try active.put(&order_key); 1317 } 1318 } 1319 1320 pub fn readEventKind( 1321 comptime hash_kind: hash.HashKind, 1322 kind_map: anytype, 1323 id: *const [event_id_size]u8, 1324 ) !?EventKind { 1325 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1326 var buffer: [64]u8 = undefined; 1327 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1328 } 1329 1330 // the event id embedded in a set entry's order key 1331 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1332 var cursor = kv_pair_cursor; 1333 const kv_pair = try cursor.readKeyValuePair(); 1334 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1335 _ = try kv_pair.key_cursor.readBytes(&order_key); 1336 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1337 } 1338 1339 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1340 // isn't exactly two non-empty segments. 1341 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1342 var it = std.mem.splitScalar(u8, path, '/'); 1343 const owner = it.next() orelse return null; 1344 const name = it.next() orelse return null; 1345 if (it.next() != null) return null; 1346 if (owner.len == 0 or name.len == 0) return null; 1347 1348 return .{ .owner = owner, .name = name }; 1349 } 1350 1351 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1352 // directory under the repos dir 1353 pub fn resolveOrCreateRepo( 1354 io: std.Io, 1355 allocator: std.mem.Allocator, 1356 admin_repo_path: []const u8, 1357 owner_name: []const u8, 1358 repo_name: []const u8, 1359 create_if_missing: bool, 1360 ) !?[event_id_size * 2]u8 { 1361 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1362 error.RepoNotFound => return null, 1363 else => |e| return e, 1364 }; 1365 defer repo.deinit(io, allocator); 1366 1367 var arena = std.heap.ArenaAllocator.init(allocator); 1368 defer arena.deinit(); 1369 1370 const moment = try currentMoment(admin_repo_opts, &repo); 1371 1372 // an already-registered repo reuses its event id, so a re-push (or a clone) 1373 // lands in the same repo 1374 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1375 return std.fmt.bytesToHex(found.event_id, .lower); 1376 } 1377 1378 if (!create_if_missing) return null; 1379 1380 // the new repo is owned by the named user, read from the name index; an 1381 // unknown owner can't own a repo, so the push is rejected 1382 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1383 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1384 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1385 var owner_user_id: [event_id_size]u8 = undefined; 1386 _ = try owner_id_cursor.readBytes(&owner_user_id); 1387 1388 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1389 1390 var id_bytes: [event_id_size]u8 = undefined; 1391 io.random(&id_bytes); 1392 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1393 1394 try consume(.xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1395 .id = event_id_hex, 1396 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1397 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1398 .event = .{ .repo = .{ 1399 .user_id = &owner_user_id, 1400 .name = repo_name, 1401 .description = "", 1402 } }, 1403 }}); 1404 1405 return event_id_hex; 1406 } 1407 1408 // 1409 // reading from xitdb 1410 // 1411 1412 // a struct field's fields share its container's map, so their names must not 1413 // collide with the container's or two fields would silently share a key 1414 fn validateFlattenedFields(comptime T: type) void { 1415 comptime { 1416 for (std.meta.fields(T)) |field| { 1417 if (@typeInfo(field.type) != .@"struct") continue; 1418 for (std.meta.fields(field.type)) |nested| { 1419 if (@hasField(T, nested.name)) 1420 @compileError("flattened field name collision in " ++ @typeName(T) ++ ": " ++ nested.name); 1421 } 1422 } 1423 } 1424 } 1425 1426 pub fn read( 1427 comptime T: type, 1428 comptime DB: type, 1429 comptime hash_kind: hash.HashKind, 1430 arena: *std.heap.ArenaAllocator, 1431 map: DB.HashMap(.read_only), 1432 ) !T { 1433 var event: T = undefined; 1434 1435 switch (@typeInfo(T)) { 1436 .@"struct" => |struct_info| { 1437 comptime validateFlattenedFields(T); 1438 inline for (struct_info.fields) |field| { 1439 switch (@typeInfo(field.type)) { 1440 .pointer => |pointer_info| { 1441 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 1442 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1443 } else { 1444 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1445 } 1446 }, 1447 .array => |array_info| { 1448 if (array_info.child == u8) { 1449 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1450 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 1451 @memcpy(@field(event, field.name)[0..], bytes); 1452 } else { 1453 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1454 } 1455 }, 1456 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 1457 .int => |int_info| switch (int_info.signedness) { 1458 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 1459 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 1460 }, 1461 .@"enum" => { 1462 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1463 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 1464 }, 1465 .optional => |optional_info| { 1466 if (optional_info.child != []const u8) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1467 // a missing key is null 1468 @field(event, field.name) = if (try map.getCursor(hash.hashInt(hash_kind, field.name))) |cursor| 1469 try cursor.readBytesAlloc(arena.allocator(), null) 1470 else 1471 null; 1472 }, 1473 // a struct field's own fields are read from the same map 1474 .@"struct" => @field(event, field.name) = try read(field.type, DB, hash_kind, arena, map), 1475 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1476 } 1477 } 1478 }, 1479 else => @compileError("read expects a struct"), 1480 } 1481 1482 return event; 1483 } 1484 1485 // whether two events carry the same data 1486 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1487 switch (@typeInfo(T)) { 1488 .@"struct" => |struct_info| { 1489 inline for (struct_info.fields) |field| { 1490 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1491 } 1492 }, 1493 else => @compileError("fieldsEqual expects a struct"), 1494 } 1495 1496 return true; 1497 } 1498 1499 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1500 switch (@typeInfo(Field)) { 1501 .pointer => |pointer_info| { 1502 if (pointer_info.size == .slice and pointer_info.child == u8) { 1503 return std.mem.eql(u8, a, b); 1504 } else { 1505 @compileError("unsupported field type: " ++ @typeName(Field)); 1506 } 1507 }, 1508 .array => |array_info| { 1509 if (array_info.child == u8) { 1510 return std.mem.eql(u8, &a, &b); 1511 } else { 1512 @compileError("unsupported field type: " ++ @typeName(Field)); 1513 } 1514 }, 1515 .bool, .int, .@"enum" => return a == b, 1516 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1517 } 1518 } 1519 1520 fn readBytes( 1521 comptime DB: type, 1522 comptime hash_kind: hash.HashKind, 1523 allocator: std.mem.Allocator, 1524 map: DB.HashMap(.read_only), 1525 field_name: []const u8, 1526 ) ![]const u8 { 1527 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1528 return try cursor.readBytesAlloc(allocator, null); 1529 } 1530 1531 fn readUint( 1532 comptime DB: type, 1533 comptime hash_kind: hash.HashKind, 1534 map: DB.HashMap(.read_only), 1535 field_name: []const u8, 1536 ) !u64 { 1537 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1538 return try cursor.readUint(); 1539 } 1540 1541 fn readInt( 1542 comptime DB: type, 1543 comptime hash_kind: hash.HashKind, 1544 map: DB.HashMap(.read_only), 1545 field_name: []const u8, 1546 ) !i64 { 1547 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1548 return try cursor.readInt(); 1549 } 1550 1551 fn readBool( 1552 comptime DB: type, 1553 comptime hash_kind: hash.HashKind, 1554 map: DB.HashMap(.read_only), 1555 field_name: []const u8, 1556 ) !bool { 1557 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1558 var buffer: [5]u8 = undefined; 1559 const bytes = try cursor.readBytesObject(&buffer); 1560 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1561 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1562 if (std.mem.eql(u8, bytes.value, "true")) return true; 1563 if (std.mem.eql(u8, bytes.value, "false")) return false; 1564 return error.InvalidBool; 1565 } 1566 1567 // 1568 // writing to xitdb 1569 // 1570 1571 pub fn upsert( 1572 comptime T: type, 1573 comptime DB: type, 1574 comptime hash_kind: hash.HashKind, 1575 map: DB.HashMap(.read_write), 1576 event: T, 1577 ) !void { 1578 switch (@typeInfo(T)) { 1579 .@"struct" => |struct_info| { 1580 comptime validateFlattenedFields(T); 1581 inline for (struct_info.fields) |field| { 1582 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1583 } 1584 }, 1585 else => @compileError("upsert expects a struct"), 1586 } 1587 } 1588 1589 fn upsertField( 1590 comptime DB: type, 1591 comptime hash_kind: hash.HashKind, 1592 map: DB.HashMap(.read_write), 1593 comptime field_name: []const u8, 1594 comptime Field: type, 1595 value: Field, 1596 ) !void { 1597 const key = hash.hashInt(hash_kind, field_name); 1598 1599 switch (@typeInfo(Field)) { 1600 .pointer => |pointer_info| { 1601 if (pointer_info.size == .slice and pointer_info.child == u8) { 1602 try upsertBytes(DB, hash_kind, map, key, value); 1603 } else { 1604 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1605 } 1606 }, 1607 .array => |array_info| { 1608 if (array_info.child == u8) { 1609 try upsertBytes(DB, hash_kind, map, key, &value); 1610 } else { 1611 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1612 } 1613 }, 1614 .int => |int_info| switch (int_info.signedness) { 1615 .unsigned => { 1616 if (try map.getCursor(key)) |value_cursor| { 1617 if (try value_cursor.readUint() == value) { 1618 return; 1619 } 1620 } 1621 1622 try map.put(key, .{ .uint = value }); 1623 }, 1624 .signed => { 1625 if (try map.getCursor(key)) |value_cursor| { 1626 if (try value_cursor.readInt() == value) { 1627 return; 1628 } 1629 } 1630 1631 try map.put(key, .{ .int = value }); 1632 }, 1633 }, 1634 .bool => { 1635 const bytes = if (value) "true" else "false"; 1636 if (try map.getCursor(key)) |value_cursor| { 1637 var buffer: [5]u8 = undefined; 1638 const existing = try value_cursor.readBytesObject(&buffer); 1639 if (existing.format_tag) |format_tag| { 1640 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1641 return; 1642 } 1643 } 1644 } 1645 1646 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1647 }, 1648 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1649 .optional => |optional_info| { 1650 if (optional_info.child != []const u8) @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1651 // a missing key is null 1652 if (value) |bytes| { 1653 try upsertBytes(DB, hash_kind, map, key, bytes); 1654 } else { 1655 _ = try map.remove(key); 1656 } 1657 }, 1658 // a struct field's own fields are stored in the same map 1659 .@"struct" => try upsert(Field, DB, hash_kind, map, value), 1660 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1661 } 1662 } 1663 1664 fn upsertBytes( 1665 comptime DB: type, 1666 comptime hash_kind: hash.HashKind, 1667 map: DB.HashMap(.read_write), 1668 key: hash.HashInt(hash_kind), 1669 value: []const u8, 1670 ) !void { 1671 var existing_cursor_maybe = try map.getCursor(key); 1672 if (existing_cursor_maybe) |*existing_cursor| { 1673 if (try bytesEqual(DB, existing_cursor, value)) { 1674 return; 1675 } 1676 } 1677 1678 var value_cursor = try map.putCursor(key); 1679 var write_buffer: [1024]u8 = undefined; 1680 var writer = try value_cursor.writer(&write_buffer); 1681 try writer.interface.writeAll(value); 1682 try writer.finish(); 1683 } 1684 1685 fn bytesEqual( 1686 comptime DB: type, 1687 cursor: *DB.Cursor(.read_only), 1688 value: []const u8, 1689 ) !bool { 1690 var read_buffer: [1024]u8 = undefined; 1691 var reader = try cursor.reader(&read_buffer); 1692 if (reader.size != value.len) { 1693 return false; 1694 } 1695 1696 var chunk_buffer: [1024]u8 = undefined; 1697 var offset: usize = 0; 1698 while (offset < value.len) { 1699 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1700 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1701 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1702 return false; 1703 } 1704 offset += chunk_len; 1705 } 1706 1707 return true; 1708 } 1709 1710 // 1711 // CommitIterator 1712 // 1713 // differs from xit's ObjectIterator in a few ways: 1714 // 1715 // 1. iterates parents first, rather than children first 1716 // 2. `next` only returns the object id, not the full Object 1717 // 3. stores its temporary state in a file on disk to avoid OOMs 1718 // 1719 1720 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1721 return struct { 1722 const DB = EventDB(repo_opts.hash); 1723 const db_name = "haxy-repo-events.db"; 1724 1725 repo_dir: std.Io.Dir, 1726 db_file: std.Io.File, 1727 db: *DB, 1728 // map of each object id to its children 1729 parent_to_children: DB.HashMap(.read_write), 1730 // tracking pending parents is necessary because a child can only 1731 // be returned after all of its unconsumed parents have been returned 1732 child_to_pending_parents: DB.HashMap(.read_write), 1733 // queue of object ids that are ready to be returned from `next` 1734 ready_queue: DB.ArrayList(.read_write), 1735 ready_queue_index: u64, 1736 // the object id at the tip of this branch 1737 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1738 // the object id furthest back in the history that hasn't been consumed 1739 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1740 1741 pub fn init( 1742 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1743 io: std.Io, 1744 allocator: std.mem.Allocator, 1745 consumed_object_ids: DB.HashMap(.read_only), 1746 ref: rf.Ref, 1747 ) !CommitIterator(repo_kind, repo_opts) { 1748 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1749 errdefer { 1750 db_file.close(io); 1751 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1752 } 1753 1754 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1755 errdefer allocator.destroy(buffer_ptr); 1756 1757 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1758 errdefer buffer_ptr.deinit(); 1759 1760 const db_ptr = try allocator.create(DB); 1761 errdefer allocator.destroy(db_ptr); 1762 // the db is scratch state that gets deleted after iteration, so 1763 // there is nothing worth fsyncing 1764 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 1765 1766 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1767 1768 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1769 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1770 1771 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1772 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1773 1774 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1775 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1776 1777 var self = CommitIterator(repo_kind, repo_opts){ 1778 .repo_dir = state.core.repo_dir, 1779 .db_file = db_file, 1780 .db = db_ptr, 1781 .parent_to_children = parent_to_children, 1782 .child_to_pending_parents = child_to_pending_parents, 1783 .ready_queue = ready_queue, 1784 .ready_queue_index = 0, 1785 .newest_object_id = null, 1786 .oldest_object_id = null, 1787 }; 1788 errdefer self.deinit(io, allocator); 1789 1790 try self.collect(state, io, allocator, consumed_object_ids, ref); 1791 1792 return self; 1793 } 1794 1795 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1796 self.db_file.close(io); 1797 self.db.core.memory.buffer.deinit(); 1798 allocator.destroy(self.db.core.memory.buffer); 1799 self.repo_dir.deleteFile(io, db_name) catch {}; 1800 allocator.destroy(self.db); 1801 } 1802 1803 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 1804 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 1805 1806 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 1807 self.ready_queue_index += 1; 1808 1809 try self.enqueueChildren(&oid); 1810 return oid; 1811 } 1812 1813 fn collect( 1814 self: *CommitIterator(repo_kind, repo_opts), 1815 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1816 io: std.Io, 1817 allocator: std.mem.Allocator, 1818 consumed_object_ids: DB.HashMap(.read_only), 1819 ref: rf.Ref, 1820 ) !void { 1821 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 1822 1823 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 1824 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 1825 var walk_queue_index: u64 = 0; 1826 1827 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 1828 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 1829 1830 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1831 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1832 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1833 try walk_queue.append(.{ .bytes = &head_oid }); 1834 1835 while (walk_queue_index < try walk_queue.count()) { 1836 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 1837 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 1838 1839 walk_queue_index += 1; 1840 1841 // if we've seen this object id, skip it 1842 if (null != try seen_object_ids.getCursor(oid_int)) { 1843 continue; 1844 } 1845 1846 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 1847 1848 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 1849 defer commit_object.deinit(); 1850 1851 // if this object id has already been consumed, skip it 1852 if (null != try consumed_object_ids.getCursor(oid_int)) { 1853 continue; 1854 } 1855 1856 if (self.newest_object_id == null) self.newest_object_id = oid; 1857 self.oldest_object_id = oid; 1858 1859 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1860 var pending_parent_count: u64 = 0; 1861 for (parent_oids) |*parent_oid| { 1862 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1863 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 1864 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 1865 1866 // if this object id has already been consumed, skip it 1867 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 1868 continue; 1869 } 1870 1871 // if this object id hasn't already been seen, add it to the walk queue 1872 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 1873 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 1874 } 1875 1876 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 1877 const children = try DB.HashSet(.read_write).init(children_cursor); 1878 try children.put(oid_int, .{ .bytes = &oid }); 1879 pending_parent_count += 1; 1880 } 1881 1882 if (pending_parent_count == 0) { 1883 try self.ready_queue.append(.{ .bytes = &oid }); 1884 } else { 1885 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 1886 } 1887 } 1888 } 1889 1890 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 1891 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 1892 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 1893 const children = try DB.HashSet(.read_only).init(children_cursor); 1894 var children_iter = try children.iterator(); 1895 1896 while (try children_iter.next()) |*child_cursor| { 1897 const kv_pair = try child_cursor.readKeyValuePair(); 1898 const child_oid_int = kv_pair.hash; 1899 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 1900 const pending_parent_count = try pending_parent_cursor.readUint(); 1901 1902 if (pending_parent_count <= 1) { 1903 _ = try self.child_to_pending_parents.remove(child_oid_int); 1904 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 1905 try self.ready_queue.append(.{ .bytes = &child_oid }); 1906 } else { 1907 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 1908 } 1909 } 1910 } 1911 1912 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 1913 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 1914 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1915 _ = try oid_cursor.readBytes(&oid); 1916 return oid; 1917 } 1918 }; 1919 } 1920