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