╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1140 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1141 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1142 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1143 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1144 const merged_key = orderKeyDesc(merged.created_ts, &event_id); 1145 1146 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1147 if (parent_id_to_field_to_oid) |map| { 1148 if (try map.getCursor(record_key)) |field_oids_cursor| { 1149 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1150 } 1151 } 1152 // created only once a field actually comes from the parent 1153 var field_oids: ?DB.SortedMap(.read_write) = null; 1154 1155 // the fields both sides changed differently, space separated 1156 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1157 var conflicted_len: usize = 0; 1158 1159 inline for (std.meta.fields(T), 0..) |field, i| { 1160 switch (outcome[i]) { 1161 // the target's value stands, so its oid does too 1162 .kept => {}, 1163 // the parent set this value, so its commit takes the field. a 1164 // parent with no oid took its own value from a merge, leaving 1165 // the field unattributed rather than crediting the target's 1166 // commit for a value it no longer holds. 1167 .parent => { 1168 if (field_oids == null) { 1169 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1170 } 1171 const map = field_oids orelse unreachable; 1172 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1173 if (parent_oid) |oid_cursor| { 1174 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1175 } else { 1176 _ = try map.remove(field.name); 1177 } 1178 }, 1179 .conflicted => { 1180 if (conflicted_len > 0) { 1181 conflicted_fields[conflicted_len] = ' '; 1182 conflicted_len += 1; 1183 } 1184 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1185 conflicted_len += field.name.len; 1186 }, 1187 } 1188 } 1189 1190 if (conflicted_len > 0) { 1191 // each side's whole record is stored by reference, so the view can 1192 // show any of them or take theirs wholesale 1193 _ = try conflicts.remove(&merged_key); 1194 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1195 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1196 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1197 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1198 if (parent_field_oids) |map| { 1199 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1200 } 1201 continue; 1202 } 1203 1204 // created_ts never changes, so the parent keys this record's conflict 1205 // identically, and it carries over when the target has none, unless the 1206 // parent's entry is unchanged from the baseline, meaning the target 1207 // inherited it too and resolving it removed it here. 1208 if (parent_conflicts) |map| { 1209 if (null == try conflicts.getCursor(&merged_key)) { 1210 if (try map.getSlot(&merged_key)) |conflict_slot| { 1211 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1212 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1213 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1214 } 1215 } 1216 } 1217 } 1218 } 1219 1220 pub fn currentMoment( 1221 comptime repo_opts: rp.RepoOpts(.xit), 1222 repo: *rp.Repo(.xit, repo_opts), 1223 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1224 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1225 } 1226 1227 // the oid of the last event commit consumed into `db`, or null before any 1228 // consume completed 1229 fn lastConsumedOid( 1230 comptime hash_kind: hash.HashKind, 1231 db: *EventDB(hash_kind), 1232 ) !?[hash.byteLen(hash_kind)]u8 { 1233 const DB = EventDB(hash_kind); 1234 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1235 const moment_cursor = try history.getCursor(-1) orelse return null; 1236 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1237 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy-last-object-id")) orelse return null; 1238 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1239 _ = try last_object_id_cursor.readBytes(&last_object_id); 1240 return last_object_id; 1241 } 1242 1243 pub fn currentMomentFromDb( 1244 comptime hash_kind: hash.HashKind, 1245 db: *EventDB(hash_kind), 1246 ) !EventDB(hash_kind).HashMap(.read_only) { 1247 const DB = EventDB(hash_kind); 1248 const last_object_id = (try lastConsumedOid(hash_kind, db)) orelse return error.NotFound; 1249 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1250 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1251 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1252 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy")) orelse return error.NotFound; 1253 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 1254 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 1255 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1256 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1257 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1258 } 1259 1260 // build the key for SortedSets sorted by timestamp. the big-endian timestamp 1261 // makes byte order match creation order; the event id breaks ties and keeps 1262 // keys unique within the same timestamp. 1263 pub fn orderKey(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1264 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1265 std.mem.writeInt(u64, key[0..@sizeOf(u64)], timestamp, .big); 1266 @memcpy(key[@sizeOf(u64)..], event_id); 1267 return key; 1268 } 1269 1270 pub fn orderKeyDesc(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1271 return orderKey(std.math.maxInt(u64) - timestamp, event_id); 1272 } 1273 1274 // add or refresh one entry in the global logical-event index. updates and 1275 // removed records preserve created_ts, so the key never moves. 1276 pub fn indexEvent( 1277 comptime DB: type, 1278 comptime hash_kind: hash.HashKind, 1279 haxy_moment: DB.HashMap(.read_write), 1280 event_id: *const [event_id_size]u8, 1281 kind: EventKind, 1282 created_ts: u64, 1283 removed: bool, 1284 ) !void { 1285 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1286 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1287 try kind_map.put(hash.hashInt(hash_kind, event_id), .{ .bytes = @tagName(kind) }); 1288 1289 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1290 const active = try DB.SortedSet(.read_write).init(active_cursor); 1291 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1292 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1293 const order_key = orderKeyDesc(created_ts, event_id); 1294 if (removed) { 1295 _ = try active.remove(&order_key); 1296 try removed_set.put(&order_key); 1297 } else { 1298 _ = try removed_set.remove(&order_key); 1299 try active.put(&order_key); 1300 } 1301 } 1302 1303 pub fn readEventKind( 1304 comptime hash_kind: hash.HashKind, 1305 kind_map: anytype, 1306 id: *const [event_id_size]u8, 1307 ) !?EventKind { 1308 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1309 var buffer: [64]u8 = undefined; 1310 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1311 } 1312 1313 // the event id embedded in a set entry's order key 1314 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1315 var cursor = kv_pair_cursor; 1316 const kv_pair = try cursor.readKeyValuePair(); 1317 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1318 _ = try kv_pair.key_cursor.readBytes(&order_key); 1319 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1320 } 1321 1322 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1323 // isn't exactly two non-empty segments. 1324 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1325 var it = std.mem.splitScalar(u8, path, '/'); 1326 const owner = it.next() orelse return null; 1327 const name = it.next() orelse return null; 1328 if (it.next() != null) return null; 1329 if (owner.len == 0 or name.len == 0) return null; 1330 1331 return .{ .owner = owner, .name = name }; 1332 } 1333 1334 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1335 // directory under the repos dir 1336 pub fn resolveOrCreateRepo( 1337 io: std.Io, 1338 allocator: std.mem.Allocator, 1339 admin_repo_path: []const u8, 1340 owner_name: []const u8, 1341 repo_name: []const u8, 1342 create_if_missing: bool, 1343 ) !?[event_id_size * 2]u8 { 1344 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1345 error.RepoNotFound => return null, 1346 else => |e| return e, 1347 }; 1348 defer repo.deinit(io, allocator); 1349 1350 var arena = std.heap.ArenaAllocator.init(allocator); 1351 defer arena.deinit(); 1352 1353 const moment = try currentMoment(admin_repo_opts, &repo); 1354 1355 // an already-registered repo reuses its event id, so a re-push (or a clone) 1356 // lands in the same repo 1357 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1358 return std.fmt.bytesToHex(found.event_id, .lower); 1359 } 1360 1361 if (!create_if_missing) return null; 1362 1363 // the new repo is owned by the named user, read from the name index; an 1364 // unknown owner can't own a repo, so the push is rejected 1365 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1366 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1367 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1368 var owner_user_id: [event_id_size]u8 = undefined; 1369 _ = try owner_id_cursor.readBytes(&owner_user_id); 1370 1371 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1372 1373 var id_bytes: [event_id_size]u8 = undefined; 1374 io.random(&id_bytes); 1375 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1376 1377 try consume(.xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1378 .id = event_id_hex, 1379 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1380 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1381 .event = .{ .repo = .{ 1382 .user_id = &owner_user_id, 1383 .name = repo_name, 1384 .description = "", 1385 } }, 1386 }}); 1387 1388 return event_id_hex; 1389 } 1390 1391 // 1392 // reading from xitdb 1393 // 1394 1395 // a struct field's fields share its container's map, so their names must not 1396 // collide with the container's or two fields would silently share a key 1397 fn validateFlattenedFields(comptime T: type) void { 1398 comptime { 1399 for (std.meta.fields(T)) |field| { 1400 if (@typeInfo(field.type) != .@"struct") continue; 1401 for (std.meta.fields(field.type)) |nested| { 1402 if (@hasField(T, nested.name)) 1403 @compileError("flattened field name collision in " ++ @typeName(T) ++ ": " ++ nested.name); 1404 } 1405 } 1406 } 1407 } 1408 1409 pub fn read( 1410 comptime T: type, 1411 comptime DB: type, 1412 comptime hash_kind: hash.HashKind, 1413 arena: *std.heap.ArenaAllocator, 1414 map: DB.HashMap(.read_only), 1415 ) !T { 1416 var event: T = undefined; 1417 1418 switch (@typeInfo(T)) { 1419 .@"struct" => |struct_info| { 1420 comptime validateFlattenedFields(T); 1421 inline for (struct_info.fields) |field| { 1422 switch (@typeInfo(field.type)) { 1423 .pointer => |pointer_info| { 1424 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 1425 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1426 } else { 1427 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1428 } 1429 }, 1430 .array => |array_info| { 1431 if (array_info.child == u8) { 1432 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1433 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 1434 @memcpy(@field(event, field.name)[0..], bytes); 1435 } else { 1436 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1437 } 1438 }, 1439 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 1440 .int => |int_info| switch (int_info.signedness) { 1441 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 1442 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 1443 }, 1444 .@"enum" => { 1445 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1446 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 1447 }, 1448 .optional => |optional_info| { 1449 if (optional_info.child != []const u8) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1450 // a missing key is null 1451 @field(event, field.name) = if (try map.getCursor(hash.hashInt(hash_kind, field.name))) |cursor| 1452 try cursor.readBytesAlloc(arena.allocator(), null) 1453 else 1454 null; 1455 }, 1456 // a struct field's own fields are read from the same map 1457 .@"struct" => @field(event, field.name) = try read(field.type, DB, hash_kind, arena, map), 1458 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1459 } 1460 } 1461 }, 1462 else => @compileError("read expects a struct"), 1463 } 1464 1465 return event; 1466 } 1467 1468 // whether two events carry the same data 1469 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1470 switch (@typeInfo(T)) { 1471 .@"struct" => |struct_info| { 1472 inline for (struct_info.fields) |field| { 1473 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1474 } 1475 }, 1476 else => @compileError("fieldsEqual expects a struct"), 1477 } 1478 1479 return true; 1480 } 1481 1482 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1483 switch (@typeInfo(Field)) { 1484 .pointer => |pointer_info| { 1485 if (pointer_info.size == .slice and pointer_info.child == u8) { 1486 return std.mem.eql(u8, a, b); 1487 } else { 1488 @compileError("unsupported field type: " ++ @typeName(Field)); 1489 } 1490 }, 1491 .array => |array_info| { 1492 if (array_info.child == u8) { 1493 return std.mem.eql(u8, &a, &b); 1494 } else { 1495 @compileError("unsupported field type: " ++ @typeName(Field)); 1496 } 1497 }, 1498 .bool, .int, .@"enum" => return a == b, 1499 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1500 } 1501 } 1502 1503 fn readBytes( 1504 comptime DB: type, 1505 comptime hash_kind: hash.HashKind, 1506 allocator: std.mem.Allocator, 1507 map: DB.HashMap(.read_only), 1508 field_name: []const u8, 1509 ) ![]const u8 { 1510 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1511 return try cursor.readBytesAlloc(allocator, null); 1512 } 1513 1514 fn readUint( 1515 comptime DB: type, 1516 comptime hash_kind: hash.HashKind, 1517 map: DB.HashMap(.read_only), 1518 field_name: []const u8, 1519 ) !u64 { 1520 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1521 return try cursor.readUint(); 1522 } 1523 1524 fn readInt( 1525 comptime DB: type, 1526 comptime hash_kind: hash.HashKind, 1527 map: DB.HashMap(.read_only), 1528 field_name: []const u8, 1529 ) !i64 { 1530 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1531 return try cursor.readInt(); 1532 } 1533 1534 fn readBool( 1535 comptime DB: type, 1536 comptime hash_kind: hash.HashKind, 1537 map: DB.HashMap(.read_only), 1538 field_name: []const u8, 1539 ) !bool { 1540 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1541 var buffer: [5]u8 = undefined; 1542 const bytes = try cursor.readBytesObject(&buffer); 1543 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1544 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1545 if (std.mem.eql(u8, bytes.value, "true")) return true; 1546 if (std.mem.eql(u8, bytes.value, "false")) return false; 1547 return error.InvalidBool; 1548 } 1549 1550 // 1551 // writing to xitdb 1552 // 1553 1554 pub fn upsert( 1555 comptime T: type, 1556 comptime DB: type, 1557 comptime hash_kind: hash.HashKind, 1558 map: DB.HashMap(.read_write), 1559 event: T, 1560 ) !void { 1561 switch (@typeInfo(T)) { 1562 .@"struct" => |struct_info| { 1563 comptime validateFlattenedFields(T); 1564 inline for (struct_info.fields) |field| { 1565 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1566 } 1567 }, 1568 else => @compileError("upsert expects a struct"), 1569 } 1570 } 1571 1572 fn upsertField( 1573 comptime DB: type, 1574 comptime hash_kind: hash.HashKind, 1575 map: DB.HashMap(.read_write), 1576 comptime field_name: []const u8, 1577 comptime Field: type, 1578 value: Field, 1579 ) !void { 1580 const key = hash.hashInt(hash_kind, field_name); 1581 1582 switch (@typeInfo(Field)) { 1583 .pointer => |pointer_info| { 1584 if (pointer_info.size == .slice and pointer_info.child == u8) { 1585 try upsertBytes(DB, hash_kind, map, key, value); 1586 } else { 1587 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1588 } 1589 }, 1590 .array => |array_info| { 1591 if (array_info.child == u8) { 1592 try upsertBytes(DB, hash_kind, map, key, &value); 1593 } else { 1594 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1595 } 1596 }, 1597 .int => |int_info| switch (int_info.signedness) { 1598 .unsigned => { 1599 if (try map.getCursor(key)) |value_cursor| { 1600 if (try value_cursor.readUint() == value) { 1601 return; 1602 } 1603 } 1604 1605 try map.put(key, .{ .uint = value }); 1606 }, 1607 .signed => { 1608 if (try map.getCursor(key)) |value_cursor| { 1609 if (try value_cursor.readInt() == value) { 1610 return; 1611 } 1612 } 1613 1614 try map.put(key, .{ .int = value }); 1615 }, 1616 }, 1617 .bool => { 1618 const bytes = if (value) "true" else "false"; 1619 if (try map.getCursor(key)) |value_cursor| { 1620 var buffer: [5]u8 = undefined; 1621 const existing = try value_cursor.readBytesObject(&buffer); 1622 if (existing.format_tag) |format_tag| { 1623 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1624 return; 1625 } 1626 } 1627 } 1628 1629 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1630 }, 1631 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1632 .optional => |optional_info| { 1633 if (optional_info.child != []const u8) @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1634 // a missing key is null 1635 if (value) |bytes| { 1636 try upsertBytes(DB, hash_kind, map, key, bytes); 1637 } else { 1638 _ = try map.remove(key); 1639 } 1640 }, 1641 // a struct field's own fields are stored in the same map 1642 .@"struct" => try upsert(Field, DB, hash_kind, map, value), 1643 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1644 } 1645 } 1646 1647 fn upsertBytes( 1648 comptime DB: type, 1649 comptime hash_kind: hash.HashKind, 1650 map: DB.HashMap(.read_write), 1651 key: hash.HashInt(hash_kind), 1652 value: []const u8, 1653 ) !void { 1654 var existing_cursor_maybe = try map.getCursor(key); 1655 if (existing_cursor_maybe) |*existing_cursor| { 1656 if (try bytesEqual(DB, existing_cursor, value)) { 1657 return; 1658 } 1659 } 1660 1661 var value_cursor = try map.putCursor(key); 1662 var write_buffer: [1024]u8 = undefined; 1663 var writer = try value_cursor.writer(&write_buffer); 1664 try writer.interface.writeAll(value); 1665 try writer.finish(); 1666 } 1667 1668 fn bytesEqual( 1669 comptime DB: type, 1670 cursor: *DB.Cursor(.read_only), 1671 value: []const u8, 1672 ) !bool { 1673 var read_buffer: [1024]u8 = undefined; 1674 var reader = try cursor.reader(&read_buffer); 1675 if (reader.size != value.len) { 1676 return false; 1677 } 1678 1679 var chunk_buffer: [1024]u8 = undefined; 1680 var offset: usize = 0; 1681 while (offset < value.len) { 1682 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1683 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1684 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1685 return false; 1686 } 1687 offset += chunk_len; 1688 } 1689 1690 return true; 1691 } 1692 1693 // 1694 // CommitIterator 1695 // 1696 // differs from xit's ObjectIterator in a few ways: 1697 // 1698 // 1. iterates parents first, rather than children first 1699 // 2. `next` only returns the object id, not the full Object 1700 // 3. stores its temporary state in a file on disk to avoid OOMs 1701 // 1702 1703 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1704 return struct { 1705 const DB = EventDB(repo_opts.hash); 1706 const db_name = "haxy-repo-events.db"; 1707 1708 repo_dir: std.Io.Dir, 1709 db_file: std.Io.File, 1710 db: *DB, 1711 // map of each object id to its children 1712 parent_to_children: DB.HashMap(.read_write), 1713 // tracking pending parents is necessary because a child can only 1714 // be returned after all of its unconsumed parents have been returned 1715 child_to_pending_parents: DB.HashMap(.read_write), 1716 // queue of object ids that are ready to be returned from `next` 1717 ready_queue: DB.ArrayList(.read_write), 1718 ready_queue_index: u64, 1719 // the object id at the tip of this branch 1720 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1721 // the object id furthest back in the history that hasn't been consumed 1722 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1723 1724 pub fn init( 1725 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1726 io: std.Io, 1727 allocator: std.mem.Allocator, 1728 consumed_object_ids: DB.HashMap(.read_only), 1729 ref: rf.Ref, 1730 ) !CommitIterator(repo_kind, repo_opts) { 1731 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1732 errdefer { 1733 db_file.close(io); 1734 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1735 } 1736 1737 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1738 errdefer allocator.destroy(buffer_ptr); 1739 1740 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1741 errdefer buffer_ptr.deinit(); 1742 1743 const db_ptr = try allocator.create(DB); 1744 errdefer allocator.destroy(db_ptr); 1745 // the db is scratch state that gets deleted after iteration, so 1746 // there is nothing worth fsyncing 1747 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 1748 1749 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1750 1751 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1752 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1753 1754 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1755 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1756 1757 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1758 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1759 1760 var self = CommitIterator(repo_kind, repo_opts){ 1761 .repo_dir = state.core.repo_dir, 1762 .db_file = db_file, 1763 .db = db_ptr, 1764 .parent_to_children = parent_to_children, 1765 .child_to_pending_parents = child_to_pending_parents, 1766 .ready_queue = ready_queue, 1767 .ready_queue_index = 0, 1768 .newest_object_id = null, 1769 .oldest_object_id = null, 1770 }; 1771 errdefer self.deinit(io, allocator); 1772 1773 try self.collect(state, io, allocator, consumed_object_ids, ref); 1774 1775 return self; 1776 } 1777 1778 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1779 self.db_file.close(io); 1780 self.db.core.memory.buffer.deinit(); 1781 allocator.destroy(self.db.core.memory.buffer); 1782 self.repo_dir.deleteFile(io, db_name) catch {}; 1783 allocator.destroy(self.db); 1784 } 1785 1786 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 1787 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 1788 1789 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 1790 self.ready_queue_index += 1; 1791 1792 try self.enqueueChildren(&oid); 1793 return oid; 1794 } 1795 1796 fn collect( 1797 self: *CommitIterator(repo_kind, repo_opts), 1798 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1799 io: std.Io, 1800 allocator: std.mem.Allocator, 1801 consumed_object_ids: DB.HashMap(.read_only), 1802 ref: rf.Ref, 1803 ) !void { 1804 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 1805 1806 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 1807 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 1808 var walk_queue_index: u64 = 0; 1809 1810 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 1811 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 1812 1813 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1814 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1815 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1816 try walk_queue.append(.{ .bytes = &head_oid }); 1817 1818 while (walk_queue_index < try walk_queue.count()) { 1819 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 1820 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 1821 1822 walk_queue_index += 1; 1823 1824 // if we've seen this object id, skip it 1825 if (null != try seen_object_ids.getCursor(oid_int)) { 1826 continue; 1827 } 1828 1829 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 1830 1831 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 1832 defer commit_object.deinit(); 1833 1834 // if this object id has already been consumed, skip it 1835 if (null != try consumed_object_ids.getCursor(oid_int)) { 1836 continue; 1837 } 1838 1839 if (self.newest_object_id == null) self.newest_object_id = oid; 1840 self.oldest_object_id = oid; 1841 1842 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1843 var pending_parent_count: u64 = 0; 1844 for (parent_oids) |*parent_oid| { 1845 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1846 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 1847 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 1848 1849 // if this object id has already been consumed, skip it 1850 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 1851 continue; 1852 } 1853 1854 // if this object id hasn't already been seen, add it to the walk queue 1855 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 1856 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 1857 } 1858 1859 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 1860 const children = try DB.HashSet(.read_write).init(children_cursor); 1861 try children.put(oid_int, .{ .bytes = &oid }); 1862 pending_parent_count += 1; 1863 } 1864 1865 if (pending_parent_count == 0) { 1866 try self.ready_queue.append(.{ .bytes = &oid }); 1867 } else { 1868 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 1869 } 1870 } 1871 } 1872 1873 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 1874 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 1875 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 1876 const children = try DB.HashSet(.read_only).init(children_cursor); 1877 var children_iter = try children.iterator(); 1878 1879 while (try children_iter.next()) |*child_cursor| { 1880 const kv_pair = try child_cursor.readKeyValuePair(); 1881 const child_oid_int = kv_pair.hash; 1882 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 1883 const pending_parent_count = try pending_parent_cursor.readUint(); 1884 1885 if (pending_parent_count <= 1) { 1886 _ = try self.child_to_pending_parents.remove(child_oid_int); 1887 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 1888 try self.ready_queue.append(.{ .bytes = &child_oid }); 1889 } else { 1890 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 1891 } 1892 } 1893 } 1894 1895 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 1896 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 1897 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1898 _ = try oid_cursor.readBytes(&oid); 1899 return oid; 1900 } 1901 }; 1902 } 1903