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