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