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