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