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