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