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