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