╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
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 email of the event's author, or null when the id names no authored event 1515 // of this kind 1516 pub fn readAuthorEmail( 1517 comptime repo_kind: rp.RepoKind, 1518 comptime repo_opts: rp.RepoOpts(repo_kind), 1519 io: std.Io, 1520 allocator: std.mem.Allocator, 1521 arena: *std.heap.ArenaAllocator, 1522 repo: *rp.Repo(repo_kind, repo_opts), 1523 kind: EventKind, 1524 id: *const [event_id_size]u8, 1525 ) !?[]const u8 { 1526 const record_map_key = switch (kind) { 1527 .issue => Issue.record_map_key, 1528 .discuss => Discussion.record_map_key, 1529 .comment => Comment.record_map_key, 1530 .attach => Attachment.record_map_key, 1531 .patchrev => PatchRev.record_map_key, 1532 .patch => Patch.record_map_key, 1533 .user, .repo, .fork => return null, 1534 }; 1535 1536 const DB = EventDB(repo_opts.hash); 1537 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; 1538 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1539 const moment = (if (event_db_maybe) |*event_db| 1540 currentMomentFromDb(repo_opts.hash, event_db.db) 1541 else if (repo_kind == .git) 1542 return null 1543 else 1544 currentMoment(repo_opts, repo)) catch return null; 1545 1546 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1547 const records = try DB.HashMap(.read_only).init(records_cursor); 1548 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1549 const record = try DB.HashMap(.read_only).init(record_cursor); 1550 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1551 } 1552 1553 // the event id embedded in a set entry's order key 1554 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1555 var cursor = kv_pair_cursor; 1556 const kv_pair = try cursor.readKeyValuePair(); 1557 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1558 _ = try kv_pair.key_cursor.readBytes(&order_key); 1559 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1560 } 1561 1562 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1563 // isn't exactly two non-empty segments. 1564 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1565 var it = std.mem.splitScalar(u8, path, '/'); 1566 const owner = it.next() orelse return null; 1567 const name = it.next() orelse return null; 1568 if (it.next() != null) return null; 1569 if (owner.len == 0 or name.len == 0) return null; 1570 1571 return .{ .owner = owner, .name = name }; 1572 } 1573 1574 pub const CreateRepoOptions = struct { 1575 read_access: Repo.Access = .private, 1576 }; 1577 1578 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1579 // directory under the repos dir 1580 pub fn resolveOrCreateRepo( 1581 io: std.Io, 1582 allocator: std.mem.Allocator, 1583 admin_repo_path: []const u8, 1584 owner_name: []const u8, 1585 repo_name: []const u8, 1586 create_options_maybe: ?CreateRepoOptions, 1587 ) !?[event_id_size * 2]u8 { 1588 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1589 error.RepoNotFound => return null, 1590 else => |e| return e, 1591 }; 1592 defer repo.deinit(io, allocator); 1593 1594 var arena = std.heap.ArenaAllocator.init(allocator); 1595 defer arena.deinit(); 1596 1597 const moment = try currentMoment(admin_repo_opts, &repo); 1598 1599 // an already-registered repo reuses its event id, so a re-push (or a clone) 1600 // lands in the same repo 1601 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1602 return std.fmt.bytesToHex(found.event_id, .lower); 1603 } 1604 1605 const create_options = create_options_maybe orelse return null; 1606 1607 // the new repo is owned by the named user, read from the name index; an 1608 // unknown owner can't own a repo, so the push is rejected 1609 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1610 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1611 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1612 var owner_user_id: [event_id_size]u8 = undefined; 1613 _ = try owner_id_cursor.readBytes(&owner_user_id); 1614 1615 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1616 1617 var id_bytes: [event_id_size]u8 = undefined; 1618 io.random(&id_bytes); 1619 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1620 1621 try consume(.server, .admin, .xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1622 .id = event_id_hex, 1623 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1624 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1625 .event = .{ .repo = .{ 1626 .user_id = &owner_user_id, 1627 .name = repo_name, 1628 .description = "", 1629 .read_access = create_options.read_access, 1630 } }, 1631 }}); 1632 1633 return event_id_hex; 1634 } 1635 1636 // 1637 // reading from xitdb 1638 // 1639 1640 pub fn read( 1641 comptime T: type, 1642 comptime DB: type, 1643 comptime hash_kind: hash.HashKind, 1644 arena: *std.heap.ArenaAllocator, 1645 map: DB.HashMap(.read_only), 1646 ) !T { 1647 var event: T = undefined; 1648 switch (@typeInfo(T)) { 1649 .@"struct" => |struct_info| { 1650 inline for (struct_info.fields) |field| { 1651 const cursor = try map.getCursor(hash.hashInt(hash_kind, field.name)); 1652 @field(event, field.name) = try readField(field.type, DB, hash_kind, arena, cursor); 1653 } 1654 }, 1655 else => @compileError("read expects a struct"), 1656 } 1657 return event; 1658 } 1659 1660 fn readField( 1661 comptime Field: type, 1662 comptime DB: type, 1663 comptime hash_kind: hash.HashKind, 1664 arena: *std.heap.ArenaAllocator, 1665 cursor_maybe: ?DB.Cursor(.read_only), 1666 ) !Field { 1667 if (@typeInfo(Field) == .optional) { 1668 // a missing key or a null union payload is null 1669 const cursor = cursor_maybe orelse return null; 1670 if (cursor.slot().tag == .none) return null; 1671 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 1672 } 1673 const cursor = cursor_maybe orelse return error.NotFound; 1674 switch (@typeInfo(Field)) { 1675 .pointer => |pointer_info| { 1676 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.is_const) { 1677 @compileError("unsupported read field type: " ++ @typeName(Field)); 1678 } 1679 return try cursor.readBytesAlloc(arena.allocator(), null); 1680 }, 1681 .array => |array_info| { 1682 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 1683 var bytes: Field = undefined; 1684 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 1685 return bytes; 1686 }, 1687 .bool => { 1688 var buffer: [5]u8 = undefined; 1689 const bytes = try cursor.readBytesObject(&buffer); 1690 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1691 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1692 if (std.mem.eql(u8, bytes.value, "true")) return true; 1693 if (std.mem.eql(u8, bytes.value, "false")) return false; 1694 return error.InvalidBool; 1695 }, 1696 .int => |int_info| return switch (int_info.signedness) { 1697 .unsigned => @intCast(try cursor.readUint()), 1698 .signed => @intCast(try cursor.readInt()), 1699 }, 1700 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 1701 .@"union" => |union_info| { 1702 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 1703 switch (cursor.slot().tag) { 1704 .bytes, .short_bytes => { 1705 const name = try cursor.readBytesAlloc(arena.allocator(), null); 1706 inline for (union_info.fields) |variant| { 1707 if (variant.type == void and std.mem.eql(u8, name, variant.name)) { 1708 return @unionInit(Field, variant.name, {}); 1709 } 1710 } 1711 return error.InvalidUnion; 1712 }, 1713 .hash_map => { 1714 const variants = try DB.HashMap(.read_only).init(cursor); 1715 var iter = try variants.iterator(); 1716 const entry = (try iter.next()) orelse return error.InvalidUnion; 1717 const pair = try entry.readKeyValuePair(); 1718 if (try iter.next() != null) return error.InvalidUnion; 1719 inline for (union_info.fields) |variant| { 1720 if (variant.type != void and pair.hash == hash.hashInt(hash_kind, variant.name)) { 1721 return @unionInit(Field, variant.name, try readField(variant.type, DB, hash_kind, arena, pair.value_cursor)); 1722 } 1723 } 1724 return error.InvalidUnion; 1725 }, 1726 else => return error.InvalidUnion, 1727 } 1728 }, 1729 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 1730 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 1731 } 1732 } 1733 1734 // whether two events carry the same data 1735 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1736 switch (@typeInfo(T)) { 1737 .@"struct" => |struct_info| { 1738 inline for (struct_info.fields) |field| { 1739 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1740 } 1741 }, 1742 else => @compileError("fieldsEqual expects a struct"), 1743 } 1744 1745 return true; 1746 } 1747 1748 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1749 switch (@typeInfo(Field)) { 1750 .pointer => |pointer_info| { 1751 if (pointer_info.size == .slice and pointer_info.child == u8) { 1752 return std.mem.eql(u8, a, b); 1753 } else { 1754 @compileError("unsupported field type: " ++ @typeName(Field)); 1755 } 1756 }, 1757 .array => |array_info| { 1758 if (array_info.child == u8) { 1759 return std.mem.eql(u8, &a, &b); 1760 } else { 1761 @compileError("unsupported field type: " ++ @typeName(Field)); 1762 } 1763 }, 1764 .void => return true, 1765 .bool, .int, .@"enum" => return a == b, 1766 .@"union" => { 1767 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1768 return switch (a) { 1769 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 1770 }; 1771 }, 1772 .@"struct" => return fieldsEqual(Field, a, b), 1773 .optional => |optional_info| { 1774 if (a) |a_value| { 1775 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 1776 return false; 1777 } 1778 return b == null; 1779 }, 1780 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1781 } 1782 } 1783 1784 // 1785 // writing to xitdb 1786 // 1787 1788 pub fn upsert( 1789 comptime T: type, 1790 comptime DB: type, 1791 comptime hash_kind: hash.HashKind, 1792 map: DB.HashMap(.read_write), 1793 event: T, 1794 ) !void { 1795 switch (@typeInfo(T)) { 1796 .@"struct" => |struct_info| { 1797 inline for (struct_info.fields) |field| { 1798 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1799 } 1800 }, 1801 else => @compileError("upsert expects a struct"), 1802 } 1803 } 1804 1805 fn upsertField( 1806 comptime DB: type, 1807 comptime hash_kind: hash.HashKind, 1808 map: DB.HashMap(.read_write), 1809 comptime field_name: []const u8, 1810 comptime Field: type, 1811 value: Field, 1812 ) !void { 1813 const key = hash.hashInt(hash_kind, field_name); 1814 1815 switch (@typeInfo(Field)) { 1816 .pointer => |pointer_info| { 1817 if (pointer_info.size == .slice and pointer_info.child == u8) { 1818 try upsertBytes(DB, hash_kind, map, key, value); 1819 } else { 1820 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1821 } 1822 }, 1823 .array => |array_info| { 1824 if (array_info.child == u8) { 1825 try upsertBytes(DB, hash_kind, map, key, &value); 1826 } else { 1827 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1828 } 1829 }, 1830 .int => |int_info| switch (int_info.signedness) { 1831 .unsigned => { 1832 if (try map.getCursor(key)) |value_cursor| { 1833 if (try value_cursor.readUint() == value) { 1834 return; 1835 } 1836 } 1837 1838 try map.put(key, .{ .uint = value }); 1839 }, 1840 .signed => { 1841 if (try map.getCursor(key)) |value_cursor| { 1842 if (try value_cursor.readInt() == value) { 1843 return; 1844 } 1845 } 1846 1847 try map.put(key, .{ .int = value }); 1848 }, 1849 }, 1850 .bool => { 1851 const bytes = if (value) "true" else "false"; 1852 if (try map.getCursor(key)) |value_cursor| { 1853 var buffer: [5]u8 = undefined; 1854 const existing = try value_cursor.readBytesObject(&buffer); 1855 if (existing.format_tag) |format_tag| { 1856 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1857 return; 1858 } 1859 } 1860 } 1861 1862 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1863 }, 1864 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1865 .@"union" => switch (value) { 1866 inline else => |payload, tag| { 1867 if (@TypeOf(payload) == void) { 1868 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 1869 } else { 1870 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 1871 if (try map.getCursor(key)) |cursor| { 1872 switch (cursor.slot().tag) { 1873 .hash_map => { 1874 const variants = try DB.HashMap(.read_only).init(cursor); 1875 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 1876 }, 1877 else => try map.put(key, .{ .slot = null }), 1878 } 1879 } 1880 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 1881 if (@typeInfo(@TypeOf(payload)) == .optional) { 1882 // keep the variant even when its payload is null 1883 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 1884 } 1885 if (try variants.getCursor(tag_key)) |cursor| { 1886 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 1887 } 1888 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 1889 } 1890 }, 1891 }, 1892 .optional => |optional_info| { 1893 // a missing key is null 1894 if (value) |child| { 1895 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 1896 } else { 1897 _ = try map.remove(key); 1898 } 1899 }, 1900 .@"struct" => try upsert( 1901 Field, 1902 DB, 1903 hash_kind, 1904 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1905 value, 1906 ), 1907 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1908 } 1909 } 1910 1911 fn upsertBytes( 1912 comptime DB: type, 1913 comptime hash_kind: hash.HashKind, 1914 map: DB.HashMap(.read_write), 1915 key: hash.HashInt(hash_kind), 1916 value: []const u8, 1917 ) !void { 1918 var existing_cursor_maybe = try map.getCursor(key); 1919 if (existing_cursor_maybe) |*existing_cursor| { 1920 if (try bytesEqual(DB, existing_cursor, value)) { 1921 return; 1922 } 1923 } 1924 1925 try map.put(key, .{ .bytes = value }); 1926 } 1927 1928 fn bytesEqual( 1929 comptime DB: type, 1930 cursor: *DB.Cursor(.read_only), 1931 value: []const u8, 1932 ) !bool { 1933 switch (cursor.slot().tag) { 1934 .bytes, .short_bytes => {}, 1935 else => return false, 1936 } 1937 var read_buffer: [1024]u8 = undefined; 1938 var reader = try cursor.reader(&read_buffer); 1939 if (reader.size != value.len) { 1940 return false; 1941 } 1942 1943 var chunk_buffer: [1024]u8 = undefined; 1944 var offset: usize = 0; 1945 while (offset < value.len) { 1946 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1947 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1948 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1949 return false; 1950 } 1951 offset += chunk_len; 1952 } 1953 1954 return true; 1955 } 1956 1957 // 1958 // CommitIterator 1959 // 1960 // differs from xit's ObjectIterator in a few ways: 1961 // 1962 // 1. iterates parents first, rather than children first 1963 // 2. `next` only returns the object id, not the full Object 1964 // 3. stores its temporary state in a file on disk to avoid OOMs 1965 // 1966 1967 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1968 return struct { 1969 const DB = EventDB(repo_opts.hash); 1970 // a plain file is used for the scratch db because each write outside 1971 // a transaction is synced anyway, so buffering would gain nothing 1972 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 1973 const db_name = "haxy-repo-events.db"; 1974 1975 repo_dir: std.Io.Dir, 1976 db_file: std.Io.File, 1977 db: *TempDB, 1978 // map of each object id to its children 1979 parent_to_children: TempDB.HashMap(.read_write), 1980 // tracking pending parents is necessary because a child can only 1981 // be returned after all of its unconsumed parents have been returned 1982 child_to_pending_parents: TempDB.HashMap(.read_write), 1983 // queue of object ids that are ready to be returned from `next` 1984 ready_queue: TempDB.ArrayList(.read_write), 1985 ready_queue_index: u64, 1986 // the object id at the tip of this branch 1987 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1988 // the object id furthest back in the history that hasn't been consumed 1989 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1990 1991 pub fn init( 1992 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1993 io: std.Io, 1994 allocator: std.mem.Allocator, 1995 consumed_object_ids: DB.HashMap(.read_only), 1996 ref: rf.Ref, 1997 ) !CommitIterator(repo_kind, repo_opts) { 1998 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1999 errdefer { 2000 db_file.close(io); 2001 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2002 } 2003 2004 // cursors point at the db, so it needs a stable address 2005 const db_ptr = try allocator.create(TempDB); 2006 errdefer allocator.destroy(db_ptr); 2007 // the db is scratch state that gets deleted after iteration, so 2008 // there is nothing worth fsyncing 2009 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2010 2011 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2012 2013 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2014 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2015 2016 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2017 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2018 2019 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2020 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2021 2022 var self = CommitIterator(repo_kind, repo_opts){ 2023 .repo_dir = state.core.repo_dir, 2024 .db_file = db_file, 2025 .db = db_ptr, 2026 .parent_to_children = parent_to_children, 2027 .child_to_pending_parents = child_to_pending_parents, 2028 .ready_queue = ready_queue, 2029 .ready_queue_index = 0, 2030 .newest_object_id = null, 2031 .oldest_object_id = null, 2032 }; 2033 errdefer self.deinit(io, allocator); 2034 2035 try self.collect(state, io, allocator, consumed_object_ids, ref); 2036 2037 return self; 2038 } 2039 2040 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2041 self.db_file.close(io); 2042 self.repo_dir.deleteFile(io, db_name) catch {}; 2043 allocator.destroy(self.db); 2044 } 2045 2046 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2047 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2048 2049 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2050 self.ready_queue_index += 1; 2051 2052 try self.enqueueChildren(&oid); 2053 return oid; 2054 } 2055 2056 fn collect( 2057 self: *CommitIterator(repo_kind, repo_opts), 2058 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2059 io: std.Io, 2060 allocator: std.mem.Allocator, 2061 consumed_object_ids: DB.HashMap(.read_only), 2062 ref: rf.Ref, 2063 ) !void { 2064 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2065 2066 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2067 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2068 var walk_queue_index: u64 = 0; 2069 2070 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2071 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2072 2073 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2074 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2075 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2076 try walk_queue.append(.{ .bytes = &head_oid }); 2077 2078 while (walk_queue_index < try walk_queue.count()) { 2079 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2080 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2081 2082 walk_queue_index += 1; 2083 2084 // if we've seen this object id, skip it 2085 if (null != try seen_object_ids.getCursor(oid_int)) { 2086 continue; 2087 } 2088 2089 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2090 2091 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2092 defer commit_object.deinit(); 2093 2094 // if this object id has already been consumed, skip it 2095 if (null != try consumed_object_ids.getCursor(oid_int)) { 2096 continue; 2097 } 2098 2099 if (self.newest_object_id == null) self.newest_object_id = oid; 2100 self.oldest_object_id = oid; 2101 2102 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2103 var pending_parent_count: u64 = 0; 2104 for (parent_oids) |*parent_oid| { 2105 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2106 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2107 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2108 2109 // if this object id has already been consumed, skip it 2110 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2111 continue; 2112 } 2113 2114 // if this object id hasn't already been seen, add it to the walk queue 2115 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2116 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2117 } 2118 2119 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2120 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2121 try children.put(oid_int, .{ .bytes = &oid }); 2122 pending_parent_count += 1; 2123 } 2124 2125 if (pending_parent_count == 0) { 2126 try self.ready_queue.append(.{ .bytes = &oid }); 2127 } else { 2128 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2129 } 2130 } 2131 } 2132 2133 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2134 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2135 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2136 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2137 var children_iter = try children.iterator(); 2138 2139 while (try children_iter.next()) |*child_cursor| { 2140 const kv_pair = try child_cursor.readKeyValuePair(); 2141 const child_oid_int = kv_pair.hash; 2142 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2143 const pending_parent_count = try pending_parent_cursor.readUint(); 2144 2145 if (pending_parent_count <= 1) { 2146 _ = try self.child_to_pending_parents.remove(child_oid_int); 2147 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2148 try self.ready_queue.append(.{ .bytes = &child_oid }); 2149 } else { 2150 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2151 } 2152 } 2153 } 2154 2155 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2156 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2157 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2158 _ = try oid_cursor.readBytes(&oid); 2159 return oid; 2160 } 2161 }; 2162 } 2163