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