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