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