╭ 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/meta" }; 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 pub const EventKind = enum { 26 user, 27 repo, 28 issue, 29 }; 30 31 pub const EventWithId = struct { 32 id: [event_id_size * 2]u8, 33 event: union(EventKind) { 34 user: ?User, 35 repo: ?Repo, 36 issue: ?Issue, 37 }, 38 39 pub fn jsonStringify(self: EventWithId, jw: anytype) !void { 40 try jw.beginObject(); 41 try jw.objectField("id"); 42 try jw.write(self.id); 43 try jw.objectField("kind"); 44 try jw.write(@tagName(self.event)); 45 try jw.objectField("data"); 46 switch (self.event) { 47 inline else => |event_maybe| try jw.write(event_maybe), 48 } 49 try jw.endObject(); 50 } 51 52 fn fromString(arena: *std.heap.ArenaAllocator, message: []const u8) !EventWithId { 53 const JsonEvent = struct { 54 id: [event_id_size * 2]u8, 55 kind: EventKind, 56 data: ?std.json.Value = null, 57 }; 58 const json_event = try std.json.parseFromSliceLeaky(JsonEvent, arena.allocator(), message, .{}); 59 return .{ 60 .id = json_event.id, 61 .event = switch (json_event.kind) { 62 .user => .{ 63 .user = if (json_event.data) |value| 64 try std.json.parseFromValueLeaky(User, arena.allocator(), value, .{}) 65 else 66 null, 67 }, 68 .repo => .{ 69 .repo = if (json_event.data) |value| 70 try std.json.parseFromValueLeaky(Repo, arena.allocator(), value, .{}) 71 else 72 null, 73 }, 74 .issue => .{ 75 .issue = if (json_event.data) |value| 76 try std.json.parseFromValueLeaky(Issue, arena.allocator(), value, .{}) 77 else 78 null, 79 }, 80 }, 81 }; 82 } 83 84 pub fn randomId(random: std.Random) [event_id_size]u8 { 85 var id_bytes: [event_id_size]u8 = undefined; 86 random.bytes(&id_bytes); 87 return id_bytes; 88 } 89 }; 90 91 pub fn consume( 92 comptime repo_opts: rp.RepoOpts(.xit), 93 io: std.Io, 94 allocator: std.mem.Allocator, 95 repo: *rp.Repo(.xit, repo_opts), 96 ref: rf.Ref, 97 ) !void { 98 const DB = rp.Repo(.xit, repo_opts).DB; 99 const State = rp.Repo(.xit, repo_opts).State; 100 101 const Ctx = struct { 102 core: *rp.Repo(.xit, repo_opts).Core, 103 io: std.Io, 104 allocator: std.mem.Allocator, 105 ref: rf.Ref, 106 107 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 108 var moment = try DB.HashMap(.read_write).init(cursor.*); 109 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 110 try consumeInTransaction(repo_opts, state, ctx.io, ctx.allocator, ctx.ref); 111 } 112 }; 113 114 try repo.core.db_file.lock(io, .exclusive); 115 defer repo.core.db_file.unlock(io); 116 117 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 118 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 119 .core = &repo.core, 120 .io = io, 121 .allocator = allocator, 122 .ref = ref, 123 }); 124 } 125 126 pub fn consumeInTransaction( 127 comptime repo_opts: rp.RepoOpts(.xit), 128 state: rp.Repo(.xit, repo_opts).State(.read_write), 129 io: std.Io, 130 allocator: std.mem.Allocator, 131 ref: rf.Ref, 132 ) !void { 133 const DB = rp.Repo(.xit, repo_opts).DB; 134 135 // the last_object_id represents the object id that was last consumed 136 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 137 if (try state.extra.moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id"))) |last_object_id_cursor| { 138 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 139 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 140 last_object_id_maybe = last_object_id_buffer; 141 } 142 143 // the list with all of haxy's state, including materialized views. 144 // the reason it is a list is so we can keep every previous haxy 145 // state, making it easy to revert to an older state if the user 146 // rebases some of the past commits. 147 const haxy_cursor = try state.extra.moment.putCursor(hash.hashInt(repo_opts.hash, "haxy")); 148 const haxy = try DB.ArrayList(.read_write).init(haxy_cursor); 149 150 // add a new item to the haxy list created above. 151 // we call the item haxy_moments. it is a map of object id to haxy moment. 152 // in other words, it maps each object id to a hash map containing the 153 // state that the database was in when that object id was consumed. 154 var haxy_moments_cursor = try haxy.appendCursor(); 155 // use the previous haxy_moments as the basis for this one if it exists 156 if (try haxy.getCursor(-2)) |last_haxy_moments_cursor| { 157 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 158 } 159 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 160 161 var commit_iter = try CommitIterator(repo_opts).init(state.readOnly(), io, allocator, haxy_moments.readOnly(), ref); 162 defer commit_iter.deinit(io, allocator); 163 164 // if there are no events to process, look at the oid at HEAD and update 165 // the last_object_id to point to it. this is important in situations 166 // where we do a merge and then force-push to remove the merge. see the 167 // merge test for an example. 168 if (commit_iter.newest_object_id == null) { 169 const head_oid_hex = (try rf.readRecur(.xit, repo_opts, state.readOnly(), io, .{ .ref = ref })) orelse return error.OidNotFound; 170 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 171 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 172 173 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 174 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 175 176 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 177 const moment_index = try moment_index_cursor.readUint(); 178 179 try haxy.slice(moment_index + 1); 180 try state.extra.moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = &head_oid }); 181 return; 182 } 183 184 // if this branch was rebased and force pushed, we need to detect that and 185 // properly revert the haxy state to the last valid state. we detect this 186 // by simply asking if the last event is a descendent of the last event 187 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 188 if (last_object_id_maybe) |*last_object_id| { 189 var is_rebased = false; 190 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 191 192 _ = mrg.getDescendent( 193 .xit, 194 repo_opts, 195 state.readOnly(), 196 io, 197 allocator, 198 &std.fmt.bytesToHex(last_object_id, .lower), 199 &std.fmt.bytesToHex(&newest_object_id, .lower), 200 ) catch |err| switch (err) { 201 error.DescendentNotFound => is_rebased = true, 202 else => |e| return e, 203 }; 204 205 if (is_rebased) { 206 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 207 var oldest_object = try obj.Object(.xit, repo_opts, .full).init(state.readOnly(), io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 208 defer oldest_object.deinit(); 209 210 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 211 switch (parent_oids.len) { 212 0 => { 213 // the branch was rebased all the way to the very beginning. 214 // we have a repo event with no parent, which means it is now 215 // the very first event. all we need to do is set the haxy list 216 // to be empty and make a new haxy_moments map to work with. 217 218 try haxy.slice(0); 219 haxy_moments_cursor = try haxy.appendCursor(); 220 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 221 222 last_object_id_maybe = null; 223 }, 224 1 => { 225 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 226 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 227 228 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 229 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 230 231 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 232 const old_moment_index = try old_moment_index_cursor.readUint(); 233 234 // resize the haxy list so we truncate all the moments that were 235 // created after the parent_oid was consumed 236 try haxy.slice(old_moment_index + 1); 237 238 // make a new haxy moment and set its initial value to the last haxy moment 239 haxy_moments_cursor = try haxy.appendCursor(); 240 const old_haxy_moments_cursor = try haxy.getCursor(old_moment_index) orelse return error.CursorNotFound; 241 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 242 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 243 244 last_object_id_maybe = oid; 245 }, 246 else => return error.UnexpectedParentCount, 247 } 248 } 249 } 250 251 while (try commit_iter.next()) |repo_event_oid| { 252 var commit_object = try obj.Object(.xit, repo_opts, .full).init(state.readOnly(), io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 253 defer commit_object.deinit(); 254 255 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 256 257 // create a moment for this object id 258 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 259 260 // if there was a previous object id, set this haxy moment's initial value to it. 261 // this efficiently "clones" the map so we make further modifications based on it. 262 if (parent_oids.len > 0) { 263 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 264 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 265 266 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 267 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 268 } 269 270 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 271 272 // merge changes from every parent after the first parent. the common 273 // ancestor is the baseline, so a later parent only contributes values 274 // it changed relative to the merge base. 275 if (parent_oids.len > 1) { 276 for (parent_oids[1..]) |*parent_oid| { 277 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 278 _ = try std.fmt.hexToBytes(&oid, parent_oid); 279 280 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 281 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 282 283 const baseline_oid_hex = try mrg.commonAncestor(.xit, repo_opts, state.readOnly(), io, allocator, &parent_oids[0], parent_oid); 284 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 285 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 286 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 287 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 288 289 try mergeChangedMapEntries(DB, haxy_moment, parent_haxy_moment, baseline_haxy_moment, true); 290 } 291 } 292 293 // associate this moment with the index it will first appear at in the haxy list. 294 // this will be important later so we can truncate that list if the user ever 295 // rebases starting at this object id. 296 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy.count() - 1 }); 297 298 // consume the event unless it's a merge commit 299 if (parent_oids.len <= 1) { 300 var arena = std.heap.ArenaAllocator.init(allocator); 301 defer arena.deinit(); 302 303 // read the message from the commit 304 try commit_object.object_reader.seekTo(commit_object.content.commit.message_position); 305 const message = try commit_object.object_reader.interface.allocRemaining(arena.allocator(), .unlimited); 306 307 const event_with_id = try EventWithId.fromString(&arena, message); 308 309 // get the id of the current event as bytes 310 var current_event_id: [event_id_size]u8 = undefined; 311 _ = try std.fmt.hexToBytes(&current_event_id, &event_with_id.id); 312 313 switch (event_with_id.event) { 314 .user => |event_maybe| try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena), 315 .repo => |event_maybe| try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena), 316 .issue => |event_maybe| try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe), 317 } 318 } 319 320 // the current object id is now the last one 321 last_object_id_maybe = repo_event_oid; 322 323 // prevent any of the data created above from being mutated by future iterations of this loop 324 try state.core.db.freeze(); 325 } 326 327 if (last_object_id_maybe) |*last_object_id| { 328 try state.extra.moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = last_object_id }); 329 } 330 } 331 332 pub fn currentMoment( 333 comptime repo_opts: rp.RepoOpts(.xit), 334 repo: *rp.Repo(.xit, repo_opts), 335 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 336 const DB = rp.Repo(.xit, repo_opts).DB; 337 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 338 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 339 const moment = try DB.HashMap(.read_only).init(moment_cursor); 340 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 341 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 342 _ = try last_object_id_cursor.readBytes(&last_object_id); 343 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 344 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 345 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 346 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 347 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 348 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 349 } 350 351 pub fn commitAndConsume( 352 comptime repo_opts: rp.RepoOpts(.xit), 353 io: std.Io, 354 allocator: std.mem.Allocator, 355 repo: *rp.Repo(.xit, repo_opts), 356 ref: rf.Ref, 357 events: []const EventWithId, 358 ) !void { 359 var json: std.Io.Writer.Allocating = .init(allocator); 360 defer json.deinit(); 361 362 for (events) |event| { 363 json.clearRetainingCapacity(); 364 try std.json.Stringify.value(event, .{}, &json.writer); 365 _ = try repo.commitAtRef(io, allocator, .{ .message = json.written() }, null, ref); 366 } 367 368 try consume(repo_opts, io, allocator, repo, ref); 369 } 370 371 // 372 // reading from xitdb 373 // 374 375 pub fn read( 376 comptime T: type, 377 comptime DB: type, 378 comptime hash_kind: hash.HashKind, 379 arena: *std.heap.ArenaAllocator, 380 map: DB.HashMap(.read_only), 381 ) !T { 382 var event: T = undefined; 383 384 switch (@typeInfo(T)) { 385 .@"struct" => |struct_info| { 386 inline for (struct_info.fields) |field| { 387 switch (@typeInfo(field.type)) { 388 .pointer => |pointer_info| { 389 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 390 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 391 } else { 392 @compileError("unsupported read field type: " ++ @typeName(field.type)); 393 } 394 }, 395 .array => |array_info| { 396 if (array_info.child == u8) { 397 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 398 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 399 @memcpy(@field(event, field.name)[0..], bytes); 400 } else { 401 @compileError("unsupported read field type: " ++ @typeName(field.type)); 402 } 403 }, 404 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 405 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 406 } 407 } 408 }, 409 else => @compileError("read expects a struct"), 410 } 411 412 return event; 413 } 414 415 fn readBytes( 416 comptime DB: type, 417 comptime hash_kind: hash.HashKind, 418 allocator: std.mem.Allocator, 419 map: DB.HashMap(.read_only), 420 field_name: []const u8, 421 ) ![]const u8 { 422 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 423 return try cursor.readBytesAlloc(allocator, null); 424 } 425 426 fn readBool( 427 comptime DB: type, 428 comptime hash_kind: hash.HashKind, 429 map: DB.HashMap(.read_only), 430 field_name: []const u8, 431 ) !bool { 432 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 433 var buffer: [5]u8 = undefined; 434 const bytes = try cursor.readBytesObject(&buffer); 435 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 436 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 437 if (std.mem.eql(u8, bytes.value, "true")) return true; 438 if (std.mem.eql(u8, bytes.value, "false")) return false; 439 return error.InvalidBool; 440 } 441 442 // 443 // writing to xitdb 444 // 445 446 pub fn upsert( 447 comptime T: type, 448 comptime DB: type, 449 comptime hash_kind: hash.HashKind, 450 map: DB.HashMap(.read_write), 451 event: T, 452 ) !void { 453 switch (@typeInfo(T)) { 454 .@"struct" => |struct_info| { 455 inline for (struct_info.fields) |field| { 456 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 457 } 458 }, 459 else => @compileError("upsert expects a struct"), 460 } 461 } 462 463 fn mergeChangedMapEntries( 464 comptime DB: type, 465 target: DB.HashMap(.read_write), 466 parent: DB.HashMap(.read_only), 467 baseline: DB.HashMap(.read_only), 468 comptime is_top_level: bool, 469 ) !void { 470 var parent_iter = try parent.iterator(); 471 while (try parent_iter.next()) |kv_pair_cursor| { 472 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 473 474 const baseline_value_cursor = try baseline.getCursor(kv_pair.hash) orelse { 475 if ((try target.getCursor(kv_pair.hash)) != null) { 476 return error.MergeConflict; 477 } 478 479 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 480 continue; 481 }; 482 483 const tag = kv_pair.value_cursor.slot().tag; 484 485 if (tag != baseline_value_cursor.slot().tag) { 486 return error.UnexpectedTag; 487 } 488 489 if (kv_pair.value_cursor.slot().value == baseline_value_cursor.slot().value) { 490 continue; 491 } 492 493 if (tag == .hash_map) { 494 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 495 if (target_existing_cursor.slot().tag != .hash_map) { 496 return error.MergeConflict; 497 } 498 499 const target_child_cursor = try target.putCursor(kv_pair.hash); 500 const target_child = try DB.HashMap(.read_write).init(target_child_cursor); 501 const parent_child = try DB.HashMap(.read_only).init(kv_pair.value_cursor); 502 const baseline_child = try DB.HashMap(.read_only).init(baseline_value_cursor); 503 try mergeChangedMapEntries(DB, target_child, parent_child, baseline_child, false); 504 } else if (is_top_level) { 505 // the moment-index is a top-level key in the haxy moment 506 // and is not a map. we don't want to do any merge of this. 507 continue; 508 } else { 509 const target_value_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 510 if (target_value_cursor.slot().value != baseline_value_cursor.slot().value) { 511 return error.MergeConflict; 512 } 513 514 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 515 } 516 } 517 } 518 519 fn upsertField( 520 comptime DB: type, 521 comptime hash_kind: hash.HashKind, 522 map: DB.HashMap(.read_write), 523 comptime field_name: []const u8, 524 comptime Field: type, 525 value: Field, 526 ) !void { 527 const key = hash.hashInt(hash_kind, field_name); 528 529 switch (@typeInfo(Field)) { 530 .pointer => |pointer_info| { 531 if (pointer_info.size == .slice and pointer_info.child == u8) { 532 try upsertBytes(DB, hash_kind, map, key, value); 533 } else { 534 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 535 } 536 }, 537 .array => |array_info| { 538 if (array_info.child == u8) { 539 try upsertBytes(DB, hash_kind, map, key, &value); 540 } else { 541 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 542 } 543 }, 544 .int => |int_info| switch (int_info.signedness) { 545 .unsigned => { 546 if (try map.getCursor(key)) |value_cursor| { 547 if (try value_cursor.readUint() == value) { 548 return; 549 } 550 } 551 552 try map.put(key, .{ .uint = value }); 553 }, 554 .signed => { 555 if (try map.getCursor(key)) |value_cursor| { 556 if (try value_cursor.readInt() == value) { 557 return; 558 } 559 } 560 561 try map.put(key, .{ .int = value }); 562 }, 563 }, 564 .bool => { 565 const bytes = if (value) "true" else "false"; 566 if (try map.getCursor(key)) |value_cursor| { 567 var buffer: [5]u8 = undefined; 568 const existing = try value_cursor.readBytesObject(&buffer); 569 if (existing.format_tag) |format_tag| { 570 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 571 return; 572 } 573 } 574 } 575 576 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 577 }, 578 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 579 } 580 } 581 582 fn upsertBytes( 583 comptime DB: type, 584 comptime hash_kind: hash.HashKind, 585 map: DB.HashMap(.read_write), 586 key: hash.HashInt(hash_kind), 587 value: []const u8, 588 ) !void { 589 var existing_cursor_maybe = try map.getCursor(key); 590 if (existing_cursor_maybe) |*existing_cursor| { 591 if (try bytesEqual(DB, existing_cursor, value)) { 592 return; 593 } 594 } 595 596 var value_cursor = try map.putCursor(key); 597 var write_buffer: [1024]u8 = undefined; 598 var writer = try value_cursor.writer(&write_buffer); 599 try writer.interface.writeAll(value); 600 try writer.finish(); 601 } 602 603 fn bytesEqual( 604 comptime DB: type, 605 cursor: *DB.Cursor(.read_only), 606 value: []const u8, 607 ) !bool { 608 var read_buffer: [1024]u8 = undefined; 609 var reader = try cursor.reader(&read_buffer); 610 if (reader.size != value.len) { 611 return false; 612 } 613 614 var chunk_buffer: [1024]u8 = undefined; 615 var offset: usize = 0; 616 while (offset < value.len) { 617 const chunk_len = @min(chunk_buffer.len, value.len - offset); 618 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 619 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 620 return false; 621 } 622 offset += chunk_len; 623 } 624 625 return true; 626 } 627 628 // 629 // CommitIterator 630 // 631 // differs from xit's ObjectIterator in a few ways: 632 // 633 // 1. iterates parents first, rather than children first 634 // 2. `next` only returns the object id, not the full Object 635 // 3. stores its temporary state in a file on disk to avoid OOMs 636 // 637 638 pub fn CommitIterator(comptime repo_opts: rp.RepoOpts(.xit)) type { 639 return struct { 640 const DB = rp.Repo(.xit, repo_opts).DB; 641 const db_name = "haxy-repo-events.db"; 642 643 repo_dir: std.Io.Dir, 644 db_file: std.Io.File, 645 db: *DB, 646 // map of each object id to its children 647 parent_to_children: DB.HashMap(.read_write), 648 // tracking pending parents is necessary because a child can only 649 // be returned after all of its unconsumed parents have been returned 650 child_to_pending_parents: DB.HashMap(.read_write), 651 // queue of object ids that are ready to be returned from `next` 652 ready_queue: DB.ArrayList(.read_write), 653 ready_queue_index: u64, 654 // the object id at the tip of this branch 655 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 656 // the object id furthest back in the history that hasn't been consumed 657 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 658 659 pub fn init( 660 state: rp.Repo(.xit, repo_opts).State(.read_only), 661 io: std.Io, 662 allocator: std.mem.Allocator, 663 consumed_object_ids: DB.HashMap(.read_only), 664 ref: rf.Ref, 665 ) !CommitIterator(repo_opts) { 666 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 667 errdefer { 668 db_file.close(io); 669 state.core.repo_dir.deleteFile(io, db_name) catch {}; 670 } 671 672 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 673 errdefer allocator.destroy(buffer_ptr); 674 675 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 676 errdefer buffer_ptr.deinit(); 677 678 const db_ptr = try allocator.create(DB); 679 errdefer allocator.destroy(db_ptr); 680 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr }); 681 682 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 683 684 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 685 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 686 687 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 688 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 689 690 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 691 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 692 693 var self = CommitIterator(repo_opts){ 694 .repo_dir = state.core.repo_dir, 695 .db_file = db_file, 696 .db = db_ptr, 697 .parent_to_children = parent_to_children, 698 .child_to_pending_parents = child_to_pending_parents, 699 .ready_queue = ready_queue, 700 .ready_queue_index = 0, 701 .newest_object_id = null, 702 .oldest_object_id = null, 703 }; 704 errdefer self.deinit(io, allocator); 705 706 try self.collect(state, io, allocator, consumed_object_ids, ref); 707 708 return self; 709 } 710 711 pub fn deinit(self: *CommitIterator(repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 712 self.db_file.close(io); 713 self.db.core.memory.buffer.deinit(); 714 allocator.destroy(self.db.core.memory.buffer); 715 self.repo_dir.deleteFile(io, db_name) catch {}; 716 allocator.destroy(self.db); 717 } 718 719 pub fn next(self: *CommitIterator(repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 720 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 721 722 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 723 self.ready_queue_index += 1; 724 725 try self.enqueueChildren(&oid); 726 return oid; 727 } 728 729 fn collect( 730 self: *CommitIterator(repo_opts), 731 state: rp.Repo(.xit, repo_opts).State(.read_only), 732 io: std.Io, 733 allocator: std.mem.Allocator, 734 consumed_object_ids: DB.HashMap(.read_only), 735 ref: rf.Ref, 736 ) !void { 737 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 738 739 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 740 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 741 var walk_queue_index: u64 = 0; 742 743 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 744 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 745 746 const head_oid_hex = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 747 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 748 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 749 try walk_queue.append(.{ .bytes = &head_oid }); 750 751 while (walk_queue_index < try walk_queue.count()) { 752 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 753 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 754 755 walk_queue_index += 1; 756 757 // if we've seen this object id, skip it 758 if (null != try seen_object_ids.getCursor(oid_int)) { 759 continue; 760 } 761 762 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 763 764 var commit_object = try obj.Object(.xit, repo_opts, .full).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 765 defer commit_object.deinit(); 766 767 // if this object id has already been consumed, skip it 768 if (null != try consumed_object_ids.getCursor(oid_int)) { 769 continue; 770 } 771 772 if (self.newest_object_id == null) self.newest_object_id = oid; 773 self.oldest_object_id = oid; 774 775 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 776 var pending_parent_count: u64 = 0; 777 for (parent_oids) |*parent_oid| { 778 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 779 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 780 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 781 782 // if this object id has already been consumed, skip it 783 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 784 continue; 785 } 786 787 // if this object id hasn't already been seen, add it to the walk queue 788 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 789 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 790 } 791 792 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 793 const children = try DB.HashSet(.read_write).init(children_cursor); 794 try children.put(oid_int, .{ .bytes = &oid }); 795 pending_parent_count += 1; 796 } 797 798 if (pending_parent_count == 0) { 799 try self.ready_queue.append(.{ .bytes = &oid }); 800 } else { 801 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 802 } 803 } 804 } 805 806 fn enqueueChildren(self: *CommitIterator(repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 807 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 808 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 809 const children = try DB.HashSet(.read_only).init(children_cursor); 810 var children_iter = try children.iterator(); 811 812 while (try children_iter.next()) |*child_cursor| { 813 const kv_pair = try child_cursor.readKeyValuePair(); 814 const child_oid_int = kv_pair.hash; 815 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 816 const pending_parent_count = try pending_parent_cursor.readUint(); 817 818 if (pending_parent_count <= 1) { 819 _ = try self.child_to_pending_parents.remove(child_oid_int); 820 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 821 try self.ready_queue.append(.{ .bytes = &child_oid }); 822 } else { 823 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 824 } 825 } 826 } 827 828 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 829 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 830 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 831 _ = try oid_cursor.readBytes(&oid); 832 return oid; 833 } 834 }; 835 } 836