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