╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
305 allocator: std.mem.Allocator, 306 repo: *rp.Repo(repo_kind, repo_opts), 307 ref: rf.Ref, 308 events: []const EventWithId, 309 ) !void { 310 for (events) |event| { 311 if (!role.allows(std.meta.activeTag(event.event))) return error.EventKindNotAllowed; 312 } 313 314 var resolved_remote_name: ?[]u8 = null; 315 defer if (resolved_remote_name) |name| allocator.free(name); 316 317 // a branch that only exists on a remote is consumed from its remote-tracking 318 // ref, while commits go on the local branch, continuing from the remote tip 319 // so a cloned repo's local branch stays connected to the server history 320 const resolved_ref: rf.Ref, const first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8 = blk: { 321 if (null != try repo.readRef(io, ref)) break :blk .{ ref, null }; 322 var remotes = try repo.listRemotes(io, allocator); 323 defer remotes.deinit(); 324 for (remotes.sections.keys()) |remote_name| { 325 const remote_ref: rf.Ref = .{ .kind = .{ .remote = remote_name }, .name = ref.name }; 326 if (try repo.readRef(io, remote_ref)) |oid| { 327 if (events.len > 0) break :blk .{ ref, .{oid} }; 328 const name = try allocator.dupe(u8, remote_name); 329 resolved_remote_name = name; 330 break :blk .{ rf.Ref{ .kind = .{ .remote = name }, .name = ref.name }, null }; 331 } 332 } 333 if (events.len > 0) break :blk .{ ref, null }; 334 // the branch is gone (or never existed): drop any db from a previous 335 // sync rather than serving its issues indefinitely 336 if (repo_kind == .git) try LocalEventDB(repo_opts.hash).delete(io, repo.core.repo_dir); 337 return; 338 }; 339 340 switch (repo_kind) { 341 .git => { 342 try commitEvents(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, ref, events, first_parent_oids); 343 344 var event_db = try LocalEventDB(repo_opts.hash).open(io, allocator, repo.core.repo_dir); 345 defer event_db.deinit(io, allocator); 346 347 try event_db.consume(repo_kind, repo_opts, io, allocator, repo, resolved_ref); 348 }, 349 .xit => { 350 const DB = rp.Repo(.xit, repo_opts).DB; 351 const State = rp.Repo(.xit, repo_opts).State; 352 353 const Ctx = struct { 354 core: *rp.Repo(.xit, repo_opts).Core, 355 io: std.Io, 356 allocator: std.mem.Allocator, 357 ref: rf.Ref, 358 events: []const EventWithId, 359 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 360 361 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 362 var moment = try DB.HashMap(.read_write).init(cursor.*); 363 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 364 365 try commitEvents(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.ref, ctx.events, ctx.first_parent_oids); 366 if (!try consumeInTransaction(role, .xit, repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 367 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "event" }); 368 } 369 }; 370 371 try repo.core.db_file.lock(io, .exclusive); 372 defer repo.core.db_file.unlock(io); 373 374 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 375 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 376 .core = &repo.core, 377 .io = io, 378 .allocator = allocator, 379 .ref = resolved_ref, 380 .events = events, 381 .first_parent_oids = first_parent_oids, 382 }) catch |err| switch (err) { 383 error.CancelTransaction => return, 384 else => |e| return e, 385 }; 386 }, 387 } 388 389 if (role == .repo and repo_kind == .xit and host_kind == .server) { 390 // since patches may have been updated, we need to recheck their mergeability 391 if (events.len == 0) { 392 // we consumed events already on the ref, and we don't know what specific 393 // patches may have been updated, so refresh all of them 394 pch.refreshMergeability(repo_opts, io, allocator, repo, null); 395 } else { 396 // we consumed specific events so we can refresh only the patches that were updated 397 for (events) |event| { 398 if (event.event != .patch) continue; 399 const id = parseEventId(&event.id) catch continue; 400 pch.refreshMergeability(repo_opts, io, allocator, repo, id); 401 } 402 } 403 } 404 } 405 406 // merge the remote events ref into the local events ref without touching head, 407 // the index, or the worktree 408 pub fn mergeEvents( 409 comptime repo_kind: rp.RepoKind, 410 comptime repo_opts: rp.RepoOpts(repo_kind), 411 io: std.Io, 412 allocator: std.mem.Allocator, 413 repo: *rp.Repo(repo_kind, repo_opts), 414 remote_ref: rf.Ref, 415 ) !void { 416 switch (repo_kind) { 417 .git => _ = try mergeEventsInTransaction(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, remote_ref), 418 .xit => { 419 const DB = rp.Repo(.xit, repo_opts).DB; 420 const State = rp.Repo(.xit, repo_opts).State; 421 422 const Ctx = struct { 423 core: *rp.Repo(.xit, repo_opts).Core, 424 io: std.Io, 425 allocator: std.mem.Allocator, 426 remote_ref: rf.Ref, 427 428 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 429 var moment = try DB.HashMap(.read_write).init(cursor.*); 430 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 431 if (!try mergeEventsInTransaction(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.remote_ref)) return error.CancelTransaction; 432 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "event" }); 433 } 434 }; 435 436 try repo.core.db_file.lock(io, .exclusive); 437 defer repo.core.db_file.unlock(io); 438 439 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 440 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 441 .core = &repo.core, 442 .io = io, 443 .allocator = allocator, 444 .remote_ref = remote_ref, 445 }) catch |err| switch (err) { 446 error.CancelTransaction => {}, 447 else => |e| return e, 448 }; 449 }, 450 } 451 } 452 453 fn mergeEventsInTransaction( 454 comptime repo_kind: rp.RepoKind, 455 comptime repo_opts: rp.RepoOpts(repo_kind), 456 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 457 io: std.Io, 458 allocator: std.mem.Allocator, 459 remote_ref: rf.Ref, 460 ) !bool { 461 const remote_oid = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = remote_ref })) orelse return false; 462 const local_oid_maybe = try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = events_ref }); 463 464 var ref_path_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 465 const ref_path = try events_ref.toPath(&ref_path_buffer); 466 const local_oid = local_oid_maybe orelse { 467 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 468 return true; 469 }; 470 if (std.mem.eql(u8, &local_oid, &remote_oid)) return false; 471 472 const ancestor_maybe: ?[hash.hexLen(repo_opts.hash)]u8 = mrg.commonAncestor(repo_kind, repo_opts, state.readOnly(), io, allocator, &local_oid, &remote_oid) catch |err| switch (err) { 473 error.NoCommonAncestor => null, 474 else => return err, 475 }; 476 if (ancestor_maybe) |ancestor| { 477 if (std.mem.eql(u8, &ancestor, &remote_oid)) return false; 478 if (std.mem.eql(u8, &ancestor, &local_oid)) { 479 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 480 return true; 481 } 482 } 483 484 const parent_oids = [_][hash.hexLen(repo_opts.hash)]u8{ local_oid, remote_oid }; 485 var tree = try obj.Tree.init(allocator); 486 defer tree.deinit(); 487 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 488 .message = "merge events", 489 .parent_oids = &parent_oids, 490 }, &tree, events_ref); 491 return true; 492 } 493 494 // the file an attach event carries: the one entry in its commit's tree. the 495 // name and oid are allocated in `arena`. 496 fn attachedFile( 497 comptime repo_kind: rp.RepoKind, 498 comptime repo_opts: rp.RepoOpts(repo_kind), 499 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 500 io: std.Io, 501 allocator: std.mem.Allocator, 502 arena: *std.heap.ArenaAllocator, 503 tree_oid: *const [hash.hexLen(repo_opts.hash)]u8, 504 ) !struct { name: []const u8, oid: []const u8 } { 505 var tree_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, tree_oid); 506 defer tree_object.deinit(); 507 508 const entries = switch (tree_object.content) { 509 .tree => |tree| tree.entries, 510 else => return error.InvalidAttachment, 511 }; 512 if (entries.count() != 1) return error.InvalidAttachment; 513 const entry = entries.values()[0]; 514 if (entry.isTree()) return error.InvalidAttachment; 515 const name = entries.keys()[0]; 516 if (!Attachment.nameValid(name)) return error.InvalidAttachment; 517 518 const oid = std.fmt.bytesToHex(entry.oid, .lower); 519 var object_reader = try obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, &oid); 520 defer object_reader.deinit(); 521 if (object_reader.header().kind != .blob) return error.InvalidAttachment; 522 523 return .{ 524 .name = try arena.allocator().dupe(u8, name), 525 .oid = try arena.allocator().dupe(u8, &oid), 526 }; 527 } 528 529 fn commitIdentity(line: []const u8) ![]const u8 { 530 const close = std.mem.indexOfScalar(u8, line, '>') orelse return error.AuthorNotFound; 531 return line[0 .. close + 1]; 532 } 533 534 // commit each event as a JSON commit message on `ref` through `state`, so a 535 // xit repo can write them inside an already-open transaction 536 pub fn commitEvents( 537 comptime repo_kind: rp.RepoKind, 538 comptime repo_opts: rp.RepoOpts(repo_kind), 539 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 540 io: std.Io, 541 allocator: std.mem.Allocator, 542 ref: rf.Ref, 543 events: []const EventWithId, 544 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 545 ) !void { 546 var parent_oids: ?[]const [hash.hexLen(repo_opts.hash)]u8 = if (first_parent_oids) |*oids| oids else null; 547 548 var json: std.Io.Writer.Allocating = .init(allocator); 549 defer json.deinit(); 550 551 for (events) |event| { 552 json.clearRetainingCapacity(); 553 try std.json.Stringify.value(event, .{}, &json.writer); 554 if (json.written().len > max_event_size) return error.EventTooLarge; 555 const author = try std.fmt.allocPrint(allocator, "{s} <{s}>", .{ event.author.name, event.author.email }); 556 defer allocator.free(author); 557 558 // every event gets a fresh tree 559 var tree = try obj.Tree.init(allocator); 560 defer tree.deinit(); 561 for (event.tree_entries) |entry| { 562 switch (entry) { 563 .blob => |blob| { 564 var oid_bytes = [_]u8{0} ** hash.byteLen(repo_opts.hash); 565 try obj.writeObject(repo_kind, repo_opts, state, io, allocator, blob.reader, .{ .kind = .blob, .size = blob.size }, &oid_bytes); 566 try tree.addBlobEntry(.{ .content = .{ .unix_permission = 0o644, .object_type = .regular_file } }, blob.name, &oid_bytes); 567 }, 568 .tree => |nested| { 569 var oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 570 _ = try std.fmt.hexToBytes(&oid_bytes, nested.oid); 571 if (!std.mem.eql(u8, nested.oid, &std.fmt.bytesToHex(oid_bytes, .lower))) return error.InvalidTreeObject; 572 try tree.addTreeEntry(nested.name, &oid_bytes); 573 }, 574 } 575 } 576 577 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 578 .author = author, 579 .message = json.written(), 580 .timestamp = event.timestamp, 581 .parent_oids = parent_oids, 582 .allow_empty = true, 583 }, &tree, ref); 584 // later events parent on the ref's new tip 585 parent_oids = null; 586 } 587 } 588 589 // a standalone event db holding events consumed from a local repo's events 590 // branch. it lives inside the repo dir but is not part of the repo's own data, 591 // so viewing a repo never mutates it. 592 pub fn LocalEventDB(comptime hash_kind: hash.HashKind) type { 593 return struct { 594 file: std.Io.File, 595 buffer: *std.Io.Writer.Allocating, 596 db: *EventDB(hash_kind), 597 598 const db_name = "haxy"; 599 const Self = @This(); 600 601 // open the db in `repo_dir` for writing, creating it if it doesn't exist 602 pub fn open(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !Self { 603 const file = try repo_dir.createFile(io, db_name, .{ .truncate = false, .read = true, .lock = .exclusive }); 604 return fromFile(io, allocator, file); 605 } 606 607 // open the db in `repo_dir` for reading, or null if it doesn't exist 608 pub fn openReadOnly(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !?Self { 609 const file = repo_dir.openFile(io, db_name, .{ .mode = .read_write, .lock = .shared }) catch |err| switch (err) { 610 error.FileNotFound => return null, 611 else => |e| return e, 612 }; 613 return try fromFile(io, allocator, file); 614 } 615 616 // remove the db from `repo_dir`, so a repo whose events branch 617 // disappeared doesn't keep showing stale issues 618 pub fn delete(io: std.Io, repo_dir: std.Io.Dir) !void { 619 repo_dir.deleteFile(io, db_name) catch |err| switch (err) { 620 error.FileNotFound => {}, 621 else => |e| return e, 622 }; 623 } 624 625 fn fromFile(io: std.Io, allocator: std.mem.Allocator, file: std.Io.File) !Self { 626 errdefer file.close(io); 627 628 const buffer = try allocator.create(std.Io.Writer.Allocating); 629 errdefer allocator.destroy(buffer); 630 buffer.* = std.Io.Writer.Allocating.init(allocator); 631 errdefer buffer.deinit(); 632 633 const db = try allocator.create(EventDB(hash_kind)); 634 errdefer allocator.destroy(db); 635 db.* = try EventDB(hash_kind).init(.{ .io = io, .file = file, .buffer = buffer }); 636 637 return .{ .file = file, .buffer = buffer, .db = db }; 638 } 639 640 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 641 self.file.close(io); 642 self.buffer.deinit(); 643 allocator.destroy(self.buffer); 644 allocator.destroy(self.db); 645 } 646 647 // consume the events on `repo`'s `ref` into this db. the db must come 648 // from `open`, whose handle holds the exclusive lock guarding the 649 // transaction. 650 pub fn consume( 651 self: *Self, 652 comptime repo_kind: rp.RepoKind, 653 comptime repo_opts: rp.RepoOpts(repo_kind), 654 io: std.Io, 655 allocator: std.mem.Allocator, 656 repo: *rp.Repo(repo_kind, repo_opts), 657 ref: rf.Ref, 658 ) !void { 659 comptime if (repo_opts.hash != hash_kind) @compileError("the repo must use the db's hash kind"); 660 const DB = EventDB(hash_kind); 661 662 const Ctx = struct { 663 repo: *rp.Repo(repo_kind, repo_opts), 664 db: *DB, 665 io: std.Io, 666 allocator: std.mem.Allocator, 667 ref: rf.Ref, 668 669 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 670 var moment = try DB.HashMap(.read_write).init(cursor.*); 671 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{} }; 672 if (!try consumeInTransaction(.repo, repo_kind, repo_opts, state, ctx.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 673 } 674 }; 675 676 const history = try DB.ArrayList(.read_write).init(self.db.rootCursor()); 677 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 678 .repo = repo, 679 .db = self.db, 680 .io = io, 681 .allocator = allocator, 682 .ref = ref, 683 }) catch |err| switch (err) { 684 error.CancelTransaction => {}, 685 else => |e| return e, 686 }; 687 } 688 }; 689 } 690 691 // consume the events on `ref` into the db `moment` writes to, returning false 692 // if there was nothing to do. events are read from `state`'s repo, which 693 // needn't be the repo backing the db — that's how a local (possibly 694 // git-backed) repo's events land in a standalone db. 695 pub fn consumeInTransaction( 696 comptime role: RepoRole, 697 comptime repo_kind: rp.RepoKind, 698 comptime repo_opts: rp.RepoOpts(repo_kind), 699 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 700 db: *EventDB(repo_opts.hash), 701 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 702 io: std.Io, 703 allocator: std.mem.Allocator, 704 ref: rf.Ref, 705 ) !bool { 706 const DB = EventDB(repo_opts.hash); 707 const read_state = state.readOnly(); 708 709 // the last_object_id represents the object id that was last consumed 710 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 711 if (try moment.getCursor(hash.hashInt(repo_opts.hash, last_object_id_key))) |last_object_id_cursor| { 712 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 713 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 714 last_object_id_maybe = last_object_id_buffer; 715 } 716 717 // the tip was already consumed, so there is nothing to do 718 if (last_object_id_maybe) |*last_object_id| { 719 const tip_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 720 var tip: [hash.byteLen(repo_opts.hash)]u8 = undefined; 721 _ = try std.fmt.hexToBytes(&tip, &tip_hex); 722 if (std.mem.eql(u8, last_object_id, &tip)) return false; 723 } 724 725 // the list with all of haxy's state, including materialized views. 726 // the reason it is a list is so we can keep every previous haxy 727 // state, making it easy to revert to an older state if the user 728 // rebases some of the past commits. 729 const haxy_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, materialized_key)); 730 const haxy = try DB.ArrayList(.read_write).init(haxy_cursor); 731 732 // add a new item to the haxy list created above. 733 // we call the item haxy_moments. it is a map of object id to haxy moment. 734 // in other words, it maps each object id to a hash map containing the 735 // state that the database was in when that object id was consumed. 736 var haxy_moments_cursor = try haxy.appendCursor(); 737 // use the previous haxy_moments as the basis for this one if it exists 738 if (try haxy.getCursor(-2)) |last_haxy_moments_cursor| { 739 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 740 } 741 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 742 743 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 744 defer commit_iter.deinit(io, allocator); 745 746 // if there are no events to process, look at the oid at HEAD and update 747 // the last_object_id to point to it. this is important in situations 748 // where we do a merge and then force-push to remove the merge. see the 749 // merge test for an example. 750 if (commit_iter.newest_object_id == null) { 751 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 752 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 753 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 754 755 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 756 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 757 758 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 759 const moment_index = try moment_index_cursor.readUint(); 760 761 try haxy.slice(moment_index + 1); 762 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = &head_oid }); 763 return true; 764 } 765 766 // if this branch was rebased and force pushed, we need to detect that and 767 // properly revert the haxy state to the last valid state. we detect this 768 // by simply asking if the last event is a descendent of the last event 769 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 770 if (last_object_id_maybe) |*last_object_id| { 771 var is_rebased = false; 772 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 773 774 _ = mrg.getDescendent( 775 repo_kind, 776 repo_opts, 777 read_state, 778 io, 779 allocator, 780 &std.fmt.bytesToHex(last_object_id, .lower), 781 &std.fmt.bytesToHex(&newest_object_id, .lower), 782 ) catch |err| switch (err) { 783 error.DescendentNotFound => is_rebased = true, 784 else => |e| return e, 785 }; 786 787 if (is_rebased) { 788 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 789 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 790 defer oldest_object.deinit(); 791 792 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 793 switch (parent_oids.len) { 794 0 => { 795 // the branch was rebased all the way to the very beginning. 796 // we have a repo event with no parent, which means it is now 797 // the very first event. all we need to do is set the haxy list 798 // to be empty and make a new haxy_moments map to work with. 799 800 try haxy.slice(0); 801 haxy_moments_cursor = try haxy.appendCursor(); 802 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 803 804 last_object_id_maybe = null; 805 }, 806 1 => { 807 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 808 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 809 810 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 811 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 812 813 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 814 const old_moment_index = try old_moment_index_cursor.readUint(); 815 816 // resize the haxy list so we truncate all the moments that were 817 // created after the parent_oid was consumed 818 try haxy.slice(old_moment_index + 1); 819 820 // make a new haxy moment and set its initial value to the last haxy moment 821 haxy_moments_cursor = try haxy.appendCursor(); 822 const old_haxy_moments_cursor = try haxy.getCursor(old_moment_index) orelse return error.CursorNotFound; 823 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 824 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 825 826 last_object_id_maybe = oid; 827 }, 828 else => return error.UnexpectedParentCount, 829 } 830 } 831 } 832 833 while (try commit_iter.next()) |repo_event_oid| { 834 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 835 defer commit_object.deinit(); 836 837 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 838 839 // create a moment for this object id 840 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 841 842 // if there was a previous object id, set this haxy moment's initial value to it. 843 // this efficiently "clones" the map so we make further modifications based on it. 844 if (parent_oids.len > 0) { 845 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 846 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 847 848 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 849 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 850 } 851 852 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 853 854 // graph generation gives every event a causal order independent of 855 // commit timestamps. concurrent events tie-break by id in their index. 856 var event_order: u64 = 1; 857 for (parent_oids) |*parent_oid| { 858 var parent_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 859 _ = try std.fmt.hexToBytes(&parent_id, parent_oid); 860 const parent_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &parent_id)) orelse return error.CursorNotFound; 861 const parent = try DB.HashMap(.read_only).init(parent_cursor); 862 const parent_order_cursor = try parent.getCursor(hash.hashInt(repo_opts.hash, event_order_key)) orelse return error.CursorNotFound; 863 const parent_order = try parent_order_cursor.readUint(); 864 event_order = @max(event_order, parent_order +| 1); 865 } 866 try haxy_moment.put(hash.hashInt(repo_opts.hash, event_order_key), .{ .uint = event_order }); 867 868 // merge changes from every parent after the first parent. the common 869 // ancestor is the baseline, so a later parent only contributes records 870 // it changed relative to the merge base. only the record maps are 871 // merged; every other view is derived from them, and each kind's 872 // `consume` re-derives its own as the winning records are written. 873 if (parent_oids.len > 1) { 874 for (parent_oids[1..]) |*parent_oid| { 875 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 876 _ = try std.fmt.hexToBytes(&oid, parent_oid); 877 878 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 879 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 880 881 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 882 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 883 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 884 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 885 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 886 887 inline for (std.meta.fields(Event)) |field| { 888 const T = @typeInfo(field.type).optional.child; 889 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 890 } 891 } 892 } 893 894 // associate this moment with the index it will first appear at in the haxy list. 895 // this will be important later so we can truncate that list if the user ever 896 // rebases starting at this object id. 897 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy.count() - 1 }); 898 899 // consume the event unless it's a merge commit 900 if (parent_oids.len <= 1) { 901 var arena = std.heap.ArenaAllocator.init(allocator); 902 defer arena.deinit(); 903 904 // read the message from the commit 905 var message: std.ArrayList(u8) = .empty; 906 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 907 908 const event_with_id = try EventWithId.fromString(&arena, message.items); 909 if (!role.allows(std.meta.activeTag(event_with_id.event))) return error.EventKindNotAllowed; 910 911 const current_event_id = try parseEventId(&event_with_id.id); 912 913 // wrap the payload into the record `consume` stores, with its 914 // commit-derived fields; on update, `consume` preserves the 915 // existing record's 916 switch (event_with_id.event) { 917 .user => |event_maybe| { 918 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 919 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 920 }, 921 .repo => |event_maybe| { 922 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 923 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 924 }, 925 .fork => |event_maybe| { 926 const record_maybe: ?Fork.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 927 try Fork.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 928 }, 929 .issue => |event_maybe| { 930 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 931 .event = event, 932 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 933 .created_order = event_order, 934 .updated_order = event_order, 935 } else null; 936 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 937 }, 938 .discuss => |event_maybe| { 939 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 940 .event = event, 941 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 942 .created_order = event_order, 943 .updated_order = event_order, 944 } else null; 945 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 946 }, 947 .comment => |event_maybe| { 948 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 949 .event = event, 950 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 951 .created_order = event_order, 952 .updated_order = event_order, 953 } else null; 954 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 955 }, 956 .attach => |event_maybe| { 957 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 958 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 959 break :blk .{ 960 .event = event, 961 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 962 .created_order = event_order, 963 .updated_order = event_order, 964 .name = entry.name, 965 .blob_oid = entry.oid, 966 }; 967 } else null; 968 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 969 }, 970 .patchrev => |event_maybe| { 971 const record_maybe: ?PatchRev.Record = if (event_maybe) |event| blk: { 972 const trees = try PatchRev.readTrees(repo_kind, repo_opts, read_state, io, allocator, &commit_object.content.commit.tree); 973 const existing_maybe = try PatchRev.readById(DB, repo_opts.hash, haxy_moment.readOnly(), &arena, &current_event_id); 974 const event_oid = std.fmt.bytesToHex(repo_event_oid, .lower); 975 976 var patch_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 977 if (existing_maybe) |existing| { 978 if (existing.patch_oid.len != patch_oid.len) return error.InvalidPatch; 979 @memcpy(&patch_oid, existing.patch_oid); 980 } else { 981 const author = try commitIdentity(commit_object.content.commit.metadata.author orelse return error.AuthorNotFound); 982 const committer = try commitIdentity(commit_object.content.commit.metadata.committer orelse author); 983 patch_oid = try PatchRev.writeSquashCommit( 984 repo_kind, 985 repo_opts, 986 state, 987 io, 988 allocator, 989 event, 990 &trees.head, 991 author, 992 committer, 993 commit_object.content.commit.metadata.timestamp, 994 ); 995 } 996 997 break :blk .{ 998 .event = event, 999 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1000 .created_order = event_order, 1001 .updated_order = event_order, 1002 .event_oid = &event_oid, 1003 .base_tree_oid = &trees.base, 1004 .head_tree_oid = &trees.head, 1005 .patch_oid = &patch_oid, 1006 }; 1007 } else null; 1008 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1009 }, 1010 .patch => |event_maybe| { 1011 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 1012 .event = event, 1013 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1014 .created_order = event_order, 1015 .updated_order = event_order, 1016 } else null; 1017 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1018 }, 1019 } 1020 } 1021 1022 // the current object id is now the last one 1023 last_object_id_maybe = repo_event_oid; 1024 1025 // prevent any of the data created above from being mutated by future iterations of this loop 1026 try db.freeze(); 1027 } 1028 1029 if (last_object_id_maybe) |*last_object_id| { 1030 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1031 } 1032 1033 return true; 1034 } 1035 1036 // the conflicted records of one kind, keyed by the same order key its id set 1037 // uses, so this doubles as the index the conflicts view lists and counts. every 1038 // value under an entry is a slot reference to a structure that already exists: 1039 // 1040 // <order key> -> conflict entry 1041 // conflicted-fields the conflicting field names, space separated 1042 // base-record the merge base's whole record 1043 // their-record the merged-in side's whole record 1044 // their-field->oid that side's field name to commit map 1045 // 1046 // our own value is the live record and our commit is in the kind's oid map, so 1047 // neither is repeated here. 1048 pub const conflicted_fields_key = "conflicted-fields"; 1049 pub const base_record_key = "base-record"; 1050 pub const their_record_key = "their-record"; 1051 pub const their_field_to_oid_key = "their-field->oid"; 1052 1053 // record the commit against every field this event changes. a merge passes no 1054 // oid, since each field's winner may come from a different side. 1055 pub fn writeOid( 1056 comptime T: type, 1057 comptime DB: type, 1058 comptime hash_kind: hash.HashKind, 1059 id_to_field_to_oid: DB.HashMap(.read_write), 1060 record_key: hash.HashInt(hash_kind), 1061 existing_maybe: ?T, 1062 event: T, 1063 event_oid: ?[]const u8, 1064 ) !void { 1065 const oid = event_oid orelse return; 1066 1067 // created only once a field actually changes 1068 var field_oids: ?DB.SortedMap(.read_write) = null; 1069 1070 inline for (std.meta.fields(T)) |field| { 1071 const changed = if (existing_maybe) |existing| 1072 !fieldEqual(field.type, @field(existing, field.name), @field(event, field.name)) 1073 else 1074 true; 1075 if (changed) { 1076 if (field_oids == null) { 1077 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1078 } 1079 if (field_oids) |map| try map.put(field.name, .{ .bytes = oid }); 1080 } 1081 } 1082 } 1083 1084 // the whole field list, space separated, is the longest it can get 1085 fn conflictedFieldsMaxLen(comptime T: type) usize { 1086 var len: usize = 0; 1087 for (std.meta.fields(T)) |field| len += field.name.len + 1; 1088 return len; 1089 } 1090 1091 pub const MergePolicy = enum { 1092 field_conflicts, 1093 target_wins, 1094 }; 1095 1096 // what a three-way merge did with a field 1097 pub const FieldMerge = enum { 1098 // the target's value stands, because neither side changed it, both made the 1099 // same change, or only the target changed it 1100 kept, 1101 parent, 1102 conflicted, 1103 }; 1104 1105 // three-way merge each field. one only the parent changed takes the parent's 1106 // value; one both sides changed differently keeps the target's. a missing 1107 // baseline makes every differing field a conflict. 1108 fn mergeFields( 1109 comptime T: type, 1110 baseline_maybe: ?T, 1111 target: T, 1112 parent: T, 1113 outcome: *[std.meta.fields(T).len]FieldMerge, 1114 ) T { 1115 var merged = target; 1116 1117 inline for (std.meta.fields(T), 0..) |field, i| { 1118 const target_value = @field(target, field.name); 1119 const parent_value = @field(parent, field.name); 1120 1121 if (!fieldEqual(field.type, target_value, parent_value)) { 1122 outcome[i] = if (baseline_maybe) |baseline| blk: { 1123 const baseline_value = @field(baseline, field.name); 1124 if (fieldEqual(field.type, target_value, baseline_value)) { 1125 @field(merged, field.name) = parent_value; 1126 break :blk .parent; 1127 } 1128 // only the target changed it 1129 if (fieldEqual(field.type, parent_value, baseline_value)) break :blk .kept; 1130 break :blk .conflicted; 1131 } else .conflicted; 1132 } 1133 } 1134 1135 return merged; 1136 } 1137 1138 // three-way merge of one kind's records from a merge parent. kinds that expose 1139 // conflicts merge field by field; the others take one whole record. the result 1140 // goes through the kind's `consume`, which re-derives the indexes from it. a 1141 // removal carries over unless the other side changed the record, so a merge 1142 // never fails. 1143 pub fn merge( 1144 comptime T: type, 1145 comptime DB: type, 1146 comptime hash_kind: hash.HashKind, 1147 allocator: std.mem.Allocator, 1148 haxy_moment: DB.HashMap(.read_write), 1149 parent_moment: DB.HashMap(.read_only), 1150 baseline_moment: DB.HashMap(.read_only), 1151 ) !void { 1152 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1153 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1154 1155 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1156 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1157 1158 var baseline_records: ?DB.HashMap(.read_only) = null; 1159 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1160 baseline_records = try DB.HashMap(.read_only).init(cursor); 1161 } 1162 1163 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1164 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1165 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1166 switch (comptime T.merge_policy) { 1167 .field_conflicts => { 1168 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1169 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1170 } 1171 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1172 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1173 } 1174 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1175 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1176 } 1177 }, 1178 .target_wins => {}, 1179 } 1180 1181 var arena = std.heap.ArenaAllocator.init(allocator); 1182 defer arena.deinit(); 1183 1184 var iter = try parent_set.iteratorFromIndex(0); 1185 while (try iter.next()) |kv_pair_cursor| { 1186 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1187 const record_key = hash.hashInt(hash_kind, &event_id); 1188 1189 _ = arena.reset(.retain_capacity); 1190 1191 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1192 const parent_slot = parent_record_cursor.slot(); 1193 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1194 1195 // the parent left this record alone 1196 if (baseline_slot) |slot| { 1197 if (slot.eql(parent_slot)) continue; 1198 } 1199 1200 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1201 1202 // re-derived every iteration, since `consume` writes through its own 1203 // handles 1204 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1205 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1206 1207 // a record the target doesn't have arrives wholesale from the parent 1208 var outcome: [std.meta.fields(T).len]FieldMerge = @splat(.parent); 1209 var merged = parent_record; 1210 1211 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1212 // both sides share the change 1213 if (target_record_cursor.slot().eql(parent_slot)) continue; 1214 1215 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1216 1217 var baseline_record: ?T.Record = null; 1218 if (baseline_records) |map| { 1219 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1220 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1221 } 1222 } 1223 1224 switch (comptime T.merge_policy) { 1225 .field_conflicts => { 1226 outcome = @splat(.kept); 1227 merged = target_record; 1228 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1229 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1230 if (comptime @hasDecl(T, "resolveMerge")) { 1231 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1232 } 1233 1234 // merge the removed state separately from serialized fields. removal 1235 // carries over an unchanged record, while an edit or restoration 1236 // keeps it active. 1237 merged.removed = if (target_record.removed == parent_record.removed) 1238 target_record.removed 1239 else if (baseline_record) |baseline| blk: { 1240 const active = if (!target_record.removed) target_record else parent_record; 1241 if (active.removed != baseline.removed) break :blk false; 1242 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1243 break :blk true; 1244 } else false; 1245 }, 1246 .target_wins => { 1247 // an uncontested parent change carries over. if both sides 1248 // changed the record, the target wins as a whole, except that 1249 // an edit or restoration wins over a removal. 1250 const target_changed = if (baseline_slot) |slot| 1251 !target_record_cursor.slot().eql(slot) 1252 else 1253 true; 1254 merged = if (!target_changed) 1255 parent_record 1256 else if (target_record.removed != parent_record.removed) 1257 if (target_record.removed) parent_record else target_record 1258 else 1259 target_record; 1260 }, 1261 } 1262 } 1263 1264 // the index is unique, so a key the target gave to a different record 1265 // leaves this one out rather than stranding that one behind a name it 1266 // no longer owns 1267 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1268 const index_key = try merged.indexKey(arena.allocator()); 1269 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1270 const name_index = try DB.HashMap(.read_write).init(name_index_cursor); 1271 if (try name_index.getCursor(hash.hashInt(hash_kind, index_key))) |owner_cursor| { 1272 var owner_id: [event_id_size]u8 = undefined; 1273 _ = try owner_cursor.readBytes(&owner_id); 1274 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1275 } 1276 } 1277 1278 // `consume` sets no oids, since each field's winner may come from 1279 // a different side 1280 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1281 1282 switch (comptime T.merge_policy) { 1283 .field_conflicts => {}, 1284 .target_wins => continue, 1285 } 1286 1287 // removed records do not carry field conflicts 1288 if (merged.removed) continue; 1289 1290 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1291 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1292 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1293 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1294 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1295 1296 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1297 if (parent_id_to_field_to_oid) |map| { 1298 if (try map.getCursor(record_key)) |field_oids_cursor| { 1299 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1300 } 1301 } 1302 // created only once a field actually comes from the parent 1303 var field_oids: ?DB.SortedMap(.read_write) = null; 1304 1305 // the fields both sides changed differently, space separated 1306 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1307 var conflicted_len: usize = 0; 1308 1309 inline for (std.meta.fields(T), 0..) |field, i| { 1310 switch (outcome[i]) { 1311 // the target's value stands, so its oid does too 1312 .kept => {}, 1313 // the parent set this value, so its commit takes the field. a 1314 // parent with no oid took its own value from a merge, leaving 1315 // the field unattributed rather than crediting the target's 1316 // commit for a value it no longer holds. 1317 .parent => { 1318 if (field_oids == null) { 1319 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1320 } 1321 const map = field_oids orelse unreachable; 1322 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1323 if (parent_oid) |oid_cursor| { 1324 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1325 } else { 1326 _ = try map.remove(field.name); 1327 } 1328 }, 1329 .conflicted => { 1330 if (conflicted_len > 0) { 1331 conflicted_fields[conflicted_len] = ' '; 1332 conflicted_len += 1; 1333 } 1334 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1335 conflicted_len += field.name.len; 1336 }, 1337 } 1338 } 1339 1340 if (conflicted_len > 0) { 1341 // each side's whole record is stored by reference, so the view can 1342 // show any of them or take theirs wholesale 1343 _ = try conflicts.remove(&merged_key); 1344 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1345 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1346 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1347 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1348 if (parent_field_oids) |map| { 1349 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1350 } 1351 continue; 1352 } 1353 1354 // created_order never changes, so the parent keys this record's conflict 1355 // identically, and it carries over when the target has none, unless the 1356 // parent's entry is unchanged from the baseline, meaning the target 1357 // inherited it too and resolving it removed it here. 1358 if (parent_conflicts) |map| { 1359 if (null == try conflicts.getCursor(&merged_key)) { 1360 if (try map.getSlot(&merged_key)) |conflict_slot| { 1361 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1362 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1363 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1364 } 1365 } 1366 } 1367 } 1368 } 1369 1370 pub fn currentMoment( 1371 comptime repo_opts: rp.RepoOpts(.xit), 1372 repo: *rp.Repo(.xit, repo_opts), 1373 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1374 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1375 } 1376 1377 pub fn currentMomentFromDb( 1378 comptime hash_kind: hash.HashKind, 1379 db: *EventDB(hash_kind), 1380 ) !EventDB(hash_kind).HashMap(.read_only) { 1381 const DB = EventDB(hash_kind); 1382 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1383 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1384 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1385 return try currentMomentFromRepoMoment(hash_kind, moment); 1386 } 1387 1388 pub fn currentMomentFromRepoMoment( 1389 comptime hash_kind: hash.HashKind, 1390 moment: EventDB(hash_kind).HashMap(.read_only), 1391 ) !EventDB(hash_kind).HashMap(.read_only) { 1392 const DB = EventDB(hash_kind); 1393 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1394 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1395 _ = try last_object_id_cursor.readBytes(&last_object_id); 1396 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, materialized_key)) orelse return error.NotFound; 1397 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 1398 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 1399 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1400 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1401 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1402 } 1403 1404 // build a sorted-set key from an order and event id. big-endian order makes 1405 // byte order match numeric order; the event id breaks ties. 1406 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1407 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1408 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1409 @memcpy(key[@sizeOf(u64)..], event_id); 1410 return key; 1411 } 1412 1413 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1414 return orderKey(std.math.maxInt(u64) - order, event_id); 1415 } 1416 1417 pub fn removedRecord( 1418 comptime T: type, 1419 comptime DB: type, 1420 comptime hash_kind: hash.HashKind, 1421 haxy_moment: DB.HashMap(.read_only), 1422 existing_maybe: ?T, 1423 ) !T { 1424 var record = existing_maybe orelse return error.EventNotFound; 1425 record.removed = true; 1426 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1427 record.updated_order = try order_cursor.readUint(); 1428 return record; 1429 } 1430 1431 // add or refresh one entry in the global logical-event index 1432 pub fn indexEvent( 1433 comptime DB: type, 1434 comptime hash_kind: hash.HashKind, 1435 haxy_moment: DB.HashMap(.read_write), 1436 event_id: *const [event_id_size]u8, 1437 kind: EventKind, 1438 existing_maybe: anytype, 1439 record: anytype, 1440 ) !void { 1441 const event_key = hash.hashInt(hash_kind, event_id); 1442 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1443 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1444 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1445 1446 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1447 const active = try DB.SortedSet(.read_write).init(active_cursor); 1448 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1449 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1450 1451 if (existing_maybe) |existing| { 1452 const old_key = orderKeyDesc(existing.updated_order, event_id); 1453 _ = try active.remove(&old_key); 1454 _ = try removed_set.remove(&old_key); 1455 } 1456 1457 const order_key = orderKeyDesc(record.updated_order, event_id); 1458 if (record.removed) { 1459 try removed_set.put(&order_key); 1460 } else { 1461 try active.put(&order_key); 1462 } 1463 } 1464 1465 pub fn touchThread( 1466 comptime DB: type, 1467 comptime hash_kind: hash.HashKind, 1468 haxy_moment: DB.HashMap(.read_write), 1469 thread_id: *const [event_id_size]u8, 1470 order: u64, 1471 arena: *std.heap.ArenaAllocator, 1472 ) !void { 1473 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1474 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1475 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1476 switch (kind) { 1477 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1478 else => {}, 1479 } 1480 } 1481 1482 pub fn readEventKind( 1483 comptime hash_kind: hash.HashKind, 1484 kind_map: anytype, 1485 id: *const [event_id_size]u8, 1486 ) !?EventKind { 1487 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1488 var buffer: [64]u8 = undefined; 1489 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1490 } 1491 1492 // the event id embedded in a set entry's order key 1493 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1494 var cursor = kv_pair_cursor; 1495 const kv_pair = try cursor.readKeyValuePair(); 1496 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1497 _ = try kv_pair.key_cursor.readBytes(&order_key); 1498 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1499 } 1500 1501 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1502 // isn't exactly two non-empty segments. 1503 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1504 var it = std.mem.splitScalar(u8, path, '/'); 1505 const owner = it.next() orelse return null; 1506 const name = it.next() orelse return null; 1507 if (it.next() != null) return null; 1508 if (owner.len == 0 or name.len == 0) return null; 1509 1510 return .{ .owner = owner, .name = name }; 1511 } 1512 1513 pub const CreateRepoOptions = struct { 1514 read_access: Repo.Access = .private, 1515 }; 1516 1517 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1518 // directory under the repos dir 1519 pub fn resolveOrCreateRepo( 1520 io: std.Io, 1521 allocator: std.mem.Allocator, 1522 admin_repo_path: []const u8, 1523 owner_name: []const u8, 1524 repo_name: []const u8, 1525 create_options_maybe: ?CreateRepoOptions, 1526 ) !?[event_id_size * 2]u8 { 1527 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1528 error.RepoNotFound => return null, 1529 else => |e| return e, 1530 }; 1531 defer repo.deinit(io, allocator); 1532 1533 var arena = std.heap.ArenaAllocator.init(allocator); 1534 defer arena.deinit(); 1535 1536 const moment = try currentMoment(admin_repo_opts, &repo); 1537 1538 // an already-registered repo reuses its event id, so a re-push (or a clone) 1539 // lands in the same repo 1540 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1541 return std.fmt.bytesToHex(found.event_id, .lower); 1542 } 1543 1544 const create_options = create_options_maybe orelse return null; 1545 1546 // the new repo is owned by the named user, read from the name index; an 1547 // unknown owner can't own a repo, so the push is rejected 1548 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1549 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1550 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1551 var owner_user_id: [event_id_size]u8 = undefined; 1552 _ = try owner_id_cursor.readBytes(&owner_user_id); 1553 1554 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1555 1556 var id_bytes: [event_id_size]u8 = undefined; 1557 io.random(&id_bytes); 1558 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1559 1560 try consume(.server, .admin, .xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1561 .id = event_id_hex, 1562 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1563 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1564 .event = .{ .repo = .{ 1565 .user_id = &owner_user_id, 1566 .name = repo_name, 1567 .description = "", 1568 .read_access = create_options.read_access, 1569 } }, 1570 }}); 1571 1572 return event_id_hex; 1573 } 1574 1575 // 1576 // reading from xitdb 1577 // 1578 1579 pub fn read( 1580 comptime T: type, 1581 comptime DB: type, 1582 comptime hash_kind: hash.HashKind, 1583 arena: *std.heap.ArenaAllocator, 1584 map: DB.HashMap(.read_only), 1585 ) !T { 1586 var event: T = undefined; 1587 1588 switch (@typeInfo(T)) { 1589 .@"struct" => |struct_info| { 1590 inline for (struct_info.fields) |field| { 1591 switch (@typeInfo(field.type)) { 1592 .pointer => |pointer_info| { 1593 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 1594 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1595 } else { 1596 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1597 } 1598 }, 1599 .array => |array_info| { 1600 if (array_info.child == u8) { 1601 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1602 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 1603 @memcpy(@field(event, field.name)[0..], bytes); 1604 } else { 1605 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1606 } 1607 }, 1608 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 1609 .int => |int_info| switch (int_info.signedness) { 1610 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 1611 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 1612 }, 1613 .@"enum" => { 1614 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1615 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 1616 }, 1617 .@"union" => { 1618 if (!@hasDecl(field.type, "decode")) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1619 @field(event, field.name) = try field.type.decode(try readBytes(DB, hash_kind, arena.allocator(), map, field.name)); 1620 }, 1621 .optional => |optional_info| { 1622 // a missing key is null 1623 if (try map.getCursor(hash.hashInt(hash_kind, field.name))) |cursor| { 1624 if (optional_info.child == []const u8) { 1625 @field(event, field.name) = try cursor.readBytesAlloc(arena.allocator(), null); 1626 } else switch (@typeInfo(optional_info.child)) { 1627 .array => |array_info| { 1628 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1629 var bytes: optional_info.child = undefined; 1630 const value = try cursor.readBytes(&bytes); 1631 if (value.len != bytes.len) return error.InvalidByteArrayLength; 1632 @field(event, field.name) = bytes; 1633 }, 1634 .@"struct" => @field(event, field.name) = try read( 1635 optional_info.child, 1636 DB, 1637 hash_kind, 1638 arena, 1639 try DB.HashMap(.read_only).init(cursor), 1640 ), 1641 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1642 } 1643 } else { 1644 @field(event, field.name) = null; 1645 } 1646 }, 1647 .@"struct" => { 1648 const cursor = try map.getCursor(hash.hashInt(hash_kind, field.name)) orelse return error.NotFound; 1649 @field(event, field.name) = try read( 1650 field.type, 1651 DB, 1652 hash_kind, 1653 arena, 1654 try DB.HashMap(.read_only).init(cursor), 1655 ); 1656 }, 1657 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1658 } 1659 } 1660 }, 1661 else => @compileError("read expects a struct"), 1662 } 1663 1664 return event; 1665 } 1666 1667 // whether two events carry the same data 1668 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1669 switch (@typeInfo(T)) { 1670 .@"struct" => |struct_info| { 1671 inline for (struct_info.fields) |field| { 1672 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1673 } 1674 }, 1675 else => @compileError("fieldsEqual expects a struct"), 1676 } 1677 1678 return true; 1679 } 1680 1681 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1682 switch (@typeInfo(Field)) { 1683 .pointer => |pointer_info| { 1684 if (pointer_info.size == .slice and pointer_info.child == u8) { 1685 return std.mem.eql(u8, a, b); 1686 } else { 1687 @compileError("unsupported field type: " ++ @typeName(Field)); 1688 } 1689 }, 1690 .array => |array_info| { 1691 if (array_info.child == u8) { 1692 return std.mem.eql(u8, &a, &b); 1693 } else { 1694 @compileError("unsupported field type: " ++ @typeName(Field)); 1695 } 1696 }, 1697 .void => return true, 1698 .bool, .int, .@"enum" => return a == b, 1699 .@"union" => { 1700 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1701 return switch (a) { 1702 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 1703 }; 1704 }, 1705 .@"struct" => return fieldsEqual(Field, a, b), 1706 .optional => |optional_info| { 1707 if (a) |a_value| { 1708 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 1709 return false; 1710 } 1711 return b == null; 1712 }, 1713 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1714 } 1715 } 1716 1717 fn readBytes( 1718 comptime DB: type, 1719 comptime hash_kind: hash.HashKind, 1720 allocator: std.mem.Allocator, 1721 map: DB.HashMap(.read_only), 1722 field_name: []const u8, 1723 ) ![]const u8 { 1724 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1725 return try cursor.readBytesAlloc(allocator, null); 1726 } 1727 1728 fn readUint( 1729 comptime DB: type, 1730 comptime hash_kind: hash.HashKind, 1731 map: DB.HashMap(.read_only), 1732 field_name: []const u8, 1733 ) !u64 { 1734 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1735 return try cursor.readUint(); 1736 } 1737 1738 fn readInt( 1739 comptime DB: type, 1740 comptime hash_kind: hash.HashKind, 1741 map: DB.HashMap(.read_only), 1742 field_name: []const u8, 1743 ) !i64 { 1744 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1745 return try cursor.readInt(); 1746 } 1747 1748 fn readBool( 1749 comptime DB: type, 1750 comptime hash_kind: hash.HashKind, 1751 map: DB.HashMap(.read_only), 1752 field_name: []const u8, 1753 ) !bool { 1754 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1755 var buffer: [5]u8 = undefined; 1756 const bytes = try cursor.readBytesObject(&buffer); 1757 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1758 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1759 if (std.mem.eql(u8, bytes.value, "true")) return true; 1760 if (std.mem.eql(u8, bytes.value, "false")) return false; 1761 return error.InvalidBool; 1762 } 1763 1764 // 1765 // writing to xitdb 1766 // 1767 1768 pub fn upsert( 1769 comptime T: type, 1770 comptime DB: type, 1771 comptime hash_kind: hash.HashKind, 1772 map: DB.HashMap(.read_write), 1773 event: T, 1774 ) !void { 1775 switch (@typeInfo(T)) { 1776 .@"struct" => |struct_info| { 1777 inline for (struct_info.fields) |field| { 1778 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1779 } 1780 }, 1781 else => @compileError("upsert expects a struct"), 1782 } 1783 } 1784 1785 fn upsertField( 1786 comptime DB: type, 1787 comptime hash_kind: hash.HashKind, 1788 map: DB.HashMap(.read_write), 1789 comptime field_name: []const u8, 1790 comptime Field: type, 1791 value: Field, 1792 ) !void { 1793 const key = hash.hashInt(hash_kind, field_name); 1794 1795 switch (@typeInfo(Field)) { 1796 .pointer => |pointer_info| { 1797 if (pointer_info.size == .slice and pointer_info.child == u8) { 1798 try upsertBytes(DB, hash_kind, map, key, value); 1799 } else { 1800 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1801 } 1802 }, 1803 .array => |array_info| { 1804 if (array_info.child == u8) { 1805 try upsertBytes(DB, hash_kind, map, key, &value); 1806 } else { 1807 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1808 } 1809 }, 1810 .int => |int_info| switch (int_info.signedness) { 1811 .unsigned => { 1812 if (try map.getCursor(key)) |value_cursor| { 1813 if (try value_cursor.readUint() == value) { 1814 return; 1815 } 1816 } 1817 1818 try map.put(key, .{ .uint = value }); 1819 }, 1820 .signed => { 1821 if (try map.getCursor(key)) |value_cursor| { 1822 if (try value_cursor.readInt() == value) { 1823 return; 1824 } 1825 } 1826 1827 try map.put(key, .{ .int = value }); 1828 }, 1829 }, 1830 .bool => { 1831 const bytes = if (value) "true" else "false"; 1832 if (try map.getCursor(key)) |value_cursor| { 1833 var buffer: [5]u8 = undefined; 1834 const existing = try value_cursor.readBytesObject(&buffer); 1835 if (existing.format_tag) |format_tag| { 1836 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1837 return; 1838 } 1839 } 1840 } 1841 1842 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1843 }, 1844 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1845 .@"union" => { 1846 if (!@hasDecl(Field, "encode") or !@hasDecl(Field, "max_encoded_len")) { 1847 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1848 } 1849 var buffer: [Field.max_encoded_len]u8 = undefined; 1850 try upsertBytes(DB, hash_kind, map, key, try value.encode(&buffer)); 1851 }, 1852 .optional => |optional_info| { 1853 // a missing key is null 1854 if (value) |child| { 1855 if (optional_info.child == []const u8) { 1856 try upsertBytes(DB, hash_kind, map, key, child); 1857 } else switch (@typeInfo(optional_info.child)) { 1858 .array => |array_info| { 1859 if (array_info.child != u8) @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1860 try upsertBytes(DB, hash_kind, map, key, &child); 1861 }, 1862 .@"struct" => try upsert( 1863 optional_info.child, 1864 DB, 1865 hash_kind, 1866 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1867 child, 1868 ), 1869 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1870 } 1871 } else { 1872 _ = try map.remove(key); 1873 } 1874 }, 1875 .@"struct" => try upsert( 1876 Field, 1877 DB, 1878 hash_kind, 1879 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1880 value, 1881 ), 1882 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1883 } 1884 } 1885 1886 fn upsertBytes( 1887 comptime DB: type, 1888 comptime hash_kind: hash.HashKind, 1889 map: DB.HashMap(.read_write), 1890 key: hash.HashInt(hash_kind), 1891 value: []const u8, 1892 ) !void { 1893 var existing_cursor_maybe = try map.getCursor(key); 1894 if (existing_cursor_maybe) |*existing_cursor| { 1895 if (try bytesEqual(DB, existing_cursor, value)) { 1896 return; 1897 } 1898 } 1899 1900 try map.put(key, .{ .bytes = value }); 1901 } 1902 1903 fn bytesEqual( 1904 comptime DB: type, 1905 cursor: *DB.Cursor(.read_only), 1906 value: []const u8, 1907 ) !bool { 1908 var read_buffer: [1024]u8 = undefined; 1909 var reader = try cursor.reader(&read_buffer); 1910 if (reader.size != value.len) { 1911 return false; 1912 } 1913 1914 var chunk_buffer: [1024]u8 = undefined; 1915 var offset: usize = 0; 1916 while (offset < value.len) { 1917 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1918 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1919 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1920 return false; 1921 } 1922 offset += chunk_len; 1923 } 1924 1925 return true; 1926 } 1927 1928 // 1929 // CommitIterator 1930 // 1931 // differs from xit's ObjectIterator in a few ways: 1932 // 1933 // 1. iterates parents first, rather than children first 1934 // 2. `next` only returns the object id, not the full Object 1935 // 3. stores its temporary state in a file on disk to avoid OOMs 1936 // 1937 1938 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1939 return struct { 1940 const DB = EventDB(repo_opts.hash); 1941 const db_name = "haxy-repo-events.db"; 1942 1943 repo_dir: std.Io.Dir, 1944 db_file: std.Io.File, 1945 db: *DB, 1946 // map of each object id to its children 1947 parent_to_children: DB.HashMap(.read_write), 1948 // tracking pending parents is necessary because a child can only 1949 // be returned after all of its unconsumed parents have been returned 1950 child_to_pending_parents: DB.HashMap(.read_write), 1951 // queue of object ids that are ready to be returned from `next` 1952 ready_queue: DB.ArrayList(.read_write), 1953 ready_queue_index: u64, 1954 // the object id at the tip of this branch 1955 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1956 // the object id furthest back in the history that hasn't been consumed 1957 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1958 1959 pub fn init( 1960 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1961 io: std.Io, 1962 allocator: std.mem.Allocator, 1963 consumed_object_ids: DB.HashMap(.read_only), 1964 ref: rf.Ref, 1965 ) !CommitIterator(repo_kind, repo_opts) { 1966 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1967 errdefer { 1968 db_file.close(io); 1969 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1970 } 1971 1972 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1973 errdefer allocator.destroy(buffer_ptr); 1974 1975 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1976 errdefer buffer_ptr.deinit(); 1977 1978 const db_ptr = try allocator.create(DB); 1979 errdefer allocator.destroy(db_ptr); 1980 // the db is scratch state that gets deleted after iteration, so 1981 // there is nothing worth fsyncing 1982 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 1983 1984 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1985 1986 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1987 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1988 1989 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1990 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1991 1992 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1993 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1994 1995 var self = CommitIterator(repo_kind, repo_opts){ 1996 .repo_dir = state.core.repo_dir, 1997 .db_file = db_file, 1998 .db = db_ptr, 1999 .parent_to_children = parent_to_children, 2000 .child_to_pending_parents = child_to_pending_parents, 2001 .ready_queue = ready_queue, 2002 .ready_queue_index = 0, 2003 .newest_object_id = null, 2004 .oldest_object_id = null, 2005 }; 2006 errdefer self.deinit(io, allocator); 2007 2008 try self.collect(state, io, allocator, consumed_object_ids, ref); 2009 2010 return self; 2011 } 2012 2013 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2014 self.db_file.close(io); 2015 self.db.core.memory.buffer.deinit(); 2016 allocator.destroy(self.db.core.memory.buffer); 2017 self.repo_dir.deleteFile(io, db_name) catch {}; 2018 allocator.destroy(self.db); 2019 } 2020 2021 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2022 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2023 2024 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2025 self.ready_queue_index += 1; 2026 2027 try self.enqueueChildren(&oid); 2028 return oid; 2029 } 2030 2031 fn collect( 2032 self: *CommitIterator(repo_kind, repo_opts), 2033 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2034 io: std.Io, 2035 allocator: std.mem.Allocator, 2036 consumed_object_ids: DB.HashMap(.read_only), 2037 ref: rf.Ref, 2038 ) !void { 2039 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 2040 2041 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2042 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 2043 var walk_queue_index: u64 = 0; 2044 2045 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2046 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 2047 2048 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2049 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2050 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2051 try walk_queue.append(.{ .bytes = &head_oid }); 2052 2053 while (walk_queue_index < try walk_queue.count()) { 2054 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2055 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2056 2057 walk_queue_index += 1; 2058 2059 // if we've seen this object id, skip it 2060 if (null != try seen_object_ids.getCursor(oid_int)) { 2061 continue; 2062 } 2063 2064 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2065 2066 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2067 defer commit_object.deinit(); 2068 2069 // if this object id has already been consumed, skip it 2070 if (null != try consumed_object_ids.getCursor(oid_int)) { 2071 continue; 2072 } 2073 2074 if (self.newest_object_id == null) self.newest_object_id = oid; 2075 self.oldest_object_id = oid; 2076 2077 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2078 var pending_parent_count: u64 = 0; 2079 for (parent_oids) |*parent_oid| { 2080 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2081 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2082 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2083 2084 // if this object id has already been consumed, skip it 2085 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2086 continue; 2087 } 2088 2089 // if this object id hasn't already been seen, add it to the walk queue 2090 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2091 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2092 } 2093 2094 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2095 const children = try DB.HashSet(.read_write).init(children_cursor); 2096 try children.put(oid_int, .{ .bytes = &oid }); 2097 pending_parent_count += 1; 2098 } 2099 2100 if (pending_parent_count == 0) { 2101 try self.ready_queue.append(.{ .bytes = &oid }); 2102 } else { 2103 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2104 } 2105 } 2106 } 2107 2108 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2109 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2110 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2111 const children = try DB.HashSet(.read_only).init(children_cursor); 2112 var children_iter = try children.iterator(); 2113 2114 while (try children_iter.next()) |*child_cursor| { 2115 const kv_pair = try child_cursor.readKeyValuePair(); 2116 const child_oid_int = kv_pair.hash; 2117 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2118 const pending_parent_count = try pending_parent_cursor.readUint(); 2119 2120 if (pending_parent_count <= 1) { 2121 _ = try self.child_to_pending_parents.remove(child_oid_int); 2122 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2123 try self.ready_queue.append(.{ .bytes = &child_oid }); 2124 } else { 2125 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2126 } 2127 } 2128 } 2129 2130 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2131 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2132 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2133 _ = try oid_cursor.readBytes(&oid); 2134 return oid; 2135 } 2136 }; 2137 } 2138