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