╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
525 }; 526 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, target_events, arena, id)) orelse return false; 527 if (patch_record.removed or patch_record.event.status.kind() != .open) return false; 528 529 // find the newest fork revision when the patch uses a fork 530 var newest: ?evt.PatchRev.WithId = null; 531 if (fork_repo) |repo| { 532 if (evt.currentMoment(repo_opts, repo)) |events| { 533 newest = evt.PatchRev.readNewest(DB, repo_opts.hash, events, arena) catch |err| blk: { 534 std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 535 break :blk null; 536 }; 537 } else |err| std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 538 } 539 540 // compare the selected revision and target against the cache 541 const patch = patch_record.event; 542 const revision = patch.revision orelse return false; 543 const target_oid = try rf.readRecur(.xit, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }); 544 var check = MergeCheck{ .revision = revision, .target_branch = patch.target_branch, .target_oid = if (target_oid) |*oid| oid else "" }; 545 const cached = try readMergeCheck(repo_opts, target_events, arena, id); 546 const current = if (patch.source_branch != null) 547 try branchCurrent(repo_opts, state.readOnly(), io, arena, patch) 548 else if (newest) |latest| 549 std.mem.eql(u8, &std.fmt.bytesToHex(latest.id, .lower), &revision.id) and revision.matches(latest.record) 550 else 551 false; 552 553 // run trial merges only for a current revision with an unresolved check 554 if (current and target_oid != null) { 555 if (cached) |value| if (value.matches(patch, check.target_oid) and value.result.source != .unknown and value.result.squash != .unknown) return false; 556 check.result = try trialMergeCheck(repo_opts, state, io, arena.child_allocator, &check, fork_repo); 557 } 558 559 // persist the result only when it differs from the cache 560 if (cached) |value| if (evt.fieldEqual(MergeCheck, value, check)) return false; 561 try saveMergeCheck(repo_opts, state.extra.moment.*, id, check); 562 return true; 563 } 564 565 fn trialMergeCheck( 566 comptime repo_opts: rp.RepoOpts(.xit), 567 state: rp.Repo(.xit, repo_opts).State(.read_write), 568 io: std.Io, 569 allocator: std.mem.Allocator, 570 check: *const MergeCheck, 571 fork_repo: ?*rp.Repo(.xit, repo_opts), 572 ) !Mergeability { 573 // freeze the parent state so trial writes copy its nodes 574 const moment = state.extra.moment; 575 const snapshot = moment.slot(); 576 // TODO: use an xitdb savepoint to also reclaim trial bytes on rollback. 577 // restoring the root leaves the appended data unused until gc. 578 try state.core.db.freeze(); 579 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 580 581 // keep the trial result in memory while discarding its state changes 582 const result = calculateMergeCheck(repo_opts, state, io, allocator, check, fork_repo); 583 584 // restore the parent state before handling any trial error 585 moment.cursor.write(.{ .slot = snapshot }) catch return error.MergeCheckRestoreFailed; 586 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 587 588 // report failed trials as unknown after the parent state is restored 589 return result catch |err| { 590 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 591 return .{}; 592 }; 593 } 594 595 fn calculateMergeCheck( 596 comptime repo_opts: rp.RepoOpts(.xit), 597 state: rp.Repo(.xit, repo_opts).State(.read_write), 598 io: std.Io, 599 allocator: std.mem.Allocator, 600 check: *const MergeCheck, 601 fork_repo: ?*rp.Repo(.xit, repo_opts), 602 ) !Mergeability { 603 const source = try oidArray(repo_opts.hash, check.revision.source_oid); 604 const squash = try oidArray(repo_opts.hash, check.revision.squash_oid); 605 606 // import fork objects into the temporary trial state 607 if (fork_repo) |repo| { 608 var fork_moment = try repo.core.latestMoment(); 609 const fork_state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_moment } }; 610 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, io, allocator, .{ .kind = .all }); 611 defer objects.deinit(); 612 try objects.include(&source); 613 try objects.include(&squash); 614 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, io, null); 615 } 616 617 // check source and squash merges against the same target 618 const target = rf.Ref{ .kind = .head, .name = check.target_branch }; 619 return .{ 620 .source = checkCommit(repo_opts, state, io, allocator, &source, target), 621 .squash = checkCommit(repo_opts, state, io, allocator, &squash, target), 622 }; 623 } 624 625 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 { 626 const DB = rp.Repo(.xit, repo_opts).DB; 627 628 // store the check under the current event history moment 629 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.last_object_id_key)) orelse return error.NotFound; 630 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 631 _ = try last_object_id_cursor.readBytes(&last_object_id); 632 const haxy_history = try DB.ArrayList(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, evt.history_key))); 633 const haxy_moments = try DB.HashMap(.read_write).init(try haxy_history.putCursor(-1)); 634 const haxy_moment = try DB.HashMap(.read_write).init(try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &last_object_id))); 635 const map = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key))); 636 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, id))); 637 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, check); 638 } 639 640 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 { 641 // check that the source branch still points to the selected commit 642 const branch = patch.source_branch orelse return false; 643 const selected = patch.revision orelse return false; 644 const oid = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return false; 645 if (!std.mem.eql(u8, &oid, selected.source_oid)) return false; 646 647 // verify that the stored revision metadata also matches 648 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*); 649 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, arena, &try evt.parseEventId(&selected.id))) orelse return false; 650 return selected.matches(revision); 651 } 652 653 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 654 try evt.PatchRev.validateOid(hash_kind, oid); 655 var result: [hash.hexLen(hash_kind)]u8 = undefined; 656 @memcpy(&result, oid); 657 return result; 658 } 659 660 fn checkCommit( 661 comptime repo_opts: rp.RepoOpts(.xit), 662 state: rp.Repo(.xit, repo_opts).State(.read_write), 663 io: std.Io, 664 allocator: std.mem.Allocator, 665 oid: *const [hash.hexLen(repo_opts.hash)]u8, 666 target: rf.Ref, 667 ) Mergeability.Status { 668 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 669 .kind = .full, 670 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 671 .dry_run = true, 672 }, target, null) catch |err| { 673 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 674 return .unknown; 675 }; 676 defer result.deinit(); 677 678 // translate the dry-run outcome into a cached status 679 return switch (result.result) { 680 .conflict => .conflict, 681 .clean, .success, .nothing, .fast_forward => .clean, 682 }; 683 } 684 685 pub const MergeInput = struct { 686 id: [evt.event_id_size * 2]u8, 687 revision: evt.Patch.MergeRevision, 688 author: evt.CommitAuthor, 689 timestamp: u64, 690 }; 691 692 pub fn publish( 693 comptime repo_opts: rp.RepoOpts(.xit), 694 io: std.Io, 695 allocator: std.mem.Allocator, 696 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 697 target_repo: *rp.Repo(.xit, repo_opts), 698 fork_path: []const u8, 699 input: PublishInput, 700 ) !void { 701 const patch_id = try evt.parseEventId(&input.id); 702 var arena = std.heap.ArenaAllocator.init(allocator); 703 defer arena.deinit(); 704 705 // validate the fork ownership and publishing identity 706 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 707 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 708 if (fork_record.removed or 709 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 710 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 711 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 712 if (user.removed or 713 !std.mem.eql(u8, user.event.name, input.author.name) or 714 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 715 716 // read the patch staged in the fork 717 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 718 defer fork_repo.deinit(io, allocator); 719 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 720 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 721 722 // check whether this patch has already been published 723 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 724 error.NotFound => null, 725 else => |other| return other, 726 }; 727 const existing = if (target_moment) |moment| 728 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 729 else 730 null; 731 if (existing) |record| { 732 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 733 } 734 735 // publish the selected revision unless the draft was already consumed 736 if (local_patch.removed) { 737 if (existing == null) return error.PatchDataUnavailable; 738 } else { 739 var patch = (existing orelse local_patch).event; 740 if (local_patch.event.revision) |selected| { 741 const revision_id = try evt.parseEventId(&selected.id); 742 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 743 if (!selected.matches(revision)) return error.PatchNotPushed; 744 patch.revision = selected; 745 } 746 if (existing == null) patch.status = .open; 747 748 // write the published patch to the target repository 749 try evt.consume(.server, .repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 750 .id = input.id, 751 .timestamp = input.timestamp, 752 .author = input.author, 753 .event = .{ .patch = patch }, 754 }}); 755 756 // remove the consumed draft from the fork 757 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 758 .id = input.id, 759 .timestamp = input.timestamp, 760 .author = input.author, 761 .event = .{ .patch = null }, 762 }}); 763 } 764 765 // mark the fork as published in the administration repository 766 if (fork_record.event.stage == .draft) { 767 var published = fork_record.event; 768 published.stage = .publish; 769 try evt.consume(.server, .admin, .xit, evt.admin_repo_opts, io, allocator, admin_repo, evt.events_ref, &.{.{ 770 .id = input.id, 771 .timestamp = input.timestamp, 772 .author = input.author, 773 .event = .{ .fork = published }, 774 }}); 775 } 776 } 777 778 pub fn editDraft( 779 comptime repo_opts: rp.RepoOpts(.xit), 780 io: std.Io, 781 allocator: std.mem.Allocator, 782 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 783 fork_path: []const u8, 784 input: EditDraftInput, 785 ) !bool { 786 // validate the submitted fields before opening repositories 787 if (!evt.Patch.fieldsValid(input.title, input.tags)) return error.InvalidFields; 788 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 789 const patch_id = try evt.parseEventId(&input.id); 790 var arena = std.heap.ArenaAllocator.init(allocator); 791 defer arena.deinit(); 792 793 // validate the draft ownership and editing identity 794 { 795 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 796 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return false; 797 if (fork_record.event.stage != .draft) return false; 798 if (fork_record.removed or 799 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 800 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 801 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 802 if (user.removed or 803 !std.mem.eql(u8, user.event.name, input.author.name) or 804 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 805 } 806 807 // read the draft patch from its fork 808 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 809 defer fork_repo.deinit(io, allocator); 810 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 811 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 812 if (record.removed) return error.PatchDataUnavailable; 813 814 // apply the edits and invalidate a revision targeting another branch 815 var patch = record.event; 816 patch.title = input.title; 817 patch.tags = input.tags; 818 patch.description = input.description; 819 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 820 patch.target_branch = input.target_branch; 821 822 // commit the updated draft metadata 823 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 824 .id = input.id, 825 .timestamp = input.timestamp, 826 .author = input.author, 827 .event = .{ .patch = patch }, 828 }}); 829 return true; 830 } 831 832 // merge the selected patch revision into its target branch 833 pub fn merge( 834 comptime repo_opts: rp.RepoOpts(.xit), 835 io: std.Io, 836 allocator: std.mem.Allocator, 837 repo_root_path: []const u8, 838 target_repo: *rp.Repo(.xit, repo_opts), 839 input: MergeInput, 840 ) !void { 841 const patch_id = try evt.parseEventId(&input.id); 842 errdefer |err| { 843 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 844 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 845 } 846 } 847 var arena = std.heap.ArenaAllocator.init(allocator); 848 defer arena.deinit(); 849 850 // validate the target patch 851 const target_moment = try evt.currentMoment(repo_opts, target_repo); 852 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 853 if (patch_record.removed) return error.InvalidPatch; 854 switch (patch_record.event.status) { 855 .open => {}, 856 .closed => return error.PatchClosed, 857 .merged => return error.PatchAlreadyMerged, 858 } 859 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 860 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 861 862 // open the fork 863 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 864 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; 865 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 866 867 // select the commit and merge identity 868 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 869 .squash => selected.squash_oid, 870 .source => selected.source_oid, 871 }) catch return error.InvalidPatch; 872 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 873 874 // merge the code and events in one target transaction 875 { 876 const DB = rp.Repo(.xit, repo_opts).DB; 877 const State = rp.Repo(.xit, repo_opts).State; 878 const Ctx = struct { 879 core: *rp.Repo(.xit, repo_opts).Core, 880 fork_repo: ?*rp.Repo(.xit, repo_opts), 881 io: std.Io, 882 allocator: std.mem.Allocator, 883 patch_id: [evt.event_id_size]u8, 884 expected_patch: evt.Patch, 885 target_ref: rf.Ref, 886 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 887 revision: evt.Patch.MergeRevision, 888 identity: []const u8, 889 author: evt.CommitAuthor, 890 timestamp: u64, 891 892 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 893 var moment = try DB.HashMap(.read_write).init(cursor.*); 894 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 895 896 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 897 defer check_arena.deinit(); 898 899 // require the fork's newest revision while both repos are locked 900 const selected_revision = ctx.expected_patch.revision orelse unreachable; 901 const revision_id = try evt.parseEventId(&selected_revision.id); 902 if (ctx.fork_repo) |repo| { 903 const fork_moment = try evt.currentMoment(repo_opts, repo); 904 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 905 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 906 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 907 908 // require a clean cached result for the selected merge style. 909 { 910 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 911 switch (availability.get(ctx.revision)) { 912 .clean => {}, 913 .conflict => return error.MergeConflict, 914 .unknown => return error.MergeCheckUnavailable, 915 } 916 } 917 918 // copy the selected commit and its dependencies 919 if (ctx.fork_repo) |repo| { 920 var fork_repo_moment = try repo.core.latestMoment(); 921 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 922 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 923 defer objects.deinit(); 924 try objects.include(&ctx.selected_oid); 925 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 926 } 927 928 // merge the selected commit 929 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 930 { 931 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 932 .kind = .full, 933 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 934 .commit_metadata = .{ 935 .author = ctx.identity, 936 .committer = ctx.identity, 937 .message = ctx.expected_patch.title, 938 .timestamp = ctx.timestamp, 939 }, 940 }, ctx.target_ref, null); 941 defer merge_result.deinit(); 942 switch (merge_result.result) { 943 .conflict => return error.MergeConflict, 944 .success, .fast_forward, .nothing => {}, 945 .clean => unreachable, 946 } 947 } 948 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 949 950 // retain the submitted revision and snapshot the merge result 951 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; 952 953 // record the merge as one undoable action. 954 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action = "merge_patch" } }); 955 } 956 }; 957 958 // lock the fork before the target for the full merge transaction. 959 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 960 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 961 try target_repo.core.db_file.lock(io, .exclusive); 962 defer target_repo.core.db_file.unlock(io); 963 964 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 965 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 966 .core = &target_repo.core, 967 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 968 .io = io, 969 .allocator = allocator, 970 .patch_id = patch_id, 971 .expected_patch = patch_record.event, 972 .target_ref = target_ref, 973 .selected_oid = selected_oid, 974 .revision = input.revision, 975 .identity = identity, 976 .author = input.author, 977 .timestamp = input.timestamp, 978 }); 979 } 980 981 // refresh other patches affected by the updated target branch. 982 refreshMergeability(repo_opts, io, allocator, target_repo, null); 983 984 // the merge moved the target branch, so its indexes follow 985 find.refresh(repo_opts, io, allocator, target_repo) catch |err| { 986 std.log.warn("failed to refresh file index: {s}", .{@errorName(err)}); 987 }; 988 cms.refresh(repo_opts, io, allocator, target_repo, null) catch |err| { 989 std.log.warn("failed to refresh commit index: {s}", .{@errorName(err)}); 990 }; 991 } 992 993 // merge a published patch and remove its fork 994 pub fn mergeAndRemoveFork( 995 comptime repo_opts: rp.RepoOpts(.xit), 996 io: std.Io, 997 allocator: std.mem.Allocator, 998 repo_root_path: []const u8, 999 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 1000 target_repo: *rp.Repo(.xit, repo_opts), 1001 input: MergeInput, 1002 ) !void { 1003 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 1004 var arena = std.heap.ArenaAllocator.init(allocator); 1005 defer arena.deinit(); 1006 1007 // remove fork data only for patches backed by a fork. 1008 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 1009 if (record.event.source_branch == null) try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 1010 } 1011 1012 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 1013 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 1014 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 1015 const name = std.mem.trimEnd(u8, line[0..open], " "); 1016 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 1017 return .{ .name = name, .email = line[open + 1 .. close] }; 1018 } 1019 1020 // import a revision after detecting a client-side merge 1021 fn importMerged( 1022 comptime repo_opts: rp.RepoOpts(.xit), 1023 state: rp.Repo(.xit, repo_opts).State(.read_write), 1024 db: *evt.EventDB(repo_opts.hash), 1025 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1026 io: std.Io, 1027 allocator: std.mem.Allocator, 1028 repo_root_path: []const u8, 1029 patch_id: *const [evt.event_id_size]u8, 1030 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1031 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1032 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1033 ) !void { 1034 var arena = std.heap.ArenaAllocator.init(allocator); 1035 defer arena.deinit(); 1036 1037 // identify which selected revision was merged by the client. 1038 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 1039 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 1040 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1041 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 1042 const selected = record.event.revision orelse return; 1043 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; 1044 1045 // open the fork when the revision is not stored in the target repository. 1046 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 }); 1047 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1048 1049 // import the revision and record the client-side merge. 1050 _ = 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); 1051 } 1052 1053 // import the revision and mark its patch merged in the current transaction 1054 fn importMergedRevision( 1055 comptime repo_opts: rp.RepoOpts(.xit), 1056 state: rp.Repo(.xit, repo_opts).State(.read_write), 1057 db: *evt.EventDB(repo_opts.hash), 1058 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1059 io: std.Io, 1060 allocator: std.mem.Allocator, 1061 fork_repo: ?*rp.Repo(.xit, repo_opts), 1062 patch_id: *const [evt.event_id_size]u8, 1063 merged: struct { 1064 revision: evt.Patch.MergeRevision, 1065 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1066 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1067 }, 1068 expected_patch: ?evt.Patch, 1069 merged_author: ?evt.CommitAuthor, 1070 merged_timestamp: u64, 1071 ) !bool { 1072 const DB = evt.EventDB(repo_opts.hash); 1073 var arena = std.heap.ArenaAllocator.init(allocator); 1074 defer arena.deinit(); 1075 1076 // read the patch and reject outdated or conflicting merge requests. 1077 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1078 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 1079 const selected = patch_record.event.revision orelse return false; 1080 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 1081 if (expected_patch) |expected| { 1082 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 1083 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 1084 const conflicts = try DB.SortedMap(.read_only).init(cursor); 1085 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 1086 } 1087 } 1088 const revision_id = try evt.parseEventId(&selected.id); 1089 1090 // resolve the selected revision from the target or its fork. 1091 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 1092 const revision = (if (fork_repo) |repo| 1093 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 1094 else 1095 current_revision) orelse return false; 1096 if (!selected.matches(revision)) return false; 1097 1098 // read the original revision commit and author. 1099 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 1100 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 } }; 1101 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1102 if (revision.event_oid.len != event_oid.len) return false; 1103 @memcpy(&event_oid, revision.event_oid); 1104 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 1105 defer event_object.deinit(); 1106 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 1107 1108 // retain the submitted revision if the target has not imported it yet. 1109 var events_buffer: [3]evt.EventWithId = undefined; 1110 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 1111 var tree_entries: [2]evt.EventTreeEntry = undefined; 1112 const needs_import = if (current_revision) |existing| existing.removed else true; 1113 if (needs_import) { 1114 tree_entries = .{ 1115 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 1116 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 1117 }; 1118 events.appendAssumeCapacity(.{ 1119 .id = selected.id, 1120 .timestamp = event_object.content.commit.metadata.timestamp, 1121 .author = original_author, 1122 .tree_entries = &tree_entries, 1123 .event = .{ .patchrev = revision.event }, 1124 }); 1125 } else { 1126 const existing = current_revision orelse unreachable; 1127 if (!selected.matches(existing)) return error.InvalidPatch; 1128 } 1129 1130 // snapshot the merge result and mark the patch as merged. 1131 { 1132 const author = merged_author orelse original_author; 1133 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 1134 var patch = patch_record.event; 1135 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 1136 events.appendAssumeCapacity(result.event); 1137 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 1138 events.appendAssumeCapacity(.{ 1139 .id = std.fmt.bytesToHex(patch_id.*, .lower), 1140 .timestamp = timestamp, 1141 .author = author, 1142 .event = .{ .patch = patch }, 1143 }); 1144 } 1145 1146 // commit and consume the revision and patch events together. 1147 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 1148 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 1149 return true; 1150 } 1151 1152 // find patches merged by commits received in a push 1153 pub fn detectMerged( 1154 comptime repo_opts: rp.RepoOpts(.xit), 1155 state: rp.Repo(.xit, repo_opts).State(.read_write), 1156 db: *evt.EventDB(repo_opts.hash), 1157 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1158 io: std.Io, 1159 allocator: std.mem.Allocator, 1160 repo_root_path: []const u8, 1161 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 1162 error_writer: *std.Io.Writer, 1163 ) !void { 1164 const DB = evt.EventDB(repo_opts.hash); 1165 var arena = std.heap.ArenaAllocator.init(allocator); 1166 defer arena.deinit(); 1167 1168 // read the revision index used to identify merged patches. 1169 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1170 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 1171 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 1172 1173 // ignore event refs and inspect only changed branch tips. 1174 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1175 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 1176 const heads_prefix = "refs/heads/"; 1177 for (updates) |update| { 1178 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 1179 std.mem.eql(u8, update.ref_name, events_ref_path) or 1180 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 1181 1182 // validate the ref tips and skip branch deletions. 1183 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 1184 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 1185 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1186 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1187 @memcpy(&old_oid, update.old_oid); 1188 @memcpy(&new_oid, update.new_oid); 1189 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 1190 1191 // traverse commits introduced by this branch update. 1192 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 1193 defer commits.deinit(); 1194 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 1195 var targets: std.ArrayList(struct { 1196 before_oid: [hash.hexLen(repo_opts.hash)]u8, 1197 after_oid: [hash.hexLen(repo_opts.hash)]u8, 1198 }) = .empty; 1199 1200 // collect merge boundaries along the target's first-parent history. 1201 { 1202 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 1203 defer first_parents.deinit(); 1204 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 1205 try first_parents.include(&new_oid); 1206 while (try first_parents.next(arena.allocator())) |commit| { 1207 defer commit.deinit(); 1208 try targets.append(arena.allocator(), .{ 1209 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 1210 .after_oid = commit.oid, 1211 }); 1212 } 1213 } 1214 1215 // visit target commits oldest first, attributing each revision to the 1216 // commit that introduced it; the shared iterator visits each ancestor once 1217 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 1218 while (targets.pop()) |target| { 1219 try commits.include(&target.after_oid); 1220 while (try commits.next(arena.allocator())) |commit| { 1221 defer commit.deinit(); 1222 1223 // find patches whose selected revision matches this commit. 1224 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 1225 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 1226 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 1227 var ids_iter = try ids.iterator(); 1228 while (try ids_iter.next()) |cursor| { 1229 const pair = try cursor.readKeyValuePair(); 1230 var patch_id: [evt.event_id_size]u8 = undefined; 1231 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 1232 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 1233 1234 // a fast-forward has no recorded merge boundary; use the old ref tip 1235 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 1236 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 1237 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 1238 continue; 1239 }; 1240 } 1241 } 1242 } 1243 } 1244 } 1245