╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
965 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 966 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 967 } 968 969 // the oid of the last event commit consumed into `db`, or null before any 970 // consume completed 971 fn lastConsumedOid( 972 comptime hash_kind: hash.HashKind, 973 db: *EventDB(hash_kind), 974 ) !?[hash.byteLen(hash_kind)]u8 { 975 const DB = EventDB(hash_kind); 976 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 977 const moment_cursor = try history.getCursor(-1) orelse return null; 978 const moment = try DB.HashMap(.read_only).init(moment_cursor); 979 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy-last-object-id")) orelse return null; 980 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 981 _ = try last_object_id_cursor.readBytes(&last_object_id); 982 return last_object_id; 983 } 984 985 pub fn currentMomentFromDb( 986 comptime hash_kind: hash.HashKind, 987 db: *EventDB(hash_kind), 988 ) !EventDB(hash_kind).HashMap(.read_only) { 989 const DB = EventDB(hash_kind); 990 const last_object_id = (try lastConsumedOid(hash_kind, db)) orelse return error.NotFound; 991 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 992 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 993 const moment = try DB.HashMap(.read_only).init(moment_cursor); 994 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy")) orelse return error.NotFound; 995 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 996 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 997 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 998 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 999 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1000 } 1001 1002 // build the key for SortedSets sorted by timestamp. the big-endian timestamp 1003 // makes byte order match creation order; the event id breaks ties and keeps 1004 // keys unique within the same timestamp. 1005 pub fn orderKey(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1006 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1007 std.mem.writeInt(u64, key[0..@sizeOf(u64)], timestamp, .big); 1008 @memcpy(key[@sizeOf(u64)..], event_id); 1009 return key; 1010 } 1011 1012 pub fn orderKeyDesc(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1013 return orderKey(std.math.maxInt(u64) - timestamp, event_id); 1014 } 1015 1016 // the event id embedded in a set entry's order key 1017 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1018 var cursor = kv_pair_cursor; 1019 const kv_pair = try cursor.readKeyValuePair(); 1020 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1021 _ = try kv_pair.key_cursor.readBytes(&order_key); 1022 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1023 } 1024 1025 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1026 // isn't exactly two non-empty segments. 1027 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1028 var it = std.mem.splitScalar(u8, path, '/'); 1029 const owner = it.next() orelse return null; 1030 const name = it.next() orelse return null; 1031 if (it.next() != null) return null; 1032 if (owner.len == 0 or name.len == 0) return null; 1033 1034 return .{ .owner = owner, .name = name }; 1035 } 1036 1037 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1038 // directory under the repos dir 1039 pub fn resolveOrCreateRepo( 1040 io: std.Io, 1041 allocator: std.mem.Allocator, 1042 admin_repo_path: []const u8, 1043 owner_name: []const u8, 1044 repo_name: []const u8, 1045 create_if_missing: bool, 1046 ) !?[event_id_size * 2]u8 { 1047 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1048 error.RepoNotFound => return null, 1049 else => |e| return e, 1050 }; 1051 defer repo.deinit(io, allocator); 1052 1053 var arena = std.heap.ArenaAllocator.init(allocator); 1054 defer arena.deinit(); 1055 1056 const moment = try currentMoment(admin_repo_opts, &repo); 1057 1058 // an already-registered repo reuses its event id, so a re-push (or a clone) 1059 // lands in the same repo 1060 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1061 return std.fmt.bytesToHex(found.event_id, .lower); 1062 } 1063 1064 if (!create_if_missing) return null; 1065 1066 // the new repo is owned by the named user, read from the name index; an 1067 // unknown owner can't own a repo, so the push is rejected 1068 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1069 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1070 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1071 var owner_user_id: [event_id_size]u8 = undefined; 1072 _ = try owner_id_cursor.readBytes(&owner_user_id); 1073 1074 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1075 1076 var id_bytes: [event_id_size]u8 = undefined; 1077 io.random(&id_bytes); 1078 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1079 1080 try consume(.xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1081 .id = event_id_hex, 1082 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1083 .author_email = owner.event.email, 1084 .event = .{ .repo = .{ 1085 .user_id = &owner_user_id, 1086 .name = repo_name, 1087 .description = "", 1088 } }, 1089 }}); 1090 1091 return event_id_hex; 1092 } 1093 1094 // 1095 // reading from xitdb 1096 // 1097 1098 // a struct field's fields share its container's map, so their names must not 1099 // collide with the container's or two fields would silently share a key 1100 fn validateFlattenedFields(comptime T: type) void { 1101 comptime { 1102 for (std.meta.fields(T)) |field| { 1103 if (@typeInfo(field.type) != .@"struct") continue; 1104 for (std.meta.fields(field.type)) |nested| { 1105 if (@hasField(T, nested.name)) 1106 @compileError("flattened field name collision in " ++ @typeName(T) ++ ": " ++ nested.name); 1107 } 1108 } 1109 } 1110 } 1111 1112 pub fn read( 1113 comptime T: type, 1114 comptime DB: type, 1115 comptime hash_kind: hash.HashKind, 1116 arena: *std.heap.ArenaAllocator, 1117 map: DB.HashMap(.read_only), 1118 ) !T { 1119 var event: T = undefined; 1120 1121 switch (@typeInfo(T)) { 1122 .@"struct" => |struct_info| { 1123 comptime validateFlattenedFields(T); 1124 inline for (struct_info.fields) |field| { 1125 switch (@typeInfo(field.type)) { 1126 .pointer => |pointer_info| { 1127 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 1128 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1129 } else { 1130 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1131 } 1132 }, 1133 .array => |array_info| { 1134 if (array_info.child == u8) { 1135 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1136 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 1137 @memcpy(@field(event, field.name)[0..], bytes); 1138 } else { 1139 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1140 } 1141 }, 1142 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 1143 .int => |int_info| switch (int_info.signedness) { 1144 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 1145 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 1146 }, 1147 .@"enum" => { 1148 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1149 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 1150 }, 1151 .optional => |optional_info| { 1152 if (optional_info.child != []const u8) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1153 // a missing key is null 1154 @field(event, field.name) = if (try map.getCursor(hash.hashInt(hash_kind, field.name))) |cursor| 1155 try cursor.readBytesAlloc(arena.allocator(), null) 1156 else 1157 null; 1158 }, 1159 // a struct field's own fields are read from the same map 1160 .@"struct" => @field(event, field.name) = try read(field.type, DB, hash_kind, arena, map), 1161 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1162 } 1163 } 1164 }, 1165 else => @compileError("read expects a struct"), 1166 } 1167 1168 return event; 1169 } 1170 1171 // whether two events carry the same data 1172 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1173 switch (@typeInfo(T)) { 1174 .@"struct" => |struct_info| { 1175 inline for (struct_info.fields) |field| { 1176 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1177 } 1178 }, 1179 else => @compileError("fieldsEqual expects a struct"), 1180 } 1181 1182 return true; 1183 } 1184 1185 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1186 switch (@typeInfo(Field)) { 1187 .pointer => |pointer_info| { 1188 if (pointer_info.size == .slice and pointer_info.child == u8) { 1189 return std.mem.eql(u8, a, b); 1190 } else { 1191 @compileError("unsupported field type: " ++ @typeName(Field)); 1192 } 1193 }, 1194 .array => |array_info| { 1195 if (array_info.child == u8) { 1196 return std.mem.eql(u8, &a, &b); 1197 } else { 1198 @compileError("unsupported field type: " ++ @typeName(Field)); 1199 } 1200 }, 1201 .bool, .int, .@"enum" => return a == b, 1202 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1203 } 1204 } 1205 1206 fn readBytes( 1207 comptime DB: type, 1208 comptime hash_kind: hash.HashKind, 1209 allocator: std.mem.Allocator, 1210 map: DB.HashMap(.read_only), 1211 field_name: []const u8, 1212 ) ![]const u8 { 1213 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1214 return try cursor.readBytesAlloc(allocator, null); 1215 } 1216 1217 fn readUint( 1218 comptime DB: type, 1219 comptime hash_kind: hash.HashKind, 1220 map: DB.HashMap(.read_only), 1221 field_name: []const u8, 1222 ) !u64 { 1223 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1224 return try cursor.readUint(); 1225 } 1226 1227 fn readInt( 1228 comptime DB: type, 1229 comptime hash_kind: hash.HashKind, 1230 map: DB.HashMap(.read_only), 1231 field_name: []const u8, 1232 ) !i64 { 1233 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1234 return try cursor.readInt(); 1235 } 1236 1237 fn readBool( 1238 comptime DB: type, 1239 comptime hash_kind: hash.HashKind, 1240 map: DB.HashMap(.read_only), 1241 field_name: []const u8, 1242 ) !bool { 1243 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1244 var buffer: [5]u8 = undefined; 1245 const bytes = try cursor.readBytesObject(&buffer); 1246 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1247 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1248 if (std.mem.eql(u8, bytes.value, "true")) return true; 1249 if (std.mem.eql(u8, bytes.value, "false")) return false; 1250 return error.InvalidBool; 1251 } 1252 1253 // 1254 // writing to xitdb 1255 // 1256 1257 pub fn upsert( 1258 comptime T: type, 1259 comptime DB: type, 1260 comptime hash_kind: hash.HashKind, 1261 map: DB.HashMap(.read_write), 1262 event: T, 1263 ) !void { 1264 switch (@typeInfo(T)) { 1265 .@"struct" => |struct_info| { 1266 comptime validateFlattenedFields(T); 1267 inline for (struct_info.fields) |field| { 1268 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1269 } 1270 }, 1271 else => @compileError("upsert expects a struct"), 1272 } 1273 } 1274 1275 fn upsertField( 1276 comptime DB: type, 1277 comptime hash_kind: hash.HashKind, 1278 map: DB.HashMap(.read_write), 1279 comptime field_name: []const u8, 1280 comptime Field: type, 1281 value: Field, 1282 ) !void { 1283 const key = hash.hashInt(hash_kind, field_name); 1284 1285 switch (@typeInfo(Field)) { 1286 .pointer => |pointer_info| { 1287 if (pointer_info.size == .slice and pointer_info.child == u8) { 1288 try upsertBytes(DB, hash_kind, map, key, value); 1289 } else { 1290 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1291 } 1292 }, 1293 .array => |array_info| { 1294 if (array_info.child == u8) { 1295 try upsertBytes(DB, hash_kind, map, key, &value); 1296 } else { 1297 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1298 } 1299 }, 1300 .int => |int_info| switch (int_info.signedness) { 1301 .unsigned => { 1302 if (try map.getCursor(key)) |value_cursor| { 1303 if (try value_cursor.readUint() == value) { 1304 return; 1305 } 1306 } 1307 1308 try map.put(key, .{ .uint = value }); 1309 }, 1310 .signed => { 1311 if (try map.getCursor(key)) |value_cursor| { 1312 if (try value_cursor.readInt() == value) { 1313 return; 1314 } 1315 } 1316 1317 try map.put(key, .{ .int = value }); 1318 }, 1319 }, 1320 .bool => { 1321 const bytes = if (value) "true" else "false"; 1322 if (try map.getCursor(key)) |value_cursor| { 1323 var buffer: [5]u8 = undefined; 1324 const existing = try value_cursor.readBytesObject(&buffer); 1325 if (existing.format_tag) |format_tag| { 1326 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1327 return; 1328 } 1329 } 1330 } 1331 1332 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1333 }, 1334 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1335 .optional => |optional_info| { 1336 if (optional_info.child != []const u8) @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1337 // a missing key is null 1338 if (value) |bytes| { 1339 try upsertBytes(DB, hash_kind, map, key, bytes); 1340 } else { 1341 _ = try map.remove(key); 1342 } 1343 }, 1344 // a struct field's own fields are stored in the same map 1345 .@"struct" => try upsert(Field, DB, hash_kind, map, value), 1346 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1347 } 1348 } 1349 1350 fn upsertBytes( 1351 comptime DB: type, 1352 comptime hash_kind: hash.HashKind, 1353 map: DB.HashMap(.read_write), 1354 key: hash.HashInt(hash_kind), 1355 value: []const u8, 1356 ) !void { 1357 var existing_cursor_maybe = try map.getCursor(key); 1358 if (existing_cursor_maybe) |*existing_cursor| { 1359 if (try bytesEqual(DB, existing_cursor, value)) { 1360 return; 1361 } 1362 } 1363 1364 var value_cursor = try map.putCursor(key); 1365 var write_buffer: [1024]u8 = undefined; 1366 var writer = try value_cursor.writer(&write_buffer); 1367 try writer.interface.writeAll(value); 1368 try writer.finish(); 1369 } 1370 1371 fn bytesEqual( 1372 comptime DB: type, 1373 cursor: *DB.Cursor(.read_only), 1374 value: []const u8, 1375 ) !bool { 1376 var read_buffer: [1024]u8 = undefined; 1377 var reader = try cursor.reader(&read_buffer); 1378 if (reader.size != value.len) { 1379 return false; 1380 } 1381 1382 var chunk_buffer: [1024]u8 = undefined; 1383 var offset: usize = 0; 1384 while (offset < value.len) { 1385 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1386 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1387 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1388 return false; 1389 } 1390 offset += chunk_len; 1391 } 1392 1393 return true; 1394 } 1395 1396 // 1397 // CommitIterator 1398 // 1399 // differs from xit's ObjectIterator in a few ways: 1400 // 1401 // 1. iterates parents first, rather than children first 1402 // 2. `next` only returns the object id, not the full Object 1403 // 3. stores its temporary state in a file on disk to avoid OOMs 1404 // 1405 1406 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1407 return struct { 1408 const DB = EventDB(repo_opts.hash); 1409 const db_name = "haxy-repo-events.db"; 1410 1411 repo_dir: std.Io.Dir, 1412 db_file: std.Io.File, 1413 db: *DB, 1414 // map of each object id to its children 1415 parent_to_children: DB.HashMap(.read_write), 1416 // tracking pending parents is necessary because a child can only 1417 // be returned after all of its unconsumed parents have been returned 1418 child_to_pending_parents: DB.HashMap(.read_write), 1419 // queue of object ids that are ready to be returned from `next` 1420 ready_queue: DB.ArrayList(.read_write), 1421 ready_queue_index: u64, 1422 // the object id at the tip of this branch 1423 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1424 // the object id furthest back in the history that hasn't been consumed 1425 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1426 1427 pub fn init( 1428 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1429 io: std.Io, 1430 allocator: std.mem.Allocator, 1431 consumed_object_ids: DB.HashMap(.read_only), 1432 ref: rf.Ref, 1433 ) !CommitIterator(repo_kind, repo_opts) { 1434 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1435 errdefer { 1436 db_file.close(io); 1437 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1438 } 1439 1440 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1441 errdefer allocator.destroy(buffer_ptr); 1442 1443 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1444 errdefer buffer_ptr.deinit(); 1445 1446 const db_ptr = try allocator.create(DB); 1447 errdefer allocator.destroy(db_ptr); 1448 // the db is scratch state that gets deleted after iteration, so 1449 // there is nothing worth fsyncing 1450 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 1451 1452 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1453 1454 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1455 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1456 1457 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1458 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1459 1460 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1461 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1462 1463 var self = CommitIterator(repo_kind, repo_opts){ 1464 .repo_dir = state.core.repo_dir, 1465 .db_file = db_file, 1466 .db = db_ptr, 1467 .parent_to_children = parent_to_children, 1468 .child_to_pending_parents = child_to_pending_parents, 1469 .ready_queue = ready_queue, 1470 .ready_queue_index = 0, 1471 .newest_object_id = null, 1472 .oldest_object_id = null, 1473 }; 1474 errdefer self.deinit(io, allocator); 1475 1476 try self.collect(state, io, allocator, consumed_object_ids, ref); 1477 1478 return self; 1479 } 1480 1481 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1482 self.db_file.close(io); 1483 self.db.core.memory.buffer.deinit(); 1484 allocator.destroy(self.db.core.memory.buffer); 1485 self.repo_dir.deleteFile(io, db_name) catch {}; 1486 allocator.destroy(self.db); 1487 } 1488 1489 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 1490 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 1491 1492 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 1493 self.ready_queue_index += 1; 1494 1495 try self.enqueueChildren(&oid); 1496 return oid; 1497 } 1498 1499 fn collect( 1500 self: *CommitIterator(repo_kind, repo_opts), 1501 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1502 io: std.Io, 1503 allocator: std.mem.Allocator, 1504 consumed_object_ids: DB.HashMap(.read_only), 1505 ref: rf.Ref, 1506 ) !void { 1507 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 1508 1509 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 1510 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 1511 var walk_queue_index: u64 = 0; 1512 1513 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 1514 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 1515 1516 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1517 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1518 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1519 try walk_queue.append(.{ .bytes = &head_oid }); 1520 1521 while (walk_queue_index < try walk_queue.count()) { 1522 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 1523 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 1524 1525 walk_queue_index += 1; 1526 1527 // if we've seen this object id, skip it 1528 if (null != try seen_object_ids.getCursor(oid_int)) { 1529 continue; 1530 } 1531 1532 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 1533 1534 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 1535 defer commit_object.deinit(); 1536 1537 // if this object id has already been consumed, skip it 1538 if (null != try consumed_object_ids.getCursor(oid_int)) { 1539 continue; 1540 } 1541 1542 if (self.newest_object_id == null) self.newest_object_id = oid; 1543 self.oldest_object_id = oid; 1544 1545 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1546 var pending_parent_count: u64 = 0; 1547 for (parent_oids) |*parent_oid| { 1548 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1549 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 1550 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 1551 1552 // if this object id has already been consumed, skip it 1553 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 1554 continue; 1555 } 1556 1557 // if this object id hasn't already been seen, add it to the walk queue 1558 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 1559 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 1560 } 1561 1562 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 1563 const children = try DB.HashSet(.read_write).init(children_cursor); 1564 try children.put(oid_int, .{ .bytes = &oid }); 1565 pending_parent_count += 1; 1566 } 1567 1568 if (pending_parent_count == 0) { 1569 try self.ready_queue.append(.{ .bytes = &oid }); 1570 } else { 1571 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 1572 } 1573 } 1574 } 1575 1576 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 1577 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 1578 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 1579 const children = try DB.HashSet(.read_only).init(children_cursor); 1580 var children_iter = try children.iterator(); 1581 1582 while (try children_iter.next()) |*child_cursor| { 1583 const kv_pair = try child_cursor.readKeyValuePair(); 1584 const child_oid_int = kv_pair.hash; 1585 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 1586 const pending_parent_count = try pending_parent_cursor.readUint(); 1587 1588 if (pending_parent_count <= 1) { 1589 _ = try self.child_to_pending_parents.remove(child_oid_int); 1590 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 1591 try self.ready_queue.append(.{ .bytes = &child_oid }); 1592 } else { 1593 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 1594 } 1595 } 1596 } 1597 1598 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 1599 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 1600 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1601 _ = try oid_cursor.readBytes(&oid); 1602 return oid; 1603 } 1604 }; 1605 } 1606