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