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