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