╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
701 if (!try consumeInTransaction(.repo, repo_kind, repo_opts, state, ctx.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 702 } 703 }; 704 705 const history = try DB.ArrayList(.read_write).init(self.db.rootCursor()); 706 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 707 .repo = repo, 708 .db = self.db, 709 .io = io, 710 .allocator = allocator, 711 .ref = ref, 712 }) catch |err| switch (err) { 713 error.CancelTransaction => {}, 714 else => |e| return e, 715 }; 716 } 717 }; 718 } 719 720 // consume the events on `ref` into the db `moment` writes to, returning false 721 // if there was nothing to do. events are read from `state`'s repo, which 722 // needn't be the repo backing the db — that's how a local (possibly 723 // git-backed) repo's events land in a standalone db. 724 pub fn consumeInTransaction( 725 comptime role: RepoRole, 726 comptime repo_kind: rp.RepoKind, 727 comptime repo_opts: rp.RepoOpts(repo_kind), 728 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 729 db: *EventDB(repo_opts.hash), 730 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 731 io: std.Io, 732 allocator: std.mem.Allocator, 733 ref: rf.Ref, 734 ) !bool { 735 const DB = EventDB(repo_opts.hash); 736 const read_state = state.readOnly(); 737 738 // the last_object_id represents the object id that was last consumed 739 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 740 if (try moment.getCursor(hash.hashInt(repo_opts.hash, last_object_id_key))) |last_object_id_cursor| { 741 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 742 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 743 last_object_id_maybe = last_object_id_buffer; 744 } 745 746 // the tip was already consumed, so there is nothing to do 747 if (last_object_id_maybe) |*last_object_id| { 748 const tip_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 749 var tip: [hash.byteLen(repo_opts.hash)]u8 = undefined; 750 _ = try std.fmt.hexToBytes(&tip, &tip_hex); 751 if (std.mem.eql(u8, last_object_id, &tip)) return false; 752 } 753 754 // the list with all of haxy's state, including materialized views. 755 // the reason it is a list is so we can keep every previous haxy 756 // state, making it easy to revert to an older state if the user 757 // rebases some of the past commits. 758 const haxy_history_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, history_key)); 759 const haxy_history = try DB.ArrayList(.read_write).init(haxy_history_cursor); 760 761 // add a new item to the haxy history list created above. 762 // we call the item haxy_moments. it is a map of object id to haxy moment. 763 // in other words, it maps each object id to a hash map containing the 764 // state that the database was in when that object id was consumed. 765 var haxy_moments_cursor = try haxy_history.appendCursor(); 766 // use the previous haxy_moments as the basis for this one if it exists 767 if (try haxy_history.getCursor(-2)) |last_haxy_moments_cursor| { 768 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 769 } 770 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 771 772 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 773 defer commit_iter.deinit(io, allocator); 774 775 // if there are no events to process, look at the oid at HEAD and update 776 // the last_object_id to point to it. this is important in situations 777 // where we do a merge and then force-push to remove the merge. see the 778 // merge test for an example. 779 if (commit_iter.newest_object_id == null) { 780 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 781 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 782 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 783 784 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 785 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 786 787 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 788 const moment_index = try moment_index_cursor.readUint(); 789 790 try haxy_history.slice(moment_index + 1); 791 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = &head_oid }); 792 return true; 793 } 794 795 // if this branch was rebased and force pushed, we need to detect that and 796 // properly revert the haxy state to the last valid state. we detect this 797 // by simply asking if the last event is a descendent of the last event 798 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 799 if (last_object_id_maybe) |*last_object_id| { 800 var is_rebased = false; 801 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 802 803 _ = mrg.getDescendent( 804 repo_kind, 805 repo_opts, 806 read_state, 807 io, 808 allocator, 809 &std.fmt.bytesToHex(last_object_id, .lower), 810 &std.fmt.bytesToHex(&newest_object_id, .lower), 811 ) catch |err| switch (err) { 812 error.DescendentNotFound => is_rebased = true, 813 else => |e| return e, 814 }; 815 816 if (is_rebased) { 817 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 818 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 819 defer oldest_object.deinit(); 820 821 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 822 switch (parent_oids.len) { 823 0 => { 824 // the branch was rebased all the way to the very beginning. 825 // we have a repo event with no parent, which means it is now 826 // the very first event. all we need to do is set the haxy 827 // history list to be empty and make a new haxy_moments map 828 // to work with. 829 830 try haxy_history.slice(0); 831 haxy_moments_cursor = try haxy_history.appendCursor(); 832 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 833 834 last_object_id_maybe = null; 835 }, 836 1 => { 837 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 838 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 839 840 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 841 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 842 843 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 844 const old_moment_index = try old_moment_index_cursor.readUint(); 845 846 // resize the haxy history list so we truncate all the 847 // moments that were created after the parent_oid was consumed 848 try haxy_history.slice(old_moment_index + 1); 849 850 // make a new haxy moment and set its initial value to the last haxy moment 851 haxy_moments_cursor = try haxy_history.appendCursor(); 852 const old_haxy_moments_cursor = try haxy_history.getCursor(old_moment_index) orelse return error.CursorNotFound; 853 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 854 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 855 856 last_object_id_maybe = oid; 857 }, 858 else => return error.UnexpectedParentCount, 859 } 860 } 861 } 862 863 while (try commit_iter.next()) |repo_event_oid| { 864 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 865 defer commit_object.deinit(); 866 867 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 868 869 // create a moment for this object id 870 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 871 872 // if there was a previous object id, set this haxy moment's initial value to it. 873 // this efficiently "clones" the map so we make further modifications based on it. 874 if (parent_oids.len > 0) { 875 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 876 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 877 878 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 879 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 880 } 881 882 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 883 884 // graph generation gives every event a causal order independent of 885 // commit timestamps. concurrent events tie-break by id in their index. 886 var event_order: u64 = 1; 887 for (parent_oids) |*parent_oid| { 888 var parent_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 889 _ = try std.fmt.hexToBytes(&parent_id, parent_oid); 890 const parent_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &parent_id)) orelse return error.CursorNotFound; 891 const parent = try DB.HashMap(.read_only).init(parent_cursor); 892 const parent_order_cursor = try parent.getCursor(hash.hashInt(repo_opts.hash, event_order_key)) orelse return error.CursorNotFound; 893 const parent_order = try parent_order_cursor.readUint(); 894 event_order = @max(event_order, parent_order +| 1); 895 } 896 try haxy_moment.put(hash.hashInt(repo_opts.hash, event_order_key), .{ .uint = event_order }); 897 898 // merge changes from every parent after the first parent. the common 899 // ancestor is the baseline, so a later parent only contributes records 900 // it changed relative to the merge base. only the record maps are 901 // merged; every other view is derived from them, and each kind's 902 // `consume` re-derives its own as the winning records are written. 903 if (parent_oids.len > 1) { 904 for (parent_oids[1..]) |*parent_oid| { 905 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 906 _ = try std.fmt.hexToBytes(&oid, parent_oid); 907 908 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 909 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 910 911 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 912 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 913 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 914 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 915 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 916 917 inline for (std.meta.fields(Event)) |field| { 918 const T = @typeInfo(field.type).optional.child; 919 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 920 } 921 } 922 } 923 924 // associate this moment with the index it will first appear at in the 925 // haxy history list. this will be important later so we can truncate 926 // that list if the user ever rebases starting at this object id. 927 const moment_index = try haxy_history.count() - 1; 928 try haxy_moment.put(hash.hashInt(repo_opts.hash, moment_index_key), .{ .uint = moment_index }); 929 930 // consume the event unless it's a merge commit 931 if (parent_oids.len <= 1) { 932 var arena = std.heap.ArenaAllocator.init(allocator); 933 defer arena.deinit(); 934 935 // read the message from the commit 936 var message: std.ArrayList(u8) = .empty; 937 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 938 939 const event_with_id = try EventWithId.fromString(&arena, message.items); 940 if (!role.allows(std.meta.activeTag(event_with_id.event))) return error.EventKindNotAllowed; 941 942 const current_event_id = try parseEventId(&event_with_id.id); 943 944 // associate the transaction with the events it writes. this is 945 // used by the undo tab to link the events that were affected 946 // by a given transaction. 947 { 948 const sets = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, moment_index_to_event_id_set_key))); 949 const ids = try DB.SortedSet(.read_write).init(try sets.putCursor(momentIndexKey(repo_opts.hash, moment_index))); 950 try ids.put(&orderKeyDesc(event_order, &current_event_id)); 951 } 952 953 // wrap the payload into the record `consume` stores, with its 954 // commit-derived fields; on update, `consume` preserves the 955 // existing record's 956 switch (event_with_id.event) { 957 .user => |event_maybe| { 958 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 959 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 960 }, 961 .repo => |event_maybe| { 962 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 963 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 964 }, 965 .fork => |event_maybe| { 966 const record_maybe: ?Fork.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 967 try Fork.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 968 }, 969 .issue => |event_maybe| { 970 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 971 .event = event, 972 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 973 .created_order = event_order, 974 .updated_order = event_order, 975 } else null; 976 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 977 }, 978 .discuss => |event_maybe| { 979 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 980 .event = event, 981 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 982 .created_order = event_order, 983 .updated_order = event_order, 984 } else null; 985 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 986 }, 987 .comment => |event_maybe| { 988 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 989 .event = event, 990 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 991 .created_order = event_order, 992 .updated_order = event_order, 993 } else null; 994 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 995 }, 996 .attach => |event_maybe| { 997 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 998 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 999 break :blk .{ 1000 .event = event, 1001 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1002 .created_order = event_order, 1003 .updated_order = event_order, 1004 .name = entry.name, 1005 .blob_oid = entry.oid, 1006 }; 1007 } else null; 1008 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1009 }, 1010 .patchrev => |event_maybe| { 1011 const record_maybe: ?PatchRev.Record = if (event_maybe) |event| blk: { 1012 const trees = try PatchRev.readTrees(repo_kind, repo_opts, read_state, io, allocator, &commit_object.content.commit.tree); 1013 const existing_maybe = try PatchRev.readById(DB, repo_opts.hash, haxy_moment.readOnly(), &arena, &current_event_id); 1014 const event_oid = std.fmt.bytesToHex(repo_event_oid, .lower); 1015 1016 var patch_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1017 if (existing_maybe) |existing| { 1018 if (existing.patch_oid.len != patch_oid.len) return error.InvalidPatch; 1019 @memcpy(&patch_oid, existing.patch_oid); 1020 } else { 1021 const author = try commitIdentity(commit_object.content.commit.metadata.author orelse return error.AuthorNotFound); 1022 const committer = try commitIdentity(commit_object.content.commit.metadata.committer orelse author); 1023 patch_oid = try PatchRev.writeSquashCommit( 1024 repo_kind, 1025 repo_opts, 1026 state, 1027 io, 1028 allocator, 1029 event, 1030 &trees.head, 1031 author, 1032 committer, 1033 commit_object.content.commit.metadata.timestamp, 1034 ); 1035 } 1036 1037 break :blk .{ 1038 .event = event, 1039 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1040 .created_order = event_order, 1041 .updated_order = event_order, 1042 .event_oid = &event_oid, 1043 .base_tree_oid = &trees.base, 1044 .head_tree_oid = &trees.head, 1045 .patch_oid = &patch_oid, 1046 .commit_count = PatchRev.commitCount(repo_kind, repo_opts, read_state, io, allocator, event.base_oid, event.source_oid) catch null, 1047 }; 1048 } else null; 1049 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1050 }, 1051 .patch => |event_maybe| { 1052 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 1053 .event = event, 1054 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1055 .created_order = event_order, 1056 .updated_order = event_order, 1057 } else null; 1058 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1059 }, 1060 } 1061 } 1062 1063 // the current object id is now the last one 1064 last_object_id_maybe = repo_event_oid; 1065 1066 // prevent any of the data created above from being mutated by future iterations of this loop 1067 try db.freeze(); 1068 } 1069 1070 if (last_object_id_maybe) |*last_object_id| { 1071 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1072 } 1073 1074 return true; 1075 } 1076 1077 // the conflicted records of one kind, keyed by the same order key its id set 1078 // uses, so this doubles as the index the conflicts view lists and counts. every 1079 // value under an entry is a slot reference to a structure that already exists: 1080 // 1081 // <order key> -> conflict entry 1082 // conflicted-fields the conflicting field names, space separated 1083 // base-record the merge base's whole record 1084 // their-record the merged-in side's whole record 1085 // their-field->oid that side's field name to commit map 1086 // 1087 // our own value is the live record and our commit is in the kind's oid map, so 1088 // neither is repeated here. 1089 pub const conflicted_fields_key = "conflicted-fields"; 1090 pub const base_record_key = "base-record"; 1091 pub const their_record_key = "their-record"; 1092 pub const their_field_to_oid_key = "their-field->oid"; 1093 1094 // record the commit against every field this event changes. a merge passes no 1095 // oid, since each field's winner may come from a different side. 1096 pub fn writeOid( 1097 comptime T: type, 1098 comptime DB: type, 1099 comptime hash_kind: hash.HashKind, 1100 id_to_field_to_oid: DB.HashMap(.read_write), 1101 record_key: hash.HashInt(hash_kind), 1102 existing_maybe: ?T, 1103 event: T, 1104 event_oid: ?[]const u8, 1105 ) !void { 1106 const oid = event_oid orelse return; 1107 1108 // created only once a field actually changes 1109 var field_oids: ?DB.SortedMap(.read_write) = null; 1110 1111 inline for (std.meta.fields(T)) |field| { 1112 const changed = if (existing_maybe) |existing| 1113 !fieldEqual(field.type, @field(existing, field.name), @field(event, field.name)) 1114 else 1115 true; 1116 if (changed) { 1117 if (field_oids == null) { 1118 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1119 } 1120 if (field_oids) |map| try map.put(field.name, .{ .bytes = oid }); 1121 } 1122 } 1123 } 1124 1125 // the whole field list, space separated, is the longest it can get 1126 fn conflictedFieldsMaxLen(comptime T: type) usize { 1127 var len: usize = 0; 1128 for (std.meta.fields(T)) |field| len += field.name.len + 1; 1129 return len; 1130 } 1131 1132 pub const MergePolicy = enum { 1133 field_conflicts, 1134 target_wins, 1135 }; 1136 1137 // what a three-way merge did with a field 1138 pub const FieldMerge = enum { 1139 // the target's value stands, because neither side changed it, both made the 1140 // same change, or only the target changed it 1141 kept, 1142 parent, 1143 conflicted, 1144 }; 1145 1146 // three-way merge each field. one only the parent changed takes the parent's 1147 // value; one both sides changed differently keeps the target's. a missing 1148 // baseline makes every differing field a conflict. 1149 fn mergeFields( 1150 comptime T: type, 1151 baseline_maybe: ?T, 1152 target: T, 1153 parent: T, 1154 outcome: *[std.meta.fields(T).len]FieldMerge, 1155 ) T { 1156 var merged = target; 1157 1158 inline for (std.meta.fields(T), 0..) |field, i| { 1159 const target_value = @field(target, field.name); 1160 const parent_value = @field(parent, field.name); 1161 1162 if (!fieldEqual(field.type, target_value, parent_value)) { 1163 outcome[i] = if (baseline_maybe) |baseline| blk: { 1164 const baseline_value = @field(baseline, field.name); 1165 if (fieldEqual(field.type, target_value, baseline_value)) { 1166 @field(merged, field.name) = parent_value; 1167 break :blk .parent; 1168 } 1169 // only the target changed it 1170 if (fieldEqual(field.type, parent_value, baseline_value)) break :blk .kept; 1171 break :blk .conflicted; 1172 } else .conflicted; 1173 } 1174 } 1175 1176 return merged; 1177 } 1178 1179 // three-way merge of one kind's records from a merge parent. kinds that expose 1180 // conflicts merge field by field; the others take one whole record. the result 1181 // goes through the kind's `consume`, which re-derives the indexes from it. a 1182 // removal carries over unless the other side changed the record, so a merge 1183 // never fails. 1184 pub fn merge( 1185 comptime T: type, 1186 comptime DB: type, 1187 comptime hash_kind: hash.HashKind, 1188 allocator: std.mem.Allocator, 1189 haxy_moment: DB.HashMap(.read_write), 1190 parent_moment: DB.HashMap(.read_only), 1191 baseline_moment: DB.HashMap(.read_only), 1192 ) !void { 1193 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1194 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1195 1196 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1197 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1198 1199 var baseline_records: ?DB.HashMap(.read_only) = null; 1200 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1201 baseline_records = try DB.HashMap(.read_only).init(cursor); 1202 } 1203 1204 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1205 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1206 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1207 switch (comptime T.merge_policy) { 1208 .field_conflicts => { 1209 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1210 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1211 } 1212 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1213 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1214 } 1215 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1216 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1217 } 1218 }, 1219 .target_wins => {}, 1220 } 1221 1222 var arena = std.heap.ArenaAllocator.init(allocator); 1223 defer arena.deinit(); 1224 1225 var iter = try parent_set.iteratorFromIndex(0); 1226 while (try iter.next()) |kv_pair_cursor| { 1227 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1228 const record_key = hash.hashInt(hash_kind, &event_id); 1229 1230 _ = arena.reset(.retain_capacity); 1231 1232 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1233 const parent_slot = parent_record_cursor.slot(); 1234 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1235 1236 // the parent left this record alone 1237 if (baseline_slot) |slot| { 1238 if (slot.eql(parent_slot)) continue; 1239 } 1240 1241 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1242 1243 // re-derived every iteration, since `consume` writes through its own 1244 // handles 1245 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1246 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1247 1248 // a record the target doesn't have arrives wholesale from the parent 1249 var outcome: [std.meta.fields(T).len]FieldMerge = @splat(.parent); 1250 var merged = parent_record; 1251 1252 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1253 // both sides share the change 1254 if (target_record_cursor.slot().eql(parent_slot)) continue; 1255 1256 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1257 1258 var baseline_record: ?T.Record = null; 1259 if (baseline_records) |map| { 1260 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1261 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1262 } 1263 } 1264 1265 switch (comptime T.merge_policy) { 1266 .field_conflicts => { 1267 outcome = @splat(.kept); 1268 merged = target_record; 1269 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1270 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1271 if (comptime @hasDecl(T, "resolveMerge")) { 1272 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1273 } 1274 1275 // merge the removed state separately from serialized fields. removal 1276 // carries over an unchanged record, while an edit or restoration 1277 // keeps it active. 1278 merged.removed = if (target_record.removed == parent_record.removed) 1279 target_record.removed 1280 else if (baseline_record) |baseline| blk: { 1281 const active = if (!target_record.removed) target_record else parent_record; 1282 if (active.removed != baseline.removed) break :blk false; 1283 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1284 break :blk true; 1285 } else false; 1286 }, 1287 .target_wins => { 1288 // an uncontested parent change carries over. if both sides 1289 // changed the record, the target wins as a whole, except that 1290 // an edit or restoration wins over a removal. 1291 const target_changed = if (baseline_slot) |slot| 1292 !target_record_cursor.slot().eql(slot) 1293 else 1294 true; 1295 merged = if (!target_changed) 1296 parent_record 1297 else if (target_record.removed != parent_record.removed) 1298 if (target_record.removed) parent_record else target_record 1299 else 1300 target_record; 1301 }, 1302 } 1303 } 1304 1305 // the index is unique, so a key the target gave to a different record 1306 // leaves this one out rather than stranding that one behind a name it 1307 // no longer owns 1308 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1309 const index_key = try merged.indexKey(arena.allocator()); 1310 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1311 const name_index = try DB.HashMap(.read_write).init(name_index_cursor); 1312 if (try name_index.getCursor(hash.hashInt(hash_kind, index_key))) |owner_cursor| { 1313 var owner_id: [event_id_size]u8 = undefined; 1314 _ = try owner_cursor.readBytes(&owner_id); 1315 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1316 } 1317 } 1318 1319 // `consume` sets no oids, since each field's winner may come from 1320 // a different side 1321 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1322 1323 switch (comptime T.merge_policy) { 1324 .field_conflicts => {}, 1325 .target_wins => continue, 1326 } 1327 1328 // removed records do not carry field conflicts 1329 if (merged.removed) continue; 1330 1331 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1332 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1333 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1334 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1335 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1336 1337 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1338 if (parent_id_to_field_to_oid) |map| { 1339 if (try map.getCursor(record_key)) |field_oids_cursor| { 1340 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1341 } 1342 } 1343 // created only once a field actually comes from the parent 1344 var field_oids: ?DB.SortedMap(.read_write) = null; 1345 1346 // the fields both sides changed differently, space separated 1347 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1348 var conflicted_len: usize = 0; 1349 1350 inline for (std.meta.fields(T), 0..) |field, i| { 1351 switch (outcome[i]) { 1352 // the target's value stands, so its oid does too 1353 .kept => {}, 1354 // the parent set this value, so its commit takes the field. a 1355 // parent with no oid took its own value from a merge, leaving 1356 // the field unattributed rather than crediting the target's 1357 // commit for a value it no longer holds. 1358 .parent => { 1359 if (field_oids == null) { 1360 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1361 } 1362 const map = field_oids orelse unreachable; 1363 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1364 if (parent_oid) |oid_cursor| { 1365 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1366 } else { 1367 _ = try map.remove(field.name); 1368 } 1369 }, 1370 .conflicted => { 1371 if (conflicted_len > 0) { 1372 conflicted_fields[conflicted_len] = ' '; 1373 conflicted_len += 1; 1374 } 1375 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1376 conflicted_len += field.name.len; 1377 }, 1378 } 1379 } 1380 1381 if (conflicted_len > 0) { 1382 // each side's whole record is stored by reference, so the view can 1383 // show any of them or take theirs wholesale 1384 _ = try conflicts.remove(&merged_key); 1385 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1386 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1387 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1388 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1389 if (parent_field_oids) |map| { 1390 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1391 } 1392 continue; 1393 } 1394 1395 // created_order never changes, so the parent keys this record's conflict 1396 // identically, and it carries over when the target has none, unless the 1397 // parent's entry is unchanged from the baseline, meaning the target 1398 // inherited it too and resolving it removed it here. 1399 if (parent_conflicts) |map| { 1400 if (null == try conflicts.getCursor(&merged_key)) { 1401 if (try map.getSlot(&merged_key)) |conflict_slot| { 1402 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1403 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1404 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1405 } 1406 } 1407 } 1408 } 1409 } 1410 1411 pub fn readFromRepo( 1412 comptime T: type, 1413 comptime repo_kind: rp.RepoKind, 1414 comptime repo_opts: rp.RepoOpts(repo_kind), 1415 io: std.Io, 1416 allocator: std.mem.Allocator, 1417 arena: *std.heap.ArenaAllocator, 1418 repo: *rp.Repo(repo_kind, repo_opts), 1419 id: *const [event_id_size]u8, 1420 ) !?T.Record { 1421 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1422 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1423 const moment = (if (event_db_maybe) |*event_db| 1424 currentMomentFromDb(repo_opts.hash, event_db.db) 1425 else if (repo_kind == .git) 1426 return null 1427 else 1428 currentMoment(repo_opts, repo)) catch return null; 1429 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1430 } 1431 1432 pub fn currentMoment( 1433 comptime repo_opts: rp.RepoOpts(.xit), 1434 repo: *rp.Repo(.xit, repo_opts), 1435 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1436 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1437 } 1438 1439 pub fn currentMomentFromDb( 1440 comptime hash_kind: hash.HashKind, 1441 db: *EventDB(hash_kind), 1442 ) !EventDB(hash_kind).HashMap(.read_only) { 1443 const DB = EventDB(hash_kind); 1444 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1445 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1446 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1447 return try currentMomentFromRepoMoment(hash_kind, moment); 1448 } 1449 1450 pub fn currentMomentFromRepoMoment( 1451 comptime hash_kind: hash.HashKind, 1452 moment: EventDB(hash_kind).HashMap(.read_only), 1453 ) !EventDB(hash_kind).HashMap(.read_only) { 1454 const DB = EventDB(hash_kind); 1455 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1456 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1457 _ = try last_object_id_cursor.readBytes(&last_object_id); 1458 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1459 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1460 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1461 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1462 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1463 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1464 } 1465 1466 // build a sorted-set key from an order and event id. big-endian order makes 1467 // byte order match numeric order; the event id breaks ties. 1468 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1469 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1470 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1471 @memcpy(key[@sizeOf(u64)..], event_id); 1472 return key; 1473 } 1474 1475 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1476 return orderKey(std.math.maxInt(u64) - order, event_id); 1477 } 1478 1479 pub fn removedRecord( 1480 comptime T: type, 1481 comptime DB: type, 1482 comptime hash_kind: hash.HashKind, 1483 haxy_moment: DB.HashMap(.read_only), 1484 existing_maybe: ?T, 1485 ) !T { 1486 var record = existing_maybe orelse return error.EventNotFound; 1487 record.removed = true; 1488 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1489 record.updated_order = try order_cursor.readUint(); 1490 return record; 1491 } 1492 1493 // add or refresh one entry in the global logical-event index 1494 pub fn indexEvent( 1495 comptime DB: type, 1496 comptime hash_kind: hash.HashKind, 1497 haxy_moment: DB.HashMap(.read_write), 1498 event_id: *const [event_id_size]u8, 1499 kind: EventKind, 1500 existing_maybe: anytype, 1501 record: anytype, 1502 ) !void { 1503 const event_key = hash.hashInt(hash_kind, event_id); 1504 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1505 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1506 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1507 1508 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1509 const active = try DB.SortedSet(.read_write).init(active_cursor); 1510 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1511 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1512 1513 if (existing_maybe) |existing| { 1514 const old_key = orderKeyDesc(existing.updated_order, event_id); 1515 _ = try active.remove(&old_key); 1516 _ = try removed_set.remove(&old_key); 1517 } 1518 1519 const order_key = orderKeyDesc(record.updated_order, event_id); 1520 if (record.removed) { 1521 try removed_set.put(&order_key); 1522 } else { 1523 try active.put(&order_key); 1524 } 1525 } 1526 1527 pub fn touchThread( 1528 comptime DB: type, 1529 comptime hash_kind: hash.HashKind, 1530 haxy_moment: DB.HashMap(.read_write), 1531 thread_id: *const [event_id_size]u8, 1532 order: u64, 1533 arena: *std.heap.ArenaAllocator, 1534 ) !void { 1535 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1536 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1537 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1538 switch (kind) { 1539 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1540 else => {}, 1541 } 1542 } 1543 1544 pub fn readEventKind( 1545 comptime hash_kind: hash.HashKind, 1546 kind_map: anytype, 1547 id: *const [event_id_size]u8, 1548 ) !?EventKind { 1549 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1550 var buffer: [64]u8 = undefined; 1551 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1552 } 1553 1554 // the email of the event's author, or null when the id names no authored event 1555 // of this kind 1556 pub fn readAuthorEmail( 1557 comptime repo_kind: rp.RepoKind, 1558 comptime repo_opts: rp.RepoOpts(repo_kind), 1559 io: std.Io, 1560 allocator: std.mem.Allocator, 1561 arena: *std.heap.ArenaAllocator, 1562 repo: *rp.Repo(repo_kind, repo_opts), 1563 kind: EventKind, 1564 id: *const [event_id_size]u8, 1565 ) !?[]const u8 { 1566 const record_map_key = switch (kind) { 1567 .issue => Issue.record_map_key, 1568 .discuss => Discussion.record_map_key, 1569 .comment => Comment.record_map_key, 1570 .attach => Attachment.record_map_key, 1571 .patchrev => PatchRev.record_map_key, 1572 .patch => Patch.record_map_key, 1573 .user, .repo, .fork => return null, 1574 }; 1575 1576 const DB = EventDB(repo_opts.hash); 1577 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1578 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1579 const moment = (if (event_db_maybe) |*event_db| 1580 currentMomentFromDb(repo_opts.hash, event_db.db) 1581 else if (repo_kind == .git) 1582 return null 1583 else 1584 currentMoment(repo_opts, repo)) catch return null; 1585 1586 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1587 const records = try DB.HashMap(.read_only).init(records_cursor); 1588 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1589 const record = try DB.HashMap(.read_only).init(record_cursor); 1590 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1591 } 1592 1593 // the event id embedded in a set entry's order key 1594 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1595 var cursor = kv_pair_cursor; 1596 const kv_pair = try cursor.readKeyValuePair(); 1597 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1598 _ = try kv_pair.key_cursor.readBytes(&order_key); 1599 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1600 } 1601 1602 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1603 // isn't exactly two non-empty segments. 1604 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1605 var it = std.mem.splitScalar(u8, path, '/'); 1606 const owner = it.next() orelse return null; 1607 const name = it.next() orelse return null; 1608 if (it.next() != null) return null; 1609 if (owner.len == 0 or name.len == 0) return null; 1610 1611 return .{ .owner = owner, .name = name }; 1612 } 1613 1614 pub const CreateRepoOptions = struct { 1615 read_access: Repo.Access = .private, 1616 }; 1617 1618 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1619 // directory under the repos dir 1620 pub fn resolveOrCreateRepo( 1621 io: std.Io, 1622 allocator: std.mem.Allocator, 1623 admin_repo_path: []const u8, 1624 owner_name: []const u8, 1625 repo_name: []const u8, 1626 create_options_maybe: ?CreateRepoOptions, 1627 ) !?[event_id_size * 2]u8 { 1628 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1629 error.RepoNotFound => return null, 1630 else => |e| return e, 1631 }; 1632 defer repo.deinit(io, allocator); 1633 1634 var arena = std.heap.ArenaAllocator.init(allocator); 1635 defer arena.deinit(); 1636 1637 const moment = try currentMoment(admin_repo_opts, &repo); 1638 1639 // an already-registered repo reuses its event id, so a re-push (or a clone) 1640 // lands in the same repo 1641 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1642 return std.fmt.bytesToHex(found.event_id, .lower); 1643 } 1644 1645 const create_options = create_options_maybe orelse return null; 1646 1647 // the new repo is owned by the named user, read from the name index; an 1648 // unknown owner can't own a repo, so the push is rejected 1649 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1650 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1651 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1652 var owner_user_id: [event_id_size]u8 = undefined; 1653 _ = try owner_id_cursor.readBytes(&owner_user_id); 1654 1655 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1656 1657 var id_bytes: [event_id_size]u8 = undefined; 1658 io.random(&id_bytes); 1659 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1660 1661 try consume(.server, .admin, .xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1662 .id = event_id_hex, 1663 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1664 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1665 .event = .{ .repo = .{ 1666 .user_id = &owner_user_id, 1667 .name = repo_name, 1668 .description = "", 1669 .read_access = create_options.read_access, 1670 } }, 1671 }}); 1672 1673 return event_id_hex; 1674 } 1675 1676 // 1677 // reading from xitdb 1678 // 1679 1680 // read just `Fields`, a subset of `T.Record`, from the record with event id 1681 // `id`, or null when there is none 1682 pub fn readRecordSubset( 1683 comptime T: type, 1684 comptime Fields: type, 1685 comptime DB: type, 1686 comptime hash_kind: hash.HashKind, 1687 haxy_moment: DB.HashMap(.read_only), 1688 arena: *std.heap.ArenaAllocator, 1689 id: []const u8, 1690 ) !?Fields { 1691 comptime assertFieldSubset(Fields, T.Record); 1692 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 1693 const records = try DB.HashMap(.read_only).init(records_cursor); 1694 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1695 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 1696 } 1697 1698 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 1699 for (@typeInfo(Sub).@"struct".fields) |field| { 1700 if (!@hasField(Full, field.name)) @compileError(@typeName(Full) ++ " has no field " ++ field.name); 1701 const FullField = @FieldType(Full, field.name); 1702 if (@typeInfo(field.type) == .@"struct") { 1703 assertFieldSubset(field.type, FullField); 1704 } else if (field.type != FullField) { 1705 @compileError(@typeName(Full) ++ "." ++ field.name ++ " is a " ++ @typeName(FullField)); 1706 } 1707 } 1708 } 1709 1710 pub fn read( 1711 comptime T: type, 1712 comptime DB: type, 1713 comptime hash_kind: hash.HashKind, 1714 arena: *std.heap.ArenaAllocator, 1715 map: DB.HashMap(.read_only), 1716 ) !T { 1717 var event: T = undefined; 1718 switch (@typeInfo(T)) { 1719 .@"struct" => |struct_info| { 1720 inline for (struct_info.fields) |field| { 1721 const cursor = try map.getCursor(hash.hashInt(hash_kind, field.name)); 1722 @field(event, field.name) = try readField(field.type, DB, hash_kind, arena, cursor); 1723 } 1724 }, 1725 else => @compileError("read expects a struct"), 1726 } 1727 return event; 1728 } 1729 1730 fn readField( 1731 comptime Field: type, 1732 comptime DB: type, 1733 comptime hash_kind: hash.HashKind, 1734 arena: *std.heap.ArenaAllocator, 1735 cursor_maybe: ?DB.Cursor(.read_only), 1736 ) !Field { 1737 if (@typeInfo(Field) == .optional) { 1738 // a missing key or a null union payload is null 1739 const cursor = cursor_maybe orelse return null; 1740 if (cursor.slot().tag == .none) return null; 1741 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 1742 } 1743 const cursor = cursor_maybe orelse return error.NotFound; 1744 switch (@typeInfo(Field)) { 1745 .pointer => |pointer_info| { 1746 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.is_const) { 1747 @compileError("unsupported read field type: " ++ @typeName(Field)); 1748 } 1749 return try cursor.readBytesAlloc(arena.allocator(), null); 1750 }, 1751 .array => |array_info| { 1752 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 1753 var bytes: Field = undefined; 1754 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 1755 return bytes; 1756 }, 1757 .bool => { 1758 var buffer: [5]u8 = undefined; 1759 const bytes = try cursor.readBytesObject(&buffer); 1760 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1761 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1762 if (std.mem.eql(u8, bytes.value, "true")) return true; 1763 if (std.mem.eql(u8, bytes.value, "false")) return false; 1764 return error.InvalidBool; 1765 }, 1766 .int => |int_info| return switch (int_info.signedness) { 1767 .unsigned => @intCast(try cursor.readUint()), 1768 .signed => @intCast(try cursor.readInt()), 1769 }, 1770 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 1771 .@"union" => |union_info| { 1772 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 1773 switch (cursor.slot().tag) { 1774 .bytes, .short_bytes => { 1775 const name = try cursor.readBytesAlloc(arena.allocator(), null); 1776 inline for (union_info.fields) |variant| { 1777 if (variant.type == void and std.mem.eql(u8, name, variant.name)) { 1778 return @unionInit(Field, variant.name, {}); 1779 } 1780 } 1781 return error.InvalidUnion; 1782 }, 1783 .hash_map => { 1784 const variants = try DB.HashMap(.read_only).init(cursor); 1785 var iter = try variants.iterator(); 1786 const entry = (try iter.next()) orelse return error.InvalidUnion; 1787 const pair = try entry.readKeyValuePair(); 1788 if (try iter.next() != null) return error.InvalidUnion; 1789 inline for (union_info.fields) |variant| { 1790 if (variant.type != void and pair.hash == hash.hashInt(hash_kind, variant.name)) { 1791 return @unionInit(Field, variant.name, try readField(variant.type, DB, hash_kind, arena, pair.value_cursor)); 1792 } 1793 } 1794 return error.InvalidUnion; 1795 }, 1796 else => return error.InvalidUnion, 1797 } 1798 }, 1799 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 1800 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 1801 } 1802 } 1803 1804 // whether two events carry the same data 1805 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1806 switch (@typeInfo(T)) { 1807 .@"struct" => |struct_info| { 1808 inline for (struct_info.fields) |field| { 1809 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1810 } 1811 }, 1812 else => @compileError("fieldsEqual expects a struct"), 1813 } 1814 1815 return true; 1816 } 1817 1818 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1819 switch (@typeInfo(Field)) { 1820 .pointer => |pointer_info| { 1821 if (pointer_info.size == .slice and pointer_info.child == u8) { 1822 return std.mem.eql(u8, a, b); 1823 } else { 1824 @compileError("unsupported field type: " ++ @typeName(Field)); 1825 } 1826 }, 1827 .array => |array_info| { 1828 if (array_info.child == u8) { 1829 return std.mem.eql(u8, &a, &b); 1830 } else { 1831 @compileError("unsupported field type: " ++ @typeName(Field)); 1832 } 1833 }, 1834 .void => return true, 1835 .bool, .int, .@"enum" => return a == b, 1836 .@"union" => { 1837 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1838 return switch (a) { 1839 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 1840 }; 1841 }, 1842 .@"struct" => return fieldsEqual(Field, a, b), 1843 .optional => |optional_info| { 1844 if (a) |a_value| { 1845 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 1846 return false; 1847 } 1848 return b == null; 1849 }, 1850 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1851 } 1852 } 1853 1854 // 1855 // writing to xitdb 1856 // 1857 1858 pub fn upsert( 1859 comptime T: type, 1860 comptime DB: type, 1861 comptime hash_kind: hash.HashKind, 1862 map: DB.HashMap(.read_write), 1863 event: T, 1864 ) !void { 1865 switch (@typeInfo(T)) { 1866 .@"struct" => |struct_info| { 1867 inline for (struct_info.fields) |field| { 1868 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1869 } 1870 }, 1871 else => @compileError("upsert expects a struct"), 1872 } 1873 } 1874 1875 fn upsertField( 1876 comptime DB: type, 1877 comptime hash_kind: hash.HashKind, 1878 map: DB.HashMap(.read_write), 1879 comptime field_name: []const u8, 1880 comptime Field: type, 1881 value: Field, 1882 ) !void { 1883 const key = hash.hashInt(hash_kind, field_name); 1884 1885 switch (@typeInfo(Field)) { 1886 .pointer => |pointer_info| { 1887 if (pointer_info.size == .slice and pointer_info.child == u8) { 1888 try upsertBytes(DB, hash_kind, map, key, value); 1889 } else { 1890 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1891 } 1892 }, 1893 .array => |array_info| { 1894 if (array_info.child == u8) { 1895 try upsertBytes(DB, hash_kind, map, key, &value); 1896 } else { 1897 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1898 } 1899 }, 1900 .int => |int_info| switch (int_info.signedness) { 1901 .unsigned => { 1902 if (try map.getCursor(key)) |value_cursor| { 1903 if (try value_cursor.readUint() == value) { 1904 return; 1905 } 1906 } 1907 1908 try map.put(key, .{ .uint = value }); 1909 }, 1910 .signed => { 1911 if (try map.getCursor(key)) |value_cursor| { 1912 if (try value_cursor.readInt() == value) { 1913 return; 1914 } 1915 } 1916 1917 try map.put(key, .{ .int = value }); 1918 }, 1919 }, 1920 .bool => { 1921 const bytes = if (value) "true" else "false"; 1922 if (try map.getCursor(key)) |value_cursor| { 1923 var buffer: [5]u8 = undefined; 1924 const existing = try value_cursor.readBytesObject(&buffer); 1925 if (existing.format_tag) |format_tag| { 1926 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1927 return; 1928 } 1929 } 1930 } 1931 1932 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1933 }, 1934 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1935 .@"union" => switch (value) { 1936 inline else => |payload, tag| { 1937 if (@TypeOf(payload) == void) { 1938 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 1939 } else { 1940 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 1941 if (try map.getCursor(key)) |cursor| { 1942 switch (cursor.slot().tag) { 1943 .hash_map => { 1944 const variants = try DB.HashMap(.read_only).init(cursor); 1945 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 1946 }, 1947 else => try map.put(key, .{ .slot = null }), 1948 } 1949 } 1950 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 1951 if (@typeInfo(@TypeOf(payload)) == .optional) { 1952 // keep the variant even when its payload is null 1953 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 1954 } 1955 if (try variants.getCursor(tag_key)) |cursor| { 1956 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 1957 } 1958 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 1959 } 1960 }, 1961 }, 1962 .optional => |optional_info| { 1963 // a missing key is null 1964 if (value) |child| { 1965 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 1966 } else { 1967 _ = try map.remove(key); 1968 } 1969 }, 1970 .@"struct" => try upsert( 1971 Field, 1972 DB, 1973 hash_kind, 1974 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1975 value, 1976 ), 1977 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1978 } 1979 } 1980 1981 fn upsertBytes( 1982 comptime DB: type, 1983 comptime hash_kind: hash.HashKind, 1984 map: DB.HashMap(.read_write), 1985 key: hash.HashInt(hash_kind), 1986 value: []const u8, 1987 ) !void { 1988 var existing_cursor_maybe = try map.getCursor(key); 1989 if (existing_cursor_maybe) |*existing_cursor| { 1990 if (try bytesEqual(DB, existing_cursor, value)) { 1991 return; 1992 } 1993 } 1994 1995 try map.put(key, .{ .bytes = value }); 1996 } 1997 1998 fn bytesEqual( 1999 comptime DB: type, 2000 cursor: *DB.Cursor(.read_only), 2001 value: []const u8, 2002 ) !bool { 2003 switch (cursor.slot().tag) { 2004 .bytes, .short_bytes => {}, 2005 else => return false, 2006 } 2007 var read_buffer: [1024]u8 = undefined; 2008 var reader = try cursor.reader(&read_buffer); 2009 if (reader.size != value.len) { 2010 return false; 2011 } 2012 2013 var chunk_buffer: [1024]u8 = undefined; 2014 var offset: usize = 0; 2015 while (offset < value.len) { 2016 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2017 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2018 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2019 return false; 2020 } 2021 offset += chunk_len; 2022 } 2023 2024 return true; 2025 } 2026 2027 // 2028 // CommitIterator 2029 // 2030 // differs from xit's ObjectIterator in a few ways: 2031 // 2032 // 1. iterates parents first, rather than children first 2033 // 2. `next` only returns the object id, not the full Object 2034 // 3. stores its temporary state in a file on disk to avoid OOMs 2035 // 2036 2037 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2038 return struct { 2039 const DB = EventDB(repo_opts.hash); 2040 // a plain file is used for the scratch db because each write outside 2041 // a transaction is synced anyway, so buffering would gain nothing 2042 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2043 const db_name = "haxy-repo-events.db"; 2044 2045 repo_dir: std.Io.Dir, 2046 db_file: std.Io.File, 2047 db: *TempDB, 2048 // map of each object id to its children 2049 parent_to_children: TempDB.HashMap(.read_write), 2050 // tracking pending parents is necessary because a child can only 2051 // be returned after all of its unconsumed parents have been returned 2052 child_to_pending_parents: TempDB.HashMap(.read_write), 2053 // queue of object ids that are ready to be returned from `next` 2054 ready_queue: TempDB.ArrayList(.read_write), 2055 ready_queue_index: u64, 2056 // the object id at the tip of this branch 2057 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2058 // the object id furthest back in the history that hasn't been consumed 2059 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2060 2061 pub fn init( 2062 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2063 io: std.Io, 2064 allocator: std.mem.Allocator, 2065 consumed_object_ids: DB.HashMap(.read_only), 2066 ref: rf.Ref, 2067 ) !CommitIterator(repo_kind, repo_opts) { 2068 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2069 errdefer { 2070 db_file.close(io); 2071 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2072 } 2073 2074 // cursors point at the db, so it needs a stable address 2075 const db_ptr = try allocator.create(TempDB); 2076 errdefer allocator.destroy(db_ptr); 2077 // the db is scratch state that gets deleted after iteration, so 2078 // there is nothing worth fsyncing 2079 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2080 2081 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2082 2083 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2084 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2085 2086 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2087 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2088 2089 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2090 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2091 2092 var self = CommitIterator(repo_kind, repo_opts){ 2093 .repo_dir = state.core.repo_dir, 2094 .db_file = db_file, 2095 .db = db_ptr, 2096 .parent_to_children = parent_to_children, 2097 .child_to_pending_parents = child_to_pending_parents, 2098 .ready_queue = ready_queue, 2099 .ready_queue_index = 0, 2100 .newest_object_id = null, 2101 .oldest_object_id = null, 2102 }; 2103 errdefer self.deinit(io, allocator); 2104 2105 try self.collect(state, io, allocator, consumed_object_ids, ref); 2106 2107 return self; 2108 } 2109 2110 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2111 self.db_file.close(io); 2112 self.repo_dir.deleteFile(io, db_name) catch {}; 2113 allocator.destroy(self.db); 2114 } 2115 2116 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2117 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2118 2119 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2120 self.ready_queue_index += 1; 2121 2122 try self.enqueueChildren(&oid); 2123 return oid; 2124 } 2125 2126 fn collect( 2127 self: *CommitIterator(repo_kind, repo_opts), 2128 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2129 io: std.Io, 2130 allocator: std.mem.Allocator, 2131 consumed_object_ids: DB.HashMap(.read_only), 2132 ref: rf.Ref, 2133 ) !void { 2134 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2135 2136 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2137 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2138 var walk_queue_index: u64 = 0; 2139 2140 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2141 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2142 2143 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2144 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2145 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2146 try walk_queue.append(.{ .bytes = &head_oid }); 2147 2148 while (walk_queue_index < try walk_queue.count()) { 2149 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2150 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2151 2152 walk_queue_index += 1; 2153 2154 // if we've seen this object id, skip it 2155 if (null != try seen_object_ids.getCursor(oid_int)) { 2156 continue; 2157 } 2158 2159 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2160 2161 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2162 defer commit_object.deinit(); 2163 2164 // if this object id has already been consumed, skip it 2165 if (null != try consumed_object_ids.getCursor(oid_int)) { 2166 continue; 2167 } 2168 2169 if (self.newest_object_id == null) self.newest_object_id = oid; 2170 self.oldest_object_id = oid; 2171 2172 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2173 var pending_parent_count: u64 = 0; 2174 for (parent_oids) |*parent_oid| { 2175 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2176 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2177 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2178 2179 // if this object id has already been consumed, skip it 2180 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2181 continue; 2182 } 2183 2184 // if this object id hasn't already been seen, add it to the walk queue 2185 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2186 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2187 } 2188 2189 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2190 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2191 try children.put(oid_int, .{ .bytes = &oid }); 2192 pending_parent_count += 1; 2193 } 2194 2195 if (pending_parent_count == 0) { 2196 try self.ready_queue.append(.{ .bytes = &oid }); 2197 } else { 2198 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2199 } 2200 } 2201 } 2202 2203 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2204 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2205 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2206 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2207 var children_iter = try children.iterator(); 2208 2209 while (try children_iter.next()) |*child_cursor| { 2210 const kv_pair = try child_cursor.readKeyValuePair(); 2211 const child_oid_int = kv_pair.hash; 2212 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2213 const pending_parent_count = try pending_parent_cursor.readUint(); 2214 2215 if (pending_parent_count <= 1) { 2216 _ = try self.child_to_pending_parents.remove(child_oid_int); 2217 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2218 try self.ready_queue.append(.{ .bytes = &child_oid }); 2219 } else { 2220 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2221 } 2222 } 2223 } 2224 2225 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2226 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2227 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2228 _ = try oid_cursor.readBytes(&oid); 2229 return oid; 2230 } 2231 }; 2232 } 2233