╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
709 std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 710 break :blk null; 711 }; 712 } else |err| std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 713 } 714 715 // compare the selected revision and target against the cache 716 const patch = patch_record.event; 717 const revision = patch.revision orelse return false; 718 const target_oid = try rf.readRecur(.xit, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }); 719 var check = MergeCheck{ .revision = revision, .target_branch = patch.target_branch, .target_oid = if (target_oid) |*oid| oid else "" }; 720 const cached = try readMergeCheck(repo_opts, target_events, arena, id); 721 const current = if (patch.source_branch != null) 722 try branchCurrent(repo_opts, state.readOnly(), io, arena, patch) 723 else if (newest) |latest| 724 std.mem.eql(u8, &std.fmt.bytesToHex(latest.id, .lower), &revision.id) and revision.matches(latest.record) 725 else 726 false; 727 728 // run trial merges only for a current revision with an unresolved check 729 if (current and target_oid != null) { 730 if (cached) |value| if (value.matches(patch, check.target_oid) and value.result.source != .unknown and value.result.squash != .unknown) return false; 731 check.result = try trialMergeCheck(repo_opts, state, io, arena.child_allocator, &check, fork_repo); 732 } 733 734 // persist the result only when it differs from the cache 735 if (cached) |value| if (evt.fieldEqual(MergeCheck, value, check)) return false; 736 try saveMergeCheck(repo_opts, state.extra.moment.*, id, check); 737 return true; 738 } 739 740 fn trialMergeCheck( 741 comptime repo_opts: rp.RepoOpts(.xit), 742 state: rp.Repo(.xit, repo_opts).State(.read_write), 743 io: std.Io, 744 allocator: std.mem.Allocator, 745 check: *const MergeCheck, 746 fork_repo: ?*rp.Repo(.xit, repo_opts), 747 ) !Mergeability { 748 // freeze the parent state so trial writes copy its nodes 749 const moment = state.extra.moment; 750 const snapshot = moment.slot(); 751 // TODO: use an xitdb savepoint to also reclaim trial bytes on rollback. 752 // restoring the root leaves the appended data unused until gc. 753 try state.core.db.freeze(); 754 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 755 756 // keep the trial result in memory while discarding its state changes 757 const result = calculateMergeCheck(repo_opts, state, io, allocator, check, fork_repo); 758 759 // restore the parent state before handling any trial error 760 moment.cursor.write(.{ .slot = snapshot }) catch return error.MergeCheckRestoreFailed; 761 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 762 763 // report failed trials as unknown after the parent state is restored 764 return result catch |err| { 765 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 766 return .{}; 767 }; 768 } 769 770 fn calculateMergeCheck( 771 comptime repo_opts: rp.RepoOpts(.xit), 772 state: rp.Repo(.xit, repo_opts).State(.read_write), 773 io: std.Io, 774 allocator: std.mem.Allocator, 775 check: *const MergeCheck, 776 fork_repo: ?*rp.Repo(.xit, repo_opts), 777 ) !Mergeability { 778 const source = try oidArray(repo_opts.hash, check.revision.source_oid); 779 const squash = try oidArray(repo_opts.hash, check.revision.squash_oid); 780 781 // import fork objects into the temporary trial state 782 if (fork_repo) |repo| { 783 var fork_moment = try repo.core.latestMoment(); 784 const fork_state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_moment } }; 785 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, io, allocator, .{ .kind = .all }); 786 defer objects.deinit(); 787 try objects.include(&source); 788 try objects.include(&squash); 789 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, io, null); 790 } 791 792 // check source and squash merges against the same target 793 const target = rf.Ref{ .kind = .head, .name = check.target_branch }; 794 return .{ 795 .source = checkCommit(repo_opts, state, io, allocator, &source, target), 796 .squash = checkCommit(repo_opts, state, io, allocator, &squash, target), 797 }; 798 } 799 800 fn saveMergeCheck(comptime repo_opts: rp.RepoOpts(.xit), moment: rp.Repo(.xit, repo_opts).DB.HashMap(.read_write), id: *const [evt.event_id_size]u8, check: MergeCheck) !void { 801 const DB = rp.Repo(.xit, repo_opts).DB; 802 803 // store the check under the current event history moment 804 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.last_object_id_key)) orelse return error.NotFound; 805 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 806 _ = try last_object_id_cursor.readBytes(&last_object_id); 807 const haxy_history = try DB.ArrayList(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, evt.history_key))); 808 const haxy_moments = try DB.HashMap(.read_write).init(try haxy_history.putCursor(-1)); 809 const haxy_moment = try DB.HashMap(.read_write).init(try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &last_object_id))); 810 const map = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key))); 811 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, id))); 812 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, check); 813 } 814 815 fn branchCurrent(comptime repo_opts: rp.RepoOpts(.xit), state: rp.Repo(.xit, repo_opts).State(.read_only), io: std.Io, arena: *std.heap.ArenaAllocator, patch: evt.Patch) !bool { 816 // check that the source branch still points to the selected commit 817 const branch = patch.source_branch orelse return false; 818 const selected = patch.revision orelse return false; 819 const oid = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return false; 820 if (!std.mem.eql(u8, &oid, selected.source_oid)) return false; 821 822 // verify that the stored revision metadata also matches 823 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*); 824 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, arena, &try evt.parseEventId(&selected.id))) orelse return false; 825 return selected.matches(revision); 826 } 827 828 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 829 try evt.PatchRev.validateOid(hash_kind, oid); 830 var result: [hash.hexLen(hash_kind)]u8 = undefined; 831 @memcpy(&result, oid); 832 return result; 833 } 834 835 fn checkCommit( 836 comptime repo_opts: rp.RepoOpts(.xit), 837 state: rp.Repo(.xit, repo_opts).State(.read_write), 838 io: std.Io, 839 allocator: std.mem.Allocator, 840 oid: *const [hash.hexLen(repo_opts.hash)]u8, 841 target: rf.Ref, 842 ) Mergeability.Status { 843 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 844 .kind = .full, 845 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 846 .dry_run = true, 847 }, target, null) catch |err| { 848 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 849 return .unknown; 850 }; 851 defer result.deinit(); 852 853 // translate the dry-run outcome into a cached status 854 return switch (result.result) { 855 .conflict => .conflict, 856 .clean, .success, .nothing, .fast_forward => .clean, 857 }; 858 } 859 860 pub const MergeInput = struct { 861 id: [evt.event_id_size * 2]u8, 862 revision: evt.Patch.MergeRevision, 863 author: evt.CommitAuthor, 864 timestamp: u64, 865 }; 866 867 pub fn publish( 868 comptime repo_opts: rp.RepoOpts(.xit), 869 io: std.Io, 870 allocator: std.mem.Allocator, 871 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 872 user_repo: *rp.Repo(.xit, evt.user_repo_opts), 873 target_repo: *rp.Repo(.xit, repo_opts), 874 fork_path: []const u8, 875 input: PublishInput, 876 ) !void { 877 const patch_id = try evt.parseEventId(&input.id); 878 var arena = std.heap.ArenaAllocator.init(allocator); 879 defer arena.deinit(); 880 881 // validate the fork ownership and publishing identity 882 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 883 const user_moment = (try evt.userMoment(user_repo)) orelse return error.InvalidPatchDraft; 884 const fork_record = (try evt.Fork.readById(evt.UserDB, evt.user_repo_opts.hash, user_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 885 if (fork_record.removed or !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 886 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 887 if (user.removed or 888 !std.mem.eql(u8, user.event.name, input.author.name) or 889 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 890 891 // read the patch staged in the fork 892 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 893 defer fork_repo.deinit(io, allocator); 894 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 895 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 896 897 // check whether this patch has already been published 898 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 899 error.NotFound => null, 900 else => |other| return other, 901 }; 902 const existing = if (target_moment) |moment| 903 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 904 else 905 null; 906 if (existing) |record| { 907 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 908 } 909 910 // publish the selected revision unless the draft was already consumed 911 if (local_patch.removed) { 912 if (existing == null) return error.PatchDataUnavailable; 913 } else { 914 var patch = (existing orelse local_patch).event; 915 if (local_patch.event.revision) |selected| { 916 const revision_id = try evt.parseEventId(&selected.id); 917 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 918 if (!selected.matches(revision)) return error.PatchNotPushed; 919 patch.revision = selected; 920 } 921 if (existing == null) patch.status = .open; 922 923 // write the published patch to the target repository 924 try evt.consume(.server, .repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 925 .id = input.id, 926 .timestamp = input.timestamp, 927 .author = input.author, 928 .event = .{ .patch = patch }, 929 }}); 930 931 // remove the consumed draft from the fork 932 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 933 .id = input.id, 934 .timestamp = input.timestamp, 935 .author = input.author, 936 .event = .{ .patch = null }, 937 }}); 938 } 939 940 // mark the fork as published in the forker's user repo 941 if (fork_record.event.stage == .draft) { 942 var published = fork_record.event; 943 published.stage = .publish; 944 try evt.consume(.server, .user, .xit, evt.user_repo_opts, io, allocator, user_repo, evt.events_ref, &.{.{ 945 .id = input.id, 946 .timestamp = input.timestamp, 947 .author = input.author, 948 .event = .{ .fork = published }, 949 }}); 950 } 951 } 952 953 pub fn editDraft( 954 comptime repo_opts: rp.RepoOpts(.xit), 955 io: std.Io, 956 allocator: std.mem.Allocator, 957 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 958 user_repo: *rp.Repo(.xit, evt.user_repo_opts), 959 fork_path: []const u8, 960 input: EditDraftInput, 961 ) !bool { 962 // validate the submitted fields before opening repositories 963 if (!evt.Patch.fieldsValid(input.title, input.labels)) return error.InvalidFields; 964 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 965 const patch_id = try evt.parseEventId(&input.id); 966 var arena = std.heap.ArenaAllocator.init(allocator); 967 defer arena.deinit(); 968 969 // validate the draft ownership and editing identity 970 { 971 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 972 const user_moment = (try evt.userMoment(user_repo)) orelse return false; 973 const fork_record = (try evt.Fork.readById(evt.UserDB, evt.user_repo_opts.hash, user_moment, &arena, &patch_id)) orelse return false; 974 if (fork_record.event.stage != .draft) return false; 975 if (fork_record.removed or !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 976 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 977 if (user.removed or 978 !std.mem.eql(u8, user.event.name, input.author.name) or 979 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 980 } 981 982 // read the draft patch from its fork 983 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 984 defer fork_repo.deinit(io, allocator); 985 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 986 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 987 if (record.removed) return error.PatchDataUnavailable; 988 989 // apply the edits and invalidate a revision targeting another branch 990 var patch = record.event; 991 patch.title = input.title; 992 patch.labels = input.labels; 993 patch.description = input.description; 994 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 995 patch.target_branch = input.target_branch; 996 997 // commit the updated draft metadata 998 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 999 .id = input.id, 1000 .timestamp = input.timestamp, 1001 .author = input.author, 1002 .event = .{ .patch = patch }, 1003 }}); 1004 return true; 1005 } 1006 1007 // merge the selected patch revision into its target branch 1008 pub fn merge( 1009 comptime repo_opts: rp.RepoOpts(.xit), 1010 io: std.Io, 1011 allocator: std.mem.Allocator, 1012 repo_root_path: []const u8, 1013 target_repo: *rp.Repo(.xit, repo_opts), 1014 input: MergeInput, 1015 ) !void { 1016 const patch_id = try evt.parseEventId(&input.id); 1017 errdefer |err| { 1018 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 1019 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 1020 } 1021 } 1022 var arena = std.heap.ArenaAllocator.init(allocator); 1023 defer arena.deinit(); 1024 1025 // validate the target patch 1026 const target_moment = try evt.currentMoment(repo_opts, target_repo); 1027 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 1028 if (patch_record.removed) return error.InvalidPatch; 1029 switch (patch_record.event.status) { 1030 .open => {}, 1031 .closed => return error.PatchClosed, 1032 .merged => return error.PatchAlreadyMerged, 1033 } 1034 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 1035 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 1036 1037 // open the fork 1038 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 1039 var fork_repo_maybe: ?rp.Repo(.xit, repo_opts) = if (patch_record.event.source_branch != null) null else rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 1040 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1041 1042 // select the commit and merge identity 1043 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 1044 .squash => selected.squash_oid, 1045 .source => selected.source_oid, 1046 }) catch return error.InvalidPatch; 1047 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 1048 1049 // merge the code and events in one target transaction 1050 { 1051 const DB = rp.Repo(.xit, repo_opts).DB; 1052 const State = rp.Repo(.xit, repo_opts).State; 1053 const Ctx = struct { 1054 core: *rp.Repo(.xit, repo_opts).Core, 1055 fork_repo: ?*rp.Repo(.xit, repo_opts), 1056 io: std.Io, 1057 allocator: std.mem.Allocator, 1058 patch_id: [evt.event_id_size]u8, 1059 expected_patch: evt.Patch, 1060 target_ref: rf.Ref, 1061 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 1062 revision: evt.Patch.MergeRevision, 1063 identity: []const u8, 1064 author: evt.CommitAuthor, 1065 timestamp: u64, 1066 1067 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 1068 var moment = try DB.HashMap(.read_write).init(cursor.*); 1069 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 1070 1071 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 1072 defer check_arena.deinit(); 1073 1074 // require the fork's newest revision while both repos are locked 1075 const selected_revision = ctx.expected_patch.revision orelse unreachable; 1076 const revision_id = try evt.parseEventId(&selected_revision.id); 1077 if (ctx.fork_repo) |repo| { 1078 const fork_moment = try evt.currentMoment(repo_opts, repo); 1079 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 1080 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 1081 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 1082 1083 // require a clean cached result for the selected merge style. 1084 { 1085 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 1086 switch (availability.get(ctx.revision)) { 1087 .clean => {}, 1088 .conflict => return error.MergeConflict, 1089 .unknown => return error.MergeCheckUnavailable, 1090 } 1091 } 1092 1093 // copy the selected commit and its dependencies 1094 if (ctx.fork_repo) |repo| { 1095 var fork_repo_moment = try repo.core.latestMoment(); 1096 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 1097 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 1098 defer objects.deinit(); 1099 try objects.include(&ctx.selected_oid); 1100 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 1101 } 1102 1103 // merge the selected commit 1104 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1105 { 1106 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 1107 .kind = .full, 1108 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 1109 .commit_metadata = .{ 1110 .author = ctx.identity, 1111 .committer = ctx.identity, 1112 .message = ctx.expected_patch.title, 1113 .timestamp = ctx.timestamp, 1114 }, 1115 }, ctx.target_ref, null); 1116 defer merge_result.deinit(); 1117 switch (merge_result.result) { 1118 .conflict => return error.MergeConflict, 1119 .success, .fast_forward, .nothing => {}, 1120 .clean => unreachable, 1121 } 1122 } 1123 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1124 1125 // retain the submitted revision and snapshot the merge result 1126 if (!try importMergedRevision(repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.fork_repo, &ctx.patch_id, .{ .revision = ctx.revision, .before_oid = &before_oid, .after_oid = &after_oid }, ctx.expected_patch, ctx.author, ctx.timestamp)) return error.PatchOutOfDate; 1127 1128 // the merge moved the target branch, so its indexes follow, 1129 // the commit index deriving from the old tip's version 1130 _ = try find.refreshInTransaction(repo_opts, state, &moment, ctx.io, ctx.allocator, null); 1131 _ = try srch_cmmt.refreshInTransaction(repo_opts, state, &moment, ctx.io, ctx.allocator, &.{.{ .old_oid = &before_oid, .new_oid = &after_oid }}, null); 1132 1133 // record the merge as one undoable action. 1134 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = merge_undo_action } }); 1135 } 1136 }; 1137 1138 // lock the fork before the target for the full merge transaction. 1139 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 1140 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 1141 try target_repo.core.db_file.lock(io, .exclusive); 1142 defer target_repo.core.db_file.unlock(io); 1143 1144 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 1145 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 1146 .core = &target_repo.core, 1147 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 1148 .io = io, 1149 .allocator = allocator, 1150 .patch_id = patch_id, 1151 .expected_patch = patch_record.event, 1152 .target_ref = target_ref, 1153 .selected_oid = selected_oid, 1154 .revision = input.revision, 1155 .identity = identity, 1156 .author = input.author, 1157 .timestamp = input.timestamp, 1158 }); 1159 } 1160 1161 // refresh other patches affected by the updated target branch. 1162 refreshOpenMergeability(repo_opts, io, allocator, target_repo, null, null); 1163 } 1164 1165 // merge a published patch and remove its fork 1166 pub fn mergeAndRemoveFork( 1167 comptime repo_opts: rp.RepoOpts(.xit), 1168 io: std.Io, 1169 allocator: std.mem.Allocator, 1170 repo_root_path: []const u8, 1171 target_repo: *rp.Repo(.xit, repo_opts), 1172 input: MergeInput, 1173 ) !void { 1174 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 1175 var arena = std.heap.ArenaAllocator.init(allocator); 1176 defer arena.deinit(); 1177 1178 // remove fork data only for patches backed by a fork 1179 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 1180 if (record.event.source_branch != null) return; 1181 // a fork already cleaned up has no repo left 1182 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 1183 const forker_id = (try fork.readForkerId(io, allocator, fork_path)) orelse return; 1184 var user_repo = (try evt.openUserRepo(io, allocator, repo_root_path, &forker_id)) orelse return error.InvalidPatchDraft; 1185 defer user_repo.deinit(io, allocator); 1186 try fork.remove(io, allocator, repo_root_path, &user_repo, &input.id, input.author); 1187 } 1188 1189 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 1190 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 1191 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 1192 const name = std.mem.trimEnd(u8, line[0..open], " "); 1193 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 1194 return .{ .name = name, .email = line[open + 1 .. close] }; 1195 } 1196 1197 // import a revision after detecting a client-side merge 1198 fn importMerged( 1199 comptime repo_opts: rp.RepoOpts(.xit), 1200 state: rp.Repo(.xit, repo_opts).State(.read_write), 1201 db: *evt.EventDB(repo_opts.hash), 1202 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1203 io: std.Io, 1204 allocator: std.mem.Allocator, 1205 repo_root_path: []const u8, 1206 patch_id: *const [evt.event_id_size]u8, 1207 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1208 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1209 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1210 ) !void { 1211 var arena = std.heap.ArenaAllocator.init(allocator); 1212 defer arena.deinit(); 1213 1214 // identify which selected revision was merged by the client. 1215 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 1216 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 1217 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1218 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 1219 const selected = record.event.revision orelse return; 1220 const revision: evt.Patch.MergeRevision = if (std.mem.eql(u8, matched_oid, selected.source_oid)) .source else if (std.mem.eql(u8, matched_oid, selected.squash_oid)) .squash else return; 1221 1222 // open the fork when the revision is not stored in the target repository. 1223 var fork_repo_maybe: ?rp.Repo(.xit, repo_opts) = if (record.event.source_branch != null) null else try rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }); 1224 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1225 1226 // import the revision and record the client-side merge. 1227 _ = try importMergedRevision(repo_opts, state, db, moment, io, allocator, if (fork_repo_maybe) |*repo| repo else null, patch_id, .{ .revision = revision, .before_oid = before_oid, .after_oid = after_oid }, null, null, 0); 1228 } 1229 1230 // import the revision and mark its patch merged in the current transaction 1231 fn importMergedRevision( 1232 comptime repo_opts: rp.RepoOpts(.xit), 1233 state: rp.Repo(.xit, repo_opts).State(.read_write), 1234 db: *evt.EventDB(repo_opts.hash), 1235 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1236 io: std.Io, 1237 allocator: std.mem.Allocator, 1238 fork_repo: ?*rp.Repo(.xit, repo_opts), 1239 patch_id: *const [evt.event_id_size]u8, 1240 merged: struct { 1241 revision: evt.Patch.MergeRevision, 1242 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1243 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1244 }, 1245 expected_patch: ?evt.Patch, 1246 merged_author: ?evt.CommitAuthor, 1247 merged_timestamp: u64, 1248 ) !bool { 1249 const DB = evt.EventDB(repo_opts.hash); 1250 var arena = std.heap.ArenaAllocator.init(allocator); 1251 defer arena.deinit(); 1252 1253 // read the patch and reject outdated or conflicting merge requests. 1254 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1255 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 1256 const selected = patch_record.event.revision orelse return false; 1257 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 1258 if (expected_patch) |expected| { 1259 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 1260 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 1261 const conflicts = try DB.SortedMap(.read_only).init(cursor); 1262 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 1263 } 1264 } 1265 const revision_id = try evt.parseEventId(&selected.id); 1266 1267 // resolve the selected revision from the target or its fork. 1268 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 1269 const revision = (if (fork_repo) |repo| 1270 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 1271 else 1272 current_revision) orelse return false; 1273 if (!selected.matches(revision)) return false; 1274 1275 // read the original revision commit and author. 1276 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 1277 const fork_state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = if (fork_repo) |repo| &repo.core else state.core, .extra = .{ .moment = &fork_repo_moment } }; 1278 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1279 if (revision.event_oid.len != event_oid.len) return false; 1280 @memcpy(&event_oid, revision.event_oid); 1281 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 1282 defer event_object.deinit(); 1283 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 1284 1285 // retain the submitted revision if the target has not imported it yet. 1286 var events_buffer: [3]evt.EventWithId = undefined; 1287 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 1288 var tree_entries: [2]evt.EventTreeEntry = undefined; 1289 const needs_import = if (current_revision) |existing| existing.removed else true; 1290 if (needs_import) { 1291 tree_entries = .{ 1292 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 1293 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 1294 }; 1295 events.appendAssumeCapacity(.{ 1296 .id = selected.id, 1297 .timestamp = event_object.content.commit.metadata.timestamp, 1298 .author = original_author, 1299 .tree_entries = &tree_entries, 1300 .event = .{ .patchrev = revision.event }, 1301 }); 1302 } else { 1303 const existing = current_revision orelse unreachable; 1304 if (!selected.matches(existing)) return error.InvalidPatch; 1305 } 1306 1307 // snapshot the merge result and mark the patch as merged. 1308 { 1309 const author = merged_author orelse original_author; 1310 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 1311 var patch = patch_record.event; 1312 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 1313 events.appendAssumeCapacity(result.event); 1314 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 1315 events.appendAssumeCapacity(.{ 1316 .id = std.fmt.bytesToHex(patch_id.*, .lower), 1317 .timestamp = timestamp, 1318 .author = author, 1319 .event = .{ .patch = patch }, 1320 }); 1321 } 1322 1323 // commit and consume the revision and patch events together. 1324 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 1325 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 1326 return true; 1327 } 1328 1329 // find patches merged by commits received in a push 1330 pub fn detectMerged( 1331 comptime repo_opts: rp.RepoOpts(.xit), 1332 state: rp.Repo(.xit, repo_opts).State(.read_write), 1333 db: *evt.EventDB(repo_opts.hash), 1334 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1335 io: std.Io, 1336 allocator: std.mem.Allocator, 1337 repo_root_path: []const u8, 1338 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 1339 error_writer: *std.Io.Writer, 1340 ) !void { 1341 const DB = evt.EventDB(repo_opts.hash); 1342 var arena = std.heap.ArenaAllocator.init(allocator); 1343 defer arena.deinit(); 1344 1345 // read the revision index used to identify merged patches. 1346 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1347 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 1348 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 1349 1350 // ignore event refs and inspect only changed branch tips. 1351 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1352 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 1353 const heads_prefix = "refs/heads/"; 1354 for (updates) |update| { 1355 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 1356 std.mem.eql(u8, update.ref_name, events_ref_path) or 1357 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 1358 1359 // validate the ref tips and skip branch deletions. 1360 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 1361 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 1362 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1363 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1364 @memcpy(&old_oid, update.old_oid); 1365 @memcpy(&new_oid, update.new_oid); 1366 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 1367 1368 // traverse commits introduced by this branch update. 1369 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 1370 defer commits.deinit(); 1371 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 1372 var targets: std.ArrayList(struct { 1373 before_oid: [hash.hexLen(repo_opts.hash)]u8, 1374 after_oid: [hash.hexLen(repo_opts.hash)]u8, 1375 }) = .empty; 1376 1377 // collect merge boundaries along the target's first-parent history. 1378 { 1379 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 1380 defer first_parents.deinit(); 1381 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 1382 try first_parents.include(&new_oid); 1383 while (try first_parents.next(arena.allocator())) |commit| { 1384 defer commit.deinit(); 1385 try targets.append(arena.allocator(), .{ 1386 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 1387 .after_oid = commit.oid, 1388 }); 1389 } 1390 } 1391 1392 // visit target commits oldest first, attributing each revision to the 1393 // commit that introduced it; the shared iterator visits each ancestor once 1394 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 1395 while (targets.pop()) |target| { 1396 try commits.include(&target.after_oid); 1397 while (try commits.next(arena.allocator())) |commit| { 1398 defer commit.deinit(); 1399 1400 // find patches whose selected revision matches this commit. 1401 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 1402 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 1403 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 1404 var ids_iter = try ids.iterator(); 1405 while (try ids_iter.next()) |cursor| { 1406 const pair = try cursor.readKeyValuePair(); 1407 var patch_id: [evt.event_id_size]u8 = undefined; 1408 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 1409 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 1410 1411 // a fast-forward has no recorded merge boundary; use the old ref tip 1412 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 1413 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 1414 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 1415 continue; 1416 }; 1417 } 1418 } 1419 } 1420 } 1421 } 1422