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