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