╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ patch.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
31 defer arena.deinit(); 32 33 // write git events through the local event database 34 if (repo_kind == .git) { 35 // reject edits based on an outdated patch 36 if (expected_patch) |expected| { 37 const current = (try evt.readFromRepo(evt.Patch, repo_kind, repo_opts, io, allocator, &arena, repo, &try evt.parseEventId(&id))) orelse return error.PatchOutOfDate; 38 if (current.removed or !evt.fieldEqual(evt.Patch, current.event, expected)) return error.PatchOutOfDate; 39 } 40 41 // capture the branch revision and consume its events 42 const events = try branchEvents(repo_kind, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, &arena, id, patch, author); 43 try evt.consume(host_kind, .repo, repo_kind, repo_opts, io, allocator, repo, evt.events_ref, &events); 44 } else { 45 const DB = evt.EventDB(repo_opts.hash); 46 47 // continue from a remote event history when the local ref is absent 48 var first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8 = null; 49 if (try repo.readRef(io, evt.events_ref) == null) { 50 var remotes = try repo.listRemotes(io, allocator); 51 defer remotes.deinit(); 52 for (remotes.sections.keys()) |name| { 53 if (try repo.readRef(io, .{ .kind = .{ .remote = name }, .name = evt.events_ref.name })) |oid| { 54 first_parent = .{oid}; 55 break; 56 } 57 } 58 } 59 60 // commit the patch, mergeability, and undo record together 61 { 62 const Ctx = struct { 63 repo: *rp.Repo(repo_kind, repo_opts), 64 io: std.Io, 65 arena: *std.heap.ArenaAllocator, 66 id: [evt.event_id_size * 2]u8, 67 patch: evt.Patch, 68 expected_patch: ?evt.Patch, 69 author: evt.CommitAuthor, 70 checks: *MergeCheckInputs(repo_opts), 71 first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8, 72 73 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 74 var moment = try DB.HashMap(.read_write).init(cursor.*); 75 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{ .moment = &moment } }; 76 77 try writeBranchPatchInTransaction(repo_opts, state, &moment, ctx.io, ctx.arena, ctx.id, ctx.patch, ctx.expected_patch, ctx.author, ctx.first_parent, ctx.checks); 78 79 // record the user action for undo 80 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action = evt.undo_action } }); 81 } 82 }; 83 84 // a branch patch has no fork, so this only names the patch to check 85 var checks: MergeCheckInputs(repo_opts) = .{}; 86 defer checks.deinit(io, allocator); 87 if (host_kind == .server) try checks.add(io, allocator, repo.core.work_path, try evt.parseEventId(&id), patch); 88 89 try repo.core.db_file.lock(io, .exclusive); 90 defer repo.core.db_file.unlock(io); 91 92 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 93 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ .repo = repo, .io = io, .arena = &arena, .id = id, .patch = patch, .expected_patch = expected_patch, .author = author, .checks = &checks, .first_parent = first_parent }); 94 } 95 } 96 } 97 98 // write one branch patch's revision into a transaction the caller owns. the 99 // undo record is the caller's to write, since the transaction may be theirs. 100 // git repos never reach here: they write through the local event database 101 pub fn writeBranchPatchInTransaction( 102 comptime repo_opts: rp.RepoOpts(.xit), 103 state: rp.Repo(.xit, repo_opts).State(.read_write), 104 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 105 io: std.Io, 106 arena: *std.heap.ArenaAllocator, 107 id: [evt.event_id_size * 2]u8, 108 patch: evt.Patch, 109 expected_patch: ?evt.Patch, 110 author: evt.CommitAuthor, 111 first_parent: ?[1][hash.hexLen(repo_opts.hash)]u8, 112 checks: *MergeCheckInputs(repo_opts), 113 ) !void { 114 const DB = evt.EventDB(repo_opts.hash); 115 116 // recheck the expected patch under the repository lock 117 if (expected_patch) |expected| { 118 const events_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 119 const current = (try evt.Patch.readById(DB, repo_opts.hash, events_moment, arena, &try evt.parseEventId(&id))) orelse return error.PatchOutOfDate; 120 if (current.removed or !evt.fieldEqual(evt.Patch, current.event, expected)) return error.PatchOutOfDate; 121 } 122 123 // capture and consume the branch revision 124 const events = try branchEvents(.xit, repo_opts, state, io, arena, id, patch, author); 125 { 126 const parent = if (try rf.readRecur(.xit, repo_opts, state.readOnly(), io, .{ .ref = evt.events_ref }) == null) first_parent else null; 127 try evt.commitEvents(.xit, repo_opts, state, io, arena.child_allocator, evt.events_ref, &events, parent); 128 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, &state.core.db, moment, io, arena.child_allocator, evt.events_ref)) return error.CancelTransaction; 129 } 130 131 // save mergeability before finishing the patch transaction 132 _ = try checks.update(state, io, arena.child_allocator); 133 } 134 135 fn branchEvents( 136 comptime repo_kind: rp.RepoKind, 137 comptime repo_opts: rp.RepoOpts(repo_kind), 138 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 139 io: std.Io, 140 arena: *std.heap.ArenaAllocator, 141 id: [evt.event_id_size * 2]u8, 142 patch: evt.Patch, 143 author: evt.CommitAuthor, 144 ) ![2]evt.EventWithId { 145 // validate the patch fields and branch names 146 const branch = patch.source_branch orelse return error.InvalidSourceBranch; 147 if (!evt.Patch.fieldsValid(patch.title, patch.tags)) return error.InvalidFields; 148 if (!evt.Patch.branchValid(branch)) return error.InvalidSourceBranch; 149 if (!evt.Patch.branchValid(patch.target_branch)) return error.InvalidTargetBranch; 150 151 // resolve both tips and their common ancestor 152 const source = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return error.InvalidSourceBranch; 153 const target = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } })) orelse return error.InvalidTargetBranch; 154 if (std.mem.eql(u8, branch, patch.target_branch)) return error.SameBranch; 155 const base = mrg.commonAncestor(repo_kind, repo_opts, state.readOnly(), io, arena.allocator(), &target, &source) catch |err| switch (err) { 156 error.NoCommonAncestor => return error.UnrelatedBranches, 157 else => return err, 158 }; 159 160 // prepare the revision and attach it to the patch event 161 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 162 const prepared = try evt.PatchRev.prepare(repo_kind, repo_opts, state, io, arena, &base, &source, patch.title, author, timestamp); 163 var updated = patch; 164 updated.revision = prepared.revision; 165 return .{ 166 prepared.event, 167 .{ .id = id, .author = author, .timestamp = timestamp, .event = .{ .patch = updated } }, 168 }; 169 } 170 171 // the open patches whose source branch has moved past the revision they 172 // stored, mapped to the record the refresh rewrites. `updates` limits the 173 // search to the branches one push changed 174 fn collectOutdatedBranchPatches( 175 comptime repo_kind: rp.RepoKind, 176 comptime repo_opts: rp.RepoOpts(repo_kind), 177 io: std.Io, 178 allocator: std.mem.Allocator, 179 arena: *std.heap.ArenaAllocator, 180 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 181 moment: evt.EventDB(repo_opts.hash).HashMap(.read_only), 182 updates: ?[]const xit.net_server_receive_pack.AppliedRefUpdate, 183 host_kind: evt.HostKind, 184 patches: *std.AutoArrayHashMapUnmanaged([evt.event_id_size]u8, evt.Patch.Record), 185 ) !void { 186 const DB = evt.EventDB(repo_opts.hash); 187 // find tracked source branches and skip conflicting patches 188 const source_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.source_to_id_set_key)) orelse return; 189 const sources = try DB.SortedMap(.read_only).init(source_cursor); 190 const conflicts = if (try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| try DB.SortedMap(.read_only).init(cursor) else null; 191 var iter = try sources.iterator(); 192 while (try iter.next()) |cursor| { 193 const pair = try cursor.readKeyValuePair(); 194 const branch = try pair.key_cursor.readBytesAlloc(arena.allocator(), null); 195 196 // limit source refreshes to branches changed by this push 197 if (updates) |changed| { 198 var found = false; 199 for (changed) |update| { 200 if (std.mem.startsWith(u8, update.ref_name, "refs/heads/") and std.mem.eql(u8, update.ref_name["refs/heads/".len..], branch)) { 201 found = true; 202 break; 203 } 204 } 205 if (!found) continue; 206 } 207 208 // read the source tip before comparing stored revisions 209 const source = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse { 210 if (host_kind == .server) std.log.warn("patch source branch missing: {s}", .{branch}); 211 continue; 212 }; 213 214 // collect open patches whose stored source tip is outdated 215 const ids = try DB.CountedHashSet(.read_only).init(pair.value_cursor); 216 var ids_iter = try ids.iterator(); 217 while (try ids_iter.next()) |id_cursor| { 218 const id_pair = try id_cursor.readKeyValuePair(); 219 var id: [evt.event_id_size]u8 = undefined; 220 if ((try id_pair.key_cursor.readBytes(&id)).len != id.len) return error.InvalidPatch; 221 const record = (try evt.Patch.readById(DB, repo_opts.hash, moment, arena, &id)) orelse continue; 222 if (record.removed or record.event.status.kind() != .open) continue; 223 if (conflicts) |map| if (try map.getCursor(&evt.orderKeyDesc(record.created_order, &id)) != null) continue; 224 if (record.event.revision) |revision| if (std.mem.eql(u8, revision.source_oid, &source)) continue; 225 try patches.put(allocator, id, record); 226 } 227 } 228 } 229 230 // refresh the patches their source branch has outrun, inside the caller's 231 // transaction, so a push and the revisions it causes land together. fork 232 // backed patches are left to `refreshBranches`: their mergeability needs a 233 // fork's lock, which has to be taken before this transaction opened 234 pub fn refreshBranchesInTransaction( 235 comptime repo_opts: rp.RepoOpts(.xit), 236 state: rp.Repo(.xit, repo_opts).State(.read_write), 237 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 238 io: std.Io, 239 allocator: std.mem.Allocator, 240 updates: ?[]const xit.net_server_receive_pack.AppliedRefUpdate, 241 ) !void { 242 var arena = std.heap.ArenaAllocator.init(allocator); 243 defer arena.deinit(); 244 var patches: std.AutoArrayHashMapUnmanaged([evt.event_id_size]u8, evt.Patch.Record) = .empty; 245 defer patches.deinit(allocator); 246 247 const events_moment = evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()) catch |err| switch (err) { 248 error.NotFound => return, 249 else => return err, 250 }; 251 try collectOutdatedBranchPatches(.xit, repo_opts, io, allocator, &arena, state.readOnly(), events_moment, updates, .server, &patches); 252 253 for (patches.keys(), patches.values()) |id, record| { 254 // a branch patch opens no fork, so its checks need no lock of their own 255 var checks: MergeCheckInputs(repo_opts) = .{}; 256 defer checks.deinit(io, allocator); 257 try checks.add(io, allocator, state.core.work_path, id, record.event); 258 259 const author = evt.CommitAuthor{ .name = "haxy", .email = record.author_email orelse "user@haxy" }; 260 writeBranchPatchInTransaction(repo_opts, state, moment, io, &arena, std.fmt.bytesToHex(id, .lower), record.event, record.event, author, null, &checks) catch |err| { 261 std.log.warn("failed to refresh branch patch: {s}", .{@errorName(err)}); 262 }; 263 } 264 } 265 266 // refresh open patches' tracked branches and, on the server, their mergeability. 267 // this runs outside the caller's transaction. 268 pub fn refreshBranches( 269 host_kind: evt.HostKind, 270 comptime repo_kind: rp.RepoKind, 271 comptime repo_opts: rp.RepoOpts(repo_kind), 272 io: std.Io, 273 allocator: std.mem.Allocator, 274 repo: *rp.Repo(repo_kind, repo_opts), 275 updates: ?[]const xit.net_server_receive_pack.AppliedRefUpdate, 276 progress_ctx_maybe: ?repo_opts.ProgressCtx, 277 ) !void { 278 const DB = evt.EventDB(repo_opts.hash); 279 var arena = std.heap.ArenaAllocator.init(allocator); 280 defer arena.deinit(); 281 var patches: std.AutoArrayHashMapUnmanaged([evt.event_id_size]u8, ?evt.Patch.Record) = .empty; 282 defer patches.deinit(allocator); 283 var outdated: std.AutoArrayHashMapUnmanaged([evt.event_id_size]u8, evt.Patch.Record) = .empty; 284 defer outdated.deinit(allocator); 285 286 // collect patches whose source or mergeability may have changed 287 collect: { 288 var local_db: ?evt.LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try evt.LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 289 defer if (local_db) |*db| db.deinit(io, allocator); 290 const moment = (if (local_db) |*db| evt.currentMomentFromDb(repo_opts.hash, db.db) else if (repo_kind == .git) break :collect else evt.currentMoment(repo_opts, repo)) catch |err| switch (err) { 291 error.NotFound => break :collect, 292 else => return err, 293 }; 294 295 // include all open server patches for mergeability checks 296 if (repo_kind == .xit and host_kind == .server) open: { 297 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse break :open; 298 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 299 const open_cursor = try statuses.getCursor("open") orelse break :open; 300 const open_patches = try DB.SortedSet(.read_only).init(open_cursor); 301 var iter = try open_patches.iteratorFromIndex(0); 302 while (try iter.next()) |cursor| try patches.put(allocator, try evt.readOrderKeyId(DB, cursor), null); 303 } 304 305 switch (repo_kind) { 306 .git => try collectOutdatedBranchPatches(repo_kind, repo_opts, io, allocator, &arena, .{ .core = &repo.core, .extra = .{} }, moment, updates, host_kind, &outdated), 307 .xit => { 308 var repo_moment = try repo.core.latestMoment(); 309 try collectOutdatedBranchPatches(repo_kind, repo_opts, io, allocator, &arena, .{ .core = &repo.core, .extra = .{ .moment = &repo_moment } }, moment, updates, host_kind, &outdated); 310 }, 311 } 312 for (outdated.keys(), outdated.values()) |id, record| try patches.put(allocator, id, record); 313 } 314 315 // start progress reporting after the patch count is known 316 if (repo_opts.ProgressCtx != void) { 317 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .start = .{ .kind = .writing_patch, .estimated_total_items = patches.count() } }) catch {}; 318 } 319 320 // refresh each patch and report its completion 321 for (patches.keys(), patches.values()) |id, record_maybe| { 322 if (record_maybe) |record| { 323 const author = evt.CommitAuthor{ .name = "haxy", .email = record.author_email orelse "user@haxy" }; 324 writeBranchPatch(host_kind, repo_kind, repo_opts, io, allocator, repo, std.fmt.bytesToHex(id, .lower), record.event, record.event, author) catch |err| { 325 if (host_kind == .server) std.log.warn("failed to refresh branch patch: {s}", .{@errorName(err)}); 326 }; 327 } 328 if (repo_kind == .xit and host_kind == .server) refreshMergeability(repo_opts, io, allocator, repo, id); 329 if (repo_opts.ProgressCtx != void) { 330 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .complete_one = .writing_patch }) catch {}; 331 } 332 } 333 334 // finish progress reporting after all patches have been visited 335 if (repo_opts.ProgressCtx != void) { 336 if (progress_ctx_maybe) |progress_ctx| progress_ctx.run(io, .{ .end = .writing_patch }) catch {}; 337 } 338 } 339 340 pub const PublishInput = struct { 341 id: [evt.event_id_size * 2]u8, 342 user_id: [evt.event_id_size]u8, 343 repo_id: [evt.event_id_size]u8, 344 author: evt.CommitAuthor, 345 timestamp: u64, 346 }; 347 348 pub const EditDraftInput = struct { 349 id: [evt.event_id_size * 2]u8, 350 user_id: [evt.event_id_size]u8, 351 repo_id: [evt.event_id_size]u8, 352 title: []const u8, 353 tags: []const u8, 354 description: []const u8, 355 target_branch: []const u8, 356 author: evt.CommitAuthor, 357 timestamp: u64, 358 }; 359 360 pub const Mergeability = struct { 361 pub const Status = enum { clean, conflict, unknown }; 362 363 source: Status = .unknown, 364 squash: Status = .unknown, 365 366 pub fn get(self: Mergeability, revision: evt.Patch.MergeRevision) Status { 367 return switch (revision) { 368 .source => self.source, 369 .squash => self.squash, 370 }; 371 } 372 373 pub fn status(self: Mergeability) Status { 374 if (self.source == .clean or self.squash == .clean) return .clean; 375 if (self.source == .conflict and self.squash == .conflict) return .conflict; 376 return .unknown; 377 } 378 }; 379 380 const MergeCheck = struct { 381 revision: evt.Patch.Revision, 382 target_branch: []const u8, 383 target_oid: []const u8, 384 result: Mergeability = .{}, 385 386 fn matches(self: MergeCheck, patch: evt.Patch, target_oid: []const u8) bool { 387 return evt.fieldEqual(?evt.Patch.Revision, self.revision, patch.revision) and 388 std.mem.eql(u8, self.target_branch, patch.target_branch) and 389 std.mem.eql(u8, self.target_oid, target_oid); 390 } 391 }; 392 393 fn readMergeCheck( 394 comptime repo_opts: rp.RepoOpts(.xit), 395 haxy_moment: evt.EventDB(repo_opts.hash).HashMap(.read_only), 396 arena: *std.heap.ArenaAllocator, 397 id: *const [evt.event_id_size]u8, 398 ) !?MergeCheck { 399 const DB = evt.EventDB(repo_opts.hash); 400 401 // find the cached check for this patch 402 const map_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key)) orelse return null; 403 const map = try DB.HashMap(.read_only).init(map_cursor); 404 const cursor = try map.getCursor(hash.hashInt(repo_opts.hash, id)) orelse return null; 405 406 // treat unrecognized cached statuses as a cache miss 407 return evt.read(MergeCheck, DB, repo_opts.hash, arena, try DB.HashMap(.read_only).init(cursor)) catch |err| switch (err) { 408 error.InvalidEnumTag => return null, 409 else => return err, 410 }; 411 } 412 413 // reads never run a merge or refresh the cache 414 pub fn readMergeability( 415 comptime repo_opts: rp.RepoOpts(.xit), 416 state: rp.Repo(.xit, repo_opts).State(.read_only), 417 io: std.Io, 418 arena: *std.heap.ArenaAllocator, 419 id: *const [evt.event_id_size]u8, 420 patch: evt.Patch, 421 ) !Mergeability { 422 // reject checks for an outdated source revision 423 if (patch.source_branch != null and !try branchCurrent(repo_opts, state, io, arena, patch)) return .{}; 424 425 // use the cached result only when the target still matches 426 const target_oid = try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }) orelse return .{}; 427 const haxy_moment = evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*) catch |err| switch (err) { 428 error.NotFound => return .{}, 429 else => return err, 430 }; 431 const cached = try readMergeCheck(repo_opts, haxy_moment, arena, id) orelse return .{}; 432 return if (cached.matches(patch, &target_oid)) cached.result else .{}; 433 } 434 435 // refresh after the caller's transaction and locks have finished. a check 436 // failure must not turn an accepted push or event into a failed operation. 437 pub fn refreshMergeability( 438 comptime repo_opts: rp.RepoOpts(.xit), 439 io: std.Io, 440 allocator: std.mem.Allocator, 441 target_repo: *rp.Repo(.xit, repo_opts), 442 id_maybe: ?[evt.event_id_size]u8, 443 ) void { 444 refreshMergeChecks(repo_opts, io, allocator, target_repo, id_maybe) catch |err| { 445 std.log.warn("failed to refresh mergeability: {s}", .{@errorName(err)}); 446 }; 447 } 448 449 fn refreshMergeChecks( 450 comptime repo_opts: rp.RepoOpts(.xit), 451 io: std.Io, 452 allocator: std.mem.Allocator, 453 target_repo: *rp.Repo(.xit, repo_opts), 454 id_maybe: ?[evt.event_id_size]u8, 455 ) !void { 456 if (id_maybe) |id| return refreshMergeCheck(repo_opts, io, allocator, target_repo, &id); 457 458 // collect open patch ids before any refresh changes the database 459 const DB = evt.EventDB(repo_opts.hash); 460 const moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 461 error.NotFound => return, 462 else => return err, 463 }; 464 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse return; 465 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 466 const open_cursor = try statuses.getCursor("open") orelse return; 467 const open = try DB.SortedSet(.read_only).init(open_cursor); 468 var ids: std.ArrayList([evt.event_id_size]u8) = .empty; 469 defer ids.deinit(allocator); 470 var iter = try open.iteratorFromIndex(0); 471 while (try iter.next()) |cursor| try ids.append(allocator, try evt.readOrderKeyId(DB, cursor)); 472 473 // refresh each collected patch independently 474 for (ids.items) |id| refreshMergeability(repo_opts, io, allocator, target_repo, id); 475 } 476 477 fn refreshMergeCheck( 478 comptime repo_opts: rp.RepoOpts(.xit), 479 io: std.Io, 480 allocator: std.mem.Allocator, 481 target_repo: *rp.Repo(.xit, repo_opts), 482 id: *const [evt.event_id_size]u8, 483 ) !void { 484 const Repo = rp.Repo(.xit, repo_opts); 485 const DB = Repo.DB; 486 var arena = std.heap.ArenaAllocator.init(allocator); 487 defer arena.deinit(); 488 489 // skip patches that no longer need mergeability checks 490 const initial = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, id)) orelse return; 491 if (initial.removed or initial.event.status.kind() != .open) return; 492 493 // acquire fork locks before the target repository lock 494 var checks: MergeCheckInputs(repo_opts) = .{}; 495 defer checks.deinit(io, allocator); 496 try checks.add(io, allocator, target_repo.core.work_path, id.*, initial.event); 497 498 // cancel the cache transaction when the result is unchanged 499 { 500 const Ctx = struct { 501 core: *Repo.Core, 502 checks: *MergeCheckInputs(repo_opts), 503 io: std.Io, 504 allocator: std.mem.Allocator, 505 506 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 507 var moment = try DB.HashMap(.read_write).init(cursor.*); 508 const state = Repo.State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 509 if (!try ctx.checks.update(state, ctx.io, ctx.allocator)) return error.CancelTransaction; 510 } 511 }; 512 513 try target_repo.core.db_file.lock(io, .exclusive); 514 defer target_repo.core.db_file.unlock(io); 515 516 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 517 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 518 .core = &target_repo.core, 519 .checks = &checks, 520 .io = io, 521 .allocator = allocator, 522 }) catch |err| switch (err) { 523 error.CancelTransaction => {}, 524 else => return err, 525 }; 526 } 527 } 528 529 // prepare fork handles before taking the target lock. this preserves the 530 // fork-before-target lock order used by publishing and merge operations. 531 pub fn MergeCheckInputs(comptime repo_opts: rp.RepoOpts(.xit)) type { 532 const Repo = rp.Repo(.xit, repo_opts); 533 return struct { 534 forks: std.AutoArrayHashMapUnmanaged([evt.event_id_size]u8, ?Repo) = .empty, 535 const Self = @This(); 536 537 pub fn prepare(self: *Self, io: std.Io, allocator: std.mem.Allocator, repo: *Repo, events: []const evt.EventWithId) !void { 538 for (events) |event| { 539 if (event.event != .patch) continue; 540 const patch = event.event.patch orelse continue; 541 try self.add(io, allocator, repo.core.work_path, try evt.parseEventId(&event.id), patch); 542 } 543 } 544 545 fn add(self: *Self, io: std.Io, allocator: std.mem.Allocator, work_path: []const u8, id: [evt.event_id_size]u8, patch: evt.Patch) !void { 546 // track each open patch once, including branch-backed patches 547 if (patch.status.kind() != .open) return; 548 const entry = try self.forks.getOrPut(allocator, id); 549 if (entry.found_existing) return; 550 entry.value_ptr.* = null; 551 if (patch.source_branch != null) return; 552 553 // open the fork before acquiring its shared lock 554 const path = try fork.forkPath(allocator, std.fs.path.dirname(work_path) orelse ".", &std.fmt.bytesToHex(id, .lower)); 555 defer allocator.free(path); 556 var opened = Repo.open(io, allocator, .{ .path = path, .require_repo_root = true }) catch |err| { 557 std.log.warn("mergeability fork unavailable: {s}", .{@errorName(err)}); 558 return; 559 }; 560 561 // transfer the locked fork to the collection for cleanup 562 errdefer opened.deinit(io, allocator); 563 try opened.core.db_file.lock(io, .shared); 564 entry.value_ptr.* = opened; 565 } 566 567 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 568 for (self.forks.values()) |*value| if (value.*) |*repo| { 569 repo.core.db_file.unlock(io); 570 repo.deinit(io, allocator); 571 }; 572 self.forks.deinit(allocator); 573 } 574 575 // optional checks may fail without rejecting a patch, but a failed 576 // restoration must abort the transaction so trial writes cannot be 577 // committed. reports whether any cached result changed. 578 pub fn update(self: *Self, state: Repo.State(.read_write), io: std.Io, allocator: std.mem.Allocator) !bool { 579 var arena = std.heap.ArenaAllocator.init(allocator); 580 defer arena.deinit(); 581 var changed = false; 582 for (self.forks.keys(), self.forks.values()) |id, *repo| { 583 const saved = updateMergeCheck(repo_opts, state, io, &arena, &id, if (repo.*) |*value| value else null) catch |err| switch (err) { 584 error.MergeCheckRestoreFailed => return err, 585 else => { 586 std.log.warn("failed to refresh mergeability: {s}", .{@errorName(err)}); 587 continue; 588 }, 589 }; 590 if (saved) changed = true; 591 } 592 return changed; 593 } 594 }; 595 } 596 597 // the caller holds the target's exclusive lock, and any fork's shared lock. 598 // this only saves the cache; it never creates a top-level history transaction. 599 fn updateMergeCheck( 600 comptime repo_opts: rp.RepoOpts(.xit), 601 state: rp.Repo(.xit, repo_opts).State(.read_write), 602 io: std.Io, 603 arena: *std.heap.ArenaAllocator, 604 id: *const [evt.event_id_size]u8, 605 fork_repo: ?*rp.Repo(.xit, repo_opts), 606 ) !bool { 607 const DB = rp.Repo(.xit, repo_opts).DB; 608 609 // read the patch from the current transaction 610 const target_events = evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.readOnly()) catch |err| switch (err) { 611 error.NotFound => return false, 612 else => return err, 613 }; 614 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, target_events, arena, id)) orelse return false; 615 if (patch_record.removed or patch_record.event.status.kind() != .open) return false; 616 617 // find the newest fork revision when the patch uses a fork 618 var newest: ?evt.PatchRev.WithId = null; 619 if (fork_repo) |repo| { 620 if (evt.currentMoment(repo_opts, repo)) |events| { 621 newest = evt.PatchRev.readNewest(DB, repo_opts.hash, events, arena) catch |err| blk: { 622 std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 623 break :blk null; 624 }; 625 } else |err| std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 626 } 627 628 // compare the selected revision and target against the cache 629 const patch = patch_record.event; 630 const revision = patch.revision orelse return false; 631 const target_oid = try rf.readRecur(.xit, repo_opts, state.readOnly(), io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }); 632 var check = MergeCheck{ .revision = revision, .target_branch = patch.target_branch, .target_oid = if (target_oid) |*oid| oid else "" }; 633 const cached = try readMergeCheck(repo_opts, target_events, arena, id); 634 const current = if (patch.source_branch != null) 635 try branchCurrent(repo_opts, state.readOnly(), io, arena, patch) 636 else if (newest) |latest| 637 std.mem.eql(u8, &std.fmt.bytesToHex(latest.id, .lower), &revision.id) and revision.matches(latest.record) 638 else 639 false; 640 641 // run trial merges only for a current revision with an unresolved check 642 if (current and target_oid != null) { 643 if (cached) |value| if (value.matches(patch, check.target_oid) and value.result.source != .unknown and value.result.squash != .unknown) return false; 644 check.result = try trialMergeCheck(repo_opts, state, io, arena.child_allocator, &check, fork_repo); 645 } 646 647 // persist the result only when it differs from the cache 648 if (cached) |value| if (evt.fieldEqual(MergeCheck, value, check)) return false; 649 try saveMergeCheck(repo_opts, state.extra.moment.*, id, check); 650 return true; 651 } 652 653 fn trialMergeCheck( 654 comptime repo_opts: rp.RepoOpts(.xit), 655 state: rp.Repo(.xit, repo_opts).State(.read_write), 656 io: std.Io, 657 allocator: std.mem.Allocator, 658 check: *const MergeCheck, 659 fork_repo: ?*rp.Repo(.xit, repo_opts), 660 ) !Mergeability { 661 // freeze the parent state so trial writes copy its nodes 662 const moment = state.extra.moment; 663 const snapshot = moment.slot(); 664 // TODO: use an xitdb savepoint to also reclaim trial bytes on rollback. 665 // restoring the root leaves the appended data unused until gc. 666 try state.core.db.freeze(); 667 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 668 669 // keep the trial result in memory while discarding its state changes 670 const result = calculateMergeCheck(repo_opts, state, io, allocator, check, fork_repo); 671 672 // restore the parent state before handling any trial error 673 moment.cursor.write(.{ .slot = snapshot }) catch return error.MergeCheckRestoreFailed; 674 moment.* = rp.Repo(.xit, repo_opts).DB.HashMap(.read_write).init(moment.cursor) catch return error.MergeCheckRestoreFailed; 675 676 // report failed trials as unknown after the parent state is restored 677 return result catch |err| { 678 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 679 return .{}; 680 }; 681 } 682 683 fn calculateMergeCheck( 684 comptime repo_opts: rp.RepoOpts(.xit), 685 state: rp.Repo(.xit, repo_opts).State(.read_write), 686 io: std.Io, 687 allocator: std.mem.Allocator, 688 check: *const MergeCheck, 689 fork_repo: ?*rp.Repo(.xit, repo_opts), 690 ) !Mergeability { 691 const source = try oidArray(repo_opts.hash, check.revision.source_oid); 692 const squash = try oidArray(repo_opts.hash, check.revision.squash_oid); 693 694 // import fork objects into the temporary trial state 695 if (fork_repo) |repo| { 696 var fork_moment = try repo.core.latestMoment(); 697 const fork_state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_moment } }; 698 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, io, allocator, .{ .kind = .all }); 699 defer objects.deinit(); 700 try objects.include(&source); 701 try objects.include(&squash); 702 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, io, null); 703 } 704 705 // check source and squash merges against the same target 706 const target = rf.Ref{ .kind = .head, .name = check.target_branch }; 707 return .{ 708 .source = checkCommit(repo_opts, state, io, allocator, &source, target), 709 .squash = checkCommit(repo_opts, state, io, allocator, &squash, target), 710 }; 711 } 712 713 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 { 714 const DB = rp.Repo(.xit, repo_opts).DB; 715 716 // store the check under the current event history moment 717 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.last_object_id_key)) orelse return error.NotFound; 718 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 719 _ = try last_object_id_cursor.readBytes(&last_object_id); 720 const haxy_history = try DB.ArrayList(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, evt.history_key))); 721 const haxy_moments = try DB.HashMap(.read_write).init(try haxy_history.putCursor(-1)); 722 const haxy_moment = try DB.HashMap(.read_write).init(try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &last_object_id))); 723 const map = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, evt.Patch.patch_id_to_mergeability_key))); 724 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, id))); 725 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, check); 726 } 727 728 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 { 729 // check that the source branch still points to the selected commit 730 const branch = patch.source_branch orelse return false; 731 const selected = patch.revision orelse return false; 732 const oid = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = branch } })) orelse return false; 733 if (!std.mem.eql(u8, &oid, selected.source_oid)) return false; 734 735 // verify that the stored revision metadata also matches 736 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, state.extra.moment.*); 737 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, arena, &try evt.parseEventId(&selected.id))) orelse return false; 738 return selected.matches(revision); 739 } 740 741 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 742 try evt.PatchRev.validateOid(hash_kind, oid); 743 var result: [hash.hexLen(hash_kind)]u8 = undefined; 744 @memcpy(&result, oid); 745 return result; 746 } 747 748 fn checkCommit( 749 comptime repo_opts: rp.RepoOpts(.xit), 750 state: rp.Repo(.xit, repo_opts).State(.read_write), 751 io: std.Io, 752 allocator: std.mem.Allocator, 753 oid: *const [hash.hexLen(repo_opts.hash)]u8, 754 target: rf.Ref, 755 ) Mergeability.Status { 756 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 757 .kind = .full, 758 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 759 .dry_run = true, 760 }, target, null) catch |err| { 761 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 762 return .unknown; 763 }; 764 defer result.deinit(); 765 766 // translate the dry-run outcome into a cached status 767 return switch (result.result) { 768 .conflict => .conflict, 769 .clean, .success, .nothing, .fast_forward => .clean, 770 }; 771 } 772 773 pub const MergeInput = struct { 774 id: [evt.event_id_size * 2]u8, 775 revision: evt.Patch.MergeRevision, 776 author: evt.CommitAuthor, 777 timestamp: u64, 778 }; 779 780 pub fn publish( 781 comptime repo_opts: rp.RepoOpts(.xit), 782 io: std.Io, 783 allocator: std.mem.Allocator, 784 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 785 target_repo: *rp.Repo(.xit, repo_opts), 786 fork_path: []const u8, 787 input: PublishInput, 788 ) !void { 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 fork ownership and publishing identity 794 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 795 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 796 if (fork_record.removed or 797 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 798 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 799 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 800 if (user.removed or 801 !std.mem.eql(u8, user.event.name, input.author.name) or 802 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 803 804 // read the patch staged in the fork 805 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 806 defer fork_repo.deinit(io, allocator); 807 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 808 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 809 810 // check whether this patch has already been published 811 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 812 error.NotFound => null, 813 else => |other| return other, 814 }; 815 const existing = if (target_moment) |moment| 816 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 817 else 818 null; 819 if (existing) |record| { 820 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 821 } 822 823 // publish the selected revision unless the draft was already consumed 824 if (local_patch.removed) { 825 if (existing == null) return error.PatchDataUnavailable; 826 } else { 827 var patch = (existing orelse local_patch).event; 828 if (local_patch.event.revision) |selected| { 829 const revision_id = try evt.parseEventId(&selected.id); 830 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 831 if (!selected.matches(revision)) return error.PatchNotPushed; 832 patch.revision = selected; 833 } 834 if (existing == null) patch.status = .open; 835 836 // write the published patch to the target repository 837 try evt.consume(.server, .repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 838 .id = input.id, 839 .timestamp = input.timestamp, 840 .author = input.author, 841 .event = .{ .patch = patch }, 842 }}); 843 844 // remove the consumed draft from the fork 845 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 846 .id = input.id, 847 .timestamp = input.timestamp, 848 .author = input.author, 849 .event = .{ .patch = null }, 850 }}); 851 } 852 853 // mark the fork as published in the administration repository 854 if (fork_record.event.stage == .draft) { 855 var published = fork_record.event; 856 published.stage = .publish; 857 try evt.consume(.server, .admin, .xit, evt.admin_repo_opts, io, allocator, admin_repo, evt.events_ref, &.{.{ 858 .id = input.id, 859 .timestamp = input.timestamp, 860 .author = input.author, 861 .event = .{ .fork = published }, 862 }}); 863 } 864 } 865 866 pub fn editDraft( 867 comptime repo_opts: rp.RepoOpts(.xit), 868 io: std.Io, 869 allocator: std.mem.Allocator, 870 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 871 fork_path: []const u8, 872 input: EditDraftInput, 873 ) !bool { 874 // validate the submitted fields before opening repositories 875 if (!evt.Patch.fieldsValid(input.title, input.tags)) return error.InvalidFields; 876 if (!evt.Patch.branchValid(input.target_branch)) return error.InvalidTargetBranch; 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 draft ownership and editing identity 882 { 883 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 884 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return false; 885 if (fork_record.event.stage != .draft) return false; 886 if (fork_record.removed or 887 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 888 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 889 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 890 if (user.removed or 891 !std.mem.eql(u8, user.event.name, input.author.name) or 892 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 893 } 894 895 // read the draft patch from its fork 896 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 897 defer fork_repo.deinit(io, allocator); 898 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 899 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 900 if (record.removed) return error.PatchDataUnavailable; 901 902 // apply the edits and invalidate a revision targeting another branch 903 var patch = record.event; 904 patch.title = input.title; 905 patch.tags = input.tags; 906 patch.description = input.description; 907 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 908 patch.target_branch = input.target_branch; 909 910 // commit the updated draft metadata 911 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 912 .id = input.id, 913 .timestamp = input.timestamp, 914 .author = input.author, 915 .event = .{ .patch = patch }, 916 }}); 917 return true; 918 } 919 920 // merge the selected patch revision into its target branch 921 pub fn merge( 922 comptime repo_opts: rp.RepoOpts(.xit), 923 io: std.Io, 924 allocator: std.mem.Allocator, 925 repo_root_path: []const u8, 926 target_repo: *rp.Repo(.xit, repo_opts), 927 input: MergeInput, 928 ) !void { 929 const patch_id = try evt.parseEventId(&input.id); 930 errdefer |err| { 931 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 932 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 933 } 934 } 935 var arena = std.heap.ArenaAllocator.init(allocator); 936 defer arena.deinit(); 937 938 // validate the target patch 939 const target_moment = try evt.currentMoment(repo_opts, target_repo); 940 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 941 if (patch_record.removed) return error.InvalidPatch; 942 switch (patch_record.event.status) { 943 .open => {}, 944 .closed => return error.PatchClosed, 945 .merged => return error.PatchAlreadyMerged, 946 } 947 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 948 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 949 950 // open the fork 951 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 952 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; 953 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 954 955 // select the commit and merge identity 956 const selected_oid = oidArray(repo_opts.hash, switch (input.revision) { 957 .squash => selected.squash_oid, 958 .source => selected.source_oid, 959 }) catch return error.InvalidPatch; 960 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 961 962 // merge the code and events in one target transaction 963 { 964 const DB = rp.Repo(.xit, repo_opts).DB; 965 const State = rp.Repo(.xit, repo_opts).State; 966 const Ctx = struct { 967 core: *rp.Repo(.xit, repo_opts).Core, 968 fork_repo: ?*rp.Repo(.xit, repo_opts), 969 io: std.Io, 970 allocator: std.mem.Allocator, 971 patch_id: [evt.event_id_size]u8, 972 expected_patch: evt.Patch, 973 target_ref: rf.Ref, 974 selected_oid: [hash.hexLen(repo_opts.hash)]u8, 975 revision: evt.Patch.MergeRevision, 976 identity: []const u8, 977 author: evt.CommitAuthor, 978 timestamp: u64, 979 980 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 981 var moment = try DB.HashMap(.read_write).init(cursor.*); 982 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 983 984 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 985 defer check_arena.deinit(); 986 987 // require the fork's newest revision while both repos are locked 988 const selected_revision = ctx.expected_patch.revision orelse unreachable; 989 const revision_id = try evt.parseEventId(&selected_revision.id); 990 if (ctx.fork_repo) |repo| { 991 const fork_moment = try evt.currentMoment(repo_opts, repo); 992 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 993 if (!std.mem.eql(u8, &newest.id, &revision_id) or !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 994 } else if (!try branchCurrent(repo_opts, state.readOnly(), ctx.io, &check_arena, ctx.expected_patch)) return error.PatchOutOfDate; 995 996 // require a clean cached result for the selected merge style. 997 { 998 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 999 switch (availability.get(ctx.revision)) { 1000 .clean => {}, 1001 .conflict => return error.MergeConflict, 1002 .unknown => return error.MergeCheckUnavailable, 1003 } 1004 } 1005 1006 // copy the selected commit and its dependencies 1007 if (ctx.fork_repo) |repo| { 1008 var fork_repo_moment = try repo.core.latestMoment(); 1009 const fork_state = State(.read_only){ .core = &repo.core, .extra = .{ .moment = &fork_repo_moment } }; 1010 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 1011 defer objects.deinit(); 1012 try objects.include(&ctx.selected_oid); 1013 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 1014 } 1015 1016 // merge the selected commit 1017 const before_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1018 { 1019 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 1020 .kind = .full, 1021 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.selected_oid }}, .algo = .patch } }, 1022 .commit_metadata = .{ 1023 .author = ctx.identity, 1024 .committer = ctx.identity, 1025 .message = ctx.expected_patch.title, 1026 .timestamp = ctx.timestamp, 1027 }, 1028 }, ctx.target_ref, null); 1029 defer merge_result.deinit(); 1030 switch (merge_result.result) { 1031 .conflict => return error.MergeConflict, 1032 .success, .fast_forward, .nothing => {}, 1033 .clean => unreachable, 1034 } 1035 } 1036 const after_oid = (try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = ctx.target_ref })) orelse return error.InvalidTargetBranch; 1037 1038 // retain the submitted revision and snapshot the merge result 1039 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; 1040 1041 // record the merge as one undoable action. 1042 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action = merge_undo_action } }); 1043 } 1044 }; 1045 1046 // lock the fork before the target for the full merge transaction. 1047 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 1048 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 1049 try target_repo.core.db_file.lock(io, .exclusive); 1050 defer target_repo.core.db_file.unlock(io); 1051 1052 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 1053 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 1054 .core = &target_repo.core, 1055 .fork_repo = if (fork_repo_maybe) |*repo| repo else null, 1056 .io = io, 1057 .allocator = allocator, 1058 .patch_id = patch_id, 1059 .expected_patch = patch_record.event, 1060 .target_ref = target_ref, 1061 .selected_oid = selected_oid, 1062 .revision = input.revision, 1063 .identity = identity, 1064 .author = input.author, 1065 .timestamp = input.timestamp, 1066 }); 1067 } 1068 1069 // refresh other patches affected by the updated target branch. 1070 refreshMergeability(repo_opts, io, allocator, target_repo, null); 1071 1072 // the merge moved the target branch, so its indexes follow 1073 find.refresh(repo_opts, io, allocator, target_repo) catch |err| { 1074 std.log.warn("failed to refresh file index: {s}", .{@errorName(err)}); 1075 }; 1076 cms.refresh(repo_opts, io, allocator, target_repo, null) catch |err| { 1077 std.log.warn("failed to refresh commit index: {s}", .{@errorName(err)}); 1078 }; 1079 } 1080 1081 // merge a published patch and remove its fork 1082 pub fn mergeAndRemoveFork( 1083 comptime repo_opts: rp.RepoOpts(.xit), 1084 io: std.Io, 1085 allocator: std.mem.Allocator, 1086 repo_root_path: []const u8, 1087 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 1088 target_repo: *rp.Repo(.xit, repo_opts), 1089 input: MergeInput, 1090 ) !void { 1091 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 1092 var arena = std.heap.ArenaAllocator.init(allocator); 1093 defer arena.deinit(); 1094 1095 // remove fork data only for patches backed by a fork. 1096 const record = (try evt.readFromRepo(evt.Patch, .xit, repo_opts, io, allocator, &arena, target_repo, &try evt.parseEventId(&input.id))) orelse return error.InvalidPatch; 1097 if (record.event.source_branch == null) try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 1098 } 1099 1100 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 1101 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 1102 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 1103 const name = std.mem.trimEnd(u8, line[0..open], " "); 1104 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 1105 return .{ .name = name, .email = line[open + 1 .. close] }; 1106 } 1107 1108 // import a revision after detecting a client-side merge 1109 fn importMerged( 1110 comptime repo_opts: rp.RepoOpts(.xit), 1111 state: rp.Repo(.xit, repo_opts).State(.read_write), 1112 db: *evt.EventDB(repo_opts.hash), 1113 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1114 io: std.Io, 1115 allocator: std.mem.Allocator, 1116 repo_root_path: []const u8, 1117 patch_id: *const [evt.event_id_size]u8, 1118 matched_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1119 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1120 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1121 ) !void { 1122 var arena = std.heap.ArenaAllocator.init(allocator); 1123 defer arena.deinit(); 1124 1125 // identify which selected revision was merged by the client. 1126 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 1127 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 1128 const events = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1129 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, events, &arena, patch_id)) orelse return; 1130 const selected = record.event.revision orelse return; 1131 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; 1132 1133 // open the fork when the revision is not stored in the target repository. 1134 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 }); 1135 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 1136 1137 // import the revision and record the client-side merge. 1138 _ = 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); 1139 } 1140 1141 // import the revision and mark its patch merged in the current transaction 1142 fn importMergedRevision( 1143 comptime repo_opts: rp.RepoOpts(.xit), 1144 state: rp.Repo(.xit, repo_opts).State(.read_write), 1145 db: *evt.EventDB(repo_opts.hash), 1146 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1147 io: std.Io, 1148 allocator: std.mem.Allocator, 1149 fork_repo: ?*rp.Repo(.xit, repo_opts), 1150 patch_id: *const [evt.event_id_size]u8, 1151 merged: struct { 1152 revision: evt.Patch.MergeRevision, 1153 before_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1154 after_oid: *const [hash.hexLen(repo_opts.hash)]u8, 1155 }, 1156 expected_patch: ?evt.Patch, 1157 merged_author: ?evt.CommitAuthor, 1158 merged_timestamp: u64, 1159 ) !bool { 1160 const DB = evt.EventDB(repo_opts.hash); 1161 var arena = std.heap.ArenaAllocator.init(allocator); 1162 defer arena.deinit(); 1163 1164 // read the patch and reject outdated or conflicting merge requests. 1165 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1166 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 1167 const selected = patch_record.event.revision orelse return false; 1168 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 1169 if (expected_patch) |expected| { 1170 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 1171 if (try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.conflicts_key))) |cursor| { 1172 const conflicts = try DB.SortedMap(.read_only).init(cursor); 1173 if (try conflicts.getCursor(&evt.orderKeyDesc(patch_record.created_order, patch_id)) != null) return false; 1174 } 1175 } 1176 const revision_id = try evt.parseEventId(&selected.id); 1177 1178 // resolve the selected revision from the target or its fork. 1179 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 1180 const revision = (if (fork_repo) |repo| 1181 try evt.PatchRev.readById(DB, repo_opts.hash, try evt.currentMoment(repo_opts, repo), &arena, &revision_id) 1182 else 1183 current_revision) orelse return false; 1184 if (!selected.matches(revision)) return false; 1185 1186 // read the original revision commit and author. 1187 var fork_repo_moment = if (fork_repo) |repo| try repo.core.latestMoment() else moment.readOnly(); 1188 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 } }; 1189 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1190 if (revision.event_oid.len != event_oid.len) return false; 1191 @memcpy(&event_oid, revision.event_oid); 1192 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 1193 defer event_object.deinit(); 1194 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 1195 1196 // retain the submitted revision if the target has not imported it yet. 1197 var events_buffer: [3]evt.EventWithId = undefined; 1198 var events: std.ArrayList(evt.EventWithId) = .initBuffer(&events_buffer); 1199 var tree_entries: [2]evt.EventTreeEntry = undefined; 1200 const needs_import = if (current_revision) |existing| existing.removed else true; 1201 if (needs_import) { 1202 tree_entries = .{ 1203 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 1204 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 1205 }; 1206 events.appendAssumeCapacity(.{ 1207 .id = selected.id, 1208 .timestamp = event_object.content.commit.metadata.timestamp, 1209 .author = original_author, 1210 .tree_entries = &tree_entries, 1211 .event = .{ .patchrev = revision.event }, 1212 }); 1213 } else { 1214 const existing = current_revision orelse unreachable; 1215 if (!selected.matches(existing)) return error.InvalidPatch; 1216 } 1217 1218 // snapshot the merge result and mark the patch as merged. 1219 { 1220 const author = merged_author orelse original_author; 1221 const timestamp = if (merged_author != null) merged_timestamp else @as(u64, @intCast(std.Io.Timestamp.now(io, .real).toSeconds())); 1222 var patch = patch_record.event; 1223 const result = try evt.PatchRev.prepare(.xit, repo_opts, state, io, &arena, merged.before_oid, merged.after_oid, patch.title, author, timestamp); 1224 events.appendAssumeCapacity(result.event); 1225 patch.status = .{ .merged = .{ .revision = merged.revision, .patchrev_id = result.event.id } }; 1226 events.appendAssumeCapacity(.{ 1227 .id = std.fmt.bytesToHex(patch_id.*, .lower), 1228 .timestamp = timestamp, 1229 .author = author, 1230 .event = .{ .patch = patch }, 1231 }); 1232 } 1233 1234 // commit and consume the revision and patch events together. 1235 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events.items, null); 1236 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 1237 return true; 1238 } 1239 1240 // find patches merged by commits received in a push 1241 pub fn detectMerged( 1242 comptime repo_opts: rp.RepoOpts(.xit), 1243 state: rp.Repo(.xit, repo_opts).State(.read_write), 1244 db: *evt.EventDB(repo_opts.hash), 1245 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 1246 io: std.Io, 1247 allocator: std.mem.Allocator, 1248 repo_root_path: []const u8, 1249 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 1250 error_writer: *std.Io.Writer, 1251 ) !void { 1252 const DB = evt.EventDB(repo_opts.hash); 1253 var arena = std.heap.ArenaAllocator.init(allocator); 1254 defer arena.deinit(); 1255 1256 // read the revision index used to identify merged patches. 1257 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 1258 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 1259 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 1260 1261 // ignore event refs and inspect only changed branch tips. 1262 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 1263 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 1264 const heads_prefix = "refs/heads/"; 1265 for (updates) |update| { 1266 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 1267 std.mem.eql(u8, update.ref_name, events_ref_path) or 1268 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 1269 1270 // validate the ref tips and skip branch deletions. 1271 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 1272 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 1273 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1274 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1275 @memcpy(&old_oid, update.old_oid); 1276 @memcpy(&new_oid, update.new_oid); 1277 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 1278 1279 // traverse commits introduced by this branch update. 1280 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 1281 defer commits.deinit(); 1282 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 1283 var targets: std.ArrayList(struct { 1284 before_oid: [hash.hexLen(repo_opts.hash)]u8, 1285 after_oid: [hash.hexLen(repo_opts.hash)]u8, 1286 }) = .empty; 1287 1288 // collect merge boundaries along the target's first-parent history. 1289 { 1290 var first_parents = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit, .first_parent = true }); 1291 defer first_parents.deinit(); 1292 if (!std.mem.allEqual(u8, &old_oid, '0')) try first_parents.exclude(&old_oid); 1293 try first_parents.include(&new_oid); 1294 while (try first_parents.next(arena.allocator())) |commit| { 1295 defer commit.deinit(); 1296 try targets.append(arena.allocator(), .{ 1297 .before_oid = (commit.content.commit.metadata.firstParent() orelse &old_oid).*, 1298 .after_oid = commit.oid, 1299 }); 1300 } 1301 } 1302 1303 // visit target commits oldest first, attributing each revision to the 1304 // commit that introduced it; the shared iterator visits each ancestor once 1305 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 1306 while (targets.pop()) |target| { 1307 try commits.include(&target.after_oid); 1308 while (try commits.next(arena.allocator())) |commit| { 1309 defer commit.deinit(); 1310 1311 // find patches whose selected revision matches this commit. 1312 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 1313 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 1314 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 1315 var ids_iter = try ids.iterator(); 1316 while (try ids_iter.next()) |cursor| { 1317 const pair = try cursor.readKeyValuePair(); 1318 var patch_id: [evt.event_id_size]u8 = undefined; 1319 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 1320 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 1321 1322 // a fast-forward has no recorded merge boundary; use the old ref tip 1323 const before_oid = if (std.mem.eql(u8, &commit.oid, &target.after_oid)) &old_oid else &target.before_oid; 1324 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid, before_oid, &target.after_oid) catch |err| { 1325 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 1326 continue; 1327 }; 1328 } 1329 } 1330 } 1331 } 1332 } 1333