╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
869 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order } else null; 870 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 871 }, 872 .issue => |event_maybe| { 873 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 874 .event = event, 875 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 876 .created_order = event_order, 877 } else null; 878 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 879 }, 880 .discuss => |event_maybe| { 881 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 882 .event = event, 883 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 884 .created_order = event_order, 885 } else null; 886 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 887 }, 888 .comment => |event_maybe| { 889 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 890 .event = event, 891 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 892 .created_order = event_order, 893 } else null; 894 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 895 }, 896 .attach => |event_maybe| { 897 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 898 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 899 break :blk .{ 900 .event = event, 901 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 902 .created_order = event_order, 903 .name = entry.name, 904 .blob_oid = entry.oid, 905 }; 906 } else null; 907 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 908 }, 909 } 910 } 911 912 // the current object id is now the last one 913 last_object_id_maybe = repo_event_oid; 914 915 // prevent any of the data created above from being mutated by future iterations of this loop 916 try db.freeze(); 917 } 918 919 if (last_object_id_maybe) |*last_object_id| { 920 try moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = last_object_id }); 921 } 922 923 return true; 924 } 925 926 // the conflicted records of one kind, keyed by the same order key its id set 927 // uses, so this doubles as the index the conflicts view lists and counts. every 928 // value under an entry is a slot reference to a structure that already exists: 929 // 930 // <order key> -> conflict entry 931 // conflicted-fields the conflicting field names, space separated 932 // base-record the merge base's whole record 933 // their-record the merged-in side's whole record 934 // their-field->oid that side's field name to commit map 935 // 936 // our own value is the live record and our commit is in the kind's oid map, so 937 // neither is repeated here. 938 pub const conflicted_fields_key = "conflicted-fields"; 939 pub const base_record_key = "base-record"; 940 pub const their_record_key = "their-record"; 941 pub const their_field_to_oid_key = "their-field->oid"; 942 943 // record the commit against every field this event changes. a merge passes no 944 // oid, since each field's winner may come from a different side. 945 pub fn writeOid( 946 comptime T: type, 947 comptime DB: type, 948 comptime hash_kind: hash.HashKind, 949 id_to_field_to_oid: DB.HashMap(.read_write), 950 record_key: hash.HashInt(hash_kind), 951 existing_maybe: ?T, 952 event: T, 953 event_oid: ?[]const u8, 954 ) !void { 955 const oid = event_oid orelse return; 956 957 // created only once a field actually changes 958 var field_oids: ?DB.SortedMap(.read_write) = null; 959 960 inline for (std.meta.fields(T)) |field| { 961 const changed = if (existing_maybe) |existing| 962 !fieldEqual(field.type, @field(existing, field.name), @field(event, field.name)) 963 else 964 true; 965 if (changed) { 966 if (field_oids == null) { 967 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 968 } 969 if (field_oids) |map| try map.put(field.name, .{ .bytes = oid }); 970 } 971 } 972 } 973 974 // the whole field list, space separated, is the longest it can get 975 fn conflictedFieldsMaxLen(comptime T: type) usize { 976 var len: usize = 0; 977 for (std.meta.fields(T)) |field| len += field.name.len + 1; 978 return len; 979 } 980 981 // what a three-way merge did with a field 982 const FieldMerge = enum { 983 // the target's value stands, because neither side changed it, both made the 984 // same change, or only the target changed it 985 kept, 986 parent, 987 conflicted, 988 }; 989 990 // three-way merge each field. one only the parent changed takes the parent's 991 // value; one both sides changed differently keeps the target's. a missing 992 // baseline makes every differing field a conflict. 993 fn mergeFields( 994 comptime T: type, 995 baseline_maybe: ?T, 996 target: T, 997 parent: T, 998 outcome: *[std.meta.fields(T).len]FieldMerge, 999 ) T { 1000 var merged = target; 1001 1002 inline for (std.meta.fields(T), 0..) |field, i| { 1003 const target_value = @field(target, field.name); 1004 const parent_value = @field(parent, field.name); 1005 1006 if (!fieldEqual(field.type, target_value, parent_value)) { 1007 outcome[i] = if (baseline_maybe) |baseline| blk: { 1008 const baseline_value = @field(baseline, field.name); 1009 if (fieldEqual(field.type, target_value, baseline_value)) { 1010 @field(merged, field.name) = parent_value; 1011 break :blk .parent; 1012 } 1013 // only the target changed it 1014 if (fieldEqual(field.type, parent_value, baseline_value)) break :blk .kept; 1015 break :blk .conflicted; 1016 } else .conflicted; 1017 } 1018 } 1019 1020 return merged; 1021 } 1022 1023 // three-way merge of one kind's records from a merge parent. kinds that expose 1024 // conflicts merge field by field; the others take one whole record. the result 1025 // goes through the kind's `consume`, which re-derives the indexes from it. a 1026 // removal carries over unless the other side changed the record, so a merge 1027 // never fails. 1028 pub fn merge( 1029 comptime T: type, 1030 comptime DB: type, 1031 comptime hash_kind: hash.HashKind, 1032 allocator: std.mem.Allocator, 1033 haxy_moment: DB.HashMap(.read_write), 1034 parent_moment: DB.HashMap(.read_only), 1035 baseline_moment: DB.HashMap(.read_only), 1036 ) !void { 1037 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_set_key)) orelse return; 1038 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1039 1040 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1041 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1042 1043 var baseline_records: ?DB.HashMap(.read_only) = null; 1044 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1045 baseline_records = try DB.HashMap(.read_only).init(cursor); 1046 } 1047 1048 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1049 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1050 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1051 switch (comptime T.merge_policy) { 1052 .field_conflicts => { 1053 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1054 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1055 } 1056 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1057 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1058 } 1059 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1060 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1061 } 1062 }, 1063 .target_wins => {}, 1064 } 1065 1066 var arena = std.heap.ArenaAllocator.init(allocator); 1067 defer arena.deinit(); 1068 1069 var iter = try parent_set.iteratorFromIndex(0); 1070 while (try iter.next()) |kv_pair_cursor| { 1071 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1072 const record_key = hash.hashInt(hash_kind, &event_id); 1073 1074 _ = arena.reset(.retain_capacity); 1075 1076 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1077 const parent_slot = parent_record_cursor.slot(); 1078 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1079 1080 // the parent left this record alone 1081 if (baseline_slot) |slot| { 1082 if (slot.eql(parent_slot)) continue; 1083 } 1084 1085 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1086 1087 // re-derived every iteration, since `consume` writes through its own 1088 // handles 1089 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1090 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1091 1092 // a record the target doesn't have arrives wholesale from the parent 1093 var outcome: [std.meta.fields(T).len]FieldMerge = @splat(.parent); 1094 var merged = parent_record; 1095 1096 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1097 // both sides share the change 1098 if (target_record_cursor.slot().eql(parent_slot)) continue; 1099 1100 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1101 1102 var baseline_record: ?T.Record = null; 1103 if (baseline_records) |map| { 1104 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1105 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1106 } 1107 } 1108 1109 switch (comptime T.merge_policy) { 1110 .field_conflicts => { 1111 outcome = @splat(.kept); 1112 merged = target_record; 1113 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1114 1115 // merge the removed state separately from serialized fields. removal 1116 // carries over an unchanged record, while an edit or restoration 1117 // keeps it active. 1118 merged.removed = if (target_record.removed == parent_record.removed) 1119 target_record.removed 1120 else if (baseline_record) |baseline| blk: { 1121 const active = if (!target_record.removed) target_record else parent_record; 1122 if (active.removed != baseline.removed) break :blk false; 1123 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1124 break :blk true; 1125 } else false; 1126 }, 1127 .target_wins => { 1128 // an uncontested parent change carries over. if both sides 1129 // changed the record, the target wins as a whole, except that 1130 // an edit or restoration wins over a removal. 1131 const target_changed = if (baseline_slot) |slot| 1132 !target_record_cursor.slot().eql(slot) 1133 else 1134 true; 1135 merged = if (!target_changed) 1136 parent_record 1137 else if (target_record.removed != parent_record.removed) 1138 if (target_record.removed) parent_record else target_record 1139 else 1140 target_record; 1141 }, 1142 } 1143 } 1144 1145 // the index is unique, so a key the target gave to a different record 1146 // leaves this one out rather than stranding that one behind a name it 1147 // no longer owns 1148 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1149 const index_key = try merged.indexKey(arena.allocator()); 1150 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1151 const name_index = try DB.HashMap(.read_write).init(name_index_cursor); 1152 if (try name_index.getCursor(hash.hashInt(hash_kind, index_key))) |owner_cursor| { 1153 var owner_id: [event_id_size]u8 = undefined; 1154 _ = try owner_cursor.readBytes(&owner_id); 1155 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1156 } 1157 } 1158 1159 // `consume` sets no oids, since each field's winner may come from 1160 // a different side 1161 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1162 1163 switch (comptime T.merge_policy) { 1164 .field_conflicts => {}, 1165 .target_wins => continue, 1166 } 1167 1168 // removed records do not carry field conflicts 1169 if (merged.removed) continue; 1170 1171 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1172 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1173 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1174 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1175 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1176 1177 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1178 if (parent_id_to_field_to_oid) |map| { 1179 if (try map.getCursor(record_key)) |field_oids_cursor| { 1180 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1181 } 1182 } 1183 // created only once a field actually comes from the parent 1184 var field_oids: ?DB.SortedMap(.read_write) = null; 1185 1186 // the fields both sides changed differently, space separated 1187 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1188 var conflicted_len: usize = 0; 1189 1190 inline for (std.meta.fields(T), 0..) |field, i| { 1191 switch (outcome[i]) { 1192 // the target's value stands, so its oid does too 1193 .kept => {}, 1194 // the parent set this value, so its commit takes the field. a 1195 // parent with no oid took its own value from a merge, leaving 1196 // the field unattributed rather than crediting the target's 1197 // commit for a value it no longer holds. 1198 .parent => { 1199 if (field_oids == null) { 1200 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1201 } 1202 const map = field_oids orelse unreachable; 1203 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1204 if (parent_oid) |oid_cursor| { 1205 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1206 } else { 1207 _ = try map.remove(field.name); 1208 } 1209 }, 1210 .conflicted => { 1211 if (conflicted_len > 0) { 1212 conflicted_fields[conflicted_len] = ' '; 1213 conflicted_len += 1; 1214 } 1215 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1216 conflicted_len += field.name.len; 1217 }, 1218 } 1219 } 1220 1221 if (conflicted_len > 0) { 1222 // each side's whole record is stored by reference, so the view can 1223 // show any of them or take theirs wholesale 1224 _ = try conflicts.remove(&merged_key); 1225 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1226 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1227 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1228 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1229 if (parent_field_oids) |map| { 1230 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1231 } 1232 continue; 1233 } 1234 1235 // created_order never changes, so the parent keys this record's conflict 1236 // identically, and it carries over when the target has none, unless the 1237 // parent's entry is unchanged from the baseline, meaning the target 1238 // inherited it too and resolving it removed it here. 1239 if (parent_conflicts) |map| { 1240 if (null == try conflicts.getCursor(&merged_key)) { 1241 if (try map.getSlot(&merged_key)) |conflict_slot| { 1242 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1243 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1244 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1245 } 1246 } 1247 } 1248 } 1249 } 1250 1251 pub fn currentMoment( 1252 comptime repo_opts: rp.RepoOpts(.xit), 1253 repo: *rp.Repo(.xit, repo_opts), 1254 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1255 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1256 } 1257 1258 // the oid of the last event commit consumed into `db`, or null before any 1259 // consume completed 1260 fn lastConsumedOid( 1261 comptime hash_kind: hash.HashKind, 1262 db: *EventDB(hash_kind), 1263 ) !?[hash.byteLen(hash_kind)]u8 { 1264 const DB = EventDB(hash_kind); 1265 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1266 const moment_cursor = try history.getCursor(-1) orelse return null; 1267 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1268 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy-last-object-id")) orelse return null; 1269 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1270 _ = try last_object_id_cursor.readBytes(&last_object_id); 1271 return last_object_id; 1272 } 1273 1274 pub fn currentMomentFromDb( 1275 comptime hash_kind: hash.HashKind, 1276 db: *EventDB(hash_kind), 1277 ) !EventDB(hash_kind).HashMap(.read_only) { 1278 const DB = EventDB(hash_kind); 1279 const last_object_id = (try lastConsumedOid(hash_kind, db)) orelse return error.NotFound; 1280 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1281 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1282 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1283 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy")) orelse return error.NotFound; 1284 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 1285 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 1286 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1287 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1288 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1289 } 1290 1291 // build a sorted-set key from an order and event id. big-endian order makes 1292 // byte order match numeric order; the event id breaks ties. 1293 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1294 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1295 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1296 @memcpy(key[@sizeOf(u64)..], event_id); 1297 return key; 1298 } 1299 1300 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1301 return orderKey(std.math.maxInt(u64) - order, event_id); 1302 } 1303 1304 // add or refresh one entry in the global logical-event index. updates and 1305 // removed records preserve created_order, so the key never moves. 1306 pub fn indexEvent( 1307 comptime DB: type, 1308 comptime hash_kind: hash.HashKind, 1309 haxy_moment: DB.HashMap(.read_write), 1310 event_id: *const [event_id_size]u8, 1311 kind: EventKind, 1312 created_order: u64, 1313 removed: bool, 1314 ) !void { 1315 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1316 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1317 try kind_map.put(hash.hashInt(hash_kind, event_id), .{ .bytes = @tagName(kind) }); 1318 1319 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1320 const active = try DB.SortedSet(.read_write).init(active_cursor); 1321 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1322 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1323 const order_key = orderKeyDesc(created_order, event_id); 1324 if (removed) { 1325 _ = try active.remove(&order_key); 1326 try removed_set.put(&order_key); 1327 } else { 1328 _ = try removed_set.remove(&order_key); 1329 try active.put(&order_key); 1330 } 1331 } 1332 1333 pub fn touchThread( 1334 comptime DB: type, 1335 comptime hash_kind: hash.HashKind, 1336 haxy_moment: DB.HashMap(.read_write), 1337 thread_id: *const [event_id_size]u8, 1338 order: u64, 1339 arena: *std.heap.ArenaAllocator, 1340 ) !void { 1341 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1342 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1343 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1344 switch (kind) { 1345 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1346 else => {}, 1347 } 1348 } 1349 1350 pub fn readEventKind( 1351 comptime hash_kind: hash.HashKind, 1352 kind_map: anytype, 1353 id: *const [event_id_size]u8, 1354 ) !?EventKind { 1355 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1356 var buffer: [64]u8 = undefined; 1357 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1358 } 1359 1360 // the event id embedded in a set entry's order key 1361 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1362 var cursor = kv_pair_cursor; 1363 const kv_pair = try cursor.readKeyValuePair(); 1364 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1365 _ = try kv_pair.key_cursor.readBytes(&order_key); 1366 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1367 } 1368 1369 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1370 // isn't exactly two non-empty segments. 1371 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1372 var it = std.mem.splitScalar(u8, path, '/'); 1373 const owner = it.next() orelse return null; 1374 const name = it.next() orelse return null; 1375 if (it.next() != null) return null; 1376 if (owner.len == 0 or name.len == 0) return null; 1377 1378 return .{ .owner = owner, .name = name }; 1379 } 1380 1381 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1382 // directory under the repos dir 1383 pub fn resolveOrCreateRepo( 1384 io: std.Io, 1385 allocator: std.mem.Allocator, 1386 admin_repo_path: []const u8, 1387 owner_name: []const u8, 1388 repo_name: []const u8, 1389 create_if_missing: bool, 1390 ) !?[event_id_size * 2]u8 { 1391 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1392 error.RepoNotFound => return null, 1393 else => |e| return e, 1394 }; 1395 defer repo.deinit(io, allocator); 1396 1397 var arena = std.heap.ArenaAllocator.init(allocator); 1398 defer arena.deinit(); 1399 1400 const moment = try currentMoment(admin_repo_opts, &repo); 1401 1402 // an already-registered repo reuses its event id, so a re-push (or a clone) 1403 // lands in the same repo 1404 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1405 return std.fmt.bytesToHex(found.event_id, .lower); 1406 } 1407 1408 if (!create_if_missing) return null; 1409 1410 // the new repo is owned by the named user, read from the name index; an 1411 // unknown owner can't own a repo, so the push is rejected 1412 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1413 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1414 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1415 var owner_user_id: [event_id_size]u8 = undefined; 1416 _ = try owner_id_cursor.readBytes(&owner_user_id); 1417 1418 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1419 1420 var id_bytes: [event_id_size]u8 = undefined; 1421 io.random(&id_bytes); 1422 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1423 1424 try consume(.xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1425 .id = event_id_hex, 1426 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1427 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1428 .event = .{ .repo = .{ 1429 .user_id = &owner_user_id, 1430 .name = repo_name, 1431 .description = "", 1432 } }, 1433 }}); 1434 1435 return event_id_hex; 1436 } 1437 1438 // 1439 // reading from xitdb 1440 // 1441 1442 // a struct field's fields share its container's map, so their names must not 1443 // collide with the container's or two fields would silently share a key 1444 fn validateFlattenedFields(comptime T: type) void { 1445 comptime { 1446 for (std.meta.fields(T)) |field| { 1447 if (@typeInfo(field.type) != .@"struct") continue; 1448 for (std.meta.fields(field.type)) |nested| { 1449 if (@hasField(T, nested.name)) 1450 @compileError("flattened field name collision in " ++ @typeName(T) ++ ": " ++ nested.name); 1451 } 1452 } 1453 } 1454 } 1455 1456 pub fn read( 1457 comptime T: type, 1458 comptime DB: type, 1459 comptime hash_kind: hash.HashKind, 1460 arena: *std.heap.ArenaAllocator, 1461 map: DB.HashMap(.read_only), 1462 ) !T { 1463 var event: T = undefined; 1464 1465 switch (@typeInfo(T)) { 1466 .@"struct" => |struct_info| { 1467 comptime validateFlattenedFields(T); 1468 inline for (struct_info.fields) |field| { 1469 switch (@typeInfo(field.type)) { 1470 .pointer => |pointer_info| { 1471 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 1472 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1473 } else { 1474 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1475 } 1476 }, 1477 .array => |array_info| { 1478 if (array_info.child == u8) { 1479 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1480 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 1481 @memcpy(@field(event, field.name)[0..], bytes); 1482 } else { 1483 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1484 } 1485 }, 1486 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 1487 .int => |int_info| switch (int_info.signedness) { 1488 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 1489 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 1490 }, 1491 .@"enum" => { 1492 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1493 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 1494 }, 1495 .optional => |optional_info| { 1496 if (optional_info.child != []const u8) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1497 // a missing key is null 1498 @field(event, field.name) = if (try map.getCursor(hash.hashInt(hash_kind, field.name))) |cursor| 1499 try cursor.readBytesAlloc(arena.allocator(), null) 1500 else 1501 null; 1502 }, 1503 // a struct field's own fields are read from the same map 1504 .@"struct" => @field(event, field.name) = try read(field.type, DB, hash_kind, arena, map), 1505 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1506 } 1507 } 1508 }, 1509 else => @compileError("read expects a struct"), 1510 } 1511 1512 return event; 1513 } 1514 1515 // whether two events carry the same data 1516 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1517 switch (@typeInfo(T)) { 1518 .@"struct" => |struct_info| { 1519 inline for (struct_info.fields) |field| { 1520 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1521 } 1522 }, 1523 else => @compileError("fieldsEqual expects a struct"), 1524 } 1525 1526 return true; 1527 } 1528 1529 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1530 switch (@typeInfo(Field)) { 1531 .pointer => |pointer_info| { 1532 if (pointer_info.size == .slice and pointer_info.child == u8) { 1533 return std.mem.eql(u8, a, b); 1534 } else { 1535 @compileError("unsupported field type: " ++ @typeName(Field)); 1536 } 1537 }, 1538 .array => |array_info| { 1539 if (array_info.child == u8) { 1540 return std.mem.eql(u8, &a, &b); 1541 } else { 1542 @compileError("unsupported field type: " ++ @typeName(Field)); 1543 } 1544 }, 1545 .bool, .int, .@"enum" => return a == b, 1546 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1547 } 1548 } 1549 1550 fn readBytes( 1551 comptime DB: type, 1552 comptime hash_kind: hash.HashKind, 1553 allocator: std.mem.Allocator, 1554 map: DB.HashMap(.read_only), 1555 field_name: []const u8, 1556 ) ![]const u8 { 1557 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1558 return try cursor.readBytesAlloc(allocator, null); 1559 } 1560 1561 fn readUint( 1562 comptime DB: type, 1563 comptime hash_kind: hash.HashKind, 1564 map: DB.HashMap(.read_only), 1565 field_name: []const u8, 1566 ) !u64 { 1567 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1568 return try cursor.readUint(); 1569 } 1570 1571 fn readInt( 1572 comptime DB: type, 1573 comptime hash_kind: hash.HashKind, 1574 map: DB.HashMap(.read_only), 1575 field_name: []const u8, 1576 ) !i64 { 1577 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1578 return try cursor.readInt(); 1579 } 1580 1581 fn readBool( 1582 comptime DB: type, 1583 comptime hash_kind: hash.HashKind, 1584 map: DB.HashMap(.read_only), 1585 field_name: []const u8, 1586 ) !bool { 1587 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1588 var buffer: [5]u8 = undefined; 1589 const bytes = try cursor.readBytesObject(&buffer); 1590 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1591 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1592 if (std.mem.eql(u8, bytes.value, "true")) return true; 1593 if (std.mem.eql(u8, bytes.value, "false")) return false; 1594 return error.InvalidBool; 1595 } 1596 1597 // 1598 // writing to xitdb 1599 // 1600 1601 pub fn upsert( 1602 comptime T: type, 1603 comptime DB: type, 1604 comptime hash_kind: hash.HashKind, 1605 map: DB.HashMap(.read_write), 1606 event: T, 1607 ) !void { 1608 switch (@typeInfo(T)) { 1609 .@"struct" => |struct_info| { 1610 comptime validateFlattenedFields(T); 1611 inline for (struct_info.fields) |field| { 1612 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1613 } 1614 }, 1615 else => @compileError("upsert expects a struct"), 1616 } 1617 } 1618 1619 fn upsertField( 1620 comptime DB: type, 1621 comptime hash_kind: hash.HashKind, 1622 map: DB.HashMap(.read_write), 1623 comptime field_name: []const u8, 1624 comptime Field: type, 1625 value: Field, 1626 ) !void { 1627 const key = hash.hashInt(hash_kind, field_name); 1628 1629 switch (@typeInfo(Field)) { 1630 .pointer => |pointer_info| { 1631 if (pointer_info.size == .slice and pointer_info.child == u8) { 1632 try upsertBytes(DB, hash_kind, map, key, value); 1633 } else { 1634 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1635 } 1636 }, 1637 .array => |array_info| { 1638 if (array_info.child == u8) { 1639 try upsertBytes(DB, hash_kind, map, key, &value); 1640 } else { 1641 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1642 } 1643 }, 1644 .int => |int_info| switch (int_info.signedness) { 1645 .unsigned => { 1646 if (try map.getCursor(key)) |value_cursor| { 1647 if (try value_cursor.readUint() == value) { 1648 return; 1649 } 1650 } 1651 1652 try map.put(key, .{ .uint = value }); 1653 }, 1654 .signed => { 1655 if (try map.getCursor(key)) |value_cursor| { 1656 if (try value_cursor.readInt() == value) { 1657 return; 1658 } 1659 } 1660 1661 try map.put(key, .{ .int = value }); 1662 }, 1663 }, 1664 .bool => { 1665 const bytes = if (value) "true" else "false"; 1666 if (try map.getCursor(key)) |value_cursor| { 1667 var buffer: [5]u8 = undefined; 1668 const existing = try value_cursor.readBytesObject(&buffer); 1669 if (existing.format_tag) |format_tag| { 1670 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1671 return; 1672 } 1673 } 1674 } 1675 1676 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1677 }, 1678 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1679 .optional => |optional_info| { 1680 if (optional_info.child != []const u8) @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1681 // a missing key is null 1682 if (value) |bytes| { 1683 try upsertBytes(DB, hash_kind, map, key, bytes); 1684 } else { 1685 _ = try map.remove(key); 1686 } 1687 }, 1688 // a struct field's own fields are stored in the same map 1689 .@"struct" => try upsert(Field, DB, hash_kind, map, value), 1690 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1691 } 1692 } 1693 1694 fn upsertBytes( 1695 comptime DB: type, 1696 comptime hash_kind: hash.HashKind, 1697 map: DB.HashMap(.read_write), 1698 key: hash.HashInt(hash_kind), 1699 value: []const u8, 1700 ) !void { 1701 var existing_cursor_maybe = try map.getCursor(key); 1702 if (existing_cursor_maybe) |*existing_cursor| { 1703 if (try bytesEqual(DB, existing_cursor, value)) { 1704 return; 1705 } 1706 } 1707 1708 var value_cursor = try map.putCursor(key); 1709 var write_buffer: [1024]u8 = undefined; 1710 var writer = try value_cursor.writer(&write_buffer); 1711 try writer.interface.writeAll(value); 1712 try writer.finish(); 1713 } 1714 1715 fn bytesEqual( 1716 comptime DB: type, 1717 cursor: *DB.Cursor(.read_only), 1718 value: []const u8, 1719 ) !bool { 1720 var read_buffer: [1024]u8 = undefined; 1721 var reader = try cursor.reader(&read_buffer); 1722 if (reader.size != value.len) { 1723 return false; 1724 } 1725 1726 var chunk_buffer: [1024]u8 = undefined; 1727 var offset: usize = 0; 1728 while (offset < value.len) { 1729 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1730 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1731 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1732 return false; 1733 } 1734 offset += chunk_len; 1735 } 1736 1737 return true; 1738 } 1739 1740 // 1741 // CommitIterator 1742 // 1743 // differs from xit's ObjectIterator in a few ways: 1744 // 1745 // 1. iterates parents first, rather than children first 1746 // 2. `next` only returns the object id, not the full Object 1747 // 3. stores its temporary state in a file on disk to avoid OOMs 1748 // 1749 1750 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1751 return struct { 1752 const DB = EventDB(repo_opts.hash); 1753 const db_name = "haxy-repo-events.db"; 1754 1755 repo_dir: std.Io.Dir, 1756 db_file: std.Io.File, 1757 db: *DB, 1758 // map of each object id to its children 1759 parent_to_children: DB.HashMap(.read_write), 1760 // tracking pending parents is necessary because a child can only 1761 // be returned after all of its unconsumed parents have been returned 1762 child_to_pending_parents: DB.HashMap(.read_write), 1763 // queue of object ids that are ready to be returned from `next` 1764 ready_queue: DB.ArrayList(.read_write), 1765 ready_queue_index: u64, 1766 // the object id at the tip of this branch 1767 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1768 // the object id furthest back in the history that hasn't been consumed 1769 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1770 1771 pub fn init( 1772 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1773 io: std.Io, 1774 allocator: std.mem.Allocator, 1775 consumed_object_ids: DB.HashMap(.read_only), 1776 ref: rf.Ref, 1777 ) !CommitIterator(repo_kind, repo_opts) { 1778 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1779 errdefer { 1780 db_file.close(io); 1781 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1782 } 1783 1784 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1785 errdefer allocator.destroy(buffer_ptr); 1786 1787 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1788 errdefer buffer_ptr.deinit(); 1789 1790 const db_ptr = try allocator.create(DB); 1791 errdefer allocator.destroy(db_ptr); 1792 // the db is scratch state that gets deleted after iteration, so 1793 // there is nothing worth fsyncing 1794 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 1795 1796 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1797 1798 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1799 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1800 1801 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1802 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1803 1804 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1805 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1806 1807 var self = CommitIterator(repo_kind, repo_opts){ 1808 .repo_dir = state.core.repo_dir, 1809 .db_file = db_file, 1810 .db = db_ptr, 1811 .parent_to_children = parent_to_children, 1812 .child_to_pending_parents = child_to_pending_parents, 1813 .ready_queue = ready_queue, 1814 .ready_queue_index = 0, 1815 .newest_object_id = null, 1816 .oldest_object_id = null, 1817 }; 1818 errdefer self.deinit(io, allocator); 1819 1820 try self.collect(state, io, allocator, consumed_object_ids, ref); 1821 1822 return self; 1823 } 1824 1825 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1826 self.db_file.close(io); 1827 self.db.core.memory.buffer.deinit(); 1828 allocator.destroy(self.db.core.memory.buffer); 1829 self.repo_dir.deleteFile(io, db_name) catch {}; 1830 allocator.destroy(self.db); 1831 } 1832 1833 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 1834 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 1835 1836 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 1837 self.ready_queue_index += 1; 1838 1839 try self.enqueueChildren(&oid); 1840 return oid; 1841 } 1842 1843 fn collect( 1844 self: *CommitIterator(repo_kind, repo_opts), 1845 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1846 io: std.Io, 1847 allocator: std.mem.Allocator, 1848 consumed_object_ids: DB.HashMap(.read_only), 1849 ref: rf.Ref, 1850 ) !void { 1851 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 1852 1853 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 1854 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 1855 var walk_queue_index: u64 = 0; 1856 1857 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 1858 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 1859 1860 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1861 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1862 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1863 try walk_queue.append(.{ .bytes = &head_oid }); 1864 1865 while (walk_queue_index < try walk_queue.count()) { 1866 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 1867 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 1868 1869 walk_queue_index += 1; 1870 1871 // if we've seen this object id, skip it 1872 if (null != try seen_object_ids.getCursor(oid_int)) { 1873 continue; 1874 } 1875 1876 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 1877 1878 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 1879 defer commit_object.deinit(); 1880 1881 // if this object id has already been consumed, skip it 1882 if (null != try consumed_object_ids.getCursor(oid_int)) { 1883 continue; 1884 } 1885 1886 if (self.newest_object_id == null) self.newest_object_id = oid; 1887 self.oldest_object_id = oid; 1888 1889 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1890 var pending_parent_count: u64 = 0; 1891 for (parent_oids) |*parent_oid| { 1892 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1893 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 1894 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 1895 1896 // if this object id has already been consumed, skip it 1897 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 1898 continue; 1899 } 1900 1901 // if this object id hasn't already been seen, add it to the walk queue 1902 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 1903 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 1904 } 1905 1906 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 1907 const children = try DB.HashSet(.read_write).init(children_cursor); 1908 try children.put(oid_int, .{ .bytes = &oid }); 1909 pending_parent_count += 1; 1910 } 1911 1912 if (pending_parent_count == 0) { 1913 try self.ready_queue.append(.{ .bytes = &oid }); 1914 } else { 1915 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 1916 } 1917 } 1918 } 1919 1920 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 1921 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 1922 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 1923 const children = try DB.HashSet(.read_only).init(children_cursor); 1924 var children_iter = try children.iterator(); 1925 1926 while (try children_iter.next()) |*child_cursor| { 1927 const kv_pair = try child_cursor.readKeyValuePair(); 1928 const child_oid_int = kv_pair.hash; 1929 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 1930 const pending_parent_count = try pending_parent_cursor.readUint(); 1931 1932 if (pending_parent_count <= 1) { 1933 _ = try self.child_to_pending_parents.remove(child_oid_int); 1934 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 1935 try self.ready_queue.append(.{ .bytes = &child_oid }); 1936 } else { 1937 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 1938 } 1939 } 1940 } 1941 1942 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 1943 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 1944 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1945 _ = try oid_cursor.readBytes(&oid); 1946 return oid; 1947 } 1948 }; 1949 } 1950