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