╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
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 readFromRepo( 1372 comptime T: type, 1373 comptime repo_kind: rp.RepoKind, 1374 comptime repo_opts: rp.RepoOpts(repo_kind), 1375 io: std.Io, 1376 allocator: std.mem.Allocator, 1377 arena: *std.heap.ArenaAllocator, 1378 repo: *rp.Repo(repo_kind, repo_opts), 1379 id: *const [event_id_size]u8, 1380 ) !?T.Record { 1381 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1382 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1383 const moment = (if (event_db_maybe) |*event_db| 1384 currentMomentFromDb(repo_opts.hash, event_db.db) 1385 else if (repo_kind == .git) 1386 return null 1387 else 1388 currentMoment(repo_opts, repo)) catch return null; 1389 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1390 } 1391 1392 pub fn currentMoment( 1393 comptime repo_opts: rp.RepoOpts(.xit), 1394 repo: *rp.Repo(.xit, repo_opts), 1395 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1396 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1397 } 1398 1399 pub fn currentMomentFromDb( 1400 comptime hash_kind: hash.HashKind, 1401 db: *EventDB(hash_kind), 1402 ) !EventDB(hash_kind).HashMap(.read_only) { 1403 const DB = EventDB(hash_kind); 1404 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1405 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1406 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1407 return try currentMomentFromRepoMoment(hash_kind, moment); 1408 } 1409 1410 pub fn currentMomentFromRepoMoment( 1411 comptime hash_kind: hash.HashKind, 1412 moment: EventDB(hash_kind).HashMap(.read_only), 1413 ) !EventDB(hash_kind).HashMap(.read_only) { 1414 const DB = EventDB(hash_kind); 1415 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1416 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1417 _ = try last_object_id_cursor.readBytes(&last_object_id); 1418 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, materialized_key)) orelse return error.NotFound; 1419 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 1420 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 1421 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1422 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1423 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1424 } 1425 1426 // build a sorted-set key from an order and event id. big-endian order makes 1427 // byte order match numeric order; the event id breaks ties. 1428 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1429 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1430 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1431 @memcpy(key[@sizeOf(u64)..], event_id); 1432 return key; 1433 } 1434 1435 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1436 return orderKey(std.math.maxInt(u64) - order, event_id); 1437 } 1438 1439 pub fn removedRecord( 1440 comptime T: type, 1441 comptime DB: type, 1442 comptime hash_kind: hash.HashKind, 1443 haxy_moment: DB.HashMap(.read_only), 1444 existing_maybe: ?T, 1445 ) !T { 1446 var record = existing_maybe orelse return error.EventNotFound; 1447 record.removed = true; 1448 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1449 record.updated_order = try order_cursor.readUint(); 1450 return record; 1451 } 1452 1453 // add or refresh one entry in the global logical-event index 1454 pub fn indexEvent( 1455 comptime DB: type, 1456 comptime hash_kind: hash.HashKind, 1457 haxy_moment: DB.HashMap(.read_write), 1458 event_id: *const [event_id_size]u8, 1459 kind: EventKind, 1460 existing_maybe: anytype, 1461 record: anytype, 1462 ) !void { 1463 const event_key = hash.hashInt(hash_kind, event_id); 1464 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1465 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1466 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1467 1468 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1469 const active = try DB.SortedSet(.read_write).init(active_cursor); 1470 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1471 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1472 1473 if (existing_maybe) |existing| { 1474 const old_key = orderKeyDesc(existing.updated_order, event_id); 1475 _ = try active.remove(&old_key); 1476 _ = try removed_set.remove(&old_key); 1477 } 1478 1479 const order_key = orderKeyDesc(record.updated_order, event_id); 1480 if (record.removed) { 1481 try removed_set.put(&order_key); 1482 } else { 1483 try active.put(&order_key); 1484 } 1485 } 1486 1487 pub fn touchThread( 1488 comptime DB: type, 1489 comptime hash_kind: hash.HashKind, 1490 haxy_moment: DB.HashMap(.read_write), 1491 thread_id: *const [event_id_size]u8, 1492 order: u64, 1493 arena: *std.heap.ArenaAllocator, 1494 ) !void { 1495 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1496 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1497 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1498 switch (kind) { 1499 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1500 else => {}, 1501 } 1502 } 1503 1504 pub fn readEventKind( 1505 comptime hash_kind: hash.HashKind, 1506 kind_map: anytype, 1507 id: *const [event_id_size]u8, 1508 ) !?EventKind { 1509 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1510 var buffer: [64]u8 = undefined; 1511 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1512 } 1513 1514 // the event id embedded in a set entry's order key 1515 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1516 var cursor = kv_pair_cursor; 1517 const kv_pair = try cursor.readKeyValuePair(); 1518 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1519 _ = try kv_pair.key_cursor.readBytes(&order_key); 1520 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1521 } 1522 1523 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1524 // isn't exactly two non-empty segments. 1525 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1526 var it = std.mem.splitScalar(u8, path, '/'); 1527 const owner = it.next() orelse return null; 1528 const name = it.next() orelse return null; 1529 if (it.next() != null) return null; 1530 if (owner.len == 0 or name.len == 0) return null; 1531 1532 return .{ .owner = owner, .name = name }; 1533 } 1534 1535 pub const CreateRepoOptions = struct { 1536 read_access: Repo.Access = .private, 1537 }; 1538 1539 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1540 // directory under the repos dir 1541 pub fn resolveOrCreateRepo( 1542 io: std.Io, 1543 allocator: std.mem.Allocator, 1544 admin_repo_path: []const u8, 1545 owner_name: []const u8, 1546 repo_name: []const u8, 1547 create_options_maybe: ?CreateRepoOptions, 1548 ) !?[event_id_size * 2]u8 { 1549 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1550 error.RepoNotFound => return null, 1551 else => |e| return e, 1552 }; 1553 defer repo.deinit(io, allocator); 1554 1555 var arena = std.heap.ArenaAllocator.init(allocator); 1556 defer arena.deinit(); 1557 1558 const moment = try currentMoment(admin_repo_opts, &repo); 1559 1560 // an already-registered repo reuses its event id, so a re-push (or a clone) 1561 // lands in the same repo 1562 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1563 return std.fmt.bytesToHex(found.event_id, .lower); 1564 } 1565 1566 const create_options = create_options_maybe orelse return null; 1567 1568 // the new repo is owned by the named user, read from the name index; an 1569 // unknown owner can't own a repo, so the push is rejected 1570 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1571 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1572 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1573 var owner_user_id: [event_id_size]u8 = undefined; 1574 _ = try owner_id_cursor.readBytes(&owner_user_id); 1575 1576 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1577 1578 var id_bytes: [event_id_size]u8 = undefined; 1579 io.random(&id_bytes); 1580 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1581 1582 try consume(.server, .admin, .xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1583 .id = event_id_hex, 1584 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1585 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1586 .event = .{ .repo = .{ 1587 .user_id = &owner_user_id, 1588 .name = repo_name, 1589 .description = "", 1590 .read_access = create_options.read_access, 1591 } }, 1592 }}); 1593 1594 return event_id_hex; 1595 } 1596 1597 // 1598 // reading from xitdb 1599 // 1600 1601 pub fn read( 1602 comptime T: type, 1603 comptime DB: type, 1604 comptime hash_kind: hash.HashKind, 1605 arena: *std.heap.ArenaAllocator, 1606 map: DB.HashMap(.read_only), 1607 ) !T { 1608 var event: T = undefined; 1609 switch (@typeInfo(T)) { 1610 .@"struct" => |struct_info| { 1611 inline for (struct_info.fields) |field| { 1612 const cursor = try map.getCursor(hash.hashInt(hash_kind, field.name)); 1613 @field(event, field.name) = try readField(field.type, DB, hash_kind, arena, cursor); 1614 } 1615 }, 1616 else => @compileError("read expects a struct"), 1617 } 1618 return event; 1619 } 1620 1621 fn readField( 1622 comptime Field: type, 1623 comptime DB: type, 1624 comptime hash_kind: hash.HashKind, 1625 arena: *std.heap.ArenaAllocator, 1626 cursor_maybe: ?DB.Cursor(.read_only), 1627 ) !Field { 1628 if (@typeInfo(Field) == .optional) { 1629 // a missing key or a null union payload is null 1630 const cursor = cursor_maybe orelse return null; 1631 if (cursor.slot().tag == .none) return null; 1632 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 1633 } 1634 const cursor = cursor_maybe orelse return error.NotFound; 1635 switch (@typeInfo(Field)) { 1636 .pointer => |pointer_info| { 1637 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.is_const) { 1638 @compileError("unsupported read field type: " ++ @typeName(Field)); 1639 } 1640 return try cursor.readBytesAlloc(arena.allocator(), null); 1641 }, 1642 .array => |array_info| { 1643 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 1644 var bytes: Field = undefined; 1645 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 1646 return bytes; 1647 }, 1648 .bool => { 1649 var buffer: [5]u8 = undefined; 1650 const bytes = try cursor.readBytesObject(&buffer); 1651 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1652 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1653 if (std.mem.eql(u8, bytes.value, "true")) return true; 1654 if (std.mem.eql(u8, bytes.value, "false")) return false; 1655 return error.InvalidBool; 1656 }, 1657 .int => |int_info| return switch (int_info.signedness) { 1658 .unsigned => @intCast(try cursor.readUint()), 1659 .signed => @intCast(try cursor.readInt()), 1660 }, 1661 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 1662 .@"union" => |union_info| { 1663 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 1664 switch (cursor.slot().tag) { 1665 .bytes, .short_bytes => { 1666 const name = try cursor.readBytesAlloc(arena.allocator(), null); 1667 inline for (union_info.fields) |variant| { 1668 if (variant.type == void and std.mem.eql(u8, name, variant.name)) { 1669 return @unionInit(Field, variant.name, {}); 1670 } 1671 } 1672 return error.InvalidUnion; 1673 }, 1674 .hash_map => { 1675 const variants = try DB.HashMap(.read_only).init(cursor); 1676 var iter = try variants.iterator(); 1677 const entry = (try iter.next()) orelse return error.InvalidUnion; 1678 const pair = try entry.readKeyValuePair(); 1679 if (try iter.next() != null) return error.InvalidUnion; 1680 inline for (union_info.fields) |variant| { 1681 if (variant.type != void and pair.hash == hash.hashInt(hash_kind, variant.name)) { 1682 return @unionInit(Field, variant.name, try readField(variant.type, DB, hash_kind, arena, pair.value_cursor)); 1683 } 1684 } 1685 return error.InvalidUnion; 1686 }, 1687 else => return error.InvalidUnion, 1688 } 1689 }, 1690 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 1691 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 1692 } 1693 } 1694 1695 // whether two events carry the same data 1696 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1697 switch (@typeInfo(T)) { 1698 .@"struct" => |struct_info| { 1699 inline for (struct_info.fields) |field| { 1700 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1701 } 1702 }, 1703 else => @compileError("fieldsEqual expects a struct"), 1704 } 1705 1706 return true; 1707 } 1708 1709 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1710 switch (@typeInfo(Field)) { 1711 .pointer => |pointer_info| { 1712 if (pointer_info.size == .slice and pointer_info.child == u8) { 1713 return std.mem.eql(u8, a, b); 1714 } else { 1715 @compileError("unsupported field type: " ++ @typeName(Field)); 1716 } 1717 }, 1718 .array => |array_info| { 1719 if (array_info.child == u8) { 1720 return std.mem.eql(u8, &a, &b); 1721 } else { 1722 @compileError("unsupported field type: " ++ @typeName(Field)); 1723 } 1724 }, 1725 .void => return true, 1726 .bool, .int, .@"enum" => return a == b, 1727 .@"union" => { 1728 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1729 return switch (a) { 1730 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 1731 }; 1732 }, 1733 .@"struct" => return fieldsEqual(Field, a, b), 1734 .optional => |optional_info| { 1735 if (a) |a_value| { 1736 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 1737 return false; 1738 } 1739 return b == null; 1740 }, 1741 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1742 } 1743 } 1744 1745 // 1746 // writing to xitdb 1747 // 1748 1749 pub fn upsert( 1750 comptime T: type, 1751 comptime DB: type, 1752 comptime hash_kind: hash.HashKind, 1753 map: DB.HashMap(.read_write), 1754 event: T, 1755 ) !void { 1756 switch (@typeInfo(T)) { 1757 .@"struct" => |struct_info| { 1758 inline for (struct_info.fields) |field| { 1759 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1760 } 1761 }, 1762 else => @compileError("upsert expects a struct"), 1763 } 1764 } 1765 1766 fn upsertField( 1767 comptime DB: type, 1768 comptime hash_kind: hash.HashKind, 1769 map: DB.HashMap(.read_write), 1770 comptime field_name: []const u8, 1771 comptime Field: type, 1772 value: Field, 1773 ) !void { 1774 const key = hash.hashInt(hash_kind, field_name); 1775 1776 switch (@typeInfo(Field)) { 1777 .pointer => |pointer_info| { 1778 if (pointer_info.size == .slice and pointer_info.child == u8) { 1779 try upsertBytes(DB, hash_kind, map, key, value); 1780 } else { 1781 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1782 } 1783 }, 1784 .array => |array_info| { 1785 if (array_info.child == u8) { 1786 try upsertBytes(DB, hash_kind, map, key, &value); 1787 } else { 1788 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1789 } 1790 }, 1791 .int => |int_info| switch (int_info.signedness) { 1792 .unsigned => { 1793 if (try map.getCursor(key)) |value_cursor| { 1794 if (try value_cursor.readUint() == value) { 1795 return; 1796 } 1797 } 1798 1799 try map.put(key, .{ .uint = value }); 1800 }, 1801 .signed => { 1802 if (try map.getCursor(key)) |value_cursor| { 1803 if (try value_cursor.readInt() == value) { 1804 return; 1805 } 1806 } 1807 1808 try map.put(key, .{ .int = value }); 1809 }, 1810 }, 1811 .bool => { 1812 const bytes = if (value) "true" else "false"; 1813 if (try map.getCursor(key)) |value_cursor| { 1814 var buffer: [5]u8 = undefined; 1815 const existing = try value_cursor.readBytesObject(&buffer); 1816 if (existing.format_tag) |format_tag| { 1817 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1818 return; 1819 } 1820 } 1821 } 1822 1823 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1824 }, 1825 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1826 .@"union" => switch (value) { 1827 inline else => |payload, tag| { 1828 if (@TypeOf(payload) == void) { 1829 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 1830 } else { 1831 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 1832 if (try map.getCursor(key)) |cursor| { 1833 switch (cursor.slot().tag) { 1834 .hash_map => { 1835 const variants = try DB.HashMap(.read_only).init(cursor); 1836 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 1837 }, 1838 else => try map.put(key, .{ .slot = null }), 1839 } 1840 } 1841 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 1842 if (@typeInfo(@TypeOf(payload)) == .optional) { 1843 // keep the variant even when its payload is null 1844 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 1845 } 1846 if (try variants.getCursor(tag_key)) |cursor| { 1847 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 1848 } 1849 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 1850 } 1851 }, 1852 }, 1853 .optional => |optional_info| { 1854 // a missing key is null 1855 if (value) |child| { 1856 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 1857 } else { 1858 _ = try map.remove(key); 1859 } 1860 }, 1861 .@"struct" => try upsert( 1862 Field, 1863 DB, 1864 hash_kind, 1865 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1866 value, 1867 ), 1868 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1869 } 1870 } 1871 1872 fn upsertBytes( 1873 comptime DB: type, 1874 comptime hash_kind: hash.HashKind, 1875 map: DB.HashMap(.read_write), 1876 key: hash.HashInt(hash_kind), 1877 value: []const u8, 1878 ) !void { 1879 var existing_cursor_maybe = try map.getCursor(key); 1880 if (existing_cursor_maybe) |*existing_cursor| { 1881 if (try bytesEqual(DB, existing_cursor, value)) { 1882 return; 1883 } 1884 } 1885 1886 try map.put(key, .{ .bytes = value }); 1887 } 1888 1889 fn bytesEqual( 1890 comptime DB: type, 1891 cursor: *DB.Cursor(.read_only), 1892 value: []const u8, 1893 ) !bool { 1894 switch (cursor.slot().tag) { 1895 .bytes, .short_bytes => {}, 1896 else => return false, 1897 } 1898 var read_buffer: [1024]u8 = undefined; 1899 var reader = try cursor.reader(&read_buffer); 1900 if (reader.size != value.len) { 1901 return false; 1902 } 1903 1904 var chunk_buffer: [1024]u8 = undefined; 1905 var offset: usize = 0; 1906 while (offset < value.len) { 1907 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1908 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1909 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1910 return false; 1911 } 1912 offset += chunk_len; 1913 } 1914 1915 return true; 1916 } 1917 1918 // 1919 // CommitIterator 1920 // 1921 // differs from xit's ObjectIterator in a few ways: 1922 // 1923 // 1. iterates parents first, rather than children first 1924 // 2. `next` only returns the object id, not the full Object 1925 // 3. stores its temporary state in a file on disk to avoid OOMs 1926 // 1927 1928 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1929 return struct { 1930 const DB = EventDB(repo_opts.hash); 1931 const db_name = "haxy-repo-events.db"; 1932 1933 repo_dir: std.Io.Dir, 1934 db_file: std.Io.File, 1935 db: *DB, 1936 // map of each object id to its children 1937 parent_to_children: DB.HashMap(.read_write), 1938 // tracking pending parents is necessary because a child can only 1939 // be returned after all of its unconsumed parents have been returned 1940 child_to_pending_parents: DB.HashMap(.read_write), 1941 // queue of object ids that are ready to be returned from `next` 1942 ready_queue: DB.ArrayList(.read_write), 1943 ready_queue_index: u64, 1944 // the object id at the tip of this branch 1945 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1946 // the object id furthest back in the history that hasn't been consumed 1947 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1948 1949 pub fn init( 1950 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1951 io: std.Io, 1952 allocator: std.mem.Allocator, 1953 consumed_object_ids: DB.HashMap(.read_only), 1954 ref: rf.Ref, 1955 ) !CommitIterator(repo_kind, repo_opts) { 1956 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1957 errdefer { 1958 db_file.close(io); 1959 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1960 } 1961 1962 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1963 errdefer allocator.destroy(buffer_ptr); 1964 1965 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1966 errdefer buffer_ptr.deinit(); 1967 1968 const db_ptr = try allocator.create(DB); 1969 errdefer allocator.destroy(db_ptr); 1970 // the db is scratch state that gets deleted after iteration, so 1971 // there is nothing worth fsyncing 1972 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 1973 1974 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1975 1976 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1977 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1978 1979 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1980 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1981 1982 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1983 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1984 1985 var self = CommitIterator(repo_kind, repo_opts){ 1986 .repo_dir = state.core.repo_dir, 1987 .db_file = db_file, 1988 .db = db_ptr, 1989 .parent_to_children = parent_to_children, 1990 .child_to_pending_parents = child_to_pending_parents, 1991 .ready_queue = ready_queue, 1992 .ready_queue_index = 0, 1993 .newest_object_id = null, 1994 .oldest_object_id = null, 1995 }; 1996 errdefer self.deinit(io, allocator); 1997 1998 try self.collect(state, io, allocator, consumed_object_ids, ref); 1999 2000 return self; 2001 } 2002 2003 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2004 self.db_file.close(io); 2005 self.db.core.memory.buffer.deinit(); 2006 allocator.destroy(self.db.core.memory.buffer); 2007 self.repo_dir.deleteFile(io, db_name) catch {}; 2008 allocator.destroy(self.db); 2009 } 2010 2011 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2012 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2013 2014 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2015 self.ready_queue_index += 1; 2016 2017 try self.enqueueChildren(&oid); 2018 return oid; 2019 } 2020 2021 fn collect( 2022 self: *CommitIterator(repo_kind, repo_opts), 2023 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2024 io: std.Io, 2025 allocator: std.mem.Allocator, 2026 consumed_object_ids: DB.HashMap(.read_only), 2027 ref: rf.Ref, 2028 ) !void { 2029 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 2030 2031 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2032 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 2033 var walk_queue_index: u64 = 0; 2034 2035 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2036 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 2037 2038 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2039 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2040 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2041 try walk_queue.append(.{ .bytes = &head_oid }); 2042 2043 while (walk_queue_index < try walk_queue.count()) { 2044 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2045 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2046 2047 walk_queue_index += 1; 2048 2049 // if we've seen this object id, skip it 2050 if (null != try seen_object_ids.getCursor(oid_int)) { 2051 continue; 2052 } 2053 2054 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2055 2056 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2057 defer commit_object.deinit(); 2058 2059 // if this object id has already been consumed, skip it 2060 if (null != try consumed_object_ids.getCursor(oid_int)) { 2061 continue; 2062 } 2063 2064 if (self.newest_object_id == null) self.newest_object_id = oid; 2065 self.oldest_object_id = oid; 2066 2067 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2068 var pending_parent_count: u64 = 0; 2069 for (parent_oids) |*parent_oid| { 2070 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2071 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2072 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2073 2074 // if this object id has already been consumed, skip it 2075 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2076 continue; 2077 } 2078 2079 // if this object id hasn't already been seen, add it to the walk queue 2080 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2081 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2082 } 2083 2084 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2085 const children = try DB.HashSet(.read_write).init(children_cursor); 2086 try children.put(oid_int, .{ .bytes = &oid }); 2087 pending_parent_count += 1; 2088 } 2089 2090 if (pending_parent_count == 0) { 2091 try self.ready_queue.append(.{ .bytes = &oid }); 2092 } else { 2093 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2094 } 2095 } 2096 } 2097 2098 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2099 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2100 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2101 const children = try DB.HashSet(.read_only).init(children_cursor); 2102 var children_iter = try children.iterator(); 2103 2104 while (try children_iter.next()) |*child_cursor| { 2105 const kv_pair = try child_cursor.readKeyValuePair(); 2106 const child_oid_int = kv_pair.hash; 2107 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2108 const pending_parent_count = try pending_parent_cursor.readUint(); 2109 2110 if (pending_parent_count <= 1) { 2111 _ = try self.child_to_pending_parents.remove(child_oid_int); 2112 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2113 try self.ready_queue.append(.{ .bytes = &child_oid }); 2114 } else { 2115 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2116 } 2117 } 2118 } 2119 2120 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2121 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2122 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2123 _ = try oid_cursor.readBytes(&oid); 2124 return oid; 2125 } 2126 }; 2127 } 2128