╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1341 pub fn writeOid( 1342 comptime T: type, 1343 comptime DB: type, 1344 comptime hash_kind: hash.HashKind, 1345 id_to_field_to_oid: DB.HashMap(.read_write), 1346 record_key: hash.HashInt(hash_kind), 1347 existing_maybe: ?T, 1348 event: T, 1349 event_oid: ?[]const u8, 1350 ) !void { 1351 const oid = event_oid orelse return; 1352 1353 // created only once a field actually changes 1354 var field_oids: ?DB.SortedMap(.read_write) = null; 1355 1356 const info = @typeInfo(T).@"struct"; 1357 inline for (info.field_names, info.field_types) |field_name, field_type| { 1358 const changed = if (existing_maybe) |existing| 1359 !fieldEqual(field_type, @field(existing, field_name), @field(event, field_name)) 1360 else 1361 true; 1362 if (changed) { 1363 if (field_oids == null) { 1364 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1365 } 1366 if (field_oids) |map| try map.put(field_name, .{ .bytes = oid }); 1367 } 1368 } 1369 } 1370 1371 // the whole field list, space separated, is the longest it can get 1372 fn conflictedFieldsMaxLen(comptime T: type) usize { 1373 var len: usize = 0; 1374 for (@typeInfo(T).@"struct".field_names) |name| len += name.len + 1; 1375 return len; 1376 } 1377 1378 pub const MergePolicy = enum { 1379 field_conflicts, 1380 target_wins, 1381 }; 1382 1383 // what a three-way merge did with a field 1384 pub const FieldMerge = enum { 1385 // the target's value stands, because neither side changed it, both made the 1386 // same change, or only the target changed it 1387 kept, 1388 parent, 1389 conflicted, 1390 }; 1391 1392 // three-way merge each field. one only the parent changed takes the parent's 1393 // value; one both sides changed differently keeps the target's. a missing 1394 // baseline makes every differing field a conflict. 1395 fn mergeFields( 1396 comptime T: type, 1397 baseline_maybe: ?T, 1398 target: T, 1399 parent: T, 1400 outcome: *[@typeInfo(T).@"struct".field_names.len]FieldMerge, 1401 ) T { 1402 var merged = target; 1403 1404 const info = @typeInfo(T).@"struct"; 1405 inline for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { 1406 const target_value = @field(target, field_name); 1407 const parent_value = @field(parent, field_name); 1408 1409 if (!fieldEqual(field_type, target_value, parent_value)) { 1410 outcome[i] = if (baseline_maybe) |baseline| blk: { 1411 const baseline_value = @field(baseline, field_name); 1412 if (fieldEqual(field_type, target_value, baseline_value)) { 1413 @field(merged, field_name) = parent_value; 1414 break :blk .parent; 1415 } 1416 // only the target changed it 1417 if (fieldEqual(field_type, parent_value, baseline_value)) break :blk .kept; 1418 break :blk .conflicted; 1419 } else .conflicted; 1420 } 1421 } 1422 1423 return merged; 1424 } 1425 1426 // three-way merge of one kind's records from a merge parent. kinds that expose 1427 // conflicts merge field by field; the others take one whole record. the result 1428 // goes through the kind's `consume`, which re-derives the indexes from it. a 1429 // removal carries over unless the other side changed the record, so a merge 1430 // never fails. 1431 pub fn merge( 1432 comptime T: type, 1433 comptime DB: type, 1434 comptime hash_kind: hash.HashKind, 1435 allocator: std.mem.Allocator, 1436 haxy_moment: DB.HashMap(.read_write), 1437 parent_moment: DB.HashMap(.read_only), 1438 baseline_moment: DB.HashMap(.read_only), 1439 ) !void { 1440 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1441 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1442 1443 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1444 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1445 1446 var baseline_records: ?DB.HashMap(.read_only) = null; 1447 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1448 baseline_records = try DB.HashMap(.read_only).init(cursor); 1449 } 1450 1451 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1452 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1453 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1454 switch (comptime T.merge_policy) { 1455 .field_conflicts => { 1456 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1457 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1458 } 1459 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1460 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1461 } 1462 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1463 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1464 } 1465 }, 1466 .target_wins => {}, 1467 } 1468 1469 var arena = std.heap.ArenaAllocator.init(allocator); 1470 defer arena.deinit(); 1471 1472 var iter = try parent_set.iteratorFromIndex(0); 1473 while (try iter.next()) |kv_pair_cursor| { 1474 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1475 const record_key = hash.hashInt(hash_kind, &event_id); 1476 1477 _ = arena.reset(.retain_capacity); 1478 1479 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1480 const parent_slot = parent_record_cursor.slot(); 1481 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1482 1483 // the parent left this record alone 1484 if (baseline_slot) |slot| { 1485 if (slot.eql(parent_slot)) continue; 1486 } 1487 1488 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1489 1490 // re-derived every iteration, since `consume` writes through its own 1491 // handles 1492 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1493 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1494 1495 // a record the target doesn't have arrives wholesale from the parent 1496 var outcome: [@typeInfo(T).@"struct".field_names.len]FieldMerge = @splat(.parent); 1497 var merged = parent_record; 1498 1499 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1500 // both sides share the change 1501 if (target_record_cursor.slot().eql(parent_slot)) continue; 1502 1503 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1504 1505 var baseline_record: ?T.Record = null; 1506 if (baseline_records) |map| { 1507 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1508 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1509 } 1510 } 1511 1512 switch (comptime T.merge_policy) { 1513 .field_conflicts => { 1514 outcome = @splat(.kept); 1515 merged = target_record; 1516 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1517 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1518 if (comptime @hasDecl(T, "resolveMerge")) { 1519 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1520 } 1521 1522 // merge the removed state separately from serialized fields. removal 1523 // carries over an unchanged record, while an edit or restoration 1524 // keeps it active. 1525 merged.removed = if (target_record.removed == parent_record.removed) 1526 target_record.removed 1527 else if (baseline_record) |baseline| blk: { 1528 const active = if (!target_record.removed) target_record else parent_record; 1529 if (active.removed != baseline.removed) break :blk false; 1530 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1531 break :blk true; 1532 } else false; 1533 }, 1534 .target_wins => { 1535 // an uncontested parent change carries over. if both sides 1536 // changed the record, the target wins as a whole, except that 1537 // an edit or restoration wins over a removal. 1538 const target_changed = if (baseline_slot) |slot| 1539 !target_record_cursor.slot().eql(slot) 1540 else 1541 true; 1542 merged = if (!target_changed) 1543 parent_record 1544 else if (target_record.removed != parent_record.removed) 1545 if (target_record.removed) parent_record else target_record 1546 else 1547 target_record; 1548 }, 1549 } 1550 } 1551 1552 // the index is unique, so a key the target gave to a different record 1553 // leaves this one out rather than stranding that one behind a name it 1554 // no longer owns 1555 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1556 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1557 const name_index = try DB.SortedMap(.read_write).init(name_index_cursor); 1558 if (try name_index.getCursor(merged.event.name)) |owner_cursor| { 1559 var owner_id: [event_id_size]u8 = undefined; 1560 _ = try owner_cursor.readBytes(&owner_id); 1561 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1562 } 1563 } 1564 1565 // `consume` sets no oids, since each field's winner may come from 1566 // a different side 1567 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1568 1569 switch (comptime T.merge_policy) { 1570 .field_conflicts => {}, 1571 .target_wins => continue, 1572 } 1573 1574 // removed records do not carry field conflicts 1575 if (merged.removed) continue; 1576 1577 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1578 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1579 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1580 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1581 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1582 1583 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1584 if (parent_id_to_field_to_oid) |map| { 1585 if (try map.getCursor(record_key)) |field_oids_cursor| { 1586 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1587 } 1588 } 1589 // created only once a field actually comes from the parent 1590 var field_oids: ?DB.SortedMap(.read_write) = null; 1591 1592 // the fields both sides changed differently, space separated 1593 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1594 var conflicted_len: usize = 0; 1595 1596 inline for (@typeInfo(T).@"struct".field_names, 0..) |field_name, i| { 1597 switch (outcome[i]) { 1598 // the target's value stands, so its oid does too 1599 .kept => {}, 1600 // the parent set this value, so its commit takes the field. a 1601 // parent with no oid took its own value from a merge, leaving 1602 // the field unattributed rather than crediting the target's 1603 // commit for a value it no longer holds. 1604 .parent => { 1605 if (field_oids == null) { 1606 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1607 } 1608 const map = field_oids orelse unreachable; 1609 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field_name) else null; 1610 if (parent_oid) |oid_cursor| { 1611 try map.put(field_name, .{ .slot = oid_cursor.slot() }); 1612 } else { 1613 _ = try map.remove(field_name); 1614 } 1615 }, 1616 .conflicted => { 1617 if (conflicted_len > 0) { 1618 conflicted_fields[conflicted_len] = ' '; 1619 conflicted_len += 1; 1620 } 1621 @memcpy(conflicted_fields[conflicted_len..][0..field_name.len], field_name); 1622 conflicted_len += field_name.len; 1623 }, 1624 } 1625 } 1626 1627 if (conflicted_len > 0) { 1628 // each side's whole record is stored by reference, so the view can 1629 // show any of them or take theirs wholesale 1630 _ = try conflicts.remove(&merged_key); 1631 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1632 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1633 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1634 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1635 if (parent_field_oids) |map| { 1636 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1637 } 1638 continue; 1639 } 1640 1641 // created_order never changes, so the parent keys this record's conflict 1642 // identically, and it carries over when the target has none, unless the 1643 // parent's entry is unchanged from the baseline, meaning the target 1644 // inherited it too and resolving it removed it here. 1645 if (parent_conflicts) |map| { 1646 if (null == try conflicts.getCursor(&merged_key)) { 1647 if (try map.getSlot(&merged_key)) |conflict_slot| { 1648 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1649 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1650 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1651 } 1652 } 1653 } 1654 } 1655 } 1656 1657 pub fn readFromRepo( 1658 comptime T: type, 1659 comptime repo_kind: rp.RepoKind, 1660 comptime repo_opts: rp.RepoOpts(repo_kind), 1661 io: std.Io, 1662 allocator: std.mem.Allocator, 1663 arena: *std.heap.ArenaAllocator, 1664 repo: *rp.Repo(repo_kind, repo_opts), 1665 id: *const [event_id_size]u8, 1666 ) !?T.Record { 1667 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; 1668 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1669 const moment = (if (event_db_maybe) |*event_db| 1670 currentMomentFromDb(repo_opts.hash, event_db.db) 1671 else if (repo_kind == .git) 1672 return null 1673 else 1674 currentMoment(repo_opts, repo)) catch return null; 1675 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1676 } 1677 1678 pub fn currentMoment( 1679 comptime repo_opts: rp.RepoOpts(.xit), 1680 repo: *rp.Repo(.xit, repo_opts), 1681 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1682 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1683 } 1684 1685 pub fn currentMomentFromDb( 1686 comptime hash_kind: hash.HashKind, 1687 db: *EventDB(hash_kind), 1688 ) !EventDB(hash_kind).HashMap(.read_only) { 1689 const DB = EventDB(hash_kind); 1690 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1691 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1692 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1693 return try currentMomentFromRepoMoment(hash_kind, moment); 1694 } 1695 1696 pub fn currentMomentFromRepoMoment( 1697 comptime hash_kind: hash.HashKind, 1698 moment: EventDB(hash_kind).HashMap(.read_only), 1699 ) !EventDB(hash_kind).HashMap(.read_only) { 1700 const DB = EventDB(hash_kind); 1701 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1702 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1703 _ = try last_object_id_cursor.readBytes(&last_object_id); 1704 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1705 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1706 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1707 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1708 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1709 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1710 } 1711 1712 // build a sorted-set key from an order and event id. big-endian order makes 1713 // byte order match numeric order; the event id breaks ties. 1714 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1715 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1716 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1717 @memcpy(key[@sizeOf(u64)..], event_id); 1718 return key; 1719 } 1720 1721 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1722 return orderKey(std.math.maxInt(u64) - order, event_id); 1723 } 1724 1725 pub fn removedRecord( 1726 comptime T: type, 1727 comptime DB: type, 1728 comptime hash_kind: hash.HashKind, 1729 haxy_moment: DB.HashMap(.read_only), 1730 existing_maybe: ?T, 1731 ) !T { 1732 var record = existing_maybe orelse return error.EventNotFound; 1733 record.removed = true; 1734 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1735 record.updated_order = try order_cursor.readUint(); 1736 return record; 1737 } 1738 1739 // add or refresh one entry in the global logical-event index 1740 pub fn indexEvent( 1741 comptime DB: type, 1742 comptime hash_kind: hash.HashKind, 1743 haxy_moment: DB.HashMap(.read_write), 1744 event_id: *const [event_id_size]u8, 1745 kind: EventKind, 1746 existing_maybe: anytype, 1747 record: anytype, 1748 ) !void { 1749 const event_key = hash.hashInt(hash_kind, event_id); 1750 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1751 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1752 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1753 1754 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1755 const active = try DB.SortedSet(.read_write).init(active_cursor); 1756 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1757 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1758 1759 if (existing_maybe) |existing| { 1760 const old_key = orderKeyDesc(existing.updated_order, event_id); 1761 _ = try active.remove(&old_key); 1762 _ = try removed_set.remove(&old_key); 1763 } 1764 1765 const order_key = orderKeyDesc(record.updated_order, event_id); 1766 if (record.removed) { 1767 try removed_set.put(&order_key); 1768 } else { 1769 try active.put(&order_key); 1770 } 1771 } 1772 1773 pub fn touchThread( 1774 comptime DB: type, 1775 comptime hash_kind: hash.HashKind, 1776 haxy_moment: DB.HashMap(.read_write), 1777 thread_id: *const [event_id_size]u8, 1778 order: u64, 1779 arena: *std.heap.ArenaAllocator, 1780 ) !void { 1781 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1782 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1783 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1784 switch (kind) { 1785 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1786 else => {}, 1787 } 1788 } 1789 1790 pub fn readEventKind( 1791 comptime hash_kind: hash.HashKind, 1792 kind_map: anytype, 1793 id: *const [event_id_size]u8, 1794 ) !?EventKind { 1795 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1796 var buffer: [64]u8 = undefined; 1797 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1798 } 1799 1800 // the email of the event's author, or null when the id names no authored event 1801 // of this kind 1802 pub fn readAuthorEmail( 1803 comptime repo_kind: rp.RepoKind, 1804 comptime repo_opts: rp.RepoOpts(repo_kind), 1805 io: std.Io, 1806 allocator: std.mem.Allocator, 1807 arena: *std.heap.ArenaAllocator, 1808 repo: *rp.Repo(repo_kind, repo_opts), 1809 kind: EventKind, 1810 id: *const [event_id_size]u8, 1811 ) !?[]const u8 { 1812 const record_map_key = switch (kind) { 1813 .issue => Issue.record_map_key, 1814 .discuss => Discussion.record_map_key, 1815 .comment => Comment.record_map_key, 1816 .attach => Attachment.record_map_key, 1817 .patchrev => PatchRev.record_map_key, 1818 .patch => Patch.record_map_key, 1819 .user, .repo, .fork, .grant => return null, 1820 }; 1821 1822 const DB = EventDB(repo_opts.hash); 1823 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; 1824 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1825 const moment = (if (event_db_maybe) |*event_db| 1826 currentMomentFromDb(repo_opts.hash, event_db.db) 1827 else if (repo_kind == .git) 1828 return null 1829 else 1830 currentMoment(repo_opts, repo)) catch return null; 1831 1832 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1833 const records = try DB.HashMap(.read_only).init(records_cursor); 1834 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1835 const record = try DB.HashMap(.read_only).init(record_cursor); 1836 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1837 } 1838 1839 // the event id embedded in a set entry's order key 1840 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1841 var cursor = kv_pair_cursor; 1842 const kv_pair = try cursor.readKeyValuePair(); 1843 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1844 _ = try kv_pair.key_cursor.readBytes(&order_key); 1845 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1846 } 1847 1848 // split a pushed "<owner>:<repo>" path into its two components, or null if it 1849 // isn't exactly two non-empty parts with no "/". 1850 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1851 if (std.mem.indexOfScalar(u8, path, '/') != null) return null; 1852 var it = std.mem.splitScalar(u8, path, ':'); 1853 const owner = it.next() orelse return null; 1854 const name = it.next() orelse return null; 1855 if (it.next() != null) return null; 1856 if (owner.len == 0 or name.len == 0) return null; 1857 1858 return .{ .owner = owner, .name = name }; 1859 } 1860 1861 pub const CreateRepoOptions = struct { 1862 read_access: Repo.Access = .private, 1863 }; 1864 1865 // the ids that locate a repo's on-disk directory 1866 pub const RepoLocation = struct { 1867 owner_id: [event_id_size]u8, 1868 repo_id: [event_id_size]u8, 1869 }; 1870 1871 // resolve a pushed `<owner>:<repo>` to the ids that locate its on-disk directory 1872 pub fn resolveOrCreateRepo( 1873 io: std.Io, 1874 allocator: std.mem.Allocator, 1875 users_dir: []const u8, 1876 admin_repo_path: []const u8, 1877 owner_name: []const u8, 1878 repo_name: []const u8, 1879 create_options_maybe: ?CreateRepoOptions, 1880 ) !?RepoLocation { 1881 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1882 error.RepoNotFound => return null, 1883 else => |e| return e, 1884 }; 1885 defer admin_repo.deinit(io, allocator); 1886 1887 var arena = std.heap.ArenaAllocator.init(allocator); 1888 defer arena.deinit(); 1889 1890 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 1891 1892 // an unknown owner can't own a repo, so the push is rejected 1893 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 1894 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 1895 defer user_repo.deinit(io, allocator); 1896 1897 // an already-registered repo reuses its event id, so a re-push (or a clone) 1898 // lands in the same repo 1899 if (try userMoment(&user_repo)) |moment| { 1900 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 1901 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 1902 } 1903 } 1904 1905 const create_options = create_options_maybe orelse return null; 1906 1907 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 1908 1909 var id_bytes: [event_id_size]u8 = undefined; 1910 io.random(&id_bytes); 1911 try writeRepoEvent(io, allocator, users_dir, &user_repo, &owner_user_id, .{ .name = owner.event.name, .email = owner.event.email }, &id_bytes, repo_name, "", create_options.read_access); 1912 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 1913 } 1914 1915 // create a bare repo with `hash_kind` and register it in its owner's user repo 1916 pub fn createRepo( 1917 io: std.Io, 1918 allocator: std.mem.Allocator, 1919 users_dir: []const u8, 1920 owner_id: *const [event_id_size]u8, 1921 owner: CommitAuthor, 1922 name: []const u8, 1923 description: []const u8, 1924 read_access: Repo.Access, 1925 hash_kind: hash.HashKind, 1926 ) !RepoLocation { 1927 try Repo.validateName(name); 1928 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 1929 defer user_repo.deinit(io, allocator); 1930 if (try userMoment(&user_repo)) |moment| { 1931 var arena = std.heap.ArenaAllocator.init(allocator); 1932 defer arena.deinit(); 1933 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 1934 } 1935 1936 var id_bytes: [event_id_size]u8 = undefined; 1937 io.random(&id_bytes); 1938 1939 // the directory comes first so a listed repo always has one 1940 { 1941 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 1942 defer allocator.free(path); 1943 switch (hash_kind) { 1944 inline else => |kind| { 1945 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 1946 defer repo.deinit(io, allocator); 1947 }, 1948 } 1949 } 1950 1951 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 1952 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 1953 } 1954 1955 // change the name, description, and read access of the repo named 1956 // `old_name` in its owner's user repo 1957 pub fn updateRepo( 1958 io: std.Io, 1959 allocator: std.mem.Allocator, 1960 users_dir: []const u8, 1961 owner_id: *const [event_id_size]u8, 1962 author: CommitAuthor, 1963 old_name: []const u8, 1964 name: []const u8, 1965 description: []const u8, 1966 read_access: Repo.Access, 1967 ) !void { 1968 try Repo.validateName(name); 1969 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 1970 defer user_repo.deinit(io, allocator); 1971 var arena = std.heap.ArenaAllocator.init(allocator); 1972 defer arena.deinit(); 1973 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 1974 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 1975 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 1976 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 1977 } 1978 1979 var event = found.repo.event; 1980 event.name = name; 1981 event.description = description; 1982 event.read_access = read_access; 1983 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 1984 .id = std.fmt.bytesToHex(found.event_id, .lower), 1985 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1986 .author = author, 1987 .event = .{ .repo = event }, 1988 }}); 1989 } 1990 1991 // create a user and their user repo, returning the new user's id 1992 pub fn createUser( 1993 io: std.Io, 1994 allocator: std.mem.Allocator, 1995 users_dir: []const u8, 1996 admin_repo: *rp.Repo(.xit, admin_repo_opts), 1997 name: []const u8, 1998 email: []const u8, 1999 password: []const u8, 2000 password_again: []const u8, 2001 ) ![event_id_size]u8 { 2002 try User.validateName(name); 2003 if (email.len == 0) return error.EmailEmpty; 2004 if (password.len == 0) return error.PasswordEmpty; 2005 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2006 // a fresh admin repo has no moment until its first event 2007 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2008 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2009 var arena = std.heap.ArenaAllocator.init(allocator); 2010 defer arena.deinit(); 2011 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2012 } else |err| switch (err) { 2013 error.NotFound => {}, 2014 else => |e| return e, 2015 } 2016 2017 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2018 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2019 2020 var id_bytes: [event_id_size]u8 = undefined; 2021 io.random(&id_bytes); 2022 2023 // the user repo comes first so a listed user can always create repos 2024 { 2025 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2026 defer allocator.free(path); 2027 var user_repo = try initUserRepo(io, allocator, path); 2028 defer user_repo.deinit(io, allocator); 2029 } 2030 2031 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2032 .id = std.fmt.bytesToHex(id_bytes, .lower), 2033 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2034 .author = .{ .name = name, .email = email }, 2035 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2036 }}); 2037 return id_bytes; 2038 } 2039 2040 // consume a new repo's event into its owner's user repo and mark it active 2041 fn writeRepoEvent( 2042 io: std.Io, 2043 allocator: std.mem.Allocator, 2044 users_dir: []const u8, 2045 user_repo: *rp.Repo(.xit, user_repo_opts), 2046 owner_id: *const [event_id_size]u8, 2047 owner: CommitAuthor, 2048 id_bytes: *const [event_id_size]u8, 2049 name: []const u8, 2050 description: []const u8, 2051 read_access: Repo.Access, 2052 ) !void { 2053 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2054 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2055 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2056 .timestamp = timestamp, 2057 .author = owner, 2058 .event = .{ .repo = .{ 2059 .user_id = owner_id, 2060 .name = name, 2061 .description = description, 2062 .read_access = read_access, 2063 } }, 2064 }}); 2065 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2066 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2067 }; 2068 } 2069 2070 // 2071 // reading from xitdb 2072 // 2073 2074 // read just `Fields`, a subset of `T.Record`, from the record with event id 2075 // `id`, or null when there is none 2076 pub fn readRecordSubset( 2077 comptime T: type, 2078 comptime Fields: type, 2079 comptime DB: type, 2080 comptime hash_kind: hash.HashKind, 2081 haxy_moment: DB.HashMap(.read_only), 2082 arena: *std.heap.ArenaAllocator, 2083 id: []const u8, 2084 ) !?Fields { 2085 comptime assertFieldSubset(Fields, T.Record); 2086 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2087 const records = try DB.HashMap(.read_only).init(records_cursor); 2088 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2089 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2090 } 2091 2092 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2093 const info = @typeInfo(Sub).@"struct"; 2094 for (info.field_names, info.field_types) |field_name, field_type| { 2095 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2096 const FullField = @FieldType(Full, field_name); 2097 if (@typeInfo(field_type) == .@"struct") { 2098 assertFieldSubset(field_type, FullField); 2099 } else if (field_type != FullField) { 2100 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2101 } 2102 } 2103 } 2104 2105 pub fn read( 2106 comptime T: type, 2107 comptime DB: type, 2108 comptime hash_kind: hash.HashKind, 2109 arena: *std.heap.ArenaAllocator, 2110 map: DB.HashMap(.read_only), 2111 ) !T { 2112 var event: T = undefined; 2113 switch (@typeInfo(T)) { 2114 .@"struct" => |struct_info| { 2115 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2116 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2117 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2118 } 2119 }, 2120 else => @compileError("read expects a struct"), 2121 } 2122 return event; 2123 } 2124 2125 fn readField( 2126 comptime Field: type, 2127 comptime DB: type, 2128 comptime hash_kind: hash.HashKind, 2129 arena: *std.heap.ArenaAllocator, 2130 cursor_maybe: ?DB.Cursor(.read_only), 2131 ) !Field { 2132 if (@typeInfo(Field) == .optional) { 2133 // a missing key or a null union payload is null 2134 const cursor = cursor_maybe orelse return null; 2135 if (cursor.slot().tag == .none) return null; 2136 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2137 } 2138 const cursor = cursor_maybe orelse return error.NotFound; 2139 switch (@typeInfo(Field)) { 2140 .pointer => |pointer_info| { 2141 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2142 @compileError("unsupported read field type: " ++ @typeName(Field)); 2143 } 2144 return try cursor.readBytesAlloc(arena.allocator(), null); 2145 }, 2146 .array => |array_info| { 2147 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2148 var bytes: Field = undefined; 2149 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2150 return bytes; 2151 }, 2152 .bool => { 2153 var buffer: [5]u8 = undefined; 2154 const bytes = try cursor.readBytesObject(&buffer); 2155 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2156 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2157 if (std.mem.eql(u8, bytes.value, "true")) return true; 2158 if (std.mem.eql(u8, bytes.value, "false")) return false; 2159 return error.InvalidBool; 2160 }, 2161 .int => |int_info| return switch (int_info.signedness) { 2162 .unsigned => @intCast(try cursor.readUint()), 2163 .signed => @intCast(try cursor.readInt()), 2164 }, 2165 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2166 .@"union" => |union_info| { 2167 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2168 switch (cursor.slot().tag) { 2169 .bytes, .short_bytes => { 2170 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2171 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2172 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2173 return @unionInit(Field, variant_name, {}); 2174 } 2175 } 2176 return error.InvalidUnion; 2177 }, 2178 .hash_map => { 2179 const variants = try DB.HashMap(.read_only).init(cursor); 2180 var iter = try variants.iterator(); 2181 const entry = (try iter.next()) orelse return error.InvalidUnion; 2182 const pair = try entry.readKeyValuePair(); 2183 if (try iter.next() != null) return error.InvalidUnion; 2184 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2185 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2186 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2187 } 2188 } 2189 return error.InvalidUnion; 2190 }, 2191 else => return error.InvalidUnion, 2192 } 2193 }, 2194 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2195 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2196 } 2197 } 2198 2199 // whether two events carry the same data 2200 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2201 switch (@typeInfo(T)) { 2202 .@"struct" => |struct_info| { 2203 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2204 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2205 } 2206 }, 2207 else => @compileError("fieldsEqual expects a struct"), 2208 } 2209 2210 return true; 2211 } 2212 2213 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2214 switch (@typeInfo(Field)) { 2215 .pointer => |pointer_info| { 2216 if (pointer_info.size == .slice and pointer_info.child == u8) { 2217 return std.mem.eql(u8, a, b); 2218 } else { 2219 @compileError("unsupported field type: " ++ @typeName(Field)); 2220 } 2221 }, 2222 .array => |array_info| { 2223 if (array_info.child == u8) { 2224 return std.mem.eql(u8, &a, &b); 2225 } else { 2226 @compileError("unsupported field type: " ++ @typeName(Field)); 2227 } 2228 }, 2229 .void => return true, 2230 .bool, .int, .@"enum" => return a == b, 2231 .@"union" => { 2232 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2233 return switch (a) { 2234 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2235 }; 2236 }, 2237 .@"struct" => return fieldsEqual(Field, a, b), 2238 .optional => |optional_info| { 2239 if (a) |a_value| { 2240 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2241 return false; 2242 } 2243 return b == null; 2244 }, 2245 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2246 } 2247 } 2248 2249 // 2250 // writing to xitdb 2251 // 2252 2253 pub fn upsert( 2254 comptime T: type, 2255 comptime DB: type, 2256 comptime hash_kind: hash.HashKind, 2257 map: DB.HashMap(.read_write), 2258 event: T, 2259 ) !void { 2260 switch (@typeInfo(T)) { 2261 .@"struct" => |struct_info| { 2262 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2263 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2264 } 2265 }, 2266 else => @compileError("upsert expects a struct"), 2267 } 2268 } 2269 2270 fn upsertField( 2271 comptime DB: type, 2272 comptime hash_kind: hash.HashKind, 2273 map: DB.HashMap(.read_write), 2274 comptime field_name: []const u8, 2275 comptime Field: type, 2276 value: Field, 2277 ) !void { 2278 const key = hash.hashInt(hash_kind, field_name); 2279 2280 switch (@typeInfo(Field)) { 2281 .pointer => |pointer_info| { 2282 if (pointer_info.size == .slice and pointer_info.child == u8) { 2283 try upsertBytes(DB, hash_kind, map, key, value); 2284 } else { 2285 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2286 } 2287 }, 2288 .array => |array_info| { 2289 if (array_info.child == u8) { 2290 try upsertBytes(DB, hash_kind, map, key, &value); 2291 } else { 2292 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2293 } 2294 }, 2295 .int => |int_info| switch (int_info.signedness) { 2296 .unsigned => { 2297 if (try map.getCursor(key)) |value_cursor| { 2298 if (try value_cursor.readUint() == value) { 2299 return; 2300 } 2301 } 2302 2303 try map.put(key, .{ .uint = value }); 2304 }, 2305 .signed => { 2306 if (try map.getCursor(key)) |value_cursor| { 2307 if (try value_cursor.readInt() == value) { 2308 return; 2309 } 2310 } 2311 2312 try map.put(key, .{ .int = value }); 2313 }, 2314 }, 2315 .bool => { 2316 const bytes = if (value) "true" else "false"; 2317 if (try map.getCursor(key)) |value_cursor| { 2318 var buffer: [5]u8 = undefined; 2319 const existing = try value_cursor.readBytesObject(&buffer); 2320 if (existing.format_tag) |format_tag| { 2321 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2322 return; 2323 } 2324 } 2325 } 2326 2327 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2328 }, 2329 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2330 .@"union" => switch (value) { 2331 inline else => |payload, tag| { 2332 if (@TypeOf(payload) == void) { 2333 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2334 } else { 2335 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2336 if (try map.getCursor(key)) |cursor| { 2337 switch (cursor.slot().tag) { 2338 .hash_map => { 2339 const variants = try DB.HashMap(.read_only).init(cursor); 2340 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2341 }, 2342 else => try map.put(key, .{ .slot = null }), 2343 } 2344 } 2345 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2346 if (@typeInfo(@TypeOf(payload)) == .optional) { 2347 // keep the variant even when its payload is null 2348 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2349 } 2350 if (try variants.getCursor(tag_key)) |cursor| { 2351 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2352 } 2353 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2354 } 2355 }, 2356 }, 2357 .optional => |optional_info| { 2358 // a missing key is null 2359 if (value) |child| { 2360 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2361 } else { 2362 _ = try map.remove(key); 2363 } 2364 }, 2365 .@"struct" => try upsert( 2366 Field, 2367 DB, 2368 hash_kind, 2369 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2370 value, 2371 ), 2372 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2373 } 2374 } 2375 2376 fn upsertBytes( 2377 comptime DB: type, 2378 comptime hash_kind: hash.HashKind, 2379 map: DB.HashMap(.read_write), 2380 key: hash.HashInt(hash_kind), 2381 value: []const u8, 2382 ) !void { 2383 var existing_cursor_maybe = try map.getCursor(key); 2384 if (existing_cursor_maybe) |*existing_cursor| { 2385 if (try bytesEqual(DB, existing_cursor, value)) { 2386 return; 2387 } 2388 } 2389 2390 try map.put(key, .{ .bytes = value }); 2391 } 2392 2393 fn bytesEqual( 2394 comptime DB: type, 2395 cursor: *DB.Cursor(.read_only), 2396 value: []const u8, 2397 ) !bool { 2398 switch (cursor.slot().tag) { 2399 .bytes, .short_bytes => {}, 2400 else => return false, 2401 } 2402 var read_buffer: [1024]u8 = undefined; 2403 var reader = try cursor.reader(&read_buffer); 2404 if (reader.size != value.len) { 2405 return false; 2406 } 2407 2408 var chunk_buffer: [1024]u8 = undefined; 2409 var offset: usize = 0; 2410 while (offset < value.len) { 2411 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2412 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2413 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2414 return false; 2415 } 2416 offset += chunk_len; 2417 } 2418 2419 return true; 2420 } 2421 2422 // 2423 // CommitIterator 2424 // 2425 // differs from xit's ObjectIterator in a few ways: 2426 // 2427 // 1. iterates parents first, rather than children first 2428 // 2. `next` only returns the object id, not the full Object 2429 // 3. stores its temporary state in a file on disk to avoid OOMs 2430 // 2431 2432 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2433 return struct { 2434 const DB = EventDB(repo_opts.hash); 2435 // a plain file is used for the scratch db because each write outside 2436 // a transaction is synced anyway, so buffering would gain nothing 2437 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2438 const db_name = "haxy-repo-events.db"; 2439 2440 repo_dir: std.Io.Dir, 2441 db_file: std.Io.File, 2442 db: *TempDB, 2443 // map of each object id to its children 2444 parent_to_children: TempDB.HashMap(.read_write), 2445 // tracking pending parents is necessary because a child can only 2446 // be returned after all of its unconsumed parents have been returned 2447 child_to_pending_parents: TempDB.HashMap(.read_write), 2448 // queue of object ids that are ready to be returned from `next` 2449 ready_queue: TempDB.ArrayList(.read_write), 2450 ready_queue_index: u64, 2451 // the object id at the tip of this branch 2452 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2453 // the object id furthest back in the history that hasn't been consumed 2454 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2455 2456 pub fn init( 2457 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2458 io: std.Io, 2459 allocator: std.mem.Allocator, 2460 consumed_object_ids: DB.HashMap(.read_only), 2461 ref: rf.Ref, 2462 ) !CommitIterator(repo_kind, repo_opts) { 2463 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2464 errdefer { 2465 db_file.close(io); 2466 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2467 } 2468 2469 // cursors point at the db, so it needs a stable address 2470 const db_ptr = try allocator.create(TempDB); 2471 errdefer allocator.destroy(db_ptr); 2472 // the db is scratch state that gets deleted after iteration, so 2473 // there is nothing worth fsyncing 2474 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2475 2476 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2477 2478 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2479 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2480 2481 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2482 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2483 2484 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2485 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2486 2487 var self = CommitIterator(repo_kind, repo_opts){ 2488 .repo_dir = state.core.repo_dir, 2489 .db_file = db_file, 2490 .db = db_ptr, 2491 .parent_to_children = parent_to_children, 2492 .child_to_pending_parents = child_to_pending_parents, 2493 .ready_queue = ready_queue, 2494 .ready_queue_index = 0, 2495 .newest_object_id = null, 2496 .oldest_object_id = null, 2497 }; 2498 errdefer self.deinit(io, allocator); 2499 2500 try self.collect(state, io, allocator, consumed_object_ids, ref); 2501 2502 return self; 2503 } 2504 2505 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2506 self.db_file.close(io); 2507 self.repo_dir.deleteFile(io, db_name) catch {}; 2508 allocator.destroy(self.db); 2509 } 2510 2511 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2512 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2513 2514 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2515 self.ready_queue_index += 1; 2516 2517 try self.enqueueChildren(&oid); 2518 return oid; 2519 } 2520 2521 fn collect( 2522 self: *CommitIterator(repo_kind, repo_opts), 2523 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2524 io: std.Io, 2525 allocator: std.mem.Allocator, 2526 consumed_object_ids: DB.HashMap(.read_only), 2527 ref: rf.Ref, 2528 ) !void { 2529 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2530 2531 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2532 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2533 var walk_queue_index: u64 = 0; 2534 2535 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2536 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2537 2538 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2539 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2540 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2541 try walk_queue.append(.{ .bytes = &head_oid }); 2542 2543 while (walk_queue_index < try walk_queue.count()) { 2544 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2545 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2546 2547 walk_queue_index += 1; 2548 2549 // if we've seen this object id, skip it 2550 if (null != try seen_object_ids.getCursor(oid_int)) { 2551 continue; 2552 } 2553 2554 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2555 2556 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2557 defer commit_object.deinit(); 2558 2559 // if this object id has already been consumed, skip it 2560 if (null != try consumed_object_ids.getCursor(oid_int)) { 2561 continue; 2562 } 2563 2564 if (self.newest_object_id == null) self.newest_object_id = oid; 2565 self.oldest_object_id = oid; 2566 2567 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2568 var pending_parent_count: u64 = 0; 2569 for (parent_oids) |*parent_oid| { 2570 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2571 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2572 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2573 2574 // if this object id has already been consumed, skip it 2575 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2576 continue; 2577 } 2578 2579 // if this object id hasn't already been seen, add it to the walk queue 2580 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2581 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2582 } 2583 2584 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2585 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2586 try children.put(oid_int, .{ .bytes = &oid }); 2587 pending_parent_count += 1; 2588 } 2589 2590 if (pending_parent_count == 0) { 2591 try self.ready_queue.append(.{ .bytes = &oid }); 2592 } else { 2593 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2594 } 2595 } 2596 } 2597 2598 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2599 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2600 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2601 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2602 var children_iter = try children.iterator(); 2603 2604 while (try children_iter.next()) |*child_cursor| { 2605 const kv_pair = try child_cursor.readKeyValuePair(); 2606 const child_oid_int = kv_pair.hash; 2607 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2608 const pending_parent_count = try pending_parent_cursor.readUint(); 2609 2610 if (pending_parent_count <= 1) { 2611 _ = try self.child_to_pending_parents.remove(child_oid_int); 2612 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2613 try self.ready_queue.append(.{ .bytes = &child_oid }); 2614 } else { 2615 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2616 } 2617 } 2618 } 2619 2620 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2621 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2622 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2623 _ = try oid_cursor.readBytes(&oid); 2624 return oid; 2625 } 2626 }; 2627 } 2628