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