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