╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
251 // sync rather than serving its issues indefinitely 252 try LocalEventDB(repo_opts.hash).delete(io, repo.core.repo_dir); 253 return; 254 }; 255 256 var event_db = try LocalEventDB(repo_opts.hash).create(io, allocator, repo.core.repo_dir); 257 defer event_db.deinit(io, allocator); 258 259 if (try lastConsumedOid(repo_opts.hash, event_db.db)) |last_oid| { 260 var tip_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 261 _ = try std.fmt.hexToBytes(&tip_bytes, &tip); 262 if (std.mem.eql(u8, &last_oid, &tip_bytes)) return; 263 } 264 265 try event_db.consume(repo_kind, repo_opts, io, allocator, repo, ref); 266 } 267 268 // consume the events on `ref` into the db `moment` writes to. events are read 269 // from `read_state`'s repo, which needn't be the repo backing the db — that's 270 // how a local (possibly git-backed) repo's events land in a standalone db. 271 pub fn consumeInTransaction( 272 comptime repo_kind: rp.RepoKind, 273 comptime repo_opts: rp.RepoOpts(repo_kind), 274 read_state: rp.Repo(repo_kind, repo_opts).State(.read_only), 275 db: *EventDB(repo_opts.hash), 276 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 277 io: std.Io, 278 allocator: std.mem.Allocator, 279 ref: rf.Ref, 280 ) !void { 281 const DB = EventDB(repo_opts.hash); 282 283 // the last_object_id represents the object id that was last consumed 284 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 285 if (try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id"))) |last_object_id_cursor| { 286 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 287 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 288 last_object_id_maybe = last_object_id_buffer; 289 } 290 291 // the list with all of haxy's state, including materialized views. 292 // the reason it is a list is so we can keep every previous haxy 293 // state, making it easy to revert to an older state if the user 294 // rebases some of the past commits. 295 const haxy_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, "haxy")); 296 const haxy = try DB.ArrayList(.read_write).init(haxy_cursor); 297 298 // add a new item to the haxy list created above. 299 // we call the item haxy_moments. it is a map of object id to haxy moment. 300 // in other words, it maps each object id to a hash map containing the 301 // state that the database was in when that object id was consumed. 302 var haxy_moments_cursor = try haxy.appendCursor(); 303 // use the previous haxy_moments as the basis for this one if it exists 304 if (try haxy.getCursor(-2)) |last_haxy_moments_cursor| { 305 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 306 } 307 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 308 309 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 310 defer commit_iter.deinit(io, allocator); 311 312 // if there are no events to process, look at the oid at HEAD and update 313 // the last_object_id to point to it. this is important in situations 314 // where we do a merge and then force-push to remove the merge. see the 315 // merge test for an example. 316 if (commit_iter.newest_object_id == null) { 317 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 318 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 319 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 320 321 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 322 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 323 324 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 325 const moment_index = try moment_index_cursor.readUint(); 326 327 try haxy.slice(moment_index + 1); 328 try moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = &head_oid }); 329 return; 330 } 331 332 // if this branch was rebased and force pushed, we need to detect that and 333 // properly revert the haxy state to the last valid state. we detect this 334 // by simply asking if the last event is a descendent of the last event 335 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 336 if (last_object_id_maybe) |*last_object_id| { 337 var is_rebased = false; 338 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 339 340 _ = mrg.getDescendent( 341 repo_kind, 342 repo_opts, 343 read_state, 344 io, 345 allocator, 346 &std.fmt.bytesToHex(last_object_id, .lower), 347 &std.fmt.bytesToHex(&newest_object_id, .lower), 348 ) catch |err| switch (err) { 349 error.DescendentNotFound => is_rebased = true, 350 else => |e| return e, 351 }; 352 353 if (is_rebased) { 354 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 355 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 356 defer oldest_object.deinit(); 357 358 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 359 switch (parent_oids.len) { 360 0 => { 361 // the branch was rebased all the way to the very beginning. 362 // we have a repo event with no parent, which means it is now 363 // the very first event. all we need to do is set the haxy list 364 // to be empty and make a new haxy_moments map to work with. 365 366 try haxy.slice(0); 367 haxy_moments_cursor = try haxy.appendCursor(); 368 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 369 370 last_object_id_maybe = null; 371 }, 372 1 => { 373 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 374 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 375 376 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 377 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 378 379 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 380 const old_moment_index = try old_moment_index_cursor.readUint(); 381 382 // resize the haxy list so we truncate all the moments that were 383 // created after the parent_oid was consumed 384 try haxy.slice(old_moment_index + 1); 385 386 // make a new haxy moment and set its initial value to the last haxy moment 387 haxy_moments_cursor = try haxy.appendCursor(); 388 const old_haxy_moments_cursor = try haxy.getCursor(old_moment_index) orelse return error.CursorNotFound; 389 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 390 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 391 392 last_object_id_maybe = oid; 393 }, 394 else => return error.UnexpectedParentCount, 395 } 396 } 397 } 398 399 while (try commit_iter.next()) |repo_event_oid| { 400 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 401 defer commit_object.deinit(); 402 403 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 404 405 // create a moment for this object id 406 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 407 408 // if there was a previous object id, set this haxy moment's initial value to it. 409 // this efficiently "clones" the map so we make further modifications based on it. 410 if (parent_oids.len > 0) { 411 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 412 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 413 414 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 415 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 416 } 417 418 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 419 420 // merge changes from every parent after the first parent. the common 421 // ancestor is the baseline, so a later parent only contributes values 422 // it changed relative to the merge base. 423 if (parent_oids.len > 1) { 424 for (parent_oids[1..]) |*parent_oid| { 425 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 426 _ = try std.fmt.hexToBytes(&oid, parent_oid); 427 428 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 429 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 430 431 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 432 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 433 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 434 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 435 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 436 437 try mergeChangedMapEntries(DB, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment, true); 438 } 439 } 440 441 // associate this moment with the index it will first appear at in the haxy list. 442 // this will be important later so we can truncate that list if the user ever 443 // rebases starting at this object id. 444 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy.count() - 1 }); 445 446 // consume the event unless it's a merge commit 447 if (parent_oids.len <= 1) { 448 var arena = std.heap.ArenaAllocator.init(allocator); 449 defer arena.deinit(); 450 451 // read the message from the commit 452 try commit_object.object_reader.seekTo(commit_object.content.commit.message_position); 453 const message = try commit_object.object_reader.interface.allocRemaining(arena.allocator(), .unlimited); 454 455 const event_with_id = try EventWithId.fromString(&arena, message); 456 457 // get the id of the current event as bytes 458 var current_event_id: [event_id_size]u8 = undefined; 459 _ = try std.fmt.hexToBytes(&current_event_id, &event_with_id.id); 460 461 const created_ts = commit_object.content.commit.metadata.timestamp; 462 463 switch (event_with_id.event) { 464 .user => |event_maybe| try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena, created_ts), 465 .repo => |event_maybe| try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena, created_ts), 466 .issue => |event_maybe| try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena, created_ts), 467 } 468 } 469 470 // the current object id is now the last one 471 last_object_id_maybe = repo_event_oid; 472 473 // prevent any of the data created above from being mutated by future iterations of this loop 474 try db.freeze(); 475 } 476 477 if (last_object_id_maybe) |*last_object_id| { 478 try moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = last_object_id }); 479 } 480 } 481 482 pub fn currentMoment( 483 comptime repo_opts: rp.RepoOpts(.xit), 484 repo: *rp.Repo(.xit, repo_opts), 485 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 486 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 487 } 488 489 // the oid of the last event commit consumed into `db`, or null before any 490 // consume completed 491 fn lastConsumedOid( 492 comptime hash_kind: hash.HashKind, 493 db: *EventDB(hash_kind), 494 ) !?[hash.byteLen(hash_kind)]u8 { 495 const DB = EventDB(hash_kind); 496 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 497 const moment_cursor = try history.getCursor(-1) orelse return null; 498 const moment = try DB.HashMap(.read_only).init(moment_cursor); 499 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy-last-object-id")) orelse return null; 500 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 501 _ = try last_object_id_cursor.readBytes(&last_object_id); 502 return last_object_id; 503 } 504 505 pub fn currentMomentFromDb( 506 comptime hash_kind: hash.HashKind, 507 db: *EventDB(hash_kind), 508 ) !EventDB(hash_kind).HashMap(.read_only) { 509 const DB = EventDB(hash_kind); 510 const last_object_id = (try lastConsumedOid(hash_kind, db)) orelse return error.NotFound; 511 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 512 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 513 const moment = try DB.HashMap(.read_only).init(moment_cursor); 514 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy")) orelse return error.NotFound; 515 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 516 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 517 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 518 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 519 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 520 } 521 522 pub fn commitAndConsume( 523 comptime repo_opts: rp.RepoOpts(.xit), 524 io: std.Io, 525 allocator: std.mem.Allocator, 526 repo: *rp.Repo(.xit, repo_opts), 527 ref: rf.Ref, 528 events: []const EventWithId, 529 ) !void { 530 var json: std.Io.Writer.Allocating = .init(allocator); 531 defer json.deinit(); 532 533 for (events) |event| { 534 json.clearRetainingCapacity(); 535 try std.json.Stringify.value(event, .{}, &json.writer); 536 _ = try repo.commitAtRef(io, allocator, .{ .message = json.written(), .timestamp = event.timestamp }, null, ref); 537 } 538 539 try consume(repo_opts, io, allocator, repo, ref); 540 } 541 542 // build the key for SortedSets sorted by timestamp. the big-endian timestamp 543 // makes byte order match creation order; the event id breaks ties and keeps 544 // keys unique within the same timestamp. 545 pub fn orderKey(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 546 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 547 std.mem.writeInt(u64, key[0..@sizeOf(u64)], timestamp, .big); 548 @memcpy(key[@sizeOf(u64)..], event_id); 549 return key; 550 } 551 552 // split a pushed "<owner>/<repo>" path into its two components, or null if it 553 // isn't exactly two non-empty segments. 554 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 555 var it = std.mem.splitScalar(u8, path, '/'); 556 const owner = it.next() orelse return null; 557 const name = it.next() orelse return null; 558 if (it.next() != null) return null; 559 if (owner.len == 0 or name.len == 0) return null; 560 561 return .{ .owner = owner, .name = name }; 562 } 563 564 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 565 // directory under the repos dir 566 pub fn resolveOrCreateRepo( 567 io: std.Io, 568 allocator: std.mem.Allocator, 569 admin_repo_path: []const u8, 570 owner_name: []const u8, 571 repo_name: []const u8, 572 create_if_missing: bool, 573 ) !?[event_id_size * 2]u8 { 574 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 575 error.RepoNotFound => return null, 576 else => |e| return e, 577 }; 578 defer repo.deinit(io, allocator); 579 580 var arena = std.heap.ArenaAllocator.init(allocator); 581 defer arena.deinit(); 582 583 const moment = try currentMoment(admin_repo_opts, &repo); 584 585 // an already-registered repo reuses its event id, so a re-push (or a clone) 586 // lands in the same repo 587 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 588 return std.fmt.bytesToHex(found.event_id, .lower); 589 } 590 591 if (!create_if_missing) return null; 592 593 // the new repo is owned by the named user, read from the name index; an 594 // unknown owner can't own a repo, so the push is rejected 595 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 596 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 597 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 598 var owner_user_id: [event_id_size]u8 = undefined; 599 _ = try owner_id_cursor.readBytes(&owner_user_id); 600 601 var id_bytes: [event_id_size]u8 = undefined; 602 io.random(&id_bytes); 603 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 604 605 try commitAndConsume(admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 606 .id = event_id_hex, 607 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 608 .event = .{ .repo = .{ 609 .user_id = &owner_user_id, 610 .name = repo_name, 611 .description = "", 612 .enable_issue = true, 613 } }, 614 }}); 615 616 return event_id_hex; 617 } 618 619 // 620 // reading from xitdb 621 // 622 623 pub fn read( 624 comptime T: type, 625 comptime DB: type, 626 comptime hash_kind: hash.HashKind, 627 arena: *std.heap.ArenaAllocator, 628 map: DB.HashMap(.read_only), 629 ) !T { 630 var event: T = undefined; 631 632 switch (@typeInfo(T)) { 633 .@"struct" => |struct_info| { 634 inline for (struct_info.fields) |field| { 635 switch (@typeInfo(field.type)) { 636 .pointer => |pointer_info| { 637 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 638 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 639 } else { 640 @compileError("unsupported read field type: " ++ @typeName(field.type)); 641 } 642 }, 643 .array => |array_info| { 644 if (array_info.child == u8) { 645 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 646 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 647 @memcpy(@field(event, field.name)[0..], bytes); 648 } else { 649 @compileError("unsupported read field type: " ++ @typeName(field.type)); 650 } 651 }, 652 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 653 .int => |int_info| switch (int_info.signedness) { 654 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 655 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 656 }, 657 .@"enum" => { 658 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 659 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 660 }, 661 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 662 } 663 } 664 }, 665 else => @compileError("read expects a struct"), 666 } 667 668 return event; 669 } 670 671 fn readBytes( 672 comptime DB: type, 673 comptime hash_kind: hash.HashKind, 674 allocator: std.mem.Allocator, 675 map: DB.HashMap(.read_only), 676 field_name: []const u8, 677 ) ![]const u8 { 678 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 679 return try cursor.readBytesAlloc(allocator, null); 680 } 681 682 fn readUint( 683 comptime DB: type, 684 comptime hash_kind: hash.HashKind, 685 map: DB.HashMap(.read_only), 686 field_name: []const u8, 687 ) !u64 { 688 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 689 return try cursor.readUint(); 690 } 691 692 fn readInt( 693 comptime DB: type, 694 comptime hash_kind: hash.HashKind, 695 map: DB.HashMap(.read_only), 696 field_name: []const u8, 697 ) !i64 { 698 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 699 return try cursor.readInt(); 700 } 701 702 fn readBool( 703 comptime DB: type, 704 comptime hash_kind: hash.HashKind, 705 map: DB.HashMap(.read_only), 706 field_name: []const u8, 707 ) !bool { 708 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 709 var buffer: [5]u8 = undefined; 710 const bytes = try cursor.readBytesObject(&buffer); 711 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 712 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 713 if (std.mem.eql(u8, bytes.value, "true")) return true; 714 if (std.mem.eql(u8, bytes.value, "false")) return false; 715 return error.InvalidBool; 716 } 717 718 // 719 // writing to xitdb 720 // 721 722 pub fn upsert( 723 comptime T: type, 724 comptime DB: type, 725 comptime hash_kind: hash.HashKind, 726 map: DB.HashMap(.read_write), 727 event: T, 728 ) !void { 729 switch (@typeInfo(T)) { 730 .@"struct" => |struct_info| { 731 inline for (struct_info.fields) |field| { 732 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 733 } 734 }, 735 else => @compileError("upsert expects a struct"), 736 } 737 } 738 739 // three-way merge of a hash map 740 fn mergeChangedMapEntries( 741 comptime DB: type, 742 allocator: std.mem.Allocator, 743 target: DB.HashMap(.read_write), 744 parent: DB.HashMap(.read_only), 745 baseline: DB.HashMap(.read_only), 746 comptime is_top_level: bool, 747 ) !void { 748 var parent_iter = try parent.iterator(); 749 while (try parent_iter.next()) |kv_pair_cursor| { 750 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 751 752 const baseline_value_cursor = try baseline.getCursor(kv_pair.hash) orelse { 753 if ((try target.getCursor(kv_pair.hash)) != null) { 754 return error.MergeConflict; 755 } 756 757 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 758 continue; 759 }; 760 761 const tag = kv_pair.value_cursor.slot().tag; 762 763 if (tag != baseline_value_cursor.slot().tag) { 764 return error.UnexpectedTag; 765 } 766 767 if (kv_pair.value_cursor.slot().value == baseline_value_cursor.slot().value) { 768 continue; 769 } 770 771 if (tag == .hash_map) { 772 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 773 if (target_existing_cursor.slot().tag != .hash_map) { 774 return error.UnexpectedTag; 775 } 776 777 const target_child_cursor = try target.putCursor(kv_pair.hash); 778 const target_child = try DB.HashMap(.read_write).init(target_child_cursor); 779 const parent_child = try DB.HashMap(.read_only).init(kv_pair.value_cursor); 780 const baseline_child = try DB.HashMap(.read_only).init(baseline_value_cursor); 781 try mergeChangedMapEntries(DB, allocator, target_child, parent_child, baseline_child, false); 782 } else if (tag == .sorted_set) { 783 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 784 if (target_existing_cursor.slot().tag != .sorted_set) { 785 return error.UnexpectedTag; 786 } 787 788 const target_child_cursor = try target.putCursor(kv_pair.hash); 789 const target_child = try DB.SortedSet(.read_write).init(target_child_cursor); 790 const parent_child = try DB.SortedSet(.read_only).init(kv_pair.value_cursor); 791 const baseline_child = try DB.SortedSet(.read_only).init(baseline_value_cursor); 792 try mergeChangedSetEntries(DB, allocator, target_child, parent_child, baseline_child); 793 } else if (tag == .sorted_map) { 794 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 795 if (target_existing_cursor.slot().tag != .sorted_map) { 796 return error.UnexpectedTag; 797 } 798 799 const target_child_cursor = try target.putCursor(kv_pair.hash); 800 const target_child = try DB.SortedMap(.read_write).init(target_child_cursor); 801 const parent_child = try DB.SortedMap(.read_only).init(kv_pair.value_cursor); 802 const baseline_child = try DB.SortedMap(.read_only).init(baseline_value_cursor); 803 try mergeChangedSortedMapEntries(DB, allocator, target_child, parent_child, baseline_child); 804 } else if (is_top_level) { 805 // the moment-index is a top-level key in the haxy moment 806 // and is not a map. we don't want to do any merge of this. 807 continue; 808 } else { 809 const target_value_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 810 if (target_value_cursor.slot().tag != baseline_value_cursor.slot().tag) { 811 return error.UnexpectedTag; 812 } 813 if (target_value_cursor.slot().value != baseline_value_cursor.slot().value) { 814 return error.MergeConflict; 815 } 816 817 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 818 } 819 } 820 } 821 822 // three-way merge of a sorted map 823 fn mergeChangedSortedMapEntries( 824 comptime DB: type, 825 allocator: std.mem.Allocator, 826 target: DB.SortedMap(.read_write), 827 parent: DB.SortedMap(.read_only), 828 baseline: DB.SortedMap(.read_only), 829 ) !void { 830 var parent_iter = try parent.iterator(); 831 while (try parent_iter.next()) |kv_pair_cursor| { 832 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 833 const key = try kv_pair.key_cursor.readBytesAlloc(allocator, null); 834 defer allocator.free(key); 835 836 const baseline_value_cursor = try baseline.getCursor(key) orelse { 837 if (try target.getCursor(key)) |target_existing_cursor| { 838 // both parents created this key. sets union (they hold 839 // independently added members); anything else conflicts. 840 const parent_tag = kv_pair.value_cursor.slot().tag; 841 if (target_existing_cursor.slot().tag != parent_tag) { 842 return error.UnexpectedTag; 843 } 844 if (parent_tag != .sorted_set) { 845 return error.MergeConflict; 846 } 847 848 const target_child_cursor = try target.putCursor(key); 849 const target_child = try DB.SortedSet(.read_write).init(target_child_cursor); 850 const parent_child = try DB.SortedSet(.read_only).init(kv_pair.value_cursor); 851 var set_iter = try parent_child.iterator(); 852 while (try set_iter.next()) |set_kv_cursor| { 853 const set_kv = try set_kv_cursor.readKeyValuePair(); 854 const set_key = try set_kv.key_cursor.readBytesAlloc(allocator, null); 855 defer allocator.free(set_key); 856 try target_child.put(set_key); 857 } 858 continue; 859 } 860 861 try target.put(key, .{ .slot = kv_pair.value_cursor.slot() }); 862 continue; 863 }; 864 865 const tag = kv_pair.value_cursor.slot().tag; 866 867 if (tag != baseline_value_cursor.slot().tag) { 868 return error.UnexpectedTag; 869 } 870 871 if (kv_pair.value_cursor.slot().value == baseline_value_cursor.slot().value) { 872 continue; 873 } 874 875 if (tag == .sorted_set) { 876 const target_existing_cursor = try target.getCursor(key) orelse return error.MergeConflict; 877 if (target_existing_cursor.slot().tag != .sorted_set) { 878 return error.UnexpectedTag; 879 } 880 881 const target_child_cursor = try target.putCursor(key); 882 const target_child = try DB.SortedSet(.read_write).init(target_child_cursor); 883 const parent_child = try DB.SortedSet(.read_only).init(kv_pair.value_cursor); 884 const baseline_child = try DB.SortedSet(.read_only).init(baseline_value_cursor); 885 try mergeChangedSetEntries(DB, allocator, target_child, parent_child, baseline_child); 886 } else { 887 const target_value_cursor = try target.getCursor(key) orelse return error.MergeConflict; 888 if (target_value_cursor.slot().tag != baseline_value_cursor.slot().tag) { 889 return error.UnexpectedTag; 890 } 891 if (target_value_cursor.slot().value != baseline_value_cursor.slot().value) { 892 return error.MergeConflict; 893 } 894 895 try target.put(key, .{ .slot = kv_pair.value_cursor.slot() }); 896 } 897 } 898 } 899 900 // three-way merge of a sorted set: apply the parent's changes relative to the 901 // baseline. keys have no values, so additions and removals can't conflict. 902 fn mergeChangedSetEntries( 903 comptime DB: type, 904 allocator: std.mem.Allocator, 905 target: DB.SortedSet(.read_write), 906 parent: DB.SortedSet(.read_only), 907 baseline: DB.SortedSet(.read_only), 908 ) !void { 909 var parent_iter = try parent.iterator(); 910 while (try parent_iter.next()) |kv_pair_cursor| { 911 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 912 const key = try kv_pair.key_cursor.readBytesAlloc(allocator, null); 913 defer allocator.free(key); 914 if (!try baseline.contains(key)) try target.put(key); 915 } 916 917 var baseline_iter = try baseline.iterator(); 918 while (try baseline_iter.next()) |kv_pair_cursor| { 919 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 920 const key = try kv_pair.key_cursor.readBytesAlloc(allocator, null); 921 defer allocator.free(key); 922 if (!try parent.contains(key)) _ = try target.remove(key); 923 } 924 } 925 926 fn upsertField( 927 comptime DB: type, 928 comptime hash_kind: hash.HashKind, 929 map: DB.HashMap(.read_write), 930 comptime field_name: []const u8, 931 comptime Field: type, 932 value: Field, 933 ) !void { 934 const key = hash.hashInt(hash_kind, field_name); 935 936 switch (@typeInfo(Field)) { 937 .pointer => |pointer_info| { 938 if (pointer_info.size == .slice and pointer_info.child == u8) { 939 try upsertBytes(DB, hash_kind, map, key, value); 940 } else { 941 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 942 } 943 }, 944 .array => |array_info| { 945 if (array_info.child == u8) { 946 try upsertBytes(DB, hash_kind, map, key, &value); 947 } else { 948 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 949 } 950 }, 951 .int => |int_info| switch (int_info.signedness) { 952 .unsigned => { 953 if (try map.getCursor(key)) |value_cursor| { 954 if (try value_cursor.readUint() == value) { 955 return; 956 } 957 } 958 959 try map.put(key, .{ .uint = value }); 960 }, 961 .signed => { 962 if (try map.getCursor(key)) |value_cursor| { 963 if (try value_cursor.readInt() == value) { 964 return; 965 } 966 } 967 968 try map.put(key, .{ .int = value }); 969 }, 970 }, 971 .bool => { 972 const bytes = if (value) "true" else "false"; 973 if (try map.getCursor(key)) |value_cursor| { 974 var buffer: [5]u8 = undefined; 975 const existing = try value_cursor.readBytesObject(&buffer); 976 if (existing.format_tag) |format_tag| { 977 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 978 return; 979 } 980 } 981 } 982 983 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 984 }, 985 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 986 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 987 } 988 } 989 990 fn upsertBytes( 991 comptime DB: type, 992 comptime hash_kind: hash.HashKind, 993 map: DB.HashMap(.read_write), 994 key: hash.HashInt(hash_kind), 995 value: []const u8, 996 ) !void { 997 var existing_cursor_maybe = try map.getCursor(key); 998 if (existing_cursor_maybe) |*existing_cursor| { 999 if (try bytesEqual(DB, existing_cursor, value)) { 1000 return; 1001 } 1002 } 1003 1004 var value_cursor = try map.putCursor(key); 1005 var write_buffer: [1024]u8 = undefined; 1006 var writer = try value_cursor.writer(&write_buffer); 1007 try writer.interface.writeAll(value); 1008 try writer.finish(); 1009 } 1010 1011 fn bytesEqual( 1012 comptime DB: type, 1013 cursor: *DB.Cursor(.read_only), 1014 value: []const u8, 1015 ) !bool { 1016 var read_buffer: [1024]u8 = undefined; 1017 var reader = try cursor.reader(&read_buffer); 1018 if (reader.size != value.len) { 1019 return false; 1020 } 1021 1022 var chunk_buffer: [1024]u8 = undefined; 1023 var offset: usize = 0; 1024 while (offset < value.len) { 1025 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1026 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1027 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1028 return false; 1029 } 1030 offset += chunk_len; 1031 } 1032 1033 return true; 1034 } 1035 1036 // 1037 // CommitIterator 1038 // 1039 // differs from xit's ObjectIterator in a few ways: 1040 // 1041 // 1. iterates parents first, rather than children first 1042 // 2. `next` only returns the object id, not the full Object 1043 // 3. stores its temporary state in a file on disk to avoid OOMs 1044 // 1045 1046 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1047 return struct { 1048 const DB = EventDB(repo_opts.hash); 1049 const db_name = "haxy-repo-events.db"; 1050 1051 repo_dir: std.Io.Dir, 1052 db_file: std.Io.File, 1053 db: *DB, 1054 // map of each object id to its children 1055 parent_to_children: DB.HashMap(.read_write), 1056 // tracking pending parents is necessary because a child can only 1057 // be returned after all of its unconsumed parents have been returned 1058 child_to_pending_parents: DB.HashMap(.read_write), 1059 // queue of object ids that are ready to be returned from `next` 1060 ready_queue: DB.ArrayList(.read_write), 1061 ready_queue_index: u64, 1062 // the object id at the tip of this branch 1063 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1064 // the object id furthest back in the history that hasn't been consumed 1065 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1066 1067 pub fn init( 1068 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1069 io: std.Io, 1070 allocator: std.mem.Allocator, 1071 consumed_object_ids: DB.HashMap(.read_only), 1072 ref: rf.Ref, 1073 ) !CommitIterator(repo_kind, repo_opts) { 1074 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1075 errdefer { 1076 db_file.close(io); 1077 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1078 } 1079 1080 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1081 errdefer allocator.destroy(buffer_ptr); 1082 1083 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1084 errdefer buffer_ptr.deinit(); 1085 1086 const db_ptr = try allocator.create(DB); 1087 errdefer allocator.destroy(db_ptr); 1088 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr }); 1089 1090 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1091 1092 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1093 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1094 1095 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1096 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1097 1098 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1099 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1100 1101 var self = CommitIterator(repo_kind, repo_opts){ 1102 .repo_dir = state.core.repo_dir, 1103 .db_file = db_file, 1104 .db = db_ptr, 1105 .parent_to_children = parent_to_children, 1106 .child_to_pending_parents = child_to_pending_parents, 1107 .ready_queue = ready_queue, 1108 .ready_queue_index = 0, 1109 .newest_object_id = null, 1110 .oldest_object_id = null, 1111 }; 1112 errdefer self.deinit(io, allocator); 1113 1114 try self.collect(state, io, allocator, consumed_object_ids, ref); 1115 1116 return self; 1117 } 1118 1119 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1120 self.db_file.close(io); 1121 self.db.core.memory.buffer.deinit(); 1122 allocator.destroy(self.db.core.memory.buffer); 1123 self.repo_dir.deleteFile(io, db_name) catch {}; 1124 allocator.destroy(self.db); 1125 } 1126 1127 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 1128 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 1129 1130 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 1131 self.ready_queue_index += 1; 1132 1133 try self.enqueueChildren(&oid); 1134 return oid; 1135 } 1136 1137 fn collect( 1138 self: *CommitIterator(repo_kind, repo_opts), 1139 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1140 io: std.Io, 1141 allocator: std.mem.Allocator, 1142 consumed_object_ids: DB.HashMap(.read_only), 1143 ref: rf.Ref, 1144 ) !void { 1145 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 1146 1147 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 1148 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 1149 var walk_queue_index: u64 = 0; 1150 1151 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 1152 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 1153 1154 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1155 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1156 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1157 try walk_queue.append(.{ .bytes = &head_oid }); 1158 1159 while (walk_queue_index < try walk_queue.count()) { 1160 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 1161 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 1162 1163 walk_queue_index += 1; 1164 1165 // if we've seen this object id, skip it 1166 if (null != try seen_object_ids.getCursor(oid_int)) { 1167 continue; 1168 } 1169 1170 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 1171 1172 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 1173 defer commit_object.deinit(); 1174 1175 // if this object id has already been consumed, skip it 1176 if (null != try consumed_object_ids.getCursor(oid_int)) { 1177 continue; 1178 } 1179 1180 if (self.newest_object_id == null) self.newest_object_id = oid; 1181 self.oldest_object_id = oid; 1182 1183 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1184 var pending_parent_count: u64 = 0; 1185 for (parent_oids) |*parent_oid| { 1186 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1187 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 1188 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 1189 1190 // if this object id has already been consumed, skip it 1191 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 1192 continue; 1193 } 1194 1195 // if this object id hasn't already been seen, add it to the walk queue 1196 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 1197 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 1198 } 1199 1200 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 1201 const children = try DB.HashSet(.read_write).init(children_cursor); 1202 try children.put(oid_int, .{ .bytes = &oid }); 1203 pending_parent_count += 1; 1204 } 1205 1206 if (pending_parent_count == 0) { 1207 try self.ready_queue.append(.{ .bytes = &oid }); 1208 } else { 1209 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 1210 } 1211 } 1212 } 1213 1214 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 1215 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 1216 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 1217 const children = try DB.HashSet(.read_only).init(children_cursor); 1218 var children_iter = try children.iterator(); 1219 1220 while (try children_iter.next()) |*child_cursor| { 1221 const kv_pair = try child_cursor.readKeyValuePair(); 1222 const child_oid_int = kv_pair.hash; 1223 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 1224 const pending_parent_count = try pending_parent_cursor.readUint(); 1225 1226 if (pending_parent_count <= 1) { 1227 _ = try self.child_to_pending_parents.remove(child_oid_int); 1228 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 1229 try self.ready_queue.append(.{ .bytes = &child_oid }); 1230 } else { 1231 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 1232 } 1233 } 1234 } 1235 1236 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 1237 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 1238 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1239 _ = try oid_cursor.readBytes(&oid); 1240 return oid; 1241 } 1242 }; 1243 } 1244