╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1309 const map = field_oids orelse unreachable; 1310 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1311 if (parent_oid) |oid_cursor| { 1312 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1313 } else { 1314 _ = try map.remove(field.name); 1315 } 1316 }, 1317 .conflicted => { 1318 if (conflicted_len > 0) { 1319 conflicted_fields[conflicted_len] = ' '; 1320 conflicted_len += 1; 1321 } 1322 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1323 conflicted_len += field.name.len; 1324 }, 1325 } 1326 } 1327 1328 if (conflicted_len > 0) { 1329 // each side's whole record is stored by reference, so the view can 1330 // show any of them or take theirs wholesale 1331 _ = try conflicts.remove(&merged_key); 1332 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1333 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1334 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1335 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1336 if (parent_field_oids) |map| { 1337 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1338 } 1339 continue; 1340 } 1341 1342 // created_order never changes, so the parent keys this record's conflict 1343 // identically, and it carries over when the target has none, unless the 1344 // parent's entry is unchanged from the baseline, meaning the target 1345 // inherited it too and resolving it removed it here. 1346 if (parent_conflicts) |map| { 1347 if (null == try conflicts.getCursor(&merged_key)) { 1348 if (try map.getSlot(&merged_key)) |conflict_slot| { 1349 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1350 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1351 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1352 } 1353 } 1354 } 1355 } 1356 } 1357 1358 pub fn currentMoment( 1359 comptime repo_opts: rp.RepoOpts(.xit), 1360 repo: *rp.Repo(.xit, repo_opts), 1361 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1362 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1363 } 1364 1365 // the oid of the last event commit consumed into `db`, or null before any 1366 // consume completed 1367 fn lastConsumedOid( 1368 comptime hash_kind: hash.HashKind, 1369 db: *EventDB(hash_kind), 1370 ) !?[hash.byteLen(hash_kind)]u8 { 1371 const DB = EventDB(hash_kind); 1372 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1373 const moment_cursor = try history.getCursor(-1) orelse return null; 1374 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1375 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy-last-object-id")) orelse return null; 1376 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1377 _ = try last_object_id_cursor.readBytes(&last_object_id); 1378 return last_object_id; 1379 } 1380 1381 pub fn currentMomentFromDb( 1382 comptime hash_kind: hash.HashKind, 1383 db: *EventDB(hash_kind), 1384 ) !EventDB(hash_kind).HashMap(.read_only) { 1385 const DB = EventDB(hash_kind); 1386 const last_object_id = (try lastConsumedOid(hash_kind, db)) orelse return error.NotFound; 1387 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1388 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1389 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1390 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy")) orelse return error.NotFound; 1391 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 1392 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 1393 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1394 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1395 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1396 } 1397 1398 // build a sorted-set key from an order and event id. big-endian order makes 1399 // byte order match numeric order; the event id breaks ties. 1400 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1401 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1402 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1403 @memcpy(key[@sizeOf(u64)..], event_id); 1404 return key; 1405 } 1406 1407 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1408 return orderKey(std.math.maxInt(u64) - order, event_id); 1409 } 1410 1411 // add or refresh one entry in the global logical-event index. updates and 1412 // removed records preserve created_order, so the key never moves. 1413 pub fn indexEvent( 1414 comptime DB: type, 1415 comptime hash_kind: hash.HashKind, 1416 haxy_moment: DB.HashMap(.read_write), 1417 event_id: *const [event_id_size]u8, 1418 kind: EventKind, 1419 created_order: u64, 1420 removed: bool, 1421 ) !void { 1422 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1423 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1424 try kind_map.put(hash.hashInt(hash_kind, event_id), .{ .bytes = @tagName(kind) }); 1425 1426 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1427 const active = try DB.SortedSet(.read_write).init(active_cursor); 1428 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1429 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1430 const order_key = orderKeyDesc(created_order, event_id); 1431 if (removed) { 1432 _ = try active.remove(&order_key); 1433 try removed_set.put(&order_key); 1434 } else { 1435 _ = try removed_set.remove(&order_key); 1436 try active.put(&order_key); 1437 } 1438 } 1439 1440 pub fn touchThread( 1441 comptime DB: type, 1442 comptime hash_kind: hash.HashKind, 1443 haxy_moment: DB.HashMap(.read_write), 1444 thread_id: *const [event_id_size]u8, 1445 order: u64, 1446 arena: *std.heap.ArenaAllocator, 1447 ) !void { 1448 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1449 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1450 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1451 switch (kind) { 1452 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1453 else => {}, 1454 } 1455 } 1456 1457 pub fn readEventKind( 1458 comptime hash_kind: hash.HashKind, 1459 kind_map: anytype, 1460 id: *const [event_id_size]u8, 1461 ) !?EventKind { 1462 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1463 var buffer: [64]u8 = undefined; 1464 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1465 } 1466 1467 // the event id embedded in a set entry's order key 1468 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1469 var cursor = kv_pair_cursor; 1470 const kv_pair = try cursor.readKeyValuePair(); 1471 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1472 _ = try kv_pair.key_cursor.readBytes(&order_key); 1473 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1474 } 1475 1476 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1477 // isn't exactly two non-empty segments. 1478 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1479 var it = std.mem.splitScalar(u8, path, '/'); 1480 const owner = it.next() orelse return null; 1481 const name = it.next() orelse return null; 1482 if (it.next() != null) return null; 1483 if (owner.len == 0 or name.len == 0) return null; 1484 1485 return .{ .owner = owner, .name = name }; 1486 } 1487 1488 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1489 // directory under the repos dir 1490 pub fn resolveOrCreateRepo( 1491 io: std.Io, 1492 allocator: std.mem.Allocator, 1493 admin_repo_path: []const u8, 1494 owner_name: []const u8, 1495 repo_name: []const u8, 1496 create_if_missing: bool, 1497 ) !?[event_id_size * 2]u8 { 1498 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1499 error.RepoNotFound => return null, 1500 else => |e| return e, 1501 }; 1502 defer repo.deinit(io, allocator); 1503 1504 var arena = std.heap.ArenaAllocator.init(allocator); 1505 defer arena.deinit(); 1506 1507 const moment = try currentMoment(admin_repo_opts, &repo); 1508 1509 // an already-registered repo reuses its event id, so a re-push (or a clone) 1510 // lands in the same repo 1511 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1512 return std.fmt.bytesToHex(found.event_id, .lower); 1513 } 1514 1515 if (!create_if_missing) return null; 1516 1517 // the new repo is owned by the named user, read from the name index; an 1518 // unknown owner can't own a repo, so the push is rejected 1519 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1520 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1521 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1522 var owner_user_id: [event_id_size]u8 = undefined; 1523 _ = try owner_id_cursor.readBytes(&owner_user_id); 1524 1525 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1526 1527 var id_bytes: [event_id_size]u8 = undefined; 1528 io.random(&id_bytes); 1529 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1530 1531 try consume(.xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1532 .id = event_id_hex, 1533 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1534 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1535 .event = .{ .repo = .{ 1536 .user_id = &owner_user_id, 1537 .name = repo_name, 1538 .description = "", 1539 } }, 1540 }}); 1541 1542 return event_id_hex; 1543 } 1544 1545 // 1546 // reading from xitdb 1547 // 1548 1549 // a struct field's fields share its container's map, so their names must not 1550 // collide with the container's or two fields would silently share a key 1551 fn validateFlattenedFields(comptime T: type) void { 1552 comptime { 1553 for (std.meta.fields(T)) |field| { 1554 if (@typeInfo(field.type) != .@"struct") continue; 1555 for (std.meta.fields(field.type)) |nested| { 1556 if (@hasField(T, nested.name)) 1557 @compileError("flattened field name collision in " ++ @typeName(T) ++ ": " ++ nested.name); 1558 } 1559 } 1560 } 1561 } 1562 1563 pub fn read( 1564 comptime T: type, 1565 comptime DB: type, 1566 comptime hash_kind: hash.HashKind, 1567 arena: *std.heap.ArenaAllocator, 1568 map: DB.HashMap(.read_only), 1569 ) !T { 1570 var event: T = undefined; 1571 1572 switch (@typeInfo(T)) { 1573 .@"struct" => |struct_info| { 1574 comptime validateFlattenedFields(T); 1575 inline for (struct_info.fields) |field| { 1576 switch (@typeInfo(field.type)) { 1577 .pointer => |pointer_info| { 1578 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 1579 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1580 } else { 1581 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1582 } 1583 }, 1584 .array => |array_info| { 1585 if (array_info.child == u8) { 1586 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1587 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 1588 @memcpy(@field(event, field.name)[0..], bytes); 1589 } else { 1590 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1591 } 1592 }, 1593 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 1594 .int => |int_info| switch (int_info.signedness) { 1595 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 1596 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 1597 }, 1598 .@"enum" => { 1599 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1600 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 1601 }, 1602 .optional => |optional_info| { 1603 // a missing key is null 1604 if (try map.getCursor(hash.hashInt(hash_kind, field.name))) |cursor| { 1605 if (optional_info.child == []const u8) { 1606 @field(event, field.name) = try cursor.readBytesAlloc(arena.allocator(), null); 1607 } else switch (@typeInfo(optional_info.child)) { 1608 .array => |array_info| { 1609 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1610 var bytes: optional_info.child = undefined; 1611 const value = try cursor.readBytes(&bytes); 1612 if (value.len != bytes.len) return error.InvalidByteArrayLength; 1613 @field(event, field.name) = bytes; 1614 }, 1615 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1616 } 1617 } else { 1618 @field(event, field.name) = null; 1619 } 1620 }, 1621 // a struct field's own fields are read from the same map 1622 .@"struct" => @field(event, field.name) = try read(field.type, DB, hash_kind, arena, map), 1623 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1624 } 1625 } 1626 }, 1627 else => @compileError("read expects a struct"), 1628 } 1629 1630 return event; 1631 } 1632 1633 // whether two events carry the same data 1634 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1635 switch (@typeInfo(T)) { 1636 .@"struct" => |struct_info| { 1637 inline for (struct_info.fields) |field| { 1638 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1639 } 1640 }, 1641 else => @compileError("fieldsEqual expects a struct"), 1642 } 1643 1644 return true; 1645 } 1646 1647 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1648 switch (@typeInfo(Field)) { 1649 .pointer => |pointer_info| { 1650 if (pointer_info.size == .slice and pointer_info.child == u8) { 1651 return std.mem.eql(u8, a, b); 1652 } else { 1653 @compileError("unsupported field type: " ++ @typeName(Field)); 1654 } 1655 }, 1656 .array => |array_info| { 1657 if (array_info.child == u8) { 1658 return std.mem.eql(u8, &a, &b); 1659 } else { 1660 @compileError("unsupported field type: " ++ @typeName(Field)); 1661 } 1662 }, 1663 .bool, .int, .@"enum" => return a == b, 1664 .optional => |optional_info| { 1665 if (a) |a_value| { 1666 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 1667 return false; 1668 } 1669 return b == null; 1670 }, 1671 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1672 } 1673 } 1674 1675 fn readBytes( 1676 comptime DB: type, 1677 comptime hash_kind: hash.HashKind, 1678 allocator: std.mem.Allocator, 1679 map: DB.HashMap(.read_only), 1680 field_name: []const u8, 1681 ) ![]const u8 { 1682 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1683 return try cursor.readBytesAlloc(allocator, null); 1684 } 1685 1686 fn readUint( 1687 comptime DB: type, 1688 comptime hash_kind: hash.HashKind, 1689 map: DB.HashMap(.read_only), 1690 field_name: []const u8, 1691 ) !u64 { 1692 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1693 return try cursor.readUint(); 1694 } 1695 1696 fn readInt( 1697 comptime DB: type, 1698 comptime hash_kind: hash.HashKind, 1699 map: DB.HashMap(.read_only), 1700 field_name: []const u8, 1701 ) !i64 { 1702 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1703 return try cursor.readInt(); 1704 } 1705 1706 fn readBool( 1707 comptime DB: type, 1708 comptime hash_kind: hash.HashKind, 1709 map: DB.HashMap(.read_only), 1710 field_name: []const u8, 1711 ) !bool { 1712 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1713 var buffer: [5]u8 = undefined; 1714 const bytes = try cursor.readBytesObject(&buffer); 1715 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1716 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1717 if (std.mem.eql(u8, bytes.value, "true")) return true; 1718 if (std.mem.eql(u8, bytes.value, "false")) return false; 1719 return error.InvalidBool; 1720 } 1721 1722 // 1723 // writing to xitdb 1724 // 1725 1726 pub fn upsert( 1727 comptime T: type, 1728 comptime DB: type, 1729 comptime hash_kind: hash.HashKind, 1730 map: DB.HashMap(.read_write), 1731 event: T, 1732 ) !void { 1733 switch (@typeInfo(T)) { 1734 .@"struct" => |struct_info| { 1735 comptime validateFlattenedFields(T); 1736 inline for (struct_info.fields) |field| { 1737 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1738 } 1739 }, 1740 else => @compileError("upsert expects a struct"), 1741 } 1742 } 1743 1744 fn upsertField( 1745 comptime DB: type, 1746 comptime hash_kind: hash.HashKind, 1747 map: DB.HashMap(.read_write), 1748 comptime field_name: []const u8, 1749 comptime Field: type, 1750 value: Field, 1751 ) !void { 1752 const key = hash.hashInt(hash_kind, field_name); 1753 1754 switch (@typeInfo(Field)) { 1755 .pointer => |pointer_info| { 1756 if (pointer_info.size == .slice and pointer_info.child == u8) { 1757 try upsertBytes(DB, hash_kind, map, key, value); 1758 } else { 1759 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1760 } 1761 }, 1762 .array => |array_info| { 1763 if (array_info.child == u8) { 1764 try upsertBytes(DB, hash_kind, map, key, &value); 1765 } else { 1766 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1767 } 1768 }, 1769 .int => |int_info| switch (int_info.signedness) { 1770 .unsigned => { 1771 if (try map.getCursor(key)) |value_cursor| { 1772 if (try value_cursor.readUint() == value) { 1773 return; 1774 } 1775 } 1776 1777 try map.put(key, .{ .uint = value }); 1778 }, 1779 .signed => { 1780 if (try map.getCursor(key)) |value_cursor| { 1781 if (try value_cursor.readInt() == value) { 1782 return; 1783 } 1784 } 1785 1786 try map.put(key, .{ .int = value }); 1787 }, 1788 }, 1789 .bool => { 1790 const bytes = if (value) "true" else "false"; 1791 if (try map.getCursor(key)) |value_cursor| { 1792 var buffer: [5]u8 = undefined; 1793 const existing = try value_cursor.readBytesObject(&buffer); 1794 if (existing.format_tag) |format_tag| { 1795 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1796 return; 1797 } 1798 } 1799 } 1800 1801 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1802 }, 1803 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1804 .optional => |optional_info| { 1805 // a missing key is null 1806 if (value) |child| { 1807 if (optional_info.child == []const u8) { 1808 try upsertBytes(DB, hash_kind, map, key, child); 1809 } else switch (@typeInfo(optional_info.child)) { 1810 .array => |array_info| { 1811 if (array_info.child != u8) @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1812 try upsertBytes(DB, hash_kind, map, key, &child); 1813 }, 1814 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1815 } 1816 } else { 1817 _ = try map.remove(key); 1818 } 1819 }, 1820 // a struct field's own fields are stored in the same map 1821 .@"struct" => try upsert(Field, DB, hash_kind, map, value), 1822 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1823 } 1824 } 1825 1826 fn upsertBytes( 1827 comptime DB: type, 1828 comptime hash_kind: hash.HashKind, 1829 map: DB.HashMap(.read_write), 1830 key: hash.HashInt(hash_kind), 1831 value: []const u8, 1832 ) !void { 1833 var existing_cursor_maybe = try map.getCursor(key); 1834 if (existing_cursor_maybe) |*existing_cursor| { 1835 if (try bytesEqual(DB, existing_cursor, value)) { 1836 return; 1837 } 1838 } 1839 1840 var value_cursor = try map.putCursor(key); 1841 var write_buffer: [1024]u8 = undefined; 1842 var writer = try value_cursor.writer(&write_buffer); 1843 try writer.interface.writeAll(value); 1844 try writer.finish(); 1845 } 1846 1847 fn bytesEqual( 1848 comptime DB: type, 1849 cursor: *DB.Cursor(.read_only), 1850 value: []const u8, 1851 ) !bool { 1852 var read_buffer: [1024]u8 = undefined; 1853 var reader = try cursor.reader(&read_buffer); 1854 if (reader.size != value.len) { 1855 return false; 1856 } 1857 1858 var chunk_buffer: [1024]u8 = undefined; 1859 var offset: usize = 0; 1860 while (offset < value.len) { 1861 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1862 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1863 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1864 return false; 1865 } 1866 offset += chunk_len; 1867 } 1868 1869 return true; 1870 } 1871 1872 // 1873 // CommitIterator 1874 // 1875 // differs from xit's ObjectIterator in a few ways: 1876 // 1877 // 1. iterates parents first, rather than children first 1878 // 2. `next` only returns the object id, not the full Object 1879 // 3. stores its temporary state in a file on disk to avoid OOMs 1880 // 1881 1882 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1883 return struct { 1884 const DB = EventDB(repo_opts.hash); 1885 const db_name = "haxy-repo-events.db"; 1886 1887 repo_dir: std.Io.Dir, 1888 db_file: std.Io.File, 1889 db: *DB, 1890 // map of each object id to its children 1891 parent_to_children: DB.HashMap(.read_write), 1892 // tracking pending parents is necessary because a child can only 1893 // be returned after all of its unconsumed parents have been returned 1894 child_to_pending_parents: DB.HashMap(.read_write), 1895 // queue of object ids that are ready to be returned from `next` 1896 ready_queue: DB.ArrayList(.read_write), 1897 ready_queue_index: u64, 1898 // the object id at the tip of this branch 1899 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1900 // the object id furthest back in the history that hasn't been consumed 1901 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1902 1903 pub fn init( 1904 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1905 io: std.Io, 1906 allocator: std.mem.Allocator, 1907 consumed_object_ids: DB.HashMap(.read_only), 1908 ref: rf.Ref, 1909 ) !CommitIterator(repo_kind, repo_opts) { 1910 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1911 errdefer { 1912 db_file.close(io); 1913 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1914 } 1915 1916 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1917 errdefer allocator.destroy(buffer_ptr); 1918 1919 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1920 errdefer buffer_ptr.deinit(); 1921 1922 const db_ptr = try allocator.create(DB); 1923 errdefer allocator.destroy(db_ptr); 1924 // the db is scratch state that gets deleted after iteration, so 1925 // there is nothing worth fsyncing 1926 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 1927 1928 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1929 1930 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1931 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1932 1933 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1934 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1935 1936 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1937 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1938 1939 var self = CommitIterator(repo_kind, repo_opts){ 1940 .repo_dir = state.core.repo_dir, 1941 .db_file = db_file, 1942 .db = db_ptr, 1943 .parent_to_children = parent_to_children, 1944 .child_to_pending_parents = child_to_pending_parents, 1945 .ready_queue = ready_queue, 1946 .ready_queue_index = 0, 1947 .newest_object_id = null, 1948 .oldest_object_id = null, 1949 }; 1950 errdefer self.deinit(io, allocator); 1951 1952 try self.collect(state, io, allocator, consumed_object_ids, ref); 1953 1954 return self; 1955 } 1956 1957 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1958 self.db_file.close(io); 1959 self.db.core.memory.buffer.deinit(); 1960 allocator.destroy(self.db.core.memory.buffer); 1961 self.repo_dir.deleteFile(io, db_name) catch {}; 1962 allocator.destroy(self.db); 1963 } 1964 1965 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 1966 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 1967 1968 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 1969 self.ready_queue_index += 1; 1970 1971 try self.enqueueChildren(&oid); 1972 return oid; 1973 } 1974 1975 fn collect( 1976 self: *CommitIterator(repo_kind, repo_opts), 1977 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1978 io: std.Io, 1979 allocator: std.mem.Allocator, 1980 consumed_object_ids: DB.HashMap(.read_only), 1981 ref: rf.Ref, 1982 ) !void { 1983 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 1984 1985 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 1986 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 1987 var walk_queue_index: u64 = 0; 1988 1989 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 1990 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 1991 1992 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1993 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1994 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1995 try walk_queue.append(.{ .bytes = &head_oid }); 1996 1997 while (walk_queue_index < try walk_queue.count()) { 1998 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 1999 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2000 2001 walk_queue_index += 1; 2002 2003 // if we've seen this object id, skip it 2004 if (null != try seen_object_ids.getCursor(oid_int)) { 2005 continue; 2006 } 2007 2008 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2009 2010 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2011 defer commit_object.deinit(); 2012 2013 // if this object id has already been consumed, skip it 2014 if (null != try consumed_object_ids.getCursor(oid_int)) { 2015 continue; 2016 } 2017 2018 if (self.newest_object_id == null) self.newest_object_id = oid; 2019 self.oldest_object_id = oid; 2020 2021 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2022 var pending_parent_count: u64 = 0; 2023 for (parent_oids) |*parent_oid| { 2024 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2025 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2026 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2027 2028 // if this object id has already been consumed, skip it 2029 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2030 continue; 2031 } 2032 2033 // if this object id hasn't already been seen, add it to the walk queue 2034 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2035 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2036 } 2037 2038 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2039 const children = try DB.HashSet(.read_write).init(children_cursor); 2040 try children.put(oid_int, .{ .bytes = &oid }); 2041 pending_parent_count += 1; 2042 } 2043 2044 if (pending_parent_count == 0) { 2045 try self.ready_queue.append(.{ .bytes = &oid }); 2046 } else { 2047 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2048 } 2049 } 2050 } 2051 2052 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2053 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2054 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2055 const children = try DB.HashSet(.read_only).init(children_cursor); 2056 var children_iter = try children.iterator(); 2057 2058 while (try children_iter.next()) |*child_cursor| { 2059 const kv_pair = try child_cursor.readKeyValuePair(); 2060 const child_oid_int = kv_pair.hash; 2061 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2062 const pending_parent_count = try pending_parent_cursor.readUint(); 2063 2064 if (pending_parent_count <= 1) { 2065 _ = try self.child_to_pending_parents.remove(child_oid_int); 2066 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2067 try self.ready_queue.append(.{ .bytes = &child_oid }); 2068 } else { 2069 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2070 } 2071 } 2072 } 2073 2074 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2075 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2076 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2077 _ = try oid_cursor.readBytes(&oid); 2078 return oid; 2079 } 2080 }; 2081 } 2082