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