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