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