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