╭ 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 fork = @import("fork.zig"); 10 const serve_common = @import("serve_common.zig"); 11 12 pub const PublishInput = struct { 13 id: [evt.event_id_size * 2]u8, 14 user_id: [evt.event_id_size]u8, 15 repo_id: [evt.event_id_size]u8, 16 author: evt.CommitAuthor, 17 timestamp: u64, 18 }; 19 20 pub const EditDraftInput = struct { 21 id: [evt.event_id_size * 2]u8, 22 user_id: [evt.event_id_size]u8, 23 repo_id: [evt.event_id_size]u8, 24 title: []const u8, 25 tags: []const u8, 26 description: []const u8, 27 target_branch: []const u8, 28 author: evt.CommitAuthor, 29 timestamp: u64, 30 }; 31 32 pub const MergeRevision = enum { squash, source }; 33 34 pub const Mergeability = struct { 35 pub const Status = enum { clean, conflict, unknown }; 36 37 source: Status = .unknown, 38 squash: Status = .unknown, 39 40 pub fn get(self: Mergeability, revision: MergeRevision) Status { 41 return switch (revision) { 42 .source => self.source, 43 .squash => self.squash, 44 }; 45 } 46 47 pub fn status(self: Mergeability) Status { 48 if (self.source == .clean or self.squash == .clean) return .clean; 49 if (self.source == .conflict and self.squash == .conflict) return .conflict; 50 return .unknown; 51 } 52 }; 53 54 const mergeability_key = "patch-id->mergeability"; 55 56 const MergeCheck = struct { 57 revision: evt.Patch.Revision, 58 target_branch: []const u8, 59 target_oid: []const u8, 60 result: Mergeability = .{}, 61 62 fn matches(self: MergeCheck, patch: evt.Patch, target_oid: []const u8) bool { 63 return evt.fieldEqual(?evt.Patch.Revision, self.revision, patch.revision) and 64 std.mem.eql(u8, self.target_branch, patch.target_branch) and 65 std.mem.eql(u8, self.target_oid, target_oid); 66 } 67 }; 68 69 fn readMergeCheck( 70 comptime repo_opts: rp.RepoOpts(.xit), 71 moment: evt.EventDB(repo_opts.hash).HashMap(.read_only), 72 arena: *std.heap.ArenaAllocator, 73 id: *const [evt.event_id_size]u8, 74 ) !?MergeCheck { 75 const DB = evt.EventDB(repo_opts.hash); 76 const map_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, mergeability_key)) orelse return null; 77 const map = try DB.HashMap(.read_only).init(map_cursor); 78 const cursor = try map.getCursor(hash.hashInt(repo_opts.hash, id)) orelse return null; 79 return evt.read(MergeCheck, DB, repo_opts.hash, arena, try DB.HashMap(.read_only).init(cursor)) catch |err| switch (err) { 80 error.InvalidEnumTag => return null, 81 else => return err, 82 }; 83 } 84 85 // reads never run a merge or refresh the cache 86 pub fn readMergeability( 87 comptime repo_opts: rp.RepoOpts(.xit), 88 state: rp.Repo(.xit, repo_opts).State(.read_only), 89 io: std.Io, 90 arena: *std.heap.ArenaAllocator, 91 id: *const [evt.event_id_size]u8, 92 patch: evt.Patch, 93 ) !Mergeability { 94 const target_oid = try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }) orelse return .{}; 95 const cached = try readMergeCheck(repo_opts, state.extra.moment.*, arena, id) orelse return .{}; 96 return if (cached.matches(patch, &target_oid)) cached.result else .{}; 97 } 98 99 // refresh after the caller's transaction and locks have finished. a check 100 // failure must not turn an accepted push or event into a failed operation. 101 pub fn refreshMergeability( 102 comptime repo_opts: rp.RepoOpts(.xit), 103 io: std.Io, 104 allocator: std.mem.Allocator, 105 target_repo: *rp.Repo(.xit, repo_opts), 106 id_maybe: ?[evt.event_id_size]u8, 107 ) void { 108 refreshMergeChecks(repo_opts, io, allocator, target_repo, id_maybe) catch |err| { 109 std.log.warn("failed to refresh mergeability: {s}", .{@errorName(err)}); 110 }; 111 } 112 113 fn refreshMergeChecks( 114 comptime repo_opts: rp.RepoOpts(.xit), 115 io: std.Io, 116 allocator: std.mem.Allocator, 117 target_repo: *rp.Repo(.xit, repo_opts), 118 id_maybe: ?[evt.event_id_size]u8, 119 ) !void { 120 if (id_maybe) |id| return refreshMergeCheck(repo_opts, io, allocator, target_repo, &id); 121 const DB = evt.EventDB(repo_opts.hash); 122 const moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 123 error.NotFound => return, 124 else => return err, 125 }; 126 const statuses_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.status_to_id_set_key)) orelse return; 127 const statuses = try DB.SortedMap(.read_only).init(statuses_cursor); 128 const open_cursor = try statuses.getCursor("open") orelse return; 129 const open = try DB.SortedSet(.read_only).init(open_cursor); 130 var ids: std.ArrayList([evt.event_id_size]u8) = .empty; 131 defer ids.deinit(allocator); 132 var iter = try open.iteratorFromIndex(0); 133 while (try iter.next()) |cursor| try ids.append(allocator, try evt.readOrderKeyId(DB, cursor)); 134 for (ids.items) |id| refreshMergeability(repo_opts, io, allocator, target_repo, id); 135 } 136 137 fn refreshMergeCheck( 138 comptime repo_opts: rp.RepoOpts(.xit), 139 io: std.Io, 140 allocator: std.mem.Allocator, 141 target_repo: *rp.Repo(.xit, repo_opts), 142 id: *const [evt.event_id_size]u8, 143 ) !void { 144 const Repo = rp.Repo(.xit, repo_opts); 145 const DB = Repo.DB; 146 var arena = std.heap.ArenaAllocator.init(allocator); 147 defer arena.deinit(); 148 const repo_root_path = std.fs.path.dirname(target_repo.core.work_path) orelse "."; 149 const path = try fork.forkPath(arena.allocator(), repo_root_path, &std.fmt.bytesToHex(id.*, .lower)); 150 var fork_repo_maybe: ?Repo = Repo.open(io, allocator, .{ .path = path, .require_repo_root = true }) catch |err| blk: { 151 std.log.warn("mergeability fork unavailable: {s}", .{@errorName(err)}); 152 break :blk null; 153 }; 154 defer if (fork_repo_maybe) |*repo| repo.deinit(io, allocator); 155 if (fork_repo_maybe) |*repo| try repo.core.db_file.lock(io, .shared); 156 defer if (fork_repo_maybe) |*repo| repo.core.db_file.unlock(io); 157 try target_repo.core.db_file.lock(io, .exclusive); 158 defer target_repo.core.db_file.unlock(io); 159 160 var target_moment = try target_repo.core.latestMoment(); 161 const target_state = Repo.State(.read_only){ .core = &target_repo.core, .extra = .{ .moment = &target_moment } }; 162 const target_events = evt.currentMomentFromRepoMoment(repo_opts.hash, target_moment) catch |err| switch (err) { 163 error.NotFound => null, 164 else => return err, 165 }; 166 var record = if (target_events) |events| try evt.Patch.readById(DB, repo_opts.hash, events, &arena, id) else null; 167 var newest: ?evt.PatchRev.WithId = null; 168 if (fork_repo_maybe) |*repo| { 169 if (evt.currentMoment(repo_opts, repo)) |events| { 170 newest = evt.PatchRev.readNewest(DB, repo_opts.hash, events, &arena) catch |err| blk: { 171 std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 172 break :blk null; 173 }; 174 if (record == null) record = try evt.Patch.readById(DB, repo_opts.hash, events, &arena, id); 175 } else |err| std.log.warn("mergeability revision unavailable: {s}", .{@errorName(err)}); 176 } 177 const patch_record = record orelse return; 178 if (patch_record.removed or patch_record.event.status.kind() != .open) return; 179 const patch = patch_record.event; 180 const revision = patch.revision orelse return; 181 const target_oid = try rf.readRecur(.xit, repo_opts, target_state, io, .{ .ref = .{ .kind = .head, .name = patch.target_branch } }); 182 var check = MergeCheck{ .revision = revision, .target_branch = patch.target_branch, .target_oid = if (target_oid) |*oid| oid else "" }; 183 const cached = try readMergeCheck(repo_opts, target_moment, &arena, id); 184 const current = if (newest) |latest| std.mem.eql(u8, &std.fmt.bytesToHex(latest.id, .lower), &revision.id) and revision.matches(latest.record) else false; 185 if (current and target_oid != null) { 186 if (cached) |value| if (value.matches(patch, check.target_oid) and value.result.source != .unknown and value.result.squash != .unknown) return; 187 const Ctx = struct { 188 repo: *Repo, 189 fork_repo: *Repo, 190 io: std.Io, 191 allocator: std.mem.Allocator, 192 check: *MergeCheck, 193 194 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 195 var moment = try DB.HashMap(.read_write).init(cursor.*); 196 const state = Repo.State(.read_write){ .core = &ctx.repo.core, .extra = .{ .moment = &moment } }; 197 var fork_moment = try ctx.fork_repo.core.latestMoment(); 198 const fork_state = Repo.State(.read_only){ .core = &ctx.fork_repo.core, .extra = .{ .moment = &fork_moment } }; 199 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 200 defer objects.deinit(); 201 const source = try oidArray(repo_opts.hash, ctx.check.revision.source_oid); 202 const squash = try oidArray(repo_opts.hash, ctx.check.revision.squash_oid); 203 try objects.include(&source); 204 try objects.include(&squash); 205 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 206 const target = rf.Ref{ .kind = .head, .name = ctx.check.target_branch }; 207 ctx.check.result.source = checkCommit(repo_opts, state, ctx.io, ctx.allocator, &source, target); 208 ctx.check.result.squash = checkCommit(repo_opts, state, ctx.io, ctx.allocator, &squash, target); 209 return error.CancelTransaction; 210 } 211 }; 212 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 213 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 214 .repo = target_repo, 215 .fork_repo = &fork_repo_maybe.?, 216 .io = io, 217 .allocator = allocator, 218 .check = &check, 219 }) catch |err| switch (err) { 220 error.CancelTransaction => {}, 221 else => std.log.warn("mergeability check failed: {s}", .{@errorName(err)}), 222 }; 223 } 224 if (cached) |value| if (evt.fieldEqual(MergeCheck, value, check)) return; 225 const Save = struct { 226 id: [evt.event_id_size]u8, 227 check: MergeCheck, 228 229 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 230 const moment = try DB.HashMap(.read_write).init(cursor.*); 231 const map = try DB.HashMap(.read_write).init(try moment.putCursor(hash.hashInt(repo_opts.hash, mergeability_key))); 232 const entry = try DB.HashMap(.read_write).init(try map.putCursor(hash.hashInt(repo_opts.hash, &ctx.id))); 233 try evt.upsert(MergeCheck, DB, repo_opts.hash, entry, ctx.check); 234 } 235 }; 236 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 237 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Save{ .id = id.*, .check = check }); 238 } 239 240 fn oidArray(comptime hash_kind: hash.HashKind, oid: []const u8) ![hash.hexLen(hash_kind)]u8 { 241 try evt.PatchRev.validateOid(hash_kind, oid); 242 var result: [hash.hexLen(hash_kind)]u8 = undefined; 243 @memcpy(&result, oid); 244 return result; 245 } 246 247 fn checkCommit( 248 comptime repo_opts: rp.RepoOpts(.xit), 249 state: rp.Repo(.xit, repo_opts).State(.read_write), 250 io: std.Io, 251 allocator: std.mem.Allocator, 252 oid: *const [hash.hexLen(repo_opts.hash)]u8, 253 target: rf.Ref, 254 ) Mergeability.Status { 255 var result = mrg.Merge(.xit, repo_opts).init(state, io, allocator, .{ 256 .kind = .full, 257 .action = .{ .new = .{ .source = &.{.{ .oid = oid }}, .algo = .patch } }, 258 .dry_run = true, 259 }, target, null) catch |err| { 260 std.log.warn("mergeability check failed: {s}", .{@errorName(err)}); 261 return .unknown; 262 }; 263 defer result.deinit(); 264 return switch (result.result) { 265 .conflict => .conflict, 266 .clean, .success, .nothing, .fast_forward => .clean, 267 }; 268 } 269 270 pub const MergeInput = struct { 271 id: [evt.event_id_size * 2]u8, 272 revision: MergeRevision, 273 author: evt.CommitAuthor, 274 timestamp: u64, 275 }; 276 277 pub fn publish( 278 comptime repo_opts: rp.RepoOpts(.xit), 279 io: std.Io, 280 allocator: std.mem.Allocator, 281 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 282 target_repo: *rp.Repo(.xit, repo_opts), 283 fork_path: []const u8, 284 input: PublishInput, 285 ) !void { 286 const patch_id = try evt.parseEventId(&input.id); 287 var arena = std.heap.ArenaAllocator.init(allocator); 288 defer arena.deinit(); 289 290 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 291 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return error.InvalidPatchDraft; 292 if (fork_record.removed or 293 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 294 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 295 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 296 if (user.removed or 297 !std.mem.eql(u8, user.event.name, input.author.name) or 298 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 299 300 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path }) catch return error.PatchDataUnavailable; 301 defer fork_repo.deinit(io, allocator); 302 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 303 const local_patch = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 304 305 const target_moment = evt.currentMoment(repo_opts, target_repo) catch |err| switch (err) { 306 error.NotFound => null, 307 else => |other| return other, 308 }; 309 const existing = if (target_moment) |moment| 310 try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, moment, &arena, &patch_id) 311 else 312 null; 313 if (existing) |record| { 314 if (record.removed or !std.mem.eql(u8, record.author_email orelse "", input.author.email)) return error.InvalidPatch; 315 } 316 if (local_patch.removed) { 317 if (existing == null) return error.PatchDataUnavailable; 318 } else { 319 var patch = (existing orelse local_patch).event; 320 if (local_patch.event.revision) |selected| { 321 const revision_id = try evt.parseEventId(&selected.id); 322 const revision = (try evt.PatchRev.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return error.PatchNotPushed; 323 if (!selected.matches(revision)) return error.PatchNotPushed; 324 patch.revision = selected; 325 } 326 if (existing == null) patch.status = .open; 327 328 try evt.consume(.server, .repo, .xit, repo_opts, io, allocator, target_repo, evt.events_ref, &.{.{ 329 .id = input.id, 330 .timestamp = input.timestamp, 331 .author = input.author, 332 .event = .{ .patch = patch }, 333 }}); 334 335 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 336 .id = input.id, 337 .timestamp = input.timestamp, 338 .author = input.author, 339 .event = .{ .patch = null }, 340 }}); 341 } 342 343 if (fork_record.event.stage == .draft) { 344 var published = fork_record.event; 345 published.stage = .publish; 346 try evt.consume(.server, .admin, .xit, evt.admin_repo_opts, io, allocator, admin_repo, evt.events_ref, &.{.{ 347 .id = input.id, 348 .timestamp = input.timestamp, 349 .author = input.author, 350 .event = .{ .fork = published }, 351 }}); 352 } 353 } 354 355 pub fn editDraft( 356 comptime repo_opts: rp.RepoOpts(.xit), 357 io: std.Io, 358 allocator: std.mem.Allocator, 359 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 360 fork_path: []const u8, 361 input: EditDraftInput, 362 ) !bool { 363 if (!evt.Patch.fieldsValid(input.title, input.tags)) return error.InvalidFields; 364 const patch_id = try evt.parseEventId(&input.id); 365 var arena = std.heap.ArenaAllocator.init(allocator); 366 defer arena.deinit(); 367 368 const admin_moment = try evt.currentMoment(evt.admin_repo_opts, admin_repo); 369 const fork_record = (try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &patch_id)) orelse return false; 370 if (fork_record.event.stage != .draft) return false; 371 if (fork_record.removed or 372 !std.mem.eql(u8, fork_record.event.user_id, &input.user_id) or 373 !std.mem.eql(u8, fork_record.event.repo_id, &input.repo_id)) return error.InvalidPatchDraft; 374 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, admin_moment, &arena, &input.user_id)) orelse return error.InvalidPatchDraft; 375 if (user.removed or 376 !std.mem.eql(u8, user.event.name, input.author.name) or 377 !std.mem.eql(u8, user.event.email, input.author.email)) return error.InvalidPatchDraft; 378 379 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 380 defer fork_repo.deinit(io, allocator); 381 const fork_moment = evt.currentMoment(repo_opts, &fork_repo) catch return error.PatchDataUnavailable; 382 const record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &arena, &patch_id)) orelse return error.PatchDataUnavailable; 383 if (record.removed) return error.PatchDataUnavailable; 384 385 var patch = record.event; 386 patch.title = input.title; 387 patch.tags = input.tags; 388 patch.description = input.description; 389 if (!std.mem.eql(u8, patch.target_branch, input.target_branch)) patch.revision = null; 390 patch.target_branch = input.target_branch; 391 try evt.consume(.server, .fork, .xit, repo_opts, io, allocator, &fork_repo, evt.events_ref, &.{.{ 392 .id = input.id, 393 .timestamp = input.timestamp, 394 .author = input.author, 395 .event = .{ .patch = patch }, 396 }}); 397 return true; 398 } 399 400 // merge the selected patch revision into its target branch 401 pub fn merge( 402 comptime repo_opts: rp.RepoOpts(.xit), 403 io: std.Io, 404 allocator: std.mem.Allocator, 405 repo_root_path: []const u8, 406 target_repo: *rp.Repo(.xit, repo_opts), 407 input: MergeInput, 408 ) !void { 409 const patch_id = try evt.parseEventId(&input.id); 410 errdefer |err| { 411 if (err == error.PatchDataUnavailable or err == error.PatchOutOfDate) { 412 refreshMergeability(repo_opts, io, allocator, target_repo, patch_id); 413 } 414 } 415 var arena = std.heap.ArenaAllocator.init(allocator); 416 defer arena.deinit(); 417 418 // validate the target patch 419 const target_moment = try evt.currentMoment(repo_opts, target_repo); 420 const patch_record = (try evt.Patch.readById(evt.EventDB(repo_opts.hash), repo_opts.hash, target_moment, &arena, &patch_id)) orelse return error.InvalidPatch; 421 if (patch_record.removed) return error.InvalidPatch; 422 switch (patch_record.event.status) { 423 .open => {}, 424 .closed => return error.PatchClosed, 425 .merged => return error.PatchAlreadyMerged, 426 } 427 const selected = patch_record.event.revision orelse return error.PatchNotPushed; 428 const target_ref = rf.Ref{ .kind = .head, .name = patch_record.event.target_branch }; 429 430 // open the fork 431 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &input.id); 432 var fork_repo = rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }) catch return error.PatchDataUnavailable; 433 defer fork_repo.deinit(io, allocator); 434 // select the commit and merge identity 435 const merge_oid = oidArray(repo_opts.hash, switch (input.revision) { 436 .squash => selected.squash_oid, 437 .source => selected.source_oid, 438 }) catch return error.InvalidPatch; 439 const identity = try std.fmt.allocPrint(arena.allocator(), "{s} <{s}>", .{ input.author.name, input.author.email }); 440 441 // merge the code and events in one target transaction 442 { 443 const DB = rp.Repo(.xit, repo_opts).DB; 444 const State = rp.Repo(.xit, repo_opts).State; 445 const Ctx = struct { 446 core: *rp.Repo(.xit, repo_opts).Core, 447 fork_repo: *rp.Repo(.xit, repo_opts), 448 io: std.Io, 449 allocator: std.mem.Allocator, 450 patch_id: [evt.event_id_size]u8, 451 expected_patch: evt.Patch, 452 target_ref: rf.Ref, 453 merge_oid: [hash.hexLen(repo_opts.hash)]u8, 454 revision: MergeRevision, 455 identity: []const u8, 456 author: evt.CommitAuthor, 457 timestamp: u64, 458 459 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 460 var moment = try DB.HashMap(.read_write).init(cursor.*); 461 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 462 463 var check_arena = std.heap.ArenaAllocator.init(ctx.allocator); 464 defer check_arena.deinit(); 465 466 // require the fork's newest revision while both repos are locked 467 const selected_revision = ctx.expected_patch.revision.?; 468 const revision_id = try evt.parseEventId(&selected_revision.id); 469 const fork_moment = try evt.currentMoment(repo_opts, ctx.fork_repo); 470 const newest = (try evt.PatchRev.readNewest(evt.EventDB(repo_opts.hash), repo_opts.hash, fork_moment, &check_arena)) orelse return error.PatchDataUnavailable; 471 if (!std.mem.eql(u8, &newest.id, &revision_id) or 472 !selected_revision.matches(newest.record)) return error.PatchOutOfDate; 473 474 const availability = try readMergeability(repo_opts, state.readOnly(), ctx.io, &check_arena, &ctx.patch_id, ctx.expected_patch); 475 switch (availability.get(ctx.revision)) { 476 .clean => {}, 477 .conflict => return error.MergeConflict, 478 .unknown => return error.MergeCheckUnavailable, 479 } 480 481 // copy the selected commit and its dependencies 482 { 483 var fork_repo_moment = try ctx.fork_repo.core.latestMoment(); 484 const fork_state = State(.read_only){ .core = &ctx.fork_repo.core, .extra = .{ .moment = &fork_repo_moment } }; 485 var objects = try obj.ObjectIterator(.xit, repo_opts).init(fork_state, ctx.io, ctx.allocator, .{ .kind = .all }); 486 defer objects.deinit(); 487 try objects.include(&ctx.merge_oid); 488 try obj.copyFromObjectIterator(.xit, repo_opts, state, .xit, repo_opts, &objects, ctx.io, null); 489 } 490 491 // import the revision and mark the patch merged 492 if (!try importMergedFromFork(repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.fork_repo, &ctx.patch_id, &ctx.merge_oid, ctx.expected_patch, ctx.author, ctx.timestamp)) return error.PatchOutOfDate; 493 494 // merge the selected commit 495 { 496 var merge_result = try mrg.Merge(.xit, repo_opts).init(state, ctx.io, ctx.allocator, .{ 497 .kind = .full, 498 .action = .{ .new = .{ .source = &.{.{ .oid = &ctx.merge_oid }}, .algo = .patch } }, 499 .commit_metadata = .{ 500 .author = ctx.identity, 501 .committer = ctx.identity, 502 .message = ctx.expected_patch.title, 503 .timestamp = ctx.timestamp, 504 }, 505 }, ctx.target_ref, null); 506 defer merge_result.deinit(); 507 switch (merge_result.result) { 508 .conflict => return error.MergeConflict, 509 .success, .nothing, .fast_forward => {}, 510 .clean => unreachable, 511 } 512 } 513 514 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "merge patch" }); 515 } 516 }; 517 518 try fork_repo.core.db_file.lock(io, .shared); 519 defer fork_repo.core.db_file.unlock(io); 520 try target_repo.core.db_file.lock(io, .exclusive); 521 defer target_repo.core.db_file.unlock(io); 522 523 const history = try DB.ArrayList(.read_write).init(target_repo.core.db.rootCursor()); 524 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 525 .core = &target_repo.core, 526 .fork_repo = &fork_repo, 527 .io = io, 528 .allocator = allocator, 529 .patch_id = patch_id, 530 .expected_patch = patch_record.event, 531 .target_ref = target_ref, 532 .merge_oid = merge_oid, 533 .revision = input.revision, 534 .identity = identity, 535 .author = input.author, 536 .timestamp = input.timestamp, 537 }); 538 } 539 refreshMergeability(repo_opts, io, allocator, target_repo, null); 540 } 541 542 // merge a published patch and remove its fork 543 pub fn mergeAndRemoveFork( 544 comptime repo_opts: rp.RepoOpts(.xit), 545 io: std.Io, 546 allocator: std.mem.Allocator, 547 repo_root_path: []const u8, 548 admin_repo: *rp.Repo(.xit, evt.admin_repo_opts), 549 target_repo: *rp.Repo(.xit, repo_opts), 550 input: MergeInput, 551 ) !void { 552 try merge(repo_opts, io, allocator, repo_root_path, target_repo, input); 553 try fork.remove(io, allocator, repo_root_path, admin_repo, &input.id, null, input.author); 554 } 555 556 fn commitAuthor(line: []const u8) !evt.CommitAuthor { 557 const open = std.mem.lastIndexOfScalar(u8, line, '<') orelse return error.AuthorNotFound; 558 const close = std.mem.indexOfScalarPos(u8, line, open + 1, '>') orelse return error.AuthorNotFound; 559 const name = std.mem.trimEnd(u8, line[0..open], " "); 560 if (name.len == 0 or close == open + 1) return error.AuthorNotFound; 561 return .{ .name = name, .email = line[open + 1 .. close] }; 562 } 563 564 // import a revision after detecting a client-side merge 565 fn importMerged( 566 comptime repo_opts: rp.RepoOpts(.xit), 567 state: rp.Repo(.xit, repo_opts).State(.read_write), 568 db: *evt.EventDB(repo_opts.hash), 569 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 570 io: std.Io, 571 allocator: std.mem.Allocator, 572 repo_root_path: []const u8, 573 patch_id: *const [evt.event_id_size]u8, 574 merged_oid: *const [hash.hexLen(repo_opts.hash)]u8, 575 ) !void { 576 var arena = std.heap.ArenaAllocator.init(allocator); 577 defer arena.deinit(); 578 579 const patch_hex = std.fmt.bytesToHex(patch_id.*, .lower); 580 const fork_path = try fork.forkPath(arena.allocator(), repo_root_path, &patch_hex); 581 var fork_repo = try rp.Repo(.xit, repo_opts).open(io, allocator, .{ .path = fork_path, .require_repo_root = true }); 582 defer fork_repo.deinit(io, allocator); 583 584 _ = try importMergedFromFork(repo_opts, state, db, moment, io, allocator, &fork_repo, patch_id, merged_oid, null, null, 0); 585 } 586 587 // import the revision and mark its patch merged in the current transaction 588 fn importMergedFromFork( 589 comptime repo_opts: rp.RepoOpts(.xit), 590 state: rp.Repo(.xit, repo_opts).State(.read_write), 591 db: *evt.EventDB(repo_opts.hash), 592 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 593 io: std.Io, 594 allocator: std.mem.Allocator, 595 fork_repo: *rp.Repo(.xit, repo_opts), 596 patch_id: *const [evt.event_id_size]u8, 597 merged_oid: *const [hash.hexLen(repo_opts.hash)]u8, 598 expected_patch: ?evt.Patch, 599 merged_author: ?evt.CommitAuthor, 600 merged_timestamp: u64, 601 ) !bool { 602 const DB = evt.EventDB(repo_opts.hash); 603 var arena = std.heap.ArenaAllocator.init(allocator); 604 defer arena.deinit(); 605 606 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 607 const patch_record = (try evt.Patch.readById(DB, repo_opts.hash, haxy_moment, &arena, patch_id)) orelse return false; 608 const selected = patch_record.event.revision orelse return false; 609 if (patch_record.removed or patch_record.event.status.kind() == .merged) return false; 610 if (expected_patch) |expected| { 611 if (!evt.fieldEqual(evt.Patch, expected, patch_record.event)) return false; 612 } 613 const revision_id = try evt.parseEventId(&selected.id); 614 if (!selected.includesOid(merged_oid)) return false; 615 616 const fork_moment = try evt.currentMoment(repo_opts, fork_repo); 617 const revision = (try evt.PatchRev.readById(DB, repo_opts.hash, fork_moment, &arena, &revision_id)) orelse return false; 618 if (!selected.matches(revision)) return false; 619 620 var fork_repo_moment = try fork_repo.core.latestMoment(); 621 const fork_state = rp.Repo(.xit, repo_opts).State(.read_only){ .core = &fork_repo.core, .extra = .{ .moment = &fork_repo_moment } }; 622 var event_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 623 if (revision.event_oid.len != event_oid.len) return false; 624 @memcpy(&event_oid, revision.event_oid); 625 var event_object = try obj.Object(.xit, repo_opts).initCommit(fork_state, io, allocator, &event_oid); 626 defer event_object.deinit(); 627 const original_author = try commitAuthor(event_object.content.commit.metadata.author orelse return false); 628 629 var events: [2]evt.EventWithId = undefined; 630 var event_count: usize = 0; 631 const current_revision = try evt.PatchRev.readById(DB, repo_opts.hash, haxy_moment, &arena, &revision_id); 632 var tree_entries: [2]evt.EventTreeEntry = undefined; 633 const needs_import = if (current_revision) |existing| existing.removed else true; 634 if (needs_import) { 635 tree_entries = .{ 636 .{ .tree = .{ .name = "base", .oid = revision.base_tree_oid } }, 637 .{ .tree = .{ .name = "head", .oid = revision.head_tree_oid } }, 638 }; 639 events[event_count] = .{ 640 .id = selected.id, 641 .timestamp = event_object.content.commit.metadata.timestamp, 642 .author = original_author, 643 .tree_entries = &tree_entries, 644 .event = .{ .patchrev = revision.event }, 645 }; 646 event_count += 1; 647 } else { 648 const existing = current_revision orelse unreachable; 649 if (!selected.matches(existing)) return error.InvalidPatch; 650 } 651 652 var patch = patch_record.event; 653 patch.status = .{ .merged = merged_oid }; 654 events[event_count] = .{ 655 .id = std.fmt.bytesToHex(patch_id.*, .lower), 656 .timestamp = if (merged_author != null) merged_timestamp else @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 657 .author = merged_author orelse original_author, 658 .event = .{ .patch = patch }, 659 }; 660 event_count += 1; 661 662 try evt.commitEvents(.xit, repo_opts, state, io, allocator, evt.events_ref, events[0..event_count], null); 663 if (!try evt.consumeInTransaction(.repo, .xit, repo_opts, state, db, moment, io, allocator, evt.events_ref)) return error.CancelTransaction; 664 return true; 665 } 666 667 // find patches merged by commits received in a push 668 pub fn detectMerged( 669 comptime repo_opts: rp.RepoOpts(.xit), 670 state: rp.Repo(.xit, repo_opts).State(.read_write), 671 db: *evt.EventDB(repo_opts.hash), 672 moment: *evt.EventDB(repo_opts.hash).HashMap(.read_write), 673 io: std.Io, 674 allocator: std.mem.Allocator, 675 repo_root_path: []const u8, 676 updates: []const xit.net_server_receive_pack.AppliedRefUpdate, 677 error_writer: *std.Io.Writer, 678 ) !void { 679 const DB = evt.EventDB(repo_opts.hash); 680 var arena = std.heap.ArenaAllocator.init(allocator); 681 defer arena.deinit(); 682 683 const haxy_moment = try evt.currentMomentFromRepoMoment(repo_opts.hash, moment.readOnly()); 684 const revisions_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, evt.Patch.revision_to_id_set_key)) orelse return; 685 const revisions = try DB.HashMap(.read_only).init(revisions_cursor); 686 var events_ref_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 687 const events_ref_path = try evt.events_ref.toPath(&events_ref_buffer); 688 const heads_prefix = "refs/heads/"; 689 for (updates) |update| { 690 if (!std.mem.startsWith(u8, update.ref_name, heads_prefix) or 691 std.mem.eql(u8, update.ref_name, events_ref_path) or 692 std.mem.eql(u8, update.old_oid, update.new_oid)) continue; 693 if (update.old_oid.len != hash.hexLen(repo_opts.hash) or 694 update.new_oid.len != hash.hexLen(repo_opts.hash)) return error.InvalidOid; 695 var old_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 696 var new_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 697 @memcpy(&old_oid, update.old_oid); 698 @memcpy(&new_oid, update.new_oid); 699 if (std.mem.allEqual(u8, &new_oid, '0')) continue; 700 701 var commits = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, arena.allocator(), .{ .kind = .commit }); 702 defer commits.deinit(); 703 if (!std.mem.allEqual(u8, &old_oid, '0')) try commits.exclude(&old_oid); 704 try commits.include(&new_oid); 705 var revision_key_buffer: [rf.MAX_REF_CONTENT_SIZE + 1 + hash.hexLen(repo_opts.hash)]u8 = undefined; 706 while (try commits.next(arena.allocator())) |commit| { 707 defer commit.deinit(); 708 const key = try std.fmt.bufPrint(&revision_key_buffer, "{s}\x00{s}", .{ update.ref_name[heads_prefix.len..], &commit.oid }); 709 const ids_cursor = try revisions.getCursor(hash.hashInt(repo_opts.hash, key)) orelse continue; 710 const ids = try DB.CountedHashSet(.read_only).init(ids_cursor); 711 var ids_iter = try ids.iterator(); 712 while (try ids_iter.next()) |cursor| { 713 const pair = try cursor.readKeyValuePair(); 714 var patch_id: [evt.event_id_size]u8 = undefined; 715 if ((try pair.key_cursor.readBytes(&patch_id)).len != patch_id.len) return error.InvalidPatch; 716 const patch_hex = std.fmt.bytesToHex(patch_id, .lower); 717 importMerged(repo_opts, state, db, moment, io, allocator, repo_root_path, &patch_id, &commit.oid) catch |err| { 718 serve_common.logError(io, error_writer, "failed to mark patch {s} as merged: {s}\n", .{ &patch_hex, @errorName(err) }); 719 continue; 720 }; 721 } 722 } 723 } 724 } 725