╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
874 if (parent_oids.len > 1) { 875 for (parent_oids[1..]) |*parent_oid| { 876 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 877 _ = try std.fmt.hexToBytes(&oid, parent_oid); 878 879 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 880 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 881 882 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 883 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 884 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 885 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 886 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 887 888 inline for (std.meta.fields(Event)) |field| { 889 const T = @typeInfo(field.type).optional.child; 890 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 891 } 892 } 893 } 894 895 // associate this moment with the index it will first appear at in the 896 // haxy history list. this will be important later so we can truncate 897 // that list if the user ever rebases starting at this object id. 898 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy_history.count() - 1 }); 899 900 // consume the event unless it's a merge commit 901 if (parent_oids.len <= 1) { 902 var arena = std.heap.ArenaAllocator.init(allocator); 903 defer arena.deinit(); 904 905 // read the message from the commit 906 var message: std.ArrayList(u8) = .empty; 907 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 908 909 const event_with_id = try EventWithId.fromString(&arena, message.items); 910 if (!role.allows(std.meta.activeTag(event_with_id.event))) return error.EventKindNotAllowed; 911 912 const current_event_id = try parseEventId(&event_with_id.id); 913 914 // wrap the payload into the record `consume` stores, with its 915 // commit-derived fields; on update, `consume` preserves the 916 // existing record's 917 switch (event_with_id.event) { 918 .user => |event_maybe| { 919 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 920 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 921 }, 922 .repo => |event_maybe| { 923 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 924 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 925 }, 926 .fork => |event_maybe| { 927 const record_maybe: ?Fork.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 928 try Fork.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 929 }, 930 .issue => |event_maybe| { 931 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 932 .event = event, 933 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 934 .created_order = event_order, 935 .updated_order = event_order, 936 } else null; 937 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 938 }, 939 .discuss => |event_maybe| { 940 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 941 .event = event, 942 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 943 .created_order = event_order, 944 .updated_order = event_order, 945 } else null; 946 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 947 }, 948 .comment => |event_maybe| { 949 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 950 .event = event, 951 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 952 .created_order = event_order, 953 .updated_order = event_order, 954 } else null; 955 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 956 }, 957 .attach => |event_maybe| { 958 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 959 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 960 break :blk .{ 961 .event = event, 962 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 963 .created_order = event_order, 964 .updated_order = event_order, 965 .name = entry.name, 966 .blob_oid = entry.oid, 967 }; 968 } else null; 969 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 970 }, 971 .patchrev => |event_maybe| { 972 const record_maybe: ?PatchRev.Record = if (event_maybe) |event| blk: { 973 const trees = try PatchRev.readTrees(repo_kind, repo_opts, read_state, io, allocator, &commit_object.content.commit.tree); 974 const existing_maybe = try PatchRev.readById(DB, repo_opts.hash, haxy_moment.readOnly(), &arena, &current_event_id); 975 const event_oid = std.fmt.bytesToHex(repo_event_oid, .lower); 976 977 var patch_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 978 if (existing_maybe) |existing| { 979 if (existing.patch_oid.len != patch_oid.len) return error.InvalidPatch; 980 @memcpy(&patch_oid, existing.patch_oid); 981 } else { 982 const author = try commitIdentity(commit_object.content.commit.metadata.author orelse return error.AuthorNotFound); 983 const committer = try commitIdentity(commit_object.content.commit.metadata.committer orelse author); 984 patch_oid = try PatchRev.writeSquashCommit( 985 repo_kind, 986 repo_opts, 987 state, 988 io, 989 allocator, 990 event, 991 &trees.head, 992 author, 993 committer, 994 commit_object.content.commit.metadata.timestamp, 995 ); 996 } 997 998 break :blk .{ 999 .event = event, 1000 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1001 .created_order = event_order, 1002 .updated_order = event_order, 1003 .event_oid = &event_oid, 1004 .base_tree_oid = &trees.base, 1005 .head_tree_oid = &trees.head, 1006 .patch_oid = &patch_oid, 1007 .commit_count = PatchRev.commitCount(repo_kind, repo_opts, read_state, io, allocator, event.base_oid, event.source_oid) catch null, 1008 }; 1009 } else null; 1010 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1011 }, 1012 .patch => |event_maybe| { 1013 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 1014 .event = event, 1015 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1016 .created_order = event_order, 1017 .updated_order = event_order, 1018 } else null; 1019 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1020 }, 1021 } 1022 } 1023 1024 // the current object id is now the last one 1025 last_object_id_maybe = repo_event_oid; 1026 1027 // prevent any of the data created above from being mutated by future iterations of this loop 1028 try db.freeze(); 1029 } 1030 1031 if (last_object_id_maybe) |*last_object_id| { 1032 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1033 } 1034 1035 return true; 1036 } 1037 1038 // the conflicted records of one kind, keyed by the same order key its id set 1039 // uses, so this doubles as the index the conflicts view lists and counts. every 1040 // value under an entry is a slot reference to a structure that already exists: 1041 // 1042 // <order key> -> conflict entry 1043 // conflicted-fields the conflicting field names, space separated 1044 // base-record the merge base's whole record 1045 // their-record the merged-in side's whole record 1046 // their-field->oid that side's field name to commit map 1047 // 1048 // our own value is the live record and our commit is in the kind's oid map, so 1049 // neither is repeated here. 1050 pub const conflicted_fields_key = "conflicted-fields"; 1051 pub const base_record_key = "base-record"; 1052 pub const their_record_key = "their-record"; 1053 pub const their_field_to_oid_key = "their-field->oid"; 1054 1055 // record the commit against every field this event changes. a merge passes no 1056 // oid, since each field's winner may come from a different side. 1057 pub fn writeOid( 1058 comptime T: type, 1059 comptime DB: type, 1060 comptime hash_kind: hash.HashKind, 1061 id_to_field_to_oid: DB.HashMap(.read_write), 1062 record_key: hash.HashInt(hash_kind), 1063 existing_maybe: ?T, 1064 event: T, 1065 event_oid: ?[]const u8, 1066 ) !void { 1067 const oid = event_oid orelse return; 1068 1069 // created only once a field actually changes 1070 var field_oids: ?DB.SortedMap(.read_write) = null; 1071 1072 inline for (std.meta.fields(T)) |field| { 1073 const changed = if (existing_maybe) |existing| 1074 !fieldEqual(field.type, @field(existing, field.name), @field(event, field.name)) 1075 else 1076 true; 1077 if (changed) { 1078 if (field_oids == null) { 1079 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1080 } 1081 if (field_oids) |map| try map.put(field.name, .{ .bytes = oid }); 1082 } 1083 } 1084 } 1085 1086 // the whole field list, space separated, is the longest it can get 1087 fn conflictedFieldsMaxLen(comptime T: type) usize { 1088 var len: usize = 0; 1089 for (std.meta.fields(T)) |field| len += field.name.len + 1; 1090 return len; 1091 } 1092 1093 pub const MergePolicy = enum { 1094 field_conflicts, 1095 target_wins, 1096 }; 1097 1098 // what a three-way merge did with a field 1099 pub const FieldMerge = enum { 1100 // the target's value stands, because neither side changed it, both made the 1101 // same change, or only the target changed it 1102 kept, 1103 parent, 1104 conflicted, 1105 }; 1106 1107 // three-way merge each field. one only the parent changed takes the parent's 1108 // value; one both sides changed differently keeps the target's. a missing 1109 // baseline makes every differing field a conflict. 1110 fn mergeFields( 1111 comptime T: type, 1112 baseline_maybe: ?T, 1113 target: T, 1114 parent: T, 1115 outcome: *[std.meta.fields(T).len]FieldMerge, 1116 ) T { 1117 var merged = target; 1118 1119 inline for (std.meta.fields(T), 0..) |field, i| { 1120 const target_value = @field(target, field.name); 1121 const parent_value = @field(parent, field.name); 1122 1123 if (!fieldEqual(field.type, target_value, parent_value)) { 1124 outcome[i] = if (baseline_maybe) |baseline| blk: { 1125 const baseline_value = @field(baseline, field.name); 1126 if (fieldEqual(field.type, target_value, baseline_value)) { 1127 @field(merged, field.name) = parent_value; 1128 break :blk .parent; 1129 } 1130 // only the target changed it 1131 if (fieldEqual(field.type, parent_value, baseline_value)) break :blk .kept; 1132 break :blk .conflicted; 1133 } else .conflicted; 1134 } 1135 } 1136 1137 return merged; 1138 } 1139 1140 // three-way merge of one kind's records from a merge parent. kinds that expose 1141 // conflicts merge field by field; the others take one whole record. the result 1142 // goes through the kind's `consume`, which re-derives the indexes from it. a 1143 // removal carries over unless the other side changed the record, so a merge 1144 // never fails. 1145 pub fn merge( 1146 comptime T: type, 1147 comptime DB: type, 1148 comptime hash_kind: hash.HashKind, 1149 allocator: std.mem.Allocator, 1150 haxy_moment: DB.HashMap(.read_write), 1151 parent_moment: DB.HashMap(.read_only), 1152 baseline_moment: DB.HashMap(.read_only), 1153 ) !void { 1154 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1155 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1156 1157 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1158 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1159 1160 var baseline_records: ?DB.HashMap(.read_only) = null; 1161 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1162 baseline_records = try DB.HashMap(.read_only).init(cursor); 1163 } 1164 1165 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1166 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1167 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1168 switch (comptime T.merge_policy) { 1169 .field_conflicts => { 1170 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1171 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1172 } 1173 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1174 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1175 } 1176 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1177 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1178 } 1179 }, 1180 .target_wins => {}, 1181 } 1182 1183 var arena = std.heap.ArenaAllocator.init(allocator); 1184 defer arena.deinit(); 1185 1186 var iter = try parent_set.iteratorFromIndex(0); 1187 while (try iter.next()) |kv_pair_cursor| { 1188 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1189 const record_key = hash.hashInt(hash_kind, &event_id); 1190 1191 _ = arena.reset(.retain_capacity); 1192 1193 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1194 const parent_slot = parent_record_cursor.slot(); 1195 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1196 1197 // the parent left this record alone 1198 if (baseline_slot) |slot| { 1199 if (slot.eql(parent_slot)) continue; 1200 } 1201 1202 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1203 1204 // re-derived every iteration, since `consume` writes through its own 1205 // handles 1206 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1207 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1208 1209 // a record the target doesn't have arrives wholesale from the parent 1210 var outcome: [std.meta.fields(T).len]FieldMerge = @splat(.parent); 1211 var merged = parent_record; 1212 1213 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1214 // both sides share the change 1215 if (target_record_cursor.slot().eql(parent_slot)) continue; 1216 1217 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1218 1219 var baseline_record: ?T.Record = null; 1220 if (baseline_records) |map| { 1221 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1222 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1223 } 1224 } 1225 1226 switch (comptime T.merge_policy) { 1227 .field_conflicts => { 1228 outcome = @splat(.kept); 1229 merged = target_record; 1230 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1231 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1232 if (comptime @hasDecl(T, "resolveMerge")) { 1233 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1234 } 1235 1236 // merge the removed state separately from serialized fields. removal 1237 // carries over an unchanged record, while an edit or restoration 1238 // keeps it active. 1239 merged.removed = if (target_record.removed == parent_record.removed) 1240 target_record.removed 1241 else if (baseline_record) |baseline| blk: { 1242 const active = if (!target_record.removed) target_record else parent_record; 1243 if (active.removed != baseline.removed) break :blk false; 1244 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1245 break :blk true; 1246 } else false; 1247 }, 1248 .target_wins => { 1249 // an uncontested parent change carries over. if both sides 1250 // changed the record, the target wins as a whole, except that 1251 // an edit or restoration wins over a removal. 1252 const target_changed = if (baseline_slot) |slot| 1253 !target_record_cursor.slot().eql(slot) 1254 else 1255 true; 1256 merged = if (!target_changed) 1257 parent_record 1258 else if (target_record.removed != parent_record.removed) 1259 if (target_record.removed) parent_record else target_record 1260 else 1261 target_record; 1262 }, 1263 } 1264 } 1265 1266 // the index is unique, so a key the target gave to a different record 1267 // leaves this one out rather than stranding that one behind a name it 1268 // no longer owns 1269 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1270 const index_key = try merged.indexKey(arena.allocator()); 1271 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1272 const name_index = try DB.HashMap(.read_write).init(name_index_cursor); 1273 if (try name_index.getCursor(hash.hashInt(hash_kind, index_key))) |owner_cursor| { 1274 var owner_id: [event_id_size]u8 = undefined; 1275 _ = try owner_cursor.readBytes(&owner_id); 1276 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1277 } 1278 } 1279 1280 // `consume` sets no oids, since each field's winner may come from 1281 // a different side 1282 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1283 1284 switch (comptime T.merge_policy) { 1285 .field_conflicts => {}, 1286 .target_wins => continue, 1287 } 1288 1289 // removed records do not carry field conflicts 1290 if (merged.removed) continue; 1291 1292 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1293 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1294 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1295 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1296 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1297 1298 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1299 if (parent_id_to_field_to_oid) |map| { 1300 if (try map.getCursor(record_key)) |field_oids_cursor| { 1301 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1302 } 1303 } 1304 // created only once a field actually comes from the parent 1305 var field_oids: ?DB.SortedMap(.read_write) = null; 1306 1307 // the fields both sides changed differently, space separated 1308 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1309 var conflicted_len: usize = 0; 1310 1311 inline for (std.meta.fields(T), 0..) |field, i| { 1312 switch (outcome[i]) { 1313 // the target's value stands, so its oid does too 1314 .kept => {}, 1315 // the parent set this value, so its commit takes the field. a 1316 // parent with no oid took its own value from a merge, leaving 1317 // the field unattributed rather than crediting the target's 1318 // commit for a value it no longer holds. 1319 .parent => { 1320 if (field_oids == null) { 1321 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1322 } 1323 const map = field_oids orelse unreachable; 1324 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1325 if (parent_oid) |oid_cursor| { 1326 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1327 } else { 1328 _ = try map.remove(field.name); 1329 } 1330 }, 1331 .conflicted => { 1332 if (conflicted_len > 0) { 1333 conflicted_fields[conflicted_len] = ' '; 1334 conflicted_len += 1; 1335 } 1336 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1337 conflicted_len += field.name.len; 1338 }, 1339 } 1340 } 1341 1342 if (conflicted_len > 0) { 1343 // each side's whole record is stored by reference, so the view can 1344 // show any of them or take theirs wholesale 1345 _ = try conflicts.remove(&merged_key); 1346 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1347 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1348 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1349 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1350 if (parent_field_oids) |map| { 1351 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1352 } 1353 continue; 1354 } 1355 1356 // created_order never changes, so the parent keys this record's conflict 1357 // identically, and it carries over when the target has none, unless the 1358 // parent's entry is unchanged from the baseline, meaning the target 1359 // inherited it too and resolving it removed it here. 1360 if (parent_conflicts) |map| { 1361 if (null == try conflicts.getCursor(&merged_key)) { 1362 if (try map.getSlot(&merged_key)) |conflict_slot| { 1363 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1364 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1365 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1366 } 1367 } 1368 } 1369 } 1370 } 1371 1372 pub fn readFromRepo( 1373 comptime T: type, 1374 comptime repo_kind: rp.RepoKind, 1375 comptime repo_opts: rp.RepoOpts(repo_kind), 1376 io: std.Io, 1377 allocator: std.mem.Allocator, 1378 arena: *std.heap.ArenaAllocator, 1379 repo: *rp.Repo(repo_kind, repo_opts), 1380 id: *const [event_id_size]u8, 1381 ) !?T.Record { 1382 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1383 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1384 const moment = (if (event_db_maybe) |*event_db| 1385 currentMomentFromDb(repo_opts.hash, event_db.db) 1386 else if (repo_kind == .git) 1387 return null 1388 else 1389 currentMoment(repo_opts, repo)) catch return null; 1390 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1391 } 1392 1393 pub fn currentMoment( 1394 comptime repo_opts: rp.RepoOpts(.xit), 1395 repo: *rp.Repo(.xit, repo_opts), 1396 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1397 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1398 } 1399 1400 pub fn currentMomentFromDb( 1401 comptime hash_kind: hash.HashKind, 1402 db: *EventDB(hash_kind), 1403 ) !EventDB(hash_kind).HashMap(.read_only) { 1404 const DB = EventDB(hash_kind); 1405 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1406 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1407 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1408 return try currentMomentFromRepoMoment(hash_kind, moment); 1409 } 1410 1411 pub fn currentMomentFromRepoMoment( 1412 comptime hash_kind: hash.HashKind, 1413 moment: EventDB(hash_kind).HashMap(.read_only), 1414 ) !EventDB(hash_kind).HashMap(.read_only) { 1415 const DB = EventDB(hash_kind); 1416 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1417 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1418 _ = try last_object_id_cursor.readBytes(&last_object_id); 1419 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1420 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1421 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1422 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1423 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1424 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1425 } 1426 1427 // build a sorted-set key from an order and event id. big-endian order makes 1428 // byte order match numeric order; the event id breaks ties. 1429 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1430 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1431 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1432 @memcpy(key[@sizeOf(u64)..], event_id); 1433 return key; 1434 } 1435 1436 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1437 return orderKey(std.math.maxInt(u64) - order, event_id); 1438 } 1439 1440 pub fn removedRecord( 1441 comptime T: type, 1442 comptime DB: type, 1443 comptime hash_kind: hash.HashKind, 1444 haxy_moment: DB.HashMap(.read_only), 1445 existing_maybe: ?T, 1446 ) !T { 1447 var record = existing_maybe orelse return error.EventNotFound; 1448 record.removed = true; 1449 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1450 record.updated_order = try order_cursor.readUint(); 1451 return record; 1452 } 1453 1454 // add or refresh one entry in the global logical-event index 1455 pub fn indexEvent( 1456 comptime DB: type, 1457 comptime hash_kind: hash.HashKind, 1458 haxy_moment: DB.HashMap(.read_write), 1459 event_id: *const [event_id_size]u8, 1460 kind: EventKind, 1461 existing_maybe: anytype, 1462 record: anytype, 1463 ) !void { 1464 const event_key = hash.hashInt(hash_kind, event_id); 1465 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1466 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1467 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1468 1469 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1470 const active = try DB.SortedSet(.read_write).init(active_cursor); 1471 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1472 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1473 1474 if (existing_maybe) |existing| { 1475 const old_key = orderKeyDesc(existing.updated_order, event_id); 1476 _ = try active.remove(&old_key); 1477 _ = try removed_set.remove(&old_key); 1478 } 1479 1480 const order_key = orderKeyDesc(record.updated_order, event_id); 1481 if (record.removed) { 1482 try removed_set.put(&order_key); 1483 } else { 1484 try active.put(&order_key); 1485 } 1486 } 1487 1488 pub fn touchThread( 1489 comptime DB: type, 1490 comptime hash_kind: hash.HashKind, 1491 haxy_moment: DB.HashMap(.read_write), 1492 thread_id: *const [event_id_size]u8, 1493 order: u64, 1494 arena: *std.heap.ArenaAllocator, 1495 ) !void { 1496 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1497 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1498 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1499 switch (kind) { 1500 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1501 else => {}, 1502 } 1503 } 1504 1505 pub fn readEventKind( 1506 comptime hash_kind: hash.HashKind, 1507 kind_map: anytype, 1508 id: *const [event_id_size]u8, 1509 ) !?EventKind { 1510 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1511 var buffer: [64]u8 = undefined; 1512 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1513 } 1514 1515 // the email of the event's author, or null when the id names no authored event 1516 // of this kind 1517 pub fn readAuthorEmail( 1518 comptime repo_kind: rp.RepoKind, 1519 comptime repo_opts: rp.RepoOpts(repo_kind), 1520 io: std.Io, 1521 allocator: std.mem.Allocator, 1522 arena: *std.heap.ArenaAllocator, 1523 repo: *rp.Repo(repo_kind, repo_opts), 1524 kind: EventKind, 1525 id: *const [event_id_size]u8, 1526 ) !?[]const u8 { 1527 const record_map_key = switch (kind) { 1528 .issue => Issue.record_map_key, 1529 .discuss => Discussion.record_map_key, 1530 .comment => Comment.record_map_key, 1531 .attach => Attachment.record_map_key, 1532 .patchrev => PatchRev.record_map_key, 1533 .patch => Patch.record_map_key, 1534 .user, .repo, .fork => return null, 1535 }; 1536 1537 const DB = EventDB(repo_opts.hash); 1538 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1539 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1540 const moment = (if (event_db_maybe) |*event_db| 1541 currentMomentFromDb(repo_opts.hash, event_db.db) 1542 else if (repo_kind == .git) 1543 return null 1544 else 1545 currentMoment(repo_opts, repo)) catch return null; 1546 1547 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1548 const records = try DB.HashMap(.read_only).init(records_cursor); 1549 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1550 const record = try DB.HashMap(.read_only).init(record_cursor); 1551 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1552 } 1553 1554 // the event id embedded in a set entry's order key 1555 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1556 var cursor = kv_pair_cursor; 1557 const kv_pair = try cursor.readKeyValuePair(); 1558 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1559 _ = try kv_pair.key_cursor.readBytes(&order_key); 1560 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1561 } 1562 1563 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1564 // isn't exactly two non-empty segments. 1565 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1566 var it = std.mem.splitScalar(u8, path, '/'); 1567 const owner = it.next() orelse return null; 1568 const name = it.next() orelse return null; 1569 if (it.next() != null) return null; 1570 if (owner.len == 0 or name.len == 0) return null; 1571 1572 return .{ .owner = owner, .name = name }; 1573 } 1574 1575 pub const CreateRepoOptions = struct { 1576 read_access: Repo.Access = .private, 1577 }; 1578 1579 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1580 // directory under the repos dir 1581 pub fn resolveOrCreateRepo( 1582 io: std.Io, 1583 allocator: std.mem.Allocator, 1584 admin_repo_path: []const u8, 1585 owner_name: []const u8, 1586 repo_name: []const u8, 1587 create_options_maybe: ?CreateRepoOptions, 1588 ) !?[event_id_size * 2]u8 { 1589 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1590 error.RepoNotFound => return null, 1591 else => |e| return e, 1592 }; 1593 defer repo.deinit(io, allocator); 1594 1595 var arena = std.heap.ArenaAllocator.init(allocator); 1596 defer arena.deinit(); 1597 1598 const moment = try currentMoment(admin_repo_opts, &repo); 1599 1600 // an already-registered repo reuses its event id, so a re-push (or a clone) 1601 // lands in the same repo 1602 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1603 return std.fmt.bytesToHex(found.event_id, .lower); 1604 } 1605 1606 const create_options = create_options_maybe orelse return null; 1607 1608 // the new repo is owned by the named user, read from the name index; an 1609 // unknown owner can't own a repo, so the push is rejected 1610 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1611 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1612 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1613 var owner_user_id: [event_id_size]u8 = undefined; 1614 _ = try owner_id_cursor.readBytes(&owner_user_id); 1615 1616 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1617 1618 var id_bytes: [event_id_size]u8 = undefined; 1619 io.random(&id_bytes); 1620 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1621 1622 try consume(.server, .admin, .xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1623 .id = event_id_hex, 1624 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1625 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1626 .event = .{ .repo = .{ 1627 .user_id = &owner_user_id, 1628 .name = repo_name, 1629 .description = "", 1630 .read_access = create_options.read_access, 1631 } }, 1632 }}); 1633 1634 return event_id_hex; 1635 } 1636 1637 // 1638 // reading from xitdb 1639 // 1640 1641 pub fn read( 1642 comptime T: type, 1643 comptime DB: type, 1644 comptime hash_kind: hash.HashKind, 1645 arena: *std.heap.ArenaAllocator, 1646 map: DB.HashMap(.read_only), 1647 ) !T { 1648 var event: T = undefined; 1649 switch (@typeInfo(T)) { 1650 .@"struct" => |struct_info| { 1651 inline for (struct_info.fields) |field| { 1652 const cursor = try map.getCursor(hash.hashInt(hash_kind, field.name)); 1653 @field(event, field.name) = try readField(field.type, DB, hash_kind, arena, cursor); 1654 } 1655 }, 1656 else => @compileError("read expects a struct"), 1657 } 1658 return event; 1659 } 1660 1661 fn readField( 1662 comptime Field: type, 1663 comptime DB: type, 1664 comptime hash_kind: hash.HashKind, 1665 arena: *std.heap.ArenaAllocator, 1666 cursor_maybe: ?DB.Cursor(.read_only), 1667 ) !Field { 1668 if (@typeInfo(Field) == .optional) { 1669 // a missing key or a null union payload is null 1670 const cursor = cursor_maybe orelse return null; 1671 if (cursor.slot().tag == .none) return null; 1672 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 1673 } 1674 const cursor = cursor_maybe orelse return error.NotFound; 1675 switch (@typeInfo(Field)) { 1676 .pointer => |pointer_info| { 1677 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.is_const) { 1678 @compileError("unsupported read field type: " ++ @typeName(Field)); 1679 } 1680 return try cursor.readBytesAlloc(arena.allocator(), null); 1681 }, 1682 .array => |array_info| { 1683 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 1684 var bytes: Field = undefined; 1685 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 1686 return bytes; 1687 }, 1688 .bool => { 1689 var buffer: [5]u8 = undefined; 1690 const bytes = try cursor.readBytesObject(&buffer); 1691 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1692 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1693 if (std.mem.eql(u8, bytes.value, "true")) return true; 1694 if (std.mem.eql(u8, bytes.value, "false")) return false; 1695 return error.InvalidBool; 1696 }, 1697 .int => |int_info| return switch (int_info.signedness) { 1698 .unsigned => @intCast(try cursor.readUint()), 1699 .signed => @intCast(try cursor.readInt()), 1700 }, 1701 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 1702 .@"union" => |union_info| { 1703 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 1704 switch (cursor.slot().tag) { 1705 .bytes, .short_bytes => { 1706 const name = try cursor.readBytesAlloc(arena.allocator(), null); 1707 inline for (union_info.fields) |variant| { 1708 if (variant.type == void and std.mem.eql(u8, name, variant.name)) { 1709 return @unionInit(Field, variant.name, {}); 1710 } 1711 } 1712 return error.InvalidUnion; 1713 }, 1714 .hash_map => { 1715 const variants = try DB.HashMap(.read_only).init(cursor); 1716 var iter = try variants.iterator(); 1717 const entry = (try iter.next()) orelse return error.InvalidUnion; 1718 const pair = try entry.readKeyValuePair(); 1719 if (try iter.next() != null) return error.InvalidUnion; 1720 inline for (union_info.fields) |variant| { 1721 if (variant.type != void and pair.hash == hash.hashInt(hash_kind, variant.name)) { 1722 return @unionInit(Field, variant.name, try readField(variant.type, DB, hash_kind, arena, pair.value_cursor)); 1723 } 1724 } 1725 return error.InvalidUnion; 1726 }, 1727 else => return error.InvalidUnion, 1728 } 1729 }, 1730 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 1731 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 1732 } 1733 } 1734 1735 // whether two events carry the same data 1736 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1737 switch (@typeInfo(T)) { 1738 .@"struct" => |struct_info| { 1739 inline for (struct_info.fields) |field| { 1740 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1741 } 1742 }, 1743 else => @compileError("fieldsEqual expects a struct"), 1744 } 1745 1746 return true; 1747 } 1748 1749 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1750 switch (@typeInfo(Field)) { 1751 .pointer => |pointer_info| { 1752 if (pointer_info.size == .slice and pointer_info.child == u8) { 1753 return std.mem.eql(u8, a, b); 1754 } else { 1755 @compileError("unsupported field type: " ++ @typeName(Field)); 1756 } 1757 }, 1758 .array => |array_info| { 1759 if (array_info.child == u8) { 1760 return std.mem.eql(u8, &a, &b); 1761 } else { 1762 @compileError("unsupported field type: " ++ @typeName(Field)); 1763 } 1764 }, 1765 .void => return true, 1766 .bool, .int, .@"enum" => return a == b, 1767 .@"union" => { 1768 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1769 return switch (a) { 1770 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 1771 }; 1772 }, 1773 .@"struct" => return fieldsEqual(Field, a, b), 1774 .optional => |optional_info| { 1775 if (a) |a_value| { 1776 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 1777 return false; 1778 } 1779 return b == null; 1780 }, 1781 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1782 } 1783 } 1784 1785 // 1786 // writing to xitdb 1787 // 1788 1789 pub fn upsert( 1790 comptime T: type, 1791 comptime DB: type, 1792 comptime hash_kind: hash.HashKind, 1793 map: DB.HashMap(.read_write), 1794 event: T, 1795 ) !void { 1796 switch (@typeInfo(T)) { 1797 .@"struct" => |struct_info| { 1798 inline for (struct_info.fields) |field| { 1799 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1800 } 1801 }, 1802 else => @compileError("upsert expects a struct"), 1803 } 1804 } 1805 1806 fn upsertField( 1807 comptime DB: type, 1808 comptime hash_kind: hash.HashKind, 1809 map: DB.HashMap(.read_write), 1810 comptime field_name: []const u8, 1811 comptime Field: type, 1812 value: Field, 1813 ) !void { 1814 const key = hash.hashInt(hash_kind, field_name); 1815 1816 switch (@typeInfo(Field)) { 1817 .pointer => |pointer_info| { 1818 if (pointer_info.size == .slice and pointer_info.child == u8) { 1819 try upsertBytes(DB, hash_kind, map, key, value); 1820 } else { 1821 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1822 } 1823 }, 1824 .array => |array_info| { 1825 if (array_info.child == u8) { 1826 try upsertBytes(DB, hash_kind, map, key, &value); 1827 } else { 1828 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1829 } 1830 }, 1831 .int => |int_info| switch (int_info.signedness) { 1832 .unsigned => { 1833 if (try map.getCursor(key)) |value_cursor| { 1834 if (try value_cursor.readUint() == value) { 1835 return; 1836 } 1837 } 1838 1839 try map.put(key, .{ .uint = value }); 1840 }, 1841 .signed => { 1842 if (try map.getCursor(key)) |value_cursor| { 1843 if (try value_cursor.readInt() == value) { 1844 return; 1845 } 1846 } 1847 1848 try map.put(key, .{ .int = value }); 1849 }, 1850 }, 1851 .bool => { 1852 const bytes = if (value) "true" else "false"; 1853 if (try map.getCursor(key)) |value_cursor| { 1854 var buffer: [5]u8 = undefined; 1855 const existing = try value_cursor.readBytesObject(&buffer); 1856 if (existing.format_tag) |format_tag| { 1857 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1858 return; 1859 } 1860 } 1861 } 1862 1863 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1864 }, 1865 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1866 .@"union" => switch (value) { 1867 inline else => |payload, tag| { 1868 if (@TypeOf(payload) == void) { 1869 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 1870 } else { 1871 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 1872 if (try map.getCursor(key)) |cursor| { 1873 switch (cursor.slot().tag) { 1874 .hash_map => { 1875 const variants = try DB.HashMap(.read_only).init(cursor); 1876 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 1877 }, 1878 else => try map.put(key, .{ .slot = null }), 1879 } 1880 } 1881 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 1882 if (@typeInfo(@TypeOf(payload)) == .optional) { 1883 // keep the variant even when its payload is null 1884 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 1885 } 1886 if (try variants.getCursor(tag_key)) |cursor| { 1887 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 1888 } 1889 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 1890 } 1891 }, 1892 }, 1893 .optional => |optional_info| { 1894 // a missing key is null 1895 if (value) |child| { 1896 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 1897 } else { 1898 _ = try map.remove(key); 1899 } 1900 }, 1901 .@"struct" => try upsert( 1902 Field, 1903 DB, 1904 hash_kind, 1905 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1906 value, 1907 ), 1908 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1909 } 1910 } 1911 1912 fn upsertBytes( 1913 comptime DB: type, 1914 comptime hash_kind: hash.HashKind, 1915 map: DB.HashMap(.read_write), 1916 key: hash.HashInt(hash_kind), 1917 value: []const u8, 1918 ) !void { 1919 var existing_cursor_maybe = try map.getCursor(key); 1920 if (existing_cursor_maybe) |*existing_cursor| { 1921 if (try bytesEqual(DB, existing_cursor, value)) { 1922 return; 1923 } 1924 } 1925 1926 try map.put(key, .{ .bytes = value }); 1927 } 1928 1929 fn bytesEqual( 1930 comptime DB: type, 1931 cursor: *DB.Cursor(.read_only), 1932 value: []const u8, 1933 ) !bool { 1934 switch (cursor.slot().tag) { 1935 .bytes, .short_bytes => {}, 1936 else => return false, 1937 } 1938 var read_buffer: [1024]u8 = undefined; 1939 var reader = try cursor.reader(&read_buffer); 1940 if (reader.size != value.len) { 1941 return false; 1942 } 1943 1944 var chunk_buffer: [1024]u8 = undefined; 1945 var offset: usize = 0; 1946 while (offset < value.len) { 1947 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1948 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1949 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1950 return false; 1951 } 1952 offset += chunk_len; 1953 } 1954 1955 return true; 1956 } 1957 1958 // 1959 // CommitIterator 1960 // 1961 // differs from xit's ObjectIterator in a few ways: 1962 // 1963 // 1. iterates parents first, rather than children first 1964 // 2. `next` only returns the object id, not the full Object 1965 // 3. stores its temporary state in a file on disk to avoid OOMs 1966 // 1967 1968 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1969 return struct { 1970 const DB = EventDB(repo_opts.hash); 1971 // a plain file is used for the scratch db because each write outside 1972 // a transaction is synced anyway, so buffering would gain nothing 1973 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 1974 const db_name = "haxy-repo-events.db"; 1975 1976 repo_dir: std.Io.Dir, 1977 db_file: std.Io.File, 1978 db: *TempDB, 1979 // map of each object id to its children 1980 parent_to_children: TempDB.HashMap(.read_write), 1981 // tracking pending parents is necessary because a child can only 1982 // be returned after all of its unconsumed parents have been returned 1983 child_to_pending_parents: TempDB.HashMap(.read_write), 1984 // queue of object ids that are ready to be returned from `next` 1985 ready_queue: TempDB.ArrayList(.read_write), 1986 ready_queue_index: u64, 1987 // the object id at the tip of this branch 1988 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1989 // the object id furthest back in the history that hasn't been consumed 1990 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1991 1992 pub fn init( 1993 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1994 io: std.Io, 1995 allocator: std.mem.Allocator, 1996 consumed_object_ids: DB.HashMap(.read_only), 1997 ref: rf.Ref, 1998 ) !CommitIterator(repo_kind, repo_opts) { 1999 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2000 errdefer { 2001 db_file.close(io); 2002 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2003 } 2004 2005 // cursors point at the db, so it needs a stable address 2006 const db_ptr = try allocator.create(TempDB); 2007 errdefer allocator.destroy(db_ptr); 2008 // the db is scratch state that gets deleted after iteration, so 2009 // there is nothing worth fsyncing 2010 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2011 2012 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2013 2014 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2015 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2016 2017 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2018 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2019 2020 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2021 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2022 2023 var self = CommitIterator(repo_kind, repo_opts){ 2024 .repo_dir = state.core.repo_dir, 2025 .db_file = db_file, 2026 .db = db_ptr, 2027 .parent_to_children = parent_to_children, 2028 .child_to_pending_parents = child_to_pending_parents, 2029 .ready_queue = ready_queue, 2030 .ready_queue_index = 0, 2031 .newest_object_id = null, 2032 .oldest_object_id = null, 2033 }; 2034 errdefer self.deinit(io, allocator); 2035 2036 try self.collect(state, io, allocator, consumed_object_ids, ref); 2037 2038 return self; 2039 } 2040 2041 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2042 self.db_file.close(io); 2043 self.repo_dir.deleteFile(io, db_name) catch {}; 2044 allocator.destroy(self.db); 2045 } 2046 2047 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2048 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2049 2050 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2051 self.ready_queue_index += 1; 2052 2053 try self.enqueueChildren(&oid); 2054 return oid; 2055 } 2056 2057 fn collect( 2058 self: *CommitIterator(repo_kind, repo_opts), 2059 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2060 io: std.Io, 2061 allocator: std.mem.Allocator, 2062 consumed_object_ids: DB.HashMap(.read_only), 2063 ref: rf.Ref, 2064 ) !void { 2065 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2066 2067 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2068 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2069 var walk_queue_index: u64 = 0; 2070 2071 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2072 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2073 2074 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2075 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2076 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2077 try walk_queue.append(.{ .bytes = &head_oid }); 2078 2079 while (walk_queue_index < try walk_queue.count()) { 2080 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2081 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2082 2083 walk_queue_index += 1; 2084 2085 // if we've seen this object id, skip it 2086 if (null != try seen_object_ids.getCursor(oid_int)) { 2087 continue; 2088 } 2089 2090 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2091 2092 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2093 defer commit_object.deinit(); 2094 2095 // if this object id has already been consumed, skip it 2096 if (null != try consumed_object_ids.getCursor(oid_int)) { 2097 continue; 2098 } 2099 2100 if (self.newest_object_id == null) self.newest_object_id = oid; 2101 self.oldest_object_id = oid; 2102 2103 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2104 var pending_parent_count: u64 = 0; 2105 for (parent_oids) |*parent_oid| { 2106 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2107 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2108 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2109 2110 // if this object id has already been consumed, skip it 2111 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2112 continue; 2113 } 2114 2115 // if this object id hasn't already been seen, add it to the walk queue 2116 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2117 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2118 } 2119 2120 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2121 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2122 try children.put(oid_int, .{ .bytes = &oid }); 2123 pending_parent_count += 1; 2124 } 2125 2126 if (pending_parent_count == 0) { 2127 try self.ready_queue.append(.{ .bytes = &oid }); 2128 } else { 2129 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2130 } 2131 } 2132 } 2133 2134 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2135 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2136 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2137 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2138 var children_iter = try children.iterator(); 2139 2140 while (try children_iter.next()) |*child_cursor| { 2141 const kv_pair = try child_cursor.readKeyValuePair(); 2142 const child_oid_int = kv_pair.hash; 2143 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2144 const pending_parent_count = try pending_parent_cursor.readUint(); 2145 2146 if (pending_parent_count <= 1) { 2147 _ = try self.child_to_pending_parents.remove(child_oid_int); 2148 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2149 try self.ready_queue.append(.{ .bytes = &child_oid }); 2150 } else { 2151 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2152 } 2153 } 2154 } 2155 2156 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2157 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2158 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2159 _ = try oid_cursor.readBytes(&oid); 2160 return oid; 2161 } 2162 }; 2163 } 2164