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