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