╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
1491 // what a three-way merge did with a field 1492 pub const FieldMerge = enum { 1493 // the target's value stands, because neither side changed it, both made the 1494 // same change, or only the target changed it 1495 kept, 1496 parent, 1497 conflicted, 1498 }; 1499 1500 // three-way merge each field. one only the parent changed takes the parent's 1501 // value; one both sides changed differently keeps the target's. a missing 1502 // baseline makes every differing field a conflict. 1503 fn mergeFields( 1504 comptime T: type, 1505 baseline_maybe: ?T, 1506 target: T, 1507 parent: T, 1508 outcome: *[@typeInfo(T).@"struct".field_names.len]FieldMerge, 1509 ) T { 1510 var merged = target; 1511 1512 const info = @typeInfo(T).@"struct"; 1513 inline for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { 1514 const target_value = @field(target, field_name); 1515 const parent_value = @field(parent, field_name); 1516 1517 if (!fieldEqual(field_type, target_value, parent_value)) { 1518 outcome[i] = if (baseline_maybe) |baseline| blk: { 1519 const baseline_value = @field(baseline, field_name); 1520 if (fieldEqual(field_type, target_value, baseline_value)) { 1521 @field(merged, field_name) = parent_value; 1522 break :blk .parent; 1523 } 1524 // only the target changed it 1525 if (fieldEqual(field_type, parent_value, baseline_value)) break :blk .kept; 1526 break :blk .conflicted; 1527 } else .conflicted; 1528 } 1529 } 1530 1531 return merged; 1532 } 1533 1534 // three-way merge of one kind's records from a merge parent. kinds that expose 1535 // conflicts merge field by field; the others take one whole record. the result 1536 // goes through the kind's `consume`, which re-derives the indexes from it. a 1537 // removal carries over unless the other side changed the record, so a merge 1538 // never fails. 1539 pub fn merge( 1540 comptime T: type, 1541 comptime DB: type, 1542 comptime hash_kind: hash.HashKind, 1543 allocator: std.mem.Allocator, 1544 haxy_moment: DB.HashMap(.read_write), 1545 parent_moment: DB.HashMap(.read_only), 1546 baseline_moment: DB.HashMap(.read_only), 1547 ) !void { 1548 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1549 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1550 1551 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1552 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1553 1554 var baseline_records: ?DB.HashMap(.read_only) = null; 1555 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1556 baseline_records = try DB.HashMap(.read_only).init(cursor); 1557 } 1558 1559 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1560 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1561 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1562 switch (comptime T.merge_policy) { 1563 .field_conflicts => { 1564 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1565 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1566 } 1567 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1568 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1569 } 1570 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1571 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1572 } 1573 }, 1574 .target_wins => {}, 1575 } 1576 1577 var arena = std.heap.ArenaAllocator.init(allocator); 1578 defer arena.deinit(); 1579 1580 var iter = try parent_set.iteratorFromIndex(0); 1581 while (try iter.next()) |kv_pair_cursor| { 1582 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1583 const record_key = hash.hashInt(hash_kind, &event_id); 1584 1585 _ = arena.reset(.retain_capacity); 1586 1587 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1588 const parent_slot = parent_record_cursor.slot(); 1589 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1590 1591 // the parent left this record alone 1592 if (baseline_slot) |slot| { 1593 if (slot.eql(parent_slot)) continue; 1594 } 1595 1596 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1597 1598 // re-derived every iteration, since `consume` writes through its own 1599 // handles 1600 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1601 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1602 1603 // a record the target doesn't have arrives wholesale from the parent 1604 var outcome: [@typeInfo(T).@"struct".field_names.len]FieldMerge = @splat(.parent); 1605 var merged = parent_record; 1606 1607 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1608 // both sides share the change 1609 if (target_record_cursor.slot().eql(parent_slot)) continue; 1610 1611 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1612 1613 var baseline_record: ?T.Record = null; 1614 if (baseline_records) |map| { 1615 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1616 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1617 } 1618 } 1619 1620 switch (comptime T.merge_policy) { 1621 .field_conflicts => { 1622 outcome = @splat(.kept); 1623 merged = target_record; 1624 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1625 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1626 if (comptime @hasDecl(T, "resolveMerge")) { 1627 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1628 } 1629 1630 // merge the removed state separately from serialized fields. removal 1631 // carries over an unchanged record, while an edit or restoration 1632 // keeps it active. 1633 merged.removed = if (target_record.removed == parent_record.removed) 1634 target_record.removed 1635 else if (baseline_record) |baseline| blk: { 1636 const active = if (!target_record.removed) target_record else parent_record; 1637 if (active.removed != baseline.removed) break :blk false; 1638 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1639 break :blk true; 1640 } else false; 1641 }, 1642 .target_wins => { 1643 // an uncontested parent change carries over. if both sides 1644 // changed the record, the target wins as a whole, except that 1645 // an edit or restoration wins over a removal. 1646 const target_changed = if (baseline_slot) |slot| 1647 !target_record_cursor.slot().eql(slot) 1648 else 1649 true; 1650 merged = if (!target_changed) 1651 parent_record 1652 else if (target_record.removed != parent_record.removed) 1653 if (target_record.removed) parent_record else target_record 1654 else 1655 target_record; 1656 }, 1657 } 1658 } 1659 1660 // the index is unique, so a key the target gave to a different record 1661 // leaves this one out rather than stranding that one behind a name it 1662 // no longer owns 1663 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1664 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1665 const name_index = try DB.SortedMap(.read_write).init(name_index_cursor); 1666 if (try name_index.getCursor(merged.event.name)) |owner_cursor| { 1667 var owner_id: [event_id_size]u8 = undefined; 1668 _ = try owner_cursor.readBytes(&owner_id); 1669 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1670 } 1671 } 1672 1673 // `consume` sets no oids, since each field's winner may come from 1674 // a different side 1675 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1676 1677 switch (comptime T.merge_policy) { 1678 .field_conflicts => {}, 1679 .target_wins => continue, 1680 } 1681 1682 // removed records do not carry field conflicts 1683 if (merged.removed) continue; 1684 1685 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1686 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1687 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1688 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1689 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1690 1691 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1692 if (parent_id_to_field_to_oid) |map| { 1693 if (try map.getCursor(record_key)) |field_oids_cursor| { 1694 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1695 } 1696 } 1697 // created only once a field actually comes from the parent 1698 var field_oids: ?DB.SortedMap(.read_write) = null; 1699 1700 // the fields both sides changed differently, space separated 1701 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1702 var conflicted_len: usize = 0; 1703 1704 inline for (@typeInfo(T).@"struct".field_names, 0..) |field_name, i| { 1705 switch (outcome[i]) { 1706 // the target's value stands, so its oid does too 1707 .kept => {}, 1708 // the parent set this value, so its commit takes the field. a 1709 // parent with no oid took its own value from a merge, leaving 1710 // the field unattributed rather than crediting the target's 1711 // commit for a value it no longer holds. 1712 .parent => { 1713 if (field_oids == null) { 1714 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1715 } 1716 const map = field_oids orelse unreachable; 1717 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field_name) else null; 1718 if (parent_oid) |oid_cursor| { 1719 try map.put(field_name, .{ .slot = oid_cursor.slot() }); 1720 } else { 1721 _ = try map.remove(field_name); 1722 } 1723 }, 1724 .conflicted => { 1725 if (conflicted_len > 0) { 1726 conflicted_fields[conflicted_len] = ' '; 1727 conflicted_len += 1; 1728 } 1729 @memcpy(conflicted_fields[conflicted_len..][0..field_name.len], field_name); 1730 conflicted_len += field_name.len; 1731 }, 1732 } 1733 } 1734 1735 if (conflicted_len > 0) { 1736 // each side's whole record is stored by reference, so the view can 1737 // show any of them or take theirs wholesale 1738 _ = try conflicts.remove(&merged_key); 1739 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1740 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1741 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1742 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1743 if (parent_field_oids) |map| { 1744 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1745 } 1746 continue; 1747 } 1748 1749 // created_order never changes, so the parent keys this record's conflict 1750 // identically, and it carries over when the target has none, unless the 1751 // parent's entry is unchanged from the baseline, meaning the target 1752 // inherited it too and resolving it removed it here. 1753 if (parent_conflicts) |map| { 1754 if (null == try conflicts.getCursor(&merged_key)) { 1755 if (try map.getSlot(&merged_key)) |conflict_slot| { 1756 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1757 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1758 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1759 } 1760 } 1761 } 1762 } 1763 } 1764 1765 // a comment, attachment or assignment a write names under a thread 1766 pub const ThreadChild = union(enum) { 1767 comment: *const [event_id_size]u8, 1768 attach: *const [event_id_size]u8, 1769 assign: *const [event_id_size]u8, 1770 }; 1771 1772 // whether `thread_id` names a thread of `thread_kind` in the repo's events, and 1773 // `child`, when given, belongs to it. a caller's url can claim any kind for any 1774 // id, so every write under a thread checks its claim here first. 1775 pub fn threadHolds( 1776 comptime repo_kind: rp.RepoKind, 1777 comptime repo_opts: rp.RepoOpts(repo_kind), 1778 io: std.Io, 1779 allocator: std.mem.Allocator, 1780 repo: *rp.Repo(repo_kind, repo_opts), 1781 thread_kind: EventKind, 1782 thread_id: *const [event_id_size]u8, 1783 child_maybe: ?ThreadChild, 1784 ) !bool { 1785 const DB = EventDB(repo_opts.hash); 1786 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; 1787 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1788 const moment = (if (event_db_maybe) |*event_db| 1789 currentMomentFromDb(repo_opts.hash, event_db.db) 1790 else if (repo_kind == .git) 1791 return false 1792 else 1793 currentMoment(repo_opts, repo)) catch return false; 1794 1795 // only these kinds are threads 1796 switch (thread_kind) { 1797 .discuss, .issue, .patch => {}, 1798 else => return false, 1799 } 1800 const kinds_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return false; 1801 const kinds = try DB.HashMap(.read_only).init(kinds_cursor); 1802 if ((try readEventKind(repo_opts.hash, kinds, thread_id)) != thread_kind) return false; 1803 1804 const child = child_maybe orelse return true; 1805 var arena = std.heap.ArenaAllocator.init(allocator); 1806 defer arena.deinit(); 1807 const thread_id_hex = std.fmt.bytesToHex(thread_id.*, .lower); 1808 switch (child) { 1809 .comment => |id| { 1810 const comment = (try readRecordSubset(Comment, struct { event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1811 return std.mem.eql(u8, &comment.event.thread_id, &thread_id_hex); 1812 }, 1813 .attach => |id| { 1814 const attachment = (try readRecordSubset(Attachment, struct { event: struct { target_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1815 return std.mem.eql(u8, &attachment.event.target_id, &thread_id_hex); 1816 }, 1817 // only an active assignment can be removed 1818 .assign => |id| { 1819 const assignment = (try readRecordSubset(Assignment, struct { removed: bool, event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1820 return !assignment.removed and std.mem.eql(u8, &assignment.event.thread_id, &thread_id_hex); 1821 }, 1822 } 1823 } 1824 1825 // remove an event a thread's page names: the thread itself, or a comment, 1826 // attachment or assignment, which must belong to it 1827 pub fn removeInThread( 1828 host: Host, 1829 comptime repo_kind: rp.RepoKind, 1830 comptime repo_opts: rp.RepoOpts(repo_kind), 1831 io: std.Io, 1832 allocator: std.mem.Allocator, 1833 repo: *rp.Repo(repo_kind, repo_opts), 1834 thread_kind: EventKind, 1835 thread_id: *const [event_id_size]u8, 1836 kind: EventKind, 1837 id: *const [event_id_size]u8, 1838 author: CommitAuthor, 1839 ) !void { 1840 const child_maybe: ?ThreadChild = switch (kind) { 1841 .comment => .{ .comment = id }, 1842 .attach => .{ .attach = id }, 1843 .assign => .{ .assign = id }, 1844 else => null, 1845 }; 1846 if (child_maybe) |child| { 1847 if (!try threadHolds(repo_kind, repo_opts, io, allocator, repo, thread_kind, thread_id, child)) return error.EventNotFound; 1848 } 1849 try remove(host, .repo, repo_kind, repo_opts, io, allocator, repo, id, kind, author); 1850 } 1851 1852 pub fn readFromRepo( 1853 comptime T: type, 1854 comptime repo_kind: rp.RepoKind, 1855 comptime repo_opts: rp.RepoOpts(repo_kind), 1856 io: std.Io, 1857 allocator: std.mem.Allocator, 1858 arena: *std.heap.ArenaAllocator, 1859 repo: *rp.Repo(repo_kind, repo_opts), 1860 id: *const [event_id_size]u8, 1861 ) !?T.Record { 1862 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; 1863 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1864 const moment = (if (event_db_maybe) |*event_db| 1865 currentMomentFromDb(repo_opts.hash, event_db.db) 1866 else if (repo_kind == .git) 1867 return null 1868 else 1869 currentMoment(repo_opts, repo)) catch return null; 1870 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1871 } 1872 1873 pub fn currentMoment( 1874 comptime repo_opts: rp.RepoOpts(.xit), 1875 repo: *rp.Repo(.xit, repo_opts), 1876 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1877 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1878 } 1879 1880 pub fn currentMomentFromDb( 1881 comptime hash_kind: hash.HashKind, 1882 db: *EventDB(hash_kind), 1883 ) !EventDB(hash_kind).HashMap(.read_only) { 1884 const DB = EventDB(hash_kind); 1885 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1886 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1887 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1888 return try currentMomentFromRepoMoment(hash_kind, moment); 1889 } 1890 1891 pub fn currentMomentFromRepoMoment( 1892 comptime hash_kind: hash.HashKind, 1893 moment: EventDB(hash_kind).HashMap(.read_only), 1894 ) !EventDB(hash_kind).HashMap(.read_only) { 1895 const DB = EventDB(hash_kind); 1896 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1897 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1898 _ = try last_object_id_cursor.readBytes(&last_object_id); 1899 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1900 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1901 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1902 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1903 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1904 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1905 } 1906 1907 // build a sorted-set key from an order and event id. big-endian order makes 1908 // byte order match numeric order; the event id breaks ties. 1909 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1910 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1911 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1912 @memcpy(key[@sizeOf(u64)..], event_id); 1913 return key; 1914 } 1915 1916 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1917 return orderKey(std.math.maxInt(u64) - order, event_id); 1918 } 1919 1920 pub fn removedRecord( 1921 comptime T: type, 1922 comptime DB: type, 1923 comptime hash_kind: hash.HashKind, 1924 haxy_moment: DB.HashMap(.read_only), 1925 existing_maybe: ?T, 1926 ) !T { 1927 var record = existing_maybe orelse return error.EventNotFound; 1928 record.removed = true; 1929 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1930 record.updated_order = try order_cursor.readUint(); 1931 return record; 1932 } 1933 1934 // add or refresh one entry in the global logical-event index 1935 pub fn indexEvent( 1936 comptime DB: type, 1937 comptime hash_kind: hash.HashKind, 1938 haxy_moment: DB.HashMap(.read_write), 1939 event_id: *const [event_id_size]u8, 1940 kind: EventKind, 1941 existing_maybe: anytype, 1942 record: anytype, 1943 ) !void { 1944 const event_key = hash.hashInt(hash_kind, event_id); 1945 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1946 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1947 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1948 1949 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1950 const active = try DB.SortedSet(.read_write).init(active_cursor); 1951 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1952 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1953 1954 if (existing_maybe) |existing| { 1955 const old_key = orderKeyDesc(existing.updated_order, event_id); 1956 _ = try active.remove(&old_key); 1957 _ = try removed_set.remove(&old_key); 1958 } 1959 1960 const order_key = orderKeyDesc(record.updated_order, event_id); 1961 if (record.removed) { 1962 try removed_set.put(&order_key); 1963 } else { 1964 try active.put(&order_key); 1965 } 1966 } 1967 1968 pub fn touchThread( 1969 comptime DB: type, 1970 comptime hash_kind: hash.HashKind, 1971 haxy_moment: DB.HashMap(.read_write), 1972 thread_id: *const [event_id_size]u8, 1973 order: u64, 1974 arena: *std.heap.ArenaAllocator, 1975 ) !void { 1976 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1977 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1978 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1979 switch (kind) { 1980 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1981 else => {}, 1982 } 1983 } 1984 1985 pub fn readEventKind( 1986 comptime hash_kind: hash.HashKind, 1987 kind_map: anytype, 1988 id: *const [event_id_size]u8, 1989 ) !?EventKind { 1990 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1991 var buffer: [64]u8 = undefined; 1992 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1993 } 1994 1995 // the email of the event's author, or null when the id names no authored event 1996 // of this kind 1997 pub fn readAuthorEmail( 1998 comptime repo_kind: rp.RepoKind, 1999 comptime repo_opts: rp.RepoOpts(repo_kind), 2000 io: std.Io, 2001 allocator: std.mem.Allocator, 2002 arena: *std.heap.ArenaAllocator, 2003 repo: *rp.Repo(repo_kind, repo_opts), 2004 kind: EventKind, 2005 id: *const [event_id_size]u8, 2006 ) !?[]const u8 { 2007 const record_map_key = switch (kind) { 2008 .discuss => Discussion.record_map_key, 2009 .issue => Issue.record_map_key, 2010 .comment => Comment.record_map_key, 2011 .attach => Attachment.record_map_key, 2012 .assign => Assignment.record_map_key, 2013 .patchrev => PatchRev.record_map_key, 2014 .patch => Patch.record_map_key, 2015 .user, .repo, .fork, .grant, .notify => return null, 2016 }; 2017 2018 const DB = EventDB(repo_opts.hash); 2019 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; 2020 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 2021 const moment = (if (event_db_maybe) |*event_db| 2022 currentMomentFromDb(repo_opts.hash, event_db.db) 2023 else if (repo_kind == .git) 2024 return null 2025 else 2026 currentMoment(repo_opts, repo)) catch return null; 2027 2028 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 2029 const records = try DB.HashMap(.read_only).init(records_cursor); 2030 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 2031 const record = try DB.HashMap(.read_only).init(record_cursor); 2032 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 2033 } 2034 2035 // the event id embedded in a set entry's order key 2036 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 2037 var cursor = kv_pair_cursor; 2038 const kv_pair = try cursor.readKeyValuePair(); 2039 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 2040 _ = try kv_pair.key_cursor.readBytes(&order_key); 2041 return order_key[@sizeOf(u64)..][0..event_id_size].*; 2042 } 2043 2044 // split a pushed "<owner>:<repo>" path into its two components, or null if it 2045 // isn't exactly two non-empty parts with no "/". 2046 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 2047 if (std.mem.indexOfScalar(u8, path, '/') != null) return null; 2048 var it = std.mem.splitScalar(u8, path, ':'); 2049 const owner = it.next() orelse return null; 2050 const name = it.next() orelse return null; 2051 if (it.next() != null) return null; 2052 if (owner.len == 0 or name.len == 0) return null; 2053 2054 return .{ .owner = owner, .name = name }; 2055 } 2056 2057 pub const CreateRepoOptions = struct { 2058 read_access: Repo.Access = .private, 2059 }; 2060 2061 // the ids that locate a repo's on-disk directory 2062 pub const RepoLocation = struct { 2063 owner_id: [event_id_size]u8, 2064 repo_id: [event_id_size]u8, 2065 }; 2066 2067 // resolve a pushed `<owner>:<repo>` to the ids that locate its on-disk directory 2068 pub fn resolveOrCreateRepo( 2069 io: std.Io, 2070 allocator: std.mem.Allocator, 2071 users_dir: []const u8, 2072 admin_repo_path: []const u8, 2073 owner_name: []const u8, 2074 repo_name: []const u8, 2075 create_options_maybe: ?CreateRepoOptions, 2076 ) !?RepoLocation { 2077 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 2078 error.RepoNotFound => return null, 2079 else => |e| return e, 2080 }; 2081 defer admin_repo.deinit(io, allocator); 2082 2083 var arena = std.heap.ArenaAllocator.init(allocator); 2084 defer arena.deinit(); 2085 2086 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 2087 2088 // an unknown owner can't own a repo, so the push is rejected 2089 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 2090 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 2091 defer user_repo.deinit(io, allocator); 2092 2093 // an already-registered repo reuses its event id, so a re-push (or a clone) 2094 // lands in the same repo 2095 if (try userMoment(&user_repo)) |moment| { 2096 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 2097 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 2098 } 2099 } 2100 2101 const create_options = create_options_maybe orelse return null; 2102 2103 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 2104 2105 var id_bytes: [event_id_size]u8 = undefined; 2106 io.random(&id_bytes); 2107 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); 2108 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 2109 } 2110 2111 // create a bare repo with `hash_kind` and register it in its owner's user repo 2112 pub fn createRepo( 2113 io: std.Io, 2114 allocator: std.mem.Allocator, 2115 users_dir: []const u8, 2116 owner_id: *const [event_id_size]u8, 2117 owner: CommitAuthor, 2118 name: []const u8, 2119 description: []const u8, 2120 read_access: Repo.Access, 2121 hash_kind: hash.HashKind, 2122 ) !RepoLocation { 2123 try Repo.validateName(name); 2124 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2125 defer user_repo.deinit(io, allocator); 2126 if (try userMoment(&user_repo)) |moment| { 2127 var arena = std.heap.ArenaAllocator.init(allocator); 2128 defer arena.deinit(); 2129 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2130 } 2131 2132 var id_bytes: [event_id_size]u8 = undefined; 2133 io.random(&id_bytes); 2134 2135 // the directory comes first so a listed repo always has one 2136 { 2137 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2138 defer allocator.free(path); 2139 switch (hash_kind) { 2140 inline else => |kind| { 2141 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2142 defer repo.deinit(io, allocator); 2143 }, 2144 } 2145 } 2146 2147 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2148 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2149 } 2150 2151 // change the name, description, read access, and tab roles of the repo 2152 // named `old_name` in its owner's user repo 2153 pub fn updateRepo( 2154 io: std.Io, 2155 allocator: std.mem.Allocator, 2156 users_dir: []const u8, 2157 owner_id: *const [event_id_size]u8, 2158 author: CommitAuthor, 2159 old_name: []const u8, 2160 name: []const u8, 2161 description: []const u8, 2162 read_access: Repo.Access, 2163 discuss_role: ?Repo.Role, 2164 issue_role: ?Repo.Role, 2165 patch_role: ?Repo.Role, 2166 ) !void { 2167 try Repo.validateName(name); 2168 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2169 defer user_repo.deinit(io, allocator); 2170 var arena = std.heap.ArenaAllocator.init(allocator); 2171 defer arena.deinit(); 2172 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2173 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2174 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2175 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2176 } 2177 2178 var event = found.repo.event; 2179 event.name = name; 2180 event.description = description; 2181 event.read_access = read_access; 2182 event.discuss_role = discuss_role; 2183 event.issue_role = issue_role; 2184 event.patch_role = patch_role; 2185 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2186 .id = std.fmt.bytesToHex(found.event_id, .lower), 2187 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2188 .author = author, 2189 .event = .{ .repo = event }, 2190 }}); 2191 } 2192 2193 // remove the repo `repo_id` from its owner's user repo, then its dir. tombstone 2194 // first so a missing repo never remains visible 2195 pub fn deleteRepo( 2196 io: std.Io, 2197 allocator: std.mem.Allocator, 2198 users_dir: []const u8, 2199 owner_id: *const [event_id_size]u8, 2200 repo_id: *const [event_id_size]u8, 2201 author: CommitAuthor, 2202 ) !void { 2203 { 2204 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2205 defer user_repo.deinit(io, allocator); 2206 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, repo_id, .repo, author); 2207 } 2208 const path = try repoPath(allocator, users_dir, owner_id, repo_id); 2209 defer allocator.free(path); 2210 try std.Io.Dir.cwd().deleteTree(io, path); 2211 } 2212 2213 // grant `user_id` `role` on the repo `repo_id` in its owner's user repo, 2214 // replacing any role they held 2215 pub fn grantRole( 2216 io: std.Io, 2217 allocator: std.mem.Allocator, 2218 users_dir: []const u8, 2219 owner_id: *const [event_id_size]u8, 2220 repo_id: *const [event_id_size]u8, 2221 user_id: *const [event_id_size]u8, 2222 role: Repo.Role, 2223 author: CommitAuthor, 2224 ) !void { 2225 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2226 defer user_repo.deinit(io, allocator); 2227 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2228 .id = std.fmt.bytesToHex(Grant.idOf(repo_id, user_id), .lower), 2229 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2230 .author = author, 2231 .event = .{ .grant = .{ .target_id = std.fmt.bytesToHex(repo_id.*, .lower), .user_id = std.fmt.bytesToHex(user_id.*, .lower), .role = role } }, 2232 }}); 2233 } 2234 2235 // revoke `user_id`'s grant on the repo `repo_id` in its owner's user repo 2236 pub fn revokeRole( 2237 io: std.Io, 2238 allocator: std.mem.Allocator, 2239 users_dir: []const u8, 2240 owner_id: *const [event_id_size]u8, 2241 repo_id: *const [event_id_size]u8, 2242 user_id: *const [event_id_size]u8, 2243 author: CommitAuthor, 2244 ) !void { 2245 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2246 defer user_repo.deinit(io, allocator); 2247 // a revoked grant stays in the kind index, which is all `remove` checks 2248 { 2249 var arena = std.heap.ArenaAllocator.init(allocator); 2250 defer arena.deinit(); 2251 const moment = (try userMoment(&user_repo)) orelse return error.EventNotFound; 2252 if (try Grant.readRole(UserDB, user_repo_opts.hash, moment, &arena, repo_id, user_id) == null) return error.EventNotFound; 2253 } 2254 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, &Grant.idOf(repo_id, user_id), .grant, author); 2255 } 2256 2257 // add `branch` to the protected branches of the repo `repo_id` in its owner's 2258 // user repo, or take it out when `protect` is false. taking out a branch that 2259 // isn't protected writes nothing. 2260 pub fn protectBranch( 2261 io: std.Io, 2262 allocator: std.mem.Allocator, 2263 users_dir: []const u8, 2264 owner_id: *const [event_id_size]u8, 2265 repo_id: *const [event_id_size]u8, 2266 branch: []const u8, 2267 protect: bool, 2268 author: CommitAuthor, 2269 ) !void { 2270 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2271 defer user_repo.deinit(io, allocator); 2272 var arena = std.heap.ArenaAllocator.init(allocator); 2273 defer arena.deinit(); 2274 const aa = arena.allocator(); 2275 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2276 const repo = (try Repo.readById(UserDB, user_repo_opts.hash, moment, &arena, repo_id)) orelse return error.NotFound; 2277 if (repo.removed) return error.NotFound; 2278 2279 var branches: std.ArrayList(u8) = .empty; 2280 var count: usize = 0; 2281 var held = false; 2282 for (try repo.event.protectedBranchNames(aa)) |name| { 2283 if (std.mem.eql(u8, name, branch)) { 2284 held = true; 2285 if (!protect) continue; 2286 } 2287 if (branches.items.len > 0) try branches.append(aa, '\n'); 2288 try branches.appendSlice(aa, name); 2289 count += 1; 2290 } 2291 if (protect) { 2292 if (held) return error.BranchProtected; 2293 if (count >= Repo.protected_branch_max_count) return error.TooManyProtectedBranches; 2294 if (branches.items.len > 0) try branches.append(aa, '\n'); 2295 try branches.appendSlice(aa, branch); 2296 } else if (!held) return; 2297 2298 var event = repo.event; 2299 event.protected_branches = branches.items; 2300 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2301 .id = std.fmt.bytesToHex(repo_id.*, .lower), 2302 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2303 .author = author, 2304 .event = .{ .repo = event }, 2305 }}); 2306 } 2307 2308 // create a user and their user repo, returning the new user's id 2309 pub fn createUser( 2310 io: std.Io, 2311 allocator: std.mem.Allocator, 2312 users_dir: []const u8, 2313 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2314 name: []const u8, 2315 email: []const u8, 2316 password: []const u8, 2317 password_again: []const u8, 2318 ) ![event_id_size]u8 { 2319 try User.validateName(name); 2320 if (email.len == 0) return error.EmailEmpty; 2321 if (password.len == 0) return error.PasswordEmpty; 2322 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2323 // a fresh admin repo has no moment until its first event 2324 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2325 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2326 var arena = std.heap.ArenaAllocator.init(allocator); 2327 defer arena.deinit(); 2328 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2329 } else |err| switch (err) { 2330 error.NotFound => {}, 2331 else => |e| return e, 2332 } 2333 2334 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2335 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2336 2337 var id_bytes: [event_id_size]u8 = undefined; 2338 io.random(&id_bytes); 2339 2340 // the user repo comes first so a listed user can always create repos 2341 { 2342 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2343 defer allocator.free(path); 2344 var user_repo = try initUserRepo(io, allocator, path); 2345 defer user_repo.deinit(io, allocator); 2346 } 2347 2348 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2349 .id = std.fmt.bytesToHex(id_bytes, .lower), 2350 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2351 .author = .{ .name = name, .email = email }, 2352 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2353 }}); 2354 return id_bytes; 2355 } 2356 2357 // change a user's email, and their password when the password fields are 2358 // filled in 2359 pub fn updateUser( 2360 io: std.Io, 2361 allocator: std.mem.Allocator, 2362 users_dir: []const u8, 2363 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2364 user_id: *const [event_id_size]u8, 2365 email: []const u8, 2366 current_password: []const u8, 2367 new_password: []const u8, 2368 new_password_again: []const u8, 2369 ) !void { 2370 if (email.len == 0) return error.EmailEmpty; 2371 var arena = std.heap.ArenaAllocator.init(allocator); 2372 defer arena.deinit(); 2373 const moment = try currentMoment(admin_repo_opts, admin_repo); 2374 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2375 if (user.removed) return error.NotFound; 2376 if (!std.mem.eql(u8, email, user.event.email) and try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2377 2378 var event = user.event; 2379 event.email = email; 2380 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2381 if (current_password.len + new_password.len + new_password_again.len > 0) { 2382 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2383 if (new_password.len == 0) return error.PasswordEmpty; 2384 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2385 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2386 } 2387 2388 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2389 .id = std.fmt.bytesToHex(user_id.*, .lower), 2390 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2391 .author = .{ .name = event.name, .email = email }, 2392 .event = .{ .user = event }, 2393 }}); 2394 } 2395 2396 // remove a user from the admin repo, then their dir with every repo and fork 2397 // in it. tombstone first so a missing user never remains visible 2398 pub fn deleteUser( 2399 io: std.Io, 2400 allocator: std.mem.Allocator, 2401 users_dir: []const u8, 2402 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2403 user_id: *const [event_id_size]u8, 2404 author: CommitAuthor, 2405 ) !void { 2406 try remove(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, user_id, .user, author); 2407 const path = try std.Io.Dir.path.join(allocator, &.{ users_dir, &std.fmt.bytesToHex(user_id.*, .lower) }); 2408 defer allocator.free(path); 2409 try std.Io.Dir.cwd().deleteTree(io, path); 2410 } 2411 2412 // add an authorized_keys line to the user's ssh keys 2413 pub fn addUserKey( 2414 io: std.Io, 2415 allocator: std.mem.Allocator, 2416 users_dir: []const u8, 2417 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2418 user_id: *const [event_id_size]u8, 2419 key_text: []const u8, 2420 ) !void { 2421 const key = std.mem.trim(u8, key_text, " \t\r"); 2422 // the keys are stored one per line 2423 if (std.mem.indexOfScalar(u8, key, '\n') != null) return error.InvalidKey; 2424 const fingerprint = User.fingerprintOfKey(key) orelse return error.InvalidKey; 2425 // the key types the ssh server verifies 2426 const key_type = std.mem.sliceTo(key, ' '); 2427 if (!std.mem.eql(u8, key_type, "ssh-ed25519") and !std.mem.eql(u8, key_type, "ssh-rsa")) return error.UnsupportedKey; 2428 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, &fingerprint, key); 2429 } 2430 2431 // remove the user's ssh key with this fingerprint. removing a key they don't 2432 // hold writes nothing. 2433 pub fn removeUserKey( 2434 io: std.Io, 2435 allocator: std.mem.Allocator, 2436 users_dir: []const u8, 2437 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2438 user_id: *const [event_id_size]u8, 2439 fingerprint: *const [User.fingerprint_len]u8, 2440 ) !void { 2441 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, fingerprint, null); 2442 } 2443 2444 // rewrite the user's ssh keys with `added` appended, or without the key with 2445 // `fingerprint` when nothing is added 2446 fn writeUserKeys( 2447 io: std.Io, 2448 allocator: std.mem.Allocator, 2449 users_dir: []const u8, 2450 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2451 user_id: *const [event_id_size]u8, 2452 fingerprint: *const [User.fingerprint_len]u8, 2453 added: ?[]const u8, 2454 ) !void { 2455 var arena = std.heap.ArenaAllocator.init(allocator); 2456 defer arena.deinit(); 2457 const moment = try currentMoment(admin_repo_opts, admin_repo); 2458 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2459 if (user.removed) return error.NotFound; 2460 2461 var keys: std.ArrayList(u8) = .empty; 2462 var count: usize = 0; 2463 var held = false; 2464 var lines = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 2465 while (lines.next()) |line| { 2466 const line_fingerprint = User.fingerprintOfKey(line) orelse continue; 2467 if (std.mem.eql(u8, &line_fingerprint, fingerprint)) { 2468 held = true; 2469 if (added == null) continue; 2470 } 2471 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2472 try keys.appendSlice(arena.allocator(), line); 2473 count += 1; 2474 } 2475 if (added) |key| { 2476 if (held) return error.KeyAdded; 2477 if (count >= User.ssh_key_max_count) return error.TooManyKeys; 2478 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2479 try keys.appendSlice(arena.allocator(), key); 2480 } else if (!held) return; 2481 2482 var event = user.event; 2483 event.ssh_keys = keys.items; 2484 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2485 .id = std.fmt.bytesToHex(user_id.*, .lower), 2486 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2487 .author = .{ .name = event.name, .email = event.email }, 2488 .event = .{ .user = event }, 2489 }}); 2490 } 2491 2492 // consume a new repo's event into its owner's user repo and mark it active 2493 fn writeRepoEvent( 2494 io: std.Io, 2495 allocator: std.mem.Allocator, 2496 users_dir: []const u8, 2497 user_repo: *rp.Repo(.xit, user_repo_opts), 2498 owner_id: *const [event_id_size]u8, 2499 owner: CommitAuthor, 2500 id_bytes: *const [event_id_size]u8, 2501 name: []const u8, 2502 description: []const u8, 2503 read_access: Repo.Access, 2504 ) !void { 2505 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2506 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2507 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2508 .timestamp = timestamp, 2509 .author = owner, 2510 .event = .{ .repo = .{ 2511 .user_id = std.fmt.bytesToHex(owner_id.*, .lower), 2512 .name = name, 2513 .description = description, 2514 .read_access = read_access, 2515 } }, 2516 }}); 2517 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2518 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2519 }; 2520 } 2521 2522 // 2523 // reading from xitdb 2524 // 2525 2526 // read just `Fields`, a subset of `T.Record`, from the record with event id 2527 // `id`, or null when there is none 2528 pub fn readRecordSubset( 2529 comptime T: type, 2530 comptime Fields: type, 2531 comptime DB: type, 2532 comptime hash_kind: hash.HashKind, 2533 haxy_moment: DB.HashMap(.read_only), 2534 arena: *std.heap.ArenaAllocator, 2535 id: []const u8, 2536 ) !?Fields { 2537 comptime assertFieldSubset(Fields, T.Record); 2538 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2539 const records = try DB.HashMap(.read_only).init(records_cursor); 2540 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2541 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2542 } 2543 2544 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2545 const info = @typeInfo(Sub).@"struct"; 2546 for (info.field_names, info.field_types) |field_name, field_type| { 2547 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2548 const FullField = @FieldType(Full, field_name); 2549 if (@typeInfo(field_type) == .@"struct") { 2550 assertFieldSubset(field_type, FullField); 2551 } else if (field_type != FullField) { 2552 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2553 } 2554 } 2555 } 2556 2557 pub fn read( 2558 comptime T: type, 2559 comptime DB: type, 2560 comptime hash_kind: hash.HashKind, 2561 arena: *std.heap.ArenaAllocator, 2562 map: DB.HashMap(.read_only), 2563 ) !T { 2564 var event: T = undefined; 2565 switch (@typeInfo(T)) { 2566 .@"struct" => |struct_info| { 2567 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2568 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2569 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2570 } 2571 }, 2572 else => @compileError("read expects a struct"), 2573 } 2574 return event; 2575 } 2576 2577 fn readField( 2578 comptime Field: type, 2579 comptime DB: type, 2580 comptime hash_kind: hash.HashKind, 2581 arena: *std.heap.ArenaAllocator, 2582 cursor_maybe: ?DB.Cursor(.read_only), 2583 ) !Field { 2584 if (@typeInfo(Field) == .optional) { 2585 // a missing key or a null union payload is null 2586 const cursor = cursor_maybe orelse return null; 2587 if (cursor.slot().tag == .none) return null; 2588 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2589 } 2590 const cursor = cursor_maybe orelse return error.NotFound; 2591 switch (@typeInfo(Field)) { 2592 .pointer => |pointer_info| { 2593 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2594 @compileError("unsupported read field type: " ++ @typeName(Field)); 2595 } 2596 return try cursor.readBytesAlloc(arena.allocator(), null); 2597 }, 2598 .array => |array_info| { 2599 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2600 var bytes: Field = undefined; 2601 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2602 return bytes; 2603 }, 2604 .bool => { 2605 var buffer: [5]u8 = undefined; 2606 const bytes = try cursor.readBytesObject(&buffer); 2607 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2608 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2609 if (std.mem.eql(u8, bytes.value, "true")) return true; 2610 if (std.mem.eql(u8, bytes.value, "false")) return false; 2611 return error.InvalidBool; 2612 }, 2613 .int => |int_info| return switch (int_info.signedness) { 2614 .unsigned => @intCast(try cursor.readUint()), 2615 .signed => @intCast(try cursor.readInt()), 2616 }, 2617 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2618 .@"union" => |union_info| { 2619 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2620 switch (cursor.slot().tag) { 2621 .bytes, .short_bytes => { 2622 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2623 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2624 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2625 return @unionInit(Field, variant_name, {}); 2626 } 2627 } 2628 return error.InvalidUnion; 2629 }, 2630 .hash_map => { 2631 const variants = try DB.HashMap(.read_only).init(cursor); 2632 var iter = try variants.iterator(); 2633 const entry = (try iter.next()) orelse return error.InvalidUnion; 2634 const pair = try entry.readKeyValuePair(); 2635 if (try iter.next() != null) return error.InvalidUnion; 2636 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2637 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2638 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2639 } 2640 } 2641 return error.InvalidUnion; 2642 }, 2643 else => return error.InvalidUnion, 2644 } 2645 }, 2646 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2647 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2648 } 2649 } 2650 2651 // whether two events carry the same data 2652 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2653 switch (@typeInfo(T)) { 2654 .@"struct" => |struct_info| { 2655 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2656 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2657 } 2658 }, 2659 else => @compileError("fieldsEqual expects a struct"), 2660 } 2661 2662 return true; 2663 } 2664 2665 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2666 switch (@typeInfo(Field)) { 2667 .pointer => |pointer_info| { 2668 if (pointer_info.size == .slice and pointer_info.child == u8) { 2669 return std.mem.eql(u8, a, b); 2670 } else { 2671 @compileError("unsupported field type: " ++ @typeName(Field)); 2672 } 2673 }, 2674 .array => |array_info| { 2675 if (array_info.child == u8) { 2676 return std.mem.eql(u8, &a, &b); 2677 } else { 2678 @compileError("unsupported field type: " ++ @typeName(Field)); 2679 } 2680 }, 2681 .void => return true, 2682 .bool, .int, .@"enum" => return a == b, 2683 .@"union" => { 2684 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2685 return switch (a) { 2686 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2687 }; 2688 }, 2689 .@"struct" => return fieldsEqual(Field, a, b), 2690 .optional => |optional_info| { 2691 if (a) |a_value| { 2692 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2693 return false; 2694 } 2695 return b == null; 2696 }, 2697 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2698 } 2699 } 2700 2701 // 2702 // writing to xitdb 2703 // 2704 2705 pub fn upsert( 2706 comptime T: type, 2707 comptime DB: type, 2708 comptime hash_kind: hash.HashKind, 2709 map: DB.HashMap(.read_write), 2710 event: T, 2711 ) !void { 2712 switch (@typeInfo(T)) { 2713 .@"struct" => |struct_info| { 2714 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2715 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2716 } 2717 }, 2718 else => @compileError("upsert expects a struct"), 2719 } 2720 } 2721 2722 fn upsertField( 2723 comptime DB: type, 2724 comptime hash_kind: hash.HashKind, 2725 map: DB.HashMap(.read_write), 2726 comptime field_name: []const u8, 2727 comptime Field: type, 2728 value: Field, 2729 ) !void { 2730 const key = hash.hashInt(hash_kind, field_name); 2731 2732 switch (@typeInfo(Field)) { 2733 .pointer => |pointer_info| { 2734 if (pointer_info.size == .slice and pointer_info.child == u8) { 2735 try upsertBytes(DB, hash_kind, map, key, value); 2736 } else { 2737 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2738 } 2739 }, 2740 .array => |array_info| { 2741 if (array_info.child == u8) { 2742 try upsertBytes(DB, hash_kind, map, key, &value); 2743 } else { 2744 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2745 } 2746 }, 2747 .int => |int_info| switch (int_info.signedness) { 2748 .unsigned => { 2749 if (try map.getCursor(key)) |value_cursor| { 2750 if (try value_cursor.readUint() == value) { 2751 return; 2752 } 2753 } 2754 2755 try map.put(key, .{ .uint = value }); 2756 }, 2757 .signed => { 2758 if (try map.getCursor(key)) |value_cursor| { 2759 if (try value_cursor.readInt() == value) { 2760 return; 2761 } 2762 } 2763 2764 try map.put(key, .{ .int = value }); 2765 }, 2766 }, 2767 .bool => { 2768 const bytes = if (value) "true" else "false"; 2769 if (try map.getCursor(key)) |value_cursor| { 2770 var buffer: [5]u8 = undefined; 2771 const existing = try value_cursor.readBytesObject(&buffer); 2772 if (existing.format_tag) |format_tag| { 2773 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2774 return; 2775 } 2776 } 2777 } 2778 2779 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2780 }, 2781 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2782 .@"union" => switch (value) { 2783 inline else => |payload, tag| { 2784 if (@TypeOf(payload) == void) { 2785 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2786 } else { 2787 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2788 if (try map.getCursor(key)) |cursor| { 2789 switch (cursor.slot().tag) { 2790 .hash_map => { 2791 const variants = try DB.HashMap(.read_only).init(cursor); 2792 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2793 }, 2794 else => try map.put(key, .{ .slot = null }), 2795 } 2796 } 2797 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2798 if (@typeInfo(@TypeOf(payload)) == .optional) { 2799 // keep the variant even when its payload is null 2800 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2801 } 2802 if (try variants.getCursor(tag_key)) |cursor| { 2803 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2804 } 2805 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2806 } 2807 }, 2808 }, 2809 .optional => |optional_info| { 2810 // a missing key is null 2811 if (value) |child| { 2812 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2813 } else { 2814 _ = try map.remove(key); 2815 } 2816 }, 2817 .@"struct" => try upsert( 2818 Field, 2819 DB, 2820 hash_kind, 2821 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2822 value, 2823 ), 2824 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2825 } 2826 } 2827 2828 fn upsertBytes( 2829 comptime DB: type, 2830 comptime hash_kind: hash.HashKind, 2831 map: DB.HashMap(.read_write), 2832 key: hash.HashInt(hash_kind), 2833 value: []const u8, 2834 ) !void { 2835 var existing_cursor_maybe = try map.getCursor(key); 2836 if (existing_cursor_maybe) |*existing_cursor| { 2837 if (try bytesEqual(DB, existing_cursor, value)) { 2838 return; 2839 } 2840 } 2841 2842 try map.put(key, .{ .bytes = value }); 2843 } 2844 2845 fn bytesEqual( 2846 comptime DB: type, 2847 cursor: *DB.Cursor(.read_only), 2848 value: []const u8, 2849 ) !bool { 2850 switch (cursor.slot().tag) { 2851 .bytes, .short_bytes => {}, 2852 else => return false, 2853 } 2854 var read_buffer: [1024]u8 = undefined; 2855 var reader = try cursor.reader(&read_buffer); 2856 if (reader.size != value.len) { 2857 return false; 2858 } 2859 2860 var chunk_buffer: [1024]u8 = undefined; 2861 var offset: usize = 0; 2862 while (offset < value.len) { 2863 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2864 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2865 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2866 return false; 2867 } 2868 offset += chunk_len; 2869 } 2870 2871 return true; 2872 } 2873 2874 // 2875 // CommitIterator 2876 // 2877 // differs from xit's ObjectIterator in a few ways: 2878 // 2879 // 1. iterates parents first, rather than children first 2880 // 2. `next` only returns the object id, not the full Object 2881 // 3. stores its temporary state in a file on disk to avoid OOMs 2882 // 2883 2884 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2885 return struct { 2886 const DB = EventDB(repo_opts.hash); 2887 // a plain file is used for the scratch db because each write outside 2888 // a transaction is synced anyway, so buffering would gain nothing 2889 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2890 const db_name = "haxy-repo-events.db"; 2891 2892 repo_dir: std.Io.Dir, 2893 db_file: std.Io.File, 2894 db: *TempDB, 2895 // map of each object id to its children 2896 parent_to_children: TempDB.HashMap(.read_write), 2897 // tracking pending parents is necessary because a child can only 2898 // be returned after all of its unconsumed parents have been returned 2899 child_to_pending_parents: TempDB.HashMap(.read_write), 2900 // queue of object ids that are ready to be returned from `next` 2901 ready_queue: TempDB.ArrayList(.read_write), 2902 ready_queue_index: u64, 2903 // the object id at the tip of this branch 2904 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2905 // the object id furthest back in the history that hasn't been consumed 2906 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2907 2908 pub fn init( 2909 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2910 io: std.Io, 2911 allocator: std.mem.Allocator, 2912 consumed_object_ids: DB.HashMap(.read_only), 2913 ref: rf.Ref, 2914 ) !CommitIterator(repo_kind, repo_opts) { 2915 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2916 errdefer { 2917 db_file.close(io); 2918 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2919 } 2920 2921 // cursors point at the db, so it needs a stable address 2922 const db_ptr = try allocator.create(TempDB); 2923 errdefer allocator.destroy(db_ptr); 2924 // the db is scratch state that gets deleted after iteration, so 2925 // there is nothing worth fsyncing 2926 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2927 2928 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2929 2930 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2931 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2932 2933 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2934 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2935 2936 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2937 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2938 2939 var self = CommitIterator(repo_kind, repo_opts){ 2940 .repo_dir = state.core.repo_dir, 2941 .db_file = db_file, 2942 .db = db_ptr, 2943 .parent_to_children = parent_to_children, 2944 .child_to_pending_parents = child_to_pending_parents, 2945 .ready_queue = ready_queue, 2946 .ready_queue_index = 0, 2947 .newest_object_id = null, 2948 .oldest_object_id = null, 2949 }; 2950 errdefer self.deinit(io, allocator); 2951 2952 try self.collect(state, io, allocator, consumed_object_ids, ref); 2953 2954 return self; 2955 } 2956 2957 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2958 self.db_file.close(io); 2959 self.repo_dir.deleteFile(io, db_name) catch {}; 2960 allocator.destroy(self.db); 2961 } 2962 2963 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2964 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2965 2966 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2967 self.ready_queue_index += 1; 2968 2969 try self.enqueueChildren(&oid); 2970 return oid; 2971 } 2972 2973 fn collect( 2974 self: *CommitIterator(repo_kind, repo_opts), 2975 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2976 io: std.Io, 2977 allocator: std.mem.Allocator, 2978 consumed_object_ids: DB.HashMap(.read_only), 2979 ref: rf.Ref, 2980 ) !void { 2981 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2982 2983 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2984 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2985 var walk_queue_index: u64 = 0; 2986 2987 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2988 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2989 2990 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2991 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2992 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2993 try walk_queue.append(.{ .bytes = &head_oid }); 2994 2995 while (walk_queue_index < try walk_queue.count()) { 2996 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2997 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2998 2999 walk_queue_index += 1; 3000 3001 // if we've seen this object id, skip it 3002 if (null != try seen_object_ids.getCursor(oid_int)) { 3003 continue; 3004 } 3005 3006 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 3007 3008 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 3009 defer commit_object.deinit(); 3010 3011 // if this object id has already been consumed, skip it 3012 if (null != try consumed_object_ids.getCursor(oid_int)) { 3013 continue; 3014 } 3015 3016 if (self.newest_object_id == null) self.newest_object_id = oid; 3017 self.oldest_object_id = oid; 3018 3019 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 3020 var pending_parent_count: u64 = 0; 3021 for (parent_oids) |*parent_oid| { 3022 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 3023 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 3024 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 3025 3026 // if this object id has already been consumed, skip it 3027 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 3028 continue; 3029 } 3030 3031 // if this object id hasn't already been seen, add it to the walk queue 3032 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 3033 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 3034 } 3035 3036 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 3037 const children = try TempDB.HashSet(.read_write).init(children_cursor); 3038 try children.put(oid_int, .{ .bytes = &oid }); 3039 pending_parent_count += 1; 3040 } 3041 3042 if (pending_parent_count == 0) { 3043 try self.ready_queue.append(.{ .bytes = &oid }); 3044 } else { 3045 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 3046 } 3047 } 3048 } 3049 3050 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 3051 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 3052 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 3053 const children = try TempDB.HashSet(.read_only).init(children_cursor); 3054 var children_iter = try children.iterator(); 3055 3056 while (try children_iter.next()) |*child_cursor| { 3057 const kv_pair = try child_cursor.readKeyValuePair(); 3058 const child_oid_int = kv_pair.hash; 3059 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 3060 const pending_parent_count = try pending_parent_cursor.readUint(); 3061 3062 if (pending_parent_count <= 1) { 3063 _ = try self.child_to_pending_parents.remove(child_oid_int); 3064 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 3065 try self.ready_queue.append(.{ .bytes = &child_oid }); 3066 } else { 3067 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 3068 } 3069 } 3070 } 3071 3072 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 3073 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 3074 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 3075 _ = try oid_cursor.readBytes(&oid); 3076 return oid; 3077 } 3078 }; 3079 } 3080