╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
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 // a comment or attachment a write names under a thread 1658 pub const ThreadChild = union(enum) { 1659 comment: *const [event_id_size]u8, 1660 attach: *const [event_id_size]u8, 1661 }; 1662 1663 // whether `thread_id` names a thread of `thread_kind` in the repo's events, and 1664 // `child`, when given, belongs to it. a caller's url can claim any kind for any 1665 // id, so every write under a thread checks its claim here first. 1666 pub fn threadHolds( 1667 comptime repo_kind: rp.RepoKind, 1668 comptime repo_opts: rp.RepoOpts(repo_kind), 1669 io: std.Io, 1670 allocator: std.mem.Allocator, 1671 repo: *rp.Repo(repo_kind, repo_opts), 1672 thread_kind: EventKind, 1673 thread_id: *const [event_id_size]u8, 1674 child_maybe: ?ThreadChild, 1675 ) !bool { 1676 const DB = EventDB(repo_opts.hash); 1677 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; 1678 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1679 const moment = (if (event_db_maybe) |*event_db| 1680 currentMomentFromDb(repo_opts.hash, event_db.db) 1681 else if (repo_kind == .git) 1682 return false 1683 else 1684 currentMoment(repo_opts, repo)) catch return false; 1685 1686 // only these kinds are threads 1687 switch (thread_kind) { 1688 .discuss, .issue, .patch => {}, 1689 else => return false, 1690 } 1691 const kinds_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return false; 1692 const kinds = try DB.HashMap(.read_only).init(kinds_cursor); 1693 if ((try readEventKind(repo_opts.hash, kinds, thread_id)) != thread_kind) return false; 1694 1695 const child = child_maybe orelse return true; 1696 var arena = std.heap.ArenaAllocator.init(allocator); 1697 defer arena.deinit(); 1698 const thread_id_hex = std.fmt.bytesToHex(thread_id.*, .lower); 1699 switch (child) { 1700 .comment => |id| { 1701 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; 1702 return std.mem.eql(u8, &comment.event.thread_id, &thread_id_hex); 1703 }, 1704 .attach => |id| { 1705 const attachment = (try readRecordSubset(Attachment, struct { event: struct { parent_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1706 return std.mem.eql(u8, &attachment.event.parent_id, &thread_id_hex); 1707 }, 1708 } 1709 } 1710 1711 // remove an event a thread's page names: the thread itself, or a comment or 1712 // attachment, which must belong to it 1713 pub fn removeInThread( 1714 host: Host, 1715 comptime repo_kind: rp.RepoKind, 1716 comptime repo_opts: rp.RepoOpts(repo_kind), 1717 io: std.Io, 1718 allocator: std.mem.Allocator, 1719 repo: *rp.Repo(repo_kind, repo_opts), 1720 thread_kind: EventKind, 1721 thread_id: *const [event_id_size]u8, 1722 kind: EventKind, 1723 id: *const [event_id_size]u8, 1724 author: CommitAuthor, 1725 ) !void { 1726 const child_maybe: ?ThreadChild = switch (kind) { 1727 .comment => .{ .comment = id }, 1728 .attach => .{ .attach = id }, 1729 else => null, 1730 }; 1731 if (child_maybe) |child| { 1732 if (!try threadHolds(repo_kind, repo_opts, io, allocator, repo, thread_kind, thread_id, child)) return error.EventNotFound; 1733 } 1734 try remove(host, .repo, repo_kind, repo_opts, io, allocator, repo, id, kind, author); 1735 } 1736 1737 pub fn readFromRepo( 1738 comptime T: type, 1739 comptime repo_kind: rp.RepoKind, 1740 comptime repo_opts: rp.RepoOpts(repo_kind), 1741 io: std.Io, 1742 allocator: std.mem.Allocator, 1743 arena: *std.heap.ArenaAllocator, 1744 repo: *rp.Repo(repo_kind, repo_opts), 1745 id: *const [event_id_size]u8, 1746 ) !?T.Record { 1747 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; 1748 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1749 const moment = (if (event_db_maybe) |*event_db| 1750 currentMomentFromDb(repo_opts.hash, event_db.db) 1751 else if (repo_kind == .git) 1752 return null 1753 else 1754 currentMoment(repo_opts, repo)) catch return null; 1755 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1756 } 1757 1758 pub fn currentMoment( 1759 comptime repo_opts: rp.RepoOpts(.xit), 1760 repo: *rp.Repo(.xit, repo_opts), 1761 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1762 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1763 } 1764 1765 pub fn currentMomentFromDb( 1766 comptime hash_kind: hash.HashKind, 1767 db: *EventDB(hash_kind), 1768 ) !EventDB(hash_kind).HashMap(.read_only) { 1769 const DB = EventDB(hash_kind); 1770 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1771 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1772 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1773 return try currentMomentFromRepoMoment(hash_kind, moment); 1774 } 1775 1776 pub fn currentMomentFromRepoMoment( 1777 comptime hash_kind: hash.HashKind, 1778 moment: EventDB(hash_kind).HashMap(.read_only), 1779 ) !EventDB(hash_kind).HashMap(.read_only) { 1780 const DB = EventDB(hash_kind); 1781 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1782 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1783 _ = try last_object_id_cursor.readBytes(&last_object_id); 1784 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1785 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1786 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1787 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1788 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1789 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1790 } 1791 1792 // build a sorted-set key from an order and event id. big-endian order makes 1793 // byte order match numeric order; the event id breaks ties. 1794 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1795 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1796 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1797 @memcpy(key[@sizeOf(u64)..], event_id); 1798 return key; 1799 } 1800 1801 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1802 return orderKey(std.math.maxInt(u64) - order, event_id); 1803 } 1804 1805 pub fn removedRecord( 1806 comptime T: type, 1807 comptime DB: type, 1808 comptime hash_kind: hash.HashKind, 1809 haxy_moment: DB.HashMap(.read_only), 1810 existing_maybe: ?T, 1811 ) !T { 1812 var record = existing_maybe orelse return error.EventNotFound; 1813 record.removed = true; 1814 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1815 record.updated_order = try order_cursor.readUint(); 1816 return record; 1817 } 1818 1819 // add or refresh one entry in the global logical-event index 1820 pub fn indexEvent( 1821 comptime DB: type, 1822 comptime hash_kind: hash.HashKind, 1823 haxy_moment: DB.HashMap(.read_write), 1824 event_id: *const [event_id_size]u8, 1825 kind: EventKind, 1826 existing_maybe: anytype, 1827 record: anytype, 1828 ) !void { 1829 const event_key = hash.hashInt(hash_kind, event_id); 1830 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1831 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1832 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1833 1834 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1835 const active = try DB.SortedSet(.read_write).init(active_cursor); 1836 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1837 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1838 1839 if (existing_maybe) |existing| { 1840 const old_key = orderKeyDesc(existing.updated_order, event_id); 1841 _ = try active.remove(&old_key); 1842 _ = try removed_set.remove(&old_key); 1843 } 1844 1845 const order_key = orderKeyDesc(record.updated_order, event_id); 1846 if (record.removed) { 1847 try removed_set.put(&order_key); 1848 } else { 1849 try active.put(&order_key); 1850 } 1851 } 1852 1853 pub fn touchThread( 1854 comptime DB: type, 1855 comptime hash_kind: hash.HashKind, 1856 haxy_moment: DB.HashMap(.read_write), 1857 thread_id: *const [event_id_size]u8, 1858 order: u64, 1859 arena: *std.heap.ArenaAllocator, 1860 ) !void { 1861 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1862 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1863 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1864 switch (kind) { 1865 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1866 else => {}, 1867 } 1868 } 1869 1870 pub fn readEventKind( 1871 comptime hash_kind: hash.HashKind, 1872 kind_map: anytype, 1873 id: *const [event_id_size]u8, 1874 ) !?EventKind { 1875 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1876 var buffer: [64]u8 = undefined; 1877 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1878 } 1879 1880 // the email of the event's author, or null when the id names no authored event 1881 // of this kind 1882 pub fn readAuthorEmail( 1883 comptime repo_kind: rp.RepoKind, 1884 comptime repo_opts: rp.RepoOpts(repo_kind), 1885 io: std.Io, 1886 allocator: std.mem.Allocator, 1887 arena: *std.heap.ArenaAllocator, 1888 repo: *rp.Repo(repo_kind, repo_opts), 1889 kind: EventKind, 1890 id: *const [event_id_size]u8, 1891 ) !?[]const u8 { 1892 const record_map_key = switch (kind) { 1893 .discuss => Discussion.record_map_key, 1894 .issue => Issue.record_map_key, 1895 .comment => Comment.record_map_key, 1896 .attach => Attachment.record_map_key, 1897 .patchrev => PatchRev.record_map_key, 1898 .patch => Patch.record_map_key, 1899 .user, .repo, .fork, .grant => return null, 1900 }; 1901 1902 const DB = EventDB(repo_opts.hash); 1903 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; 1904 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1905 const moment = (if (event_db_maybe) |*event_db| 1906 currentMomentFromDb(repo_opts.hash, event_db.db) 1907 else if (repo_kind == .git) 1908 return null 1909 else 1910 currentMoment(repo_opts, repo)) catch return null; 1911 1912 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1913 const records = try DB.HashMap(.read_only).init(records_cursor); 1914 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1915 const record = try DB.HashMap(.read_only).init(record_cursor); 1916 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1917 } 1918 1919 // the event id embedded in a set entry's order key 1920 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1921 var cursor = kv_pair_cursor; 1922 const kv_pair = try cursor.readKeyValuePair(); 1923 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1924 _ = try kv_pair.key_cursor.readBytes(&order_key); 1925 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1926 } 1927 1928 // split a pushed "<owner>:<repo>" path into its two components, or null if it 1929 // isn't exactly two non-empty parts with no "/". 1930 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1931 if (std.mem.indexOfScalar(u8, path, '/') != null) return null; 1932 var it = std.mem.splitScalar(u8, path, ':'); 1933 const owner = it.next() orelse return null; 1934 const name = it.next() orelse return null; 1935 if (it.next() != null) return null; 1936 if (owner.len == 0 or name.len == 0) return null; 1937 1938 return .{ .owner = owner, .name = name }; 1939 } 1940 1941 pub const CreateRepoOptions = struct { 1942 read_access: Repo.Access = .private, 1943 }; 1944 1945 // the ids that locate a repo's on-disk directory 1946 pub const RepoLocation = struct { 1947 owner_id: [event_id_size]u8, 1948 repo_id: [event_id_size]u8, 1949 }; 1950 1951 // resolve a pushed `<owner>:<repo>` to the ids that locate its on-disk directory 1952 pub fn resolveOrCreateRepo( 1953 io: std.Io, 1954 allocator: std.mem.Allocator, 1955 users_dir: []const u8, 1956 admin_repo_path: []const u8, 1957 owner_name: []const u8, 1958 repo_name: []const u8, 1959 create_options_maybe: ?CreateRepoOptions, 1960 ) !?RepoLocation { 1961 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1962 error.RepoNotFound => return null, 1963 else => |e| return e, 1964 }; 1965 defer admin_repo.deinit(io, allocator); 1966 1967 var arena = std.heap.ArenaAllocator.init(allocator); 1968 defer arena.deinit(); 1969 1970 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 1971 1972 // an unknown owner can't own a repo, so the push is rejected 1973 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 1974 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 1975 defer user_repo.deinit(io, allocator); 1976 1977 // an already-registered repo reuses its event id, so a re-push (or a clone) 1978 // lands in the same repo 1979 if (try userMoment(&user_repo)) |moment| { 1980 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 1981 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 1982 } 1983 } 1984 1985 const create_options = create_options_maybe orelse return null; 1986 1987 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 1988 1989 var id_bytes: [event_id_size]u8 = undefined; 1990 io.random(&id_bytes); 1991 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); 1992 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 1993 } 1994 1995 // create a bare repo with `hash_kind` and register it in its owner's user repo 1996 pub fn createRepo( 1997 io: std.Io, 1998 allocator: std.mem.Allocator, 1999 users_dir: []const u8, 2000 owner_id: *const [event_id_size]u8, 2001 owner: CommitAuthor, 2002 name: []const u8, 2003 description: []const u8, 2004 read_access: Repo.Access, 2005 hash_kind: hash.HashKind, 2006 ) !RepoLocation { 2007 try Repo.validateName(name); 2008 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2009 defer user_repo.deinit(io, allocator); 2010 if (try userMoment(&user_repo)) |moment| { 2011 var arena = std.heap.ArenaAllocator.init(allocator); 2012 defer arena.deinit(); 2013 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2014 } 2015 2016 var id_bytes: [event_id_size]u8 = undefined; 2017 io.random(&id_bytes); 2018 2019 // the directory comes first so a listed repo always has one 2020 { 2021 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2022 defer allocator.free(path); 2023 switch (hash_kind) { 2024 inline else => |kind| { 2025 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2026 defer repo.deinit(io, allocator); 2027 }, 2028 } 2029 } 2030 2031 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2032 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2033 } 2034 2035 // change the name, description, read access, and tab roles of the repo 2036 // named `old_name` in its owner's user repo 2037 pub fn updateRepo( 2038 io: std.Io, 2039 allocator: std.mem.Allocator, 2040 users_dir: []const u8, 2041 owner_id: *const [event_id_size]u8, 2042 author: CommitAuthor, 2043 old_name: []const u8, 2044 name: []const u8, 2045 description: []const u8, 2046 read_access: Repo.Access, 2047 discuss_role: ?Repo.Role, 2048 issue_role: ?Repo.Role, 2049 patch_role: ?Repo.Role, 2050 ) !void { 2051 try Repo.validateName(name); 2052 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2053 defer user_repo.deinit(io, allocator); 2054 var arena = std.heap.ArenaAllocator.init(allocator); 2055 defer arena.deinit(); 2056 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2057 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2058 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2059 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2060 } 2061 2062 var event = found.repo.event; 2063 event.name = name; 2064 event.description = description; 2065 event.read_access = read_access; 2066 event.discuss_role = discuss_role; 2067 event.issue_role = issue_role; 2068 event.patch_role = patch_role; 2069 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2070 .id = std.fmt.bytesToHex(found.event_id, .lower), 2071 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2072 .author = author, 2073 .event = .{ .repo = event }, 2074 }}); 2075 } 2076 2077 // create a user and their user repo, returning the new user's id 2078 pub fn createUser( 2079 io: std.Io, 2080 allocator: std.mem.Allocator, 2081 users_dir: []const u8, 2082 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2083 name: []const u8, 2084 email: []const u8, 2085 password: []const u8, 2086 password_again: []const u8, 2087 ) ![event_id_size]u8 { 2088 try User.validateName(name); 2089 if (email.len == 0) return error.EmailEmpty; 2090 if (password.len == 0) return error.PasswordEmpty; 2091 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2092 // a fresh admin repo has no moment until its first event 2093 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2094 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2095 var arena = std.heap.ArenaAllocator.init(allocator); 2096 defer arena.deinit(); 2097 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2098 } else |err| switch (err) { 2099 error.NotFound => {}, 2100 else => |e| return e, 2101 } 2102 2103 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2104 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2105 2106 var id_bytes: [event_id_size]u8 = undefined; 2107 io.random(&id_bytes); 2108 2109 // the user repo comes first so a listed user can always create repos 2110 { 2111 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2112 defer allocator.free(path); 2113 var user_repo = try initUserRepo(io, allocator, path); 2114 defer user_repo.deinit(io, allocator); 2115 } 2116 2117 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2118 .id = std.fmt.bytesToHex(id_bytes, .lower), 2119 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2120 .author = .{ .name = name, .email = email }, 2121 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2122 }}); 2123 return id_bytes; 2124 } 2125 2126 // consume a new repo's event into its owner's user repo and mark it active 2127 fn writeRepoEvent( 2128 io: std.Io, 2129 allocator: std.mem.Allocator, 2130 users_dir: []const u8, 2131 user_repo: *rp.Repo(.xit, user_repo_opts), 2132 owner_id: *const [event_id_size]u8, 2133 owner: CommitAuthor, 2134 id_bytes: *const [event_id_size]u8, 2135 name: []const u8, 2136 description: []const u8, 2137 read_access: Repo.Access, 2138 ) !void { 2139 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2140 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2141 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2142 .timestamp = timestamp, 2143 .author = owner, 2144 .event = .{ .repo = .{ 2145 .user_id = owner_id, 2146 .name = name, 2147 .description = description, 2148 .read_access = read_access, 2149 } }, 2150 }}); 2151 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2152 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2153 }; 2154 } 2155 2156 // 2157 // reading from xitdb 2158 // 2159 2160 // read just `Fields`, a subset of `T.Record`, from the record with event id 2161 // `id`, or null when there is none 2162 pub fn readRecordSubset( 2163 comptime T: type, 2164 comptime Fields: type, 2165 comptime DB: type, 2166 comptime hash_kind: hash.HashKind, 2167 haxy_moment: DB.HashMap(.read_only), 2168 arena: *std.heap.ArenaAllocator, 2169 id: []const u8, 2170 ) !?Fields { 2171 comptime assertFieldSubset(Fields, T.Record); 2172 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2173 const records = try DB.HashMap(.read_only).init(records_cursor); 2174 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2175 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2176 } 2177 2178 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2179 const info = @typeInfo(Sub).@"struct"; 2180 for (info.field_names, info.field_types) |field_name, field_type| { 2181 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2182 const FullField = @FieldType(Full, field_name); 2183 if (@typeInfo(field_type) == .@"struct") { 2184 assertFieldSubset(field_type, FullField); 2185 } else if (field_type != FullField) { 2186 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2187 } 2188 } 2189 } 2190 2191 pub fn read( 2192 comptime T: type, 2193 comptime DB: type, 2194 comptime hash_kind: hash.HashKind, 2195 arena: *std.heap.ArenaAllocator, 2196 map: DB.HashMap(.read_only), 2197 ) !T { 2198 var event: T = undefined; 2199 switch (@typeInfo(T)) { 2200 .@"struct" => |struct_info| { 2201 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2202 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2203 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2204 } 2205 }, 2206 else => @compileError("read expects a struct"), 2207 } 2208 return event; 2209 } 2210 2211 fn readField( 2212 comptime Field: type, 2213 comptime DB: type, 2214 comptime hash_kind: hash.HashKind, 2215 arena: *std.heap.ArenaAllocator, 2216 cursor_maybe: ?DB.Cursor(.read_only), 2217 ) !Field { 2218 if (@typeInfo(Field) == .optional) { 2219 // a missing key or a null union payload is null 2220 const cursor = cursor_maybe orelse return null; 2221 if (cursor.slot().tag == .none) return null; 2222 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2223 } 2224 const cursor = cursor_maybe orelse return error.NotFound; 2225 switch (@typeInfo(Field)) { 2226 .pointer => |pointer_info| { 2227 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2228 @compileError("unsupported read field type: " ++ @typeName(Field)); 2229 } 2230 return try cursor.readBytesAlloc(arena.allocator(), null); 2231 }, 2232 .array => |array_info| { 2233 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2234 var bytes: Field = undefined; 2235 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2236 return bytes; 2237 }, 2238 .bool => { 2239 var buffer: [5]u8 = undefined; 2240 const bytes = try cursor.readBytesObject(&buffer); 2241 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2242 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2243 if (std.mem.eql(u8, bytes.value, "true")) return true; 2244 if (std.mem.eql(u8, bytes.value, "false")) return false; 2245 return error.InvalidBool; 2246 }, 2247 .int => |int_info| return switch (int_info.signedness) { 2248 .unsigned => @intCast(try cursor.readUint()), 2249 .signed => @intCast(try cursor.readInt()), 2250 }, 2251 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2252 .@"union" => |union_info| { 2253 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2254 switch (cursor.slot().tag) { 2255 .bytes, .short_bytes => { 2256 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2257 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2258 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2259 return @unionInit(Field, variant_name, {}); 2260 } 2261 } 2262 return error.InvalidUnion; 2263 }, 2264 .hash_map => { 2265 const variants = try DB.HashMap(.read_only).init(cursor); 2266 var iter = try variants.iterator(); 2267 const entry = (try iter.next()) orelse return error.InvalidUnion; 2268 const pair = try entry.readKeyValuePair(); 2269 if (try iter.next() != null) return error.InvalidUnion; 2270 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2271 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2272 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2273 } 2274 } 2275 return error.InvalidUnion; 2276 }, 2277 else => return error.InvalidUnion, 2278 } 2279 }, 2280 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2281 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2282 } 2283 } 2284 2285 // whether two events carry the same data 2286 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2287 switch (@typeInfo(T)) { 2288 .@"struct" => |struct_info| { 2289 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2290 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2291 } 2292 }, 2293 else => @compileError("fieldsEqual expects a struct"), 2294 } 2295 2296 return true; 2297 } 2298 2299 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2300 switch (@typeInfo(Field)) { 2301 .pointer => |pointer_info| { 2302 if (pointer_info.size == .slice and pointer_info.child == u8) { 2303 return std.mem.eql(u8, a, b); 2304 } else { 2305 @compileError("unsupported field type: " ++ @typeName(Field)); 2306 } 2307 }, 2308 .array => |array_info| { 2309 if (array_info.child == u8) { 2310 return std.mem.eql(u8, &a, &b); 2311 } else { 2312 @compileError("unsupported field type: " ++ @typeName(Field)); 2313 } 2314 }, 2315 .void => return true, 2316 .bool, .int, .@"enum" => return a == b, 2317 .@"union" => { 2318 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2319 return switch (a) { 2320 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2321 }; 2322 }, 2323 .@"struct" => return fieldsEqual(Field, a, b), 2324 .optional => |optional_info| { 2325 if (a) |a_value| { 2326 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2327 return false; 2328 } 2329 return b == null; 2330 }, 2331 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2332 } 2333 } 2334 2335 // 2336 // writing to xitdb 2337 // 2338 2339 pub fn upsert( 2340 comptime T: type, 2341 comptime DB: type, 2342 comptime hash_kind: hash.HashKind, 2343 map: DB.HashMap(.read_write), 2344 event: T, 2345 ) !void { 2346 switch (@typeInfo(T)) { 2347 .@"struct" => |struct_info| { 2348 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2349 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2350 } 2351 }, 2352 else => @compileError("upsert expects a struct"), 2353 } 2354 } 2355 2356 fn upsertField( 2357 comptime DB: type, 2358 comptime hash_kind: hash.HashKind, 2359 map: DB.HashMap(.read_write), 2360 comptime field_name: []const u8, 2361 comptime Field: type, 2362 value: Field, 2363 ) !void { 2364 const key = hash.hashInt(hash_kind, field_name); 2365 2366 switch (@typeInfo(Field)) { 2367 .pointer => |pointer_info| { 2368 if (pointer_info.size == .slice and pointer_info.child == u8) { 2369 try upsertBytes(DB, hash_kind, map, key, value); 2370 } else { 2371 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2372 } 2373 }, 2374 .array => |array_info| { 2375 if (array_info.child == u8) { 2376 try upsertBytes(DB, hash_kind, map, key, &value); 2377 } else { 2378 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2379 } 2380 }, 2381 .int => |int_info| switch (int_info.signedness) { 2382 .unsigned => { 2383 if (try map.getCursor(key)) |value_cursor| { 2384 if (try value_cursor.readUint() == value) { 2385 return; 2386 } 2387 } 2388 2389 try map.put(key, .{ .uint = value }); 2390 }, 2391 .signed => { 2392 if (try map.getCursor(key)) |value_cursor| { 2393 if (try value_cursor.readInt() == value) { 2394 return; 2395 } 2396 } 2397 2398 try map.put(key, .{ .int = value }); 2399 }, 2400 }, 2401 .bool => { 2402 const bytes = if (value) "true" else "false"; 2403 if (try map.getCursor(key)) |value_cursor| { 2404 var buffer: [5]u8 = undefined; 2405 const existing = try value_cursor.readBytesObject(&buffer); 2406 if (existing.format_tag) |format_tag| { 2407 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2408 return; 2409 } 2410 } 2411 } 2412 2413 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2414 }, 2415 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2416 .@"union" => switch (value) { 2417 inline else => |payload, tag| { 2418 if (@TypeOf(payload) == void) { 2419 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2420 } else { 2421 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2422 if (try map.getCursor(key)) |cursor| { 2423 switch (cursor.slot().tag) { 2424 .hash_map => { 2425 const variants = try DB.HashMap(.read_only).init(cursor); 2426 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2427 }, 2428 else => try map.put(key, .{ .slot = null }), 2429 } 2430 } 2431 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2432 if (@typeInfo(@TypeOf(payload)) == .optional) { 2433 // keep the variant even when its payload is null 2434 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2435 } 2436 if (try variants.getCursor(tag_key)) |cursor| { 2437 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2438 } 2439 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2440 } 2441 }, 2442 }, 2443 .optional => |optional_info| { 2444 // a missing key is null 2445 if (value) |child| { 2446 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2447 } else { 2448 _ = try map.remove(key); 2449 } 2450 }, 2451 .@"struct" => try upsert( 2452 Field, 2453 DB, 2454 hash_kind, 2455 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2456 value, 2457 ), 2458 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2459 } 2460 } 2461 2462 fn upsertBytes( 2463 comptime DB: type, 2464 comptime hash_kind: hash.HashKind, 2465 map: DB.HashMap(.read_write), 2466 key: hash.HashInt(hash_kind), 2467 value: []const u8, 2468 ) !void { 2469 var existing_cursor_maybe = try map.getCursor(key); 2470 if (existing_cursor_maybe) |*existing_cursor| { 2471 if (try bytesEqual(DB, existing_cursor, value)) { 2472 return; 2473 } 2474 } 2475 2476 try map.put(key, .{ .bytes = value }); 2477 } 2478 2479 fn bytesEqual( 2480 comptime DB: type, 2481 cursor: *DB.Cursor(.read_only), 2482 value: []const u8, 2483 ) !bool { 2484 switch (cursor.slot().tag) { 2485 .bytes, .short_bytes => {}, 2486 else => return false, 2487 } 2488 var read_buffer: [1024]u8 = undefined; 2489 var reader = try cursor.reader(&read_buffer); 2490 if (reader.size != value.len) { 2491 return false; 2492 } 2493 2494 var chunk_buffer: [1024]u8 = undefined; 2495 var offset: usize = 0; 2496 while (offset < value.len) { 2497 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2498 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2499 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2500 return false; 2501 } 2502 offset += chunk_len; 2503 } 2504 2505 return true; 2506 } 2507 2508 // 2509 // CommitIterator 2510 // 2511 // differs from xit's ObjectIterator in a few ways: 2512 // 2513 // 1. iterates parents first, rather than children first 2514 // 2. `next` only returns the object id, not the full Object 2515 // 3. stores its temporary state in a file on disk to avoid OOMs 2516 // 2517 2518 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2519 return struct { 2520 const DB = EventDB(repo_opts.hash); 2521 // a plain file is used for the scratch db because each write outside 2522 // a transaction is synced anyway, so buffering would gain nothing 2523 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2524 const db_name = "haxy-repo-events.db"; 2525 2526 repo_dir: std.Io.Dir, 2527 db_file: std.Io.File, 2528 db: *TempDB, 2529 // map of each object id to its children 2530 parent_to_children: TempDB.HashMap(.read_write), 2531 // tracking pending parents is necessary because a child can only 2532 // be returned after all of its unconsumed parents have been returned 2533 child_to_pending_parents: TempDB.HashMap(.read_write), 2534 // queue of object ids that are ready to be returned from `next` 2535 ready_queue: TempDB.ArrayList(.read_write), 2536 ready_queue_index: u64, 2537 // the object id at the tip of this branch 2538 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2539 // the object id furthest back in the history that hasn't been consumed 2540 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2541 2542 pub fn init( 2543 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2544 io: std.Io, 2545 allocator: std.mem.Allocator, 2546 consumed_object_ids: DB.HashMap(.read_only), 2547 ref: rf.Ref, 2548 ) !CommitIterator(repo_kind, repo_opts) { 2549 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2550 errdefer { 2551 db_file.close(io); 2552 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2553 } 2554 2555 // cursors point at the db, so it needs a stable address 2556 const db_ptr = try allocator.create(TempDB); 2557 errdefer allocator.destroy(db_ptr); 2558 // the db is scratch state that gets deleted after iteration, so 2559 // there is nothing worth fsyncing 2560 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2561 2562 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2563 2564 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2565 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2566 2567 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2568 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2569 2570 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2571 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2572 2573 var self = CommitIterator(repo_kind, repo_opts){ 2574 .repo_dir = state.core.repo_dir, 2575 .db_file = db_file, 2576 .db = db_ptr, 2577 .parent_to_children = parent_to_children, 2578 .child_to_pending_parents = child_to_pending_parents, 2579 .ready_queue = ready_queue, 2580 .ready_queue_index = 0, 2581 .newest_object_id = null, 2582 .oldest_object_id = null, 2583 }; 2584 errdefer self.deinit(io, allocator); 2585 2586 try self.collect(state, io, allocator, consumed_object_ids, ref); 2587 2588 return self; 2589 } 2590 2591 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2592 self.db_file.close(io); 2593 self.repo_dir.deleteFile(io, db_name) catch {}; 2594 allocator.destroy(self.db); 2595 } 2596 2597 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2598 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2599 2600 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2601 self.ready_queue_index += 1; 2602 2603 try self.enqueueChildren(&oid); 2604 return oid; 2605 } 2606 2607 fn collect( 2608 self: *CommitIterator(repo_kind, repo_opts), 2609 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2610 io: std.Io, 2611 allocator: std.mem.Allocator, 2612 consumed_object_ids: DB.HashMap(.read_only), 2613 ref: rf.Ref, 2614 ) !void { 2615 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2616 2617 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2618 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2619 var walk_queue_index: u64 = 0; 2620 2621 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2622 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2623 2624 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2625 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2626 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2627 try walk_queue.append(.{ .bytes = &head_oid }); 2628 2629 while (walk_queue_index < try walk_queue.count()) { 2630 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2631 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2632 2633 walk_queue_index += 1; 2634 2635 // if we've seen this object id, skip it 2636 if (null != try seen_object_ids.getCursor(oid_int)) { 2637 continue; 2638 } 2639 2640 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2641 2642 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2643 defer commit_object.deinit(); 2644 2645 // if this object id has already been consumed, skip it 2646 if (null != try consumed_object_ids.getCursor(oid_int)) { 2647 continue; 2648 } 2649 2650 if (self.newest_object_id == null) self.newest_object_id = oid; 2651 self.oldest_object_id = oid; 2652 2653 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2654 var pending_parent_count: u64 = 0; 2655 for (parent_oids) |*parent_oid| { 2656 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2657 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2658 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2659 2660 // if this object id has already been consumed, skip it 2661 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2662 continue; 2663 } 2664 2665 // if this object id hasn't already been seen, add it to the walk queue 2666 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2667 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2668 } 2669 2670 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2671 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2672 try children.put(oid_int, .{ .bytes = &oid }); 2673 pending_parent_count += 1; 2674 } 2675 2676 if (pending_parent_count == 0) { 2677 try self.ready_queue.append(.{ .bytes = &oid }); 2678 } else { 2679 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2680 } 2681 } 2682 } 2683 2684 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2685 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2686 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2687 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2688 var children_iter = try children.iterator(); 2689 2690 while (try children_iter.next()) |*child_cursor| { 2691 const kv_pair = try child_cursor.readKeyValuePair(); 2692 const child_oid_int = kv_pair.hash; 2693 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2694 const pending_parent_count = try pending_parent_cursor.readUint(); 2695 2696 if (pending_parent_count <= 1) { 2697 _ = try self.child_to_pending_parents.remove(child_oid_int); 2698 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2699 try self.ready_queue.append(.{ .bytes = &child_oid }); 2700 } else { 2701 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2702 } 2703 } 2704 } 2705 2706 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2707 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2708 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2709 _ = try oid_cursor.readBytes(&oid); 2710 return oid; 2711 } 2712 }; 2713 } 2714