╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
719 parent_moment: DB.HashMap(.read_only), 720 baseline_moment: DB.HashMap(.read_only), 721 ) !void { 722 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_set_key)) orelse return; 723 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 724 725 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 726 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 727 728 var baseline_records: ?DB.HashMap(.read_only) = null; 729 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 730 baseline_records = try DB.HashMap(.read_only).init(cursor); 731 } 732 733 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 734 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 735 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 736 } 737 738 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 739 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 740 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 741 } 742 743 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 744 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 745 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 746 } 747 748 var arena = std.heap.ArenaAllocator.init(allocator); 749 defer arena.deinit(); 750 751 // a record the parent deleted is deleted here too, unless the target 752 // changed it. runs first so a delete and recreate is applied in that order. 753 deletions: { 754 const baseline_map = baseline_records orelse break :deletions; 755 const baseline_set_cursor = try baseline_moment.getCursor(hash.hashInt(hash_kind, T.id_set_key)) orelse break :deletions; 756 const baseline_set = try DB.SortedSet(.read_only).init(baseline_set_cursor); 757 758 var baseline_iter = try baseline_set.iteratorFromIndex(0); 759 while (try baseline_iter.next()) |kv_pair_cursor| { 760 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 761 const record_key = hash.hashInt(hash_kind, &event_id); 762 763 if (null != try parent_records.getSlot(record_key)) continue; 764 const baseline_record_cursor = try baseline_map.getCursor(record_key) orelse continue; 765 766 _ = arena.reset(.retain_capacity); 767 768 // re-derived every iteration, since `consume` writes through its 769 // own handles 770 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 771 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 772 const target_record_cursor = try target_records.getCursor(record_key) orelse continue; 773 774 if (!target_record_cursor.slot().eql(baseline_record_cursor.slot())) { 775 // every write copies the record's block, so only a content 776 // change means the target kept it 777 const target_record = try read(T, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 778 const baseline_record = try read(T, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 779 if (!fieldsEqual(T, target_record, baseline_record)) continue; 780 } 781 782 try T.consume(DB, hash_kind, haxy_moment, &event_id, null, &arena, 0, null); 783 } 784 } 785 786 var iter = try parent_set.iteratorFromIndex(0); 787 while (try iter.next()) |kv_pair_cursor| { 788 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 789 const record_key = hash.hashInt(hash_kind, &event_id); 790 791 _ = arena.reset(.retain_capacity); 792 793 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 794 const parent_slot = parent_record_cursor.slot(); 795 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 796 797 // the parent left this record alone 798 if (baseline_slot) |slot| { 799 if (slot.eql(parent_slot)) continue; 800 } 801 802 const parent_record = try read(T, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 803 804 // re-derived every iteration, since `consume` writes through its own 805 // handles 806 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 807 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 808 809 // a record the target doesn't have, or deleted, arrives wholesale from 810 // the parent 811 var outcome: [std.meta.fields(T).len]FieldMerge = @splat(.parent); 812 var merged = parent_record; 813 814 if (try target_records.getCursor(record_key)) |target_record_cursor| { 815 // both sides share the change 816 if (target_record_cursor.slot().eql(parent_slot)) continue; 817 818 const target_record = try read(T, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 819 820 var baseline_record: ?T = null; 821 if (baseline_records) |map| { 822 if (try map.getCursor(record_key)) |baseline_record_cursor| { 823 baseline_record = try read(T, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 824 } 825 } 826 827 outcome = @splat(.kept); 828 merged = mergeFields(T, baseline_record, target_record, parent_record, &outcome); 829 } 830 831 // the index is unique, so a key the target gave to a different record 832 // leaves this one out rather than stranding that one behind a name it 833 // no longer owns 834 if (@hasDecl(T, "name_index_key")) { 835 const index_key = try merged.indexKey(arena.allocator()); 836 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 837 const name_index = try DB.HashMap(.read_write).init(name_index_cursor); 838 if (try name_index.getCursor(hash.hashInt(hash_kind, index_key))) |owner_cursor| { 839 var owner_id: [event_id_size]u8 = undefined; 840 _ = try owner_cursor.readBytes(&owner_id); 841 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 842 } 843 } 844 845 // `consume` sets no oids, since each field's winner may come from 846 // a different side 847 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, merged.created_ts, null); 848 849 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 850 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 851 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 852 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 853 const merged_key = orderKeyDesc(merged.created_ts, &event_id); 854 855 // both created only once a field actually comes from the parent 856 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 857 if (parent_id_to_field_to_oid) |map| { 858 if (try map.getCursor(record_key)) |field_oids_cursor| { 859 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 860 } 861 } 862 var field_oids: ?DB.SortedMap(.read_write) = null; 863 864 // the fields both sides changed differently, space separated 865 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 866 var conflicted_len: usize = 0; 867 868 inline for (std.meta.fields(T), 0..) |field, i| { 869 if (comptime !std.mem.eql(u8, field.name, "created_ts")) { 870 switch (outcome[i]) { 871 // the target's value stands, so its oid does too 872 .kept => {}, 873 .parent => if (parent_field_oids) |parent_map| { 874 if (try parent_map.getCursor(field.name)) |oid_cursor| { 875 if (field_oids == null) { 876 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 877 } 878 if (field_oids) |map| try map.put(field.name, .{ .slot = oid_cursor.slot() }); 879 } 880 }, 881 .conflicted => { 882 if (conflicted_len > 0) { 883 conflicted_fields[conflicted_len] = ' '; 884 conflicted_len += 1; 885 } 886 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 887 conflicted_len += field.name.len; 888 }, 889 } 890 } 891 } 892 893 if (conflicted_len > 0) { 894 // each side's whole record is stored by reference, so the view can 895 // show any of them or take theirs wholesale 896 _ = try conflicts.remove(&merged_key); 897 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 898 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 899 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 900 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 901 if (parent_field_oids) |map| { 902 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 903 } 904 continue; 905 } 906 907 // created_ts never changes, so the parent keys this record's conflict 908 // identically, and it carries over when the target has none, unless the 909 // parent's entry is unchanged from the baseline, meaning the target 910 // inherited it too and resolving it removed it here. 911 if (parent_conflicts) |map| { 912 if (null == try conflicts.getCursor(&merged_key)) { 913 if (try map.getSlot(&merged_key)) |conflict_slot| { 914 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 915 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 916 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 917 } 918 } 919 } 920 } 921 } 922 923 pub fn currentMoment( 924 comptime repo_opts: rp.RepoOpts(.xit), 925 repo: *rp.Repo(.xit, repo_opts), 926 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 927 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 928 } 929 930 // the oid of the last event commit consumed into `db`, or null before any 931 // consume completed 932 fn lastConsumedOid( 933 comptime hash_kind: hash.HashKind, 934 db: *EventDB(hash_kind), 935 ) !?[hash.byteLen(hash_kind)]u8 { 936 const DB = EventDB(hash_kind); 937 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 938 const moment_cursor = try history.getCursor(-1) orelse return null; 939 const moment = try DB.HashMap(.read_only).init(moment_cursor); 940 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy-last-object-id")) orelse return null; 941 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 942 _ = try last_object_id_cursor.readBytes(&last_object_id); 943 return last_object_id; 944 } 945 946 pub fn currentMomentFromDb( 947 comptime hash_kind: hash.HashKind, 948 db: *EventDB(hash_kind), 949 ) !EventDB(hash_kind).HashMap(.read_only) { 950 const DB = EventDB(hash_kind); 951 const last_object_id = (try lastConsumedOid(hash_kind, db)) orelse return error.NotFound; 952 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 953 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 954 const moment = try DB.HashMap(.read_only).init(moment_cursor); 955 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy")) orelse return error.NotFound; 956 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 957 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 958 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 959 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 960 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 961 } 962 963 // build the key for SortedSets sorted by timestamp. the big-endian timestamp 964 // makes byte order match creation order; the event id breaks ties and keeps 965 // keys unique within the same timestamp. 966 pub fn orderKey(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 967 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 968 std.mem.writeInt(u64, key[0..@sizeOf(u64)], timestamp, .big); 969 @memcpy(key[@sizeOf(u64)..], event_id); 970 return key; 971 } 972 973 pub fn orderKeyDesc(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 974 return orderKey(std.math.maxInt(u64) - timestamp, event_id); 975 } 976 977 // the event id embedded in a set entry's order key 978 fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 979 var cursor = kv_pair_cursor; 980 const kv_pair = try cursor.readKeyValuePair(); 981 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 982 _ = try kv_pair.key_cursor.readBytes(&order_key); 983 return order_key[@sizeOf(u64)..][0..event_id_size].*; 984 } 985 986 // split a pushed "<owner>/<repo>" path into its two components, or null if it 987 // isn't exactly two non-empty segments. 988 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 989 var it = std.mem.splitScalar(u8, path, '/'); 990 const owner = it.next() orelse return null; 991 const name = it.next() orelse return null; 992 if (it.next() != null) return null; 993 if (owner.len == 0 or name.len == 0) return null; 994 995 return .{ .owner = owner, .name = name }; 996 } 997 998 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 999 // directory under the repos dir 1000 pub fn resolveOrCreateRepo( 1001 io: std.Io, 1002 allocator: std.mem.Allocator, 1003 admin_repo_path: []const u8, 1004 owner_name: []const u8, 1005 repo_name: []const u8, 1006 create_if_missing: bool, 1007 ) !?[event_id_size * 2]u8 { 1008 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1009 error.RepoNotFound => return null, 1010 else => |e| return e, 1011 }; 1012 defer repo.deinit(io, allocator); 1013 1014 var arena = std.heap.ArenaAllocator.init(allocator); 1015 defer arena.deinit(); 1016 1017 const moment = try currentMoment(admin_repo_opts, &repo); 1018 1019 // an already-registered repo reuses its event id, so a re-push (or a clone) 1020 // lands in the same repo 1021 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1022 return std.fmt.bytesToHex(found.event_id, .lower); 1023 } 1024 1025 if (!create_if_missing) return null; 1026 1027 // the new repo is owned by the named user, read from the name index; an 1028 // unknown owner can't own a repo, so the push is rejected 1029 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1030 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1031 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1032 var owner_user_id: [event_id_size]u8 = undefined; 1033 _ = try owner_id_cursor.readBytes(&owner_user_id); 1034 1035 var id_bytes: [event_id_size]u8 = undefined; 1036 io.random(&id_bytes); 1037 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1038 1039 try consume(.xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1040 .id = event_id_hex, 1041 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1042 .event = .{ .repo = .{ 1043 .user_id = &owner_user_id, 1044 .name = repo_name, 1045 .description = "", 1046 } }, 1047 }}); 1048 1049 return event_id_hex; 1050 } 1051 1052 // 1053 // reading from xitdb 1054 // 1055 1056 pub fn read( 1057 comptime T: type, 1058 comptime DB: type, 1059 comptime hash_kind: hash.HashKind, 1060 arena: *std.heap.ArenaAllocator, 1061 map: DB.HashMap(.read_only), 1062 ) !T { 1063 var event: T = undefined; 1064 1065 switch (@typeInfo(T)) { 1066 .@"struct" => |struct_info| { 1067 inline for (struct_info.fields) |field| { 1068 switch (@typeInfo(field.type)) { 1069 .pointer => |pointer_info| { 1070 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 1071 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1072 } else { 1073 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1074 } 1075 }, 1076 .array => |array_info| { 1077 if (array_info.child == u8) { 1078 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1079 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 1080 @memcpy(@field(event, field.name)[0..], bytes); 1081 } else { 1082 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1083 } 1084 }, 1085 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 1086 .int => |int_info| switch (int_info.signedness) { 1087 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 1088 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 1089 }, 1090 .@"enum" => { 1091 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1092 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 1093 }, 1094 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1095 } 1096 } 1097 }, 1098 else => @compileError("read expects a struct"), 1099 } 1100 1101 return event; 1102 } 1103 1104 // whether two events carry the same data. `created_ts` comes from the commit 1105 // rather than the payload, so it isn't compared. 1106 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1107 switch (@typeInfo(T)) { 1108 .@"struct" => |struct_info| { 1109 inline for (struct_info.fields) |field| { 1110 if (comptime std.mem.eql(u8, field.name, "created_ts")) continue; 1111 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1112 } 1113 }, 1114 else => @compileError("fieldsEqual expects a struct"), 1115 } 1116 1117 return true; 1118 } 1119 1120 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1121 switch (@typeInfo(Field)) { 1122 .pointer => |pointer_info| { 1123 if (pointer_info.size == .slice and pointer_info.child == u8) { 1124 return std.mem.eql(u8, a, b); 1125 } else { 1126 @compileError("unsupported field type: " ++ @typeName(Field)); 1127 } 1128 }, 1129 .array => |array_info| { 1130 if (array_info.child == u8) { 1131 return std.mem.eql(u8, &a, &b); 1132 } else { 1133 @compileError("unsupported field type: " ++ @typeName(Field)); 1134 } 1135 }, 1136 .bool, .int, .@"enum" => return a == b, 1137 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1138 } 1139 } 1140 1141 fn readBytes( 1142 comptime DB: type, 1143 comptime hash_kind: hash.HashKind, 1144 allocator: std.mem.Allocator, 1145 map: DB.HashMap(.read_only), 1146 field_name: []const u8, 1147 ) ![]const u8 { 1148 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1149 return try cursor.readBytesAlloc(allocator, null); 1150 } 1151 1152 fn readUint( 1153 comptime DB: type, 1154 comptime hash_kind: hash.HashKind, 1155 map: DB.HashMap(.read_only), 1156 field_name: []const u8, 1157 ) !u64 { 1158 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1159 return try cursor.readUint(); 1160 } 1161 1162 fn readInt( 1163 comptime DB: type, 1164 comptime hash_kind: hash.HashKind, 1165 map: DB.HashMap(.read_only), 1166 field_name: []const u8, 1167 ) !i64 { 1168 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1169 return try cursor.readInt(); 1170 } 1171 1172 fn readBool( 1173 comptime DB: type, 1174 comptime hash_kind: hash.HashKind, 1175 map: DB.HashMap(.read_only), 1176 field_name: []const u8, 1177 ) !bool { 1178 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1179 var buffer: [5]u8 = undefined; 1180 const bytes = try cursor.readBytesObject(&buffer); 1181 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1182 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1183 if (std.mem.eql(u8, bytes.value, "true")) return true; 1184 if (std.mem.eql(u8, bytes.value, "false")) return false; 1185 return error.InvalidBool; 1186 } 1187 1188 // 1189 // writing to xitdb 1190 // 1191 1192 pub fn upsert( 1193 comptime T: type, 1194 comptime DB: type, 1195 comptime hash_kind: hash.HashKind, 1196 map: DB.HashMap(.read_write), 1197 event: T, 1198 ) !void { 1199 switch (@typeInfo(T)) { 1200 .@"struct" => |struct_info| { 1201 inline for (struct_info.fields) |field| { 1202 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1203 } 1204 }, 1205 else => @compileError("upsert expects a struct"), 1206 } 1207 } 1208 1209 fn upsertField( 1210 comptime DB: type, 1211 comptime hash_kind: hash.HashKind, 1212 map: DB.HashMap(.read_write), 1213 comptime field_name: []const u8, 1214 comptime Field: type, 1215 value: Field, 1216 ) !void { 1217 const key = hash.hashInt(hash_kind, field_name); 1218 1219 switch (@typeInfo(Field)) { 1220 .pointer => |pointer_info| { 1221 if (pointer_info.size == .slice and pointer_info.child == u8) { 1222 try upsertBytes(DB, hash_kind, map, key, value); 1223 } else { 1224 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1225 } 1226 }, 1227 .array => |array_info| { 1228 if (array_info.child == u8) { 1229 try upsertBytes(DB, hash_kind, map, key, &value); 1230 } else { 1231 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1232 } 1233 }, 1234 .int => |int_info| switch (int_info.signedness) { 1235 .unsigned => { 1236 if (try map.getCursor(key)) |value_cursor| { 1237 if (try value_cursor.readUint() == value) { 1238 return; 1239 } 1240 } 1241 1242 try map.put(key, .{ .uint = value }); 1243 }, 1244 .signed => { 1245 if (try map.getCursor(key)) |value_cursor| { 1246 if (try value_cursor.readInt() == value) { 1247 return; 1248 } 1249 } 1250 1251 try map.put(key, .{ .int = value }); 1252 }, 1253 }, 1254 .bool => { 1255 const bytes = if (value) "true" else "false"; 1256 if (try map.getCursor(key)) |value_cursor| { 1257 var buffer: [5]u8 = undefined; 1258 const existing = try value_cursor.readBytesObject(&buffer); 1259 if (existing.format_tag) |format_tag| { 1260 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1261 return; 1262 } 1263 } 1264 } 1265 1266 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1267 }, 1268 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1269 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1270 } 1271 } 1272 1273 fn upsertBytes( 1274 comptime DB: type, 1275 comptime hash_kind: hash.HashKind, 1276 map: DB.HashMap(.read_write), 1277 key: hash.HashInt(hash_kind), 1278 value: []const u8, 1279 ) !void { 1280 var existing_cursor_maybe = try map.getCursor(key); 1281 if (existing_cursor_maybe) |*existing_cursor| { 1282 if (try bytesEqual(DB, existing_cursor, value)) { 1283 return; 1284 } 1285 } 1286 1287 var value_cursor = try map.putCursor(key); 1288 var write_buffer: [1024]u8 = undefined; 1289 var writer = try value_cursor.writer(&write_buffer); 1290 try writer.interface.writeAll(value); 1291 try writer.finish(); 1292 } 1293 1294 fn bytesEqual( 1295 comptime DB: type, 1296 cursor: *DB.Cursor(.read_only), 1297 value: []const u8, 1298 ) !bool { 1299 var read_buffer: [1024]u8 = undefined; 1300 var reader = try cursor.reader(&read_buffer); 1301 if (reader.size != value.len) { 1302 return false; 1303 } 1304 1305 var chunk_buffer: [1024]u8 = undefined; 1306 var offset: usize = 0; 1307 while (offset < value.len) { 1308 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1309 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1310 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1311 return false; 1312 } 1313 offset += chunk_len; 1314 } 1315 1316 return true; 1317 } 1318 1319 // 1320 // CommitIterator 1321 // 1322 // differs from xit's ObjectIterator in a few ways: 1323 // 1324 // 1. iterates parents first, rather than children first 1325 // 2. `next` only returns the object id, not the full Object 1326 // 3. stores its temporary state in a file on disk to avoid OOMs 1327 // 1328 1329 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1330 return struct { 1331 const DB = EventDB(repo_opts.hash); 1332 const db_name = "haxy-repo-events.db"; 1333 1334 repo_dir: std.Io.Dir, 1335 db_file: std.Io.File, 1336 db: *DB, 1337 // map of each object id to its children 1338 parent_to_children: DB.HashMap(.read_write), 1339 // tracking pending parents is necessary because a child can only 1340 // be returned after all of its unconsumed parents have been returned 1341 child_to_pending_parents: DB.HashMap(.read_write), 1342 // queue of object ids that are ready to be returned from `next` 1343 ready_queue: DB.ArrayList(.read_write), 1344 ready_queue_index: u64, 1345 // the object id at the tip of this branch 1346 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1347 // the object id furthest back in the history that hasn't been consumed 1348 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1349 1350 pub fn init( 1351 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1352 io: std.Io, 1353 allocator: std.mem.Allocator, 1354 consumed_object_ids: DB.HashMap(.read_only), 1355 ref: rf.Ref, 1356 ) !CommitIterator(repo_kind, repo_opts) { 1357 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1358 errdefer { 1359 db_file.close(io); 1360 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1361 } 1362 1363 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1364 errdefer allocator.destroy(buffer_ptr); 1365 1366 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1367 errdefer buffer_ptr.deinit(); 1368 1369 const db_ptr = try allocator.create(DB); 1370 errdefer allocator.destroy(db_ptr); 1371 // the db is scratch state that gets deleted after iteration, so 1372 // there is nothing worth fsyncing 1373 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 1374 1375 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1376 1377 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1378 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1379 1380 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1381 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1382 1383 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1384 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1385 1386 var self = CommitIterator(repo_kind, repo_opts){ 1387 .repo_dir = state.core.repo_dir, 1388 .db_file = db_file, 1389 .db = db_ptr, 1390 .parent_to_children = parent_to_children, 1391 .child_to_pending_parents = child_to_pending_parents, 1392 .ready_queue = ready_queue, 1393 .ready_queue_index = 0, 1394 .newest_object_id = null, 1395 .oldest_object_id = null, 1396 }; 1397 errdefer self.deinit(io, allocator); 1398 1399 try self.collect(state, io, allocator, consumed_object_ids, ref); 1400 1401 return self; 1402 } 1403 1404 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1405 self.db_file.close(io); 1406 self.db.core.memory.buffer.deinit(); 1407 allocator.destroy(self.db.core.memory.buffer); 1408 self.repo_dir.deleteFile(io, db_name) catch {}; 1409 allocator.destroy(self.db); 1410 } 1411 1412 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 1413 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 1414 1415 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 1416 self.ready_queue_index += 1; 1417 1418 try self.enqueueChildren(&oid); 1419 return oid; 1420 } 1421 1422 fn collect( 1423 self: *CommitIterator(repo_kind, repo_opts), 1424 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1425 io: std.Io, 1426 allocator: std.mem.Allocator, 1427 consumed_object_ids: DB.HashMap(.read_only), 1428 ref: rf.Ref, 1429 ) !void { 1430 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 1431 1432 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 1433 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 1434 var walk_queue_index: u64 = 0; 1435 1436 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 1437 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 1438 1439 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1440 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1441 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1442 try walk_queue.append(.{ .bytes = &head_oid }); 1443 1444 while (walk_queue_index < try walk_queue.count()) { 1445 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 1446 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 1447 1448 walk_queue_index += 1; 1449 1450 // if we've seen this object id, skip it 1451 if (null != try seen_object_ids.getCursor(oid_int)) { 1452 continue; 1453 } 1454 1455 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 1456 1457 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 1458 defer commit_object.deinit(); 1459 1460 // if this object id has already been consumed, skip it 1461 if (null != try consumed_object_ids.getCursor(oid_int)) { 1462 continue; 1463 } 1464 1465 if (self.newest_object_id == null) self.newest_object_id = oid; 1466 self.oldest_object_id = oid; 1467 1468 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1469 var pending_parent_count: u64 = 0; 1470 for (parent_oids) |*parent_oid| { 1471 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1472 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 1473 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 1474 1475 // if this object id has already been consumed, skip it 1476 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 1477 continue; 1478 } 1479 1480 // if this object id hasn't already been seen, add it to the walk queue 1481 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 1482 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 1483 } 1484 1485 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 1486 const children = try DB.HashSet(.read_write).init(children_cursor); 1487 try children.put(oid_int, .{ .bytes = &oid }); 1488 pending_parent_count += 1; 1489 } 1490 1491 if (pending_parent_count == 0) { 1492 try self.ready_queue.append(.{ .bytes = &oid }); 1493 } else { 1494 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 1495 } 1496 } 1497 } 1498 1499 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 1500 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 1501 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 1502 const children = try DB.HashSet(.read_only).init(children_cursor); 1503 var children_iter = try children.iterator(); 1504 1505 while (try children_iter.next()) |*child_cursor| { 1506 const kv_pair = try child_cursor.readKeyValuePair(); 1507 const child_oid_int = kv_pair.hash; 1508 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 1509 const pending_parent_count = try pending_parent_cursor.readUint(); 1510 1511 if (pending_parent_count <= 1) { 1512 _ = try self.child_to_pending_parents.remove(child_oid_int); 1513 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 1514 try self.ready_queue.append(.{ .bytes = &child_oid }); 1515 } else { 1516 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 1517 } 1518 } 1519 } 1520 1521 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 1522 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 1523 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1524 _ = try oid_cursor.readBytes(&oid); 1525 return oid; 1526 } 1527 }; 1528 } 1529