╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2260 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2261 2262 var id_bytes: [event_id_size]u8 = undefined; 2263 io.random(&id_bytes); 2264 2265 // the user repo comes first so a listed user can always create repos 2266 { 2267 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2268 defer allocator.free(path); 2269 var user_repo = try initUserRepo(io, allocator, path); 2270 defer user_repo.deinit(io, allocator); 2271 } 2272 2273 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2274 .id = std.fmt.bytesToHex(id_bytes, .lower), 2275 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2276 .author = .{ .name = name, .email = email }, 2277 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2278 }}); 2279 return id_bytes; 2280 } 2281 2282 // change a user's email, and their password when the password fields are 2283 // filled in 2284 pub fn updateUser( 2285 io: std.Io, 2286 allocator: std.mem.Allocator, 2287 users_dir: []const u8, 2288 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2289 user_id: *const [event_id_size]u8, 2290 email: []const u8, 2291 current_password: []const u8, 2292 new_password: []const u8, 2293 new_password_again: []const u8, 2294 ) !void { 2295 if (email.len == 0) return error.EmailEmpty; 2296 var arena = std.heap.ArenaAllocator.init(allocator); 2297 defer arena.deinit(); 2298 const moment = try currentMoment(admin_repo_opts, admin_repo); 2299 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2300 if (user.removed) return error.NotFound; 2301 if (!std.mem.eql(u8, email, user.event.email) and try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2302 2303 var event = user.event; 2304 event.email = email; 2305 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2306 if (current_password.len + new_password.len + new_password_again.len > 0) { 2307 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2308 if (new_password.len == 0) return error.PasswordEmpty; 2309 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2310 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2311 } 2312 2313 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2314 .id = std.fmt.bytesToHex(user_id.*, .lower), 2315 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2316 .author = .{ .name = event.name, .email = email }, 2317 .event = .{ .user = event }, 2318 }}); 2319 } 2320 2321 // add an authorized_keys line to the user's ssh keys 2322 pub fn addUserKey( 2323 io: std.Io, 2324 allocator: std.mem.Allocator, 2325 users_dir: []const u8, 2326 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2327 user_id: *const [event_id_size]u8, 2328 key_text: []const u8, 2329 ) !void { 2330 const key = std.mem.trim(u8, key_text, " \t\r"); 2331 // the keys are stored one per line 2332 if (std.mem.indexOfScalar(u8, key, '\n') != null) return error.InvalidKey; 2333 const fingerprint = User.fingerprintOfKey(key) orelse return error.InvalidKey; 2334 // the key types the ssh server verifies 2335 const key_type = std.mem.sliceTo(key, ' '); 2336 if (!std.mem.eql(u8, key_type, "ssh-ed25519") and !std.mem.eql(u8, key_type, "ssh-rsa")) return error.UnsupportedKey; 2337 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, &fingerprint, key); 2338 } 2339 2340 // remove the user's ssh key with this fingerprint. removing a key they don't 2341 // hold writes nothing. 2342 pub fn removeUserKey( 2343 io: std.Io, 2344 allocator: std.mem.Allocator, 2345 users_dir: []const u8, 2346 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2347 user_id: *const [event_id_size]u8, 2348 fingerprint: *const [User.fingerprint_len]u8, 2349 ) !void { 2350 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, fingerprint, null); 2351 } 2352 2353 // rewrite the user's ssh keys with `added` appended, or without the key with 2354 // `fingerprint` when nothing is added 2355 fn writeUserKeys( 2356 io: std.Io, 2357 allocator: std.mem.Allocator, 2358 users_dir: []const u8, 2359 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2360 user_id: *const [event_id_size]u8, 2361 fingerprint: *const [User.fingerprint_len]u8, 2362 added: ?[]const u8, 2363 ) !void { 2364 var arena = std.heap.ArenaAllocator.init(allocator); 2365 defer arena.deinit(); 2366 const moment = try currentMoment(admin_repo_opts, admin_repo); 2367 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2368 if (user.removed) return error.NotFound; 2369 2370 var keys: std.ArrayList(u8) = .empty; 2371 var count: usize = 0; 2372 var held = false; 2373 var lines = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 2374 while (lines.next()) |line| { 2375 const line_fingerprint = User.fingerprintOfKey(line) orelse continue; 2376 if (std.mem.eql(u8, &line_fingerprint, fingerprint)) { 2377 held = true; 2378 if (added == null) continue; 2379 } 2380 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2381 try keys.appendSlice(arena.allocator(), line); 2382 count += 1; 2383 } 2384 if (added) |key| { 2385 if (held) return error.KeyAdded; 2386 if (count >= User.ssh_key_max_count) return error.TooManyKeys; 2387 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2388 try keys.appendSlice(arena.allocator(), key); 2389 } else if (!held) return; 2390 2391 var event = user.event; 2392 event.ssh_keys = keys.items; 2393 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2394 .id = std.fmt.bytesToHex(user_id.*, .lower), 2395 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2396 .author = .{ .name = event.name, .email = event.email }, 2397 .event = .{ .user = event }, 2398 }}); 2399 } 2400 2401 // consume a new repo's event into its owner's user repo and mark it active 2402 fn writeRepoEvent( 2403 io: std.Io, 2404 allocator: std.mem.Allocator, 2405 users_dir: []const u8, 2406 user_repo: *rp.Repo(.xit, user_repo_opts), 2407 owner_id: *const [event_id_size]u8, 2408 owner: CommitAuthor, 2409 id_bytes: *const [event_id_size]u8, 2410 name: []const u8, 2411 description: []const u8, 2412 read_access: Repo.Access, 2413 ) !void { 2414 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2415 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2416 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2417 .timestamp = timestamp, 2418 .author = owner, 2419 .event = .{ .repo = .{ 2420 .user_id = std.fmt.bytesToHex(owner_id.*, .lower), 2421 .name = name, 2422 .description = description, 2423 .read_access = read_access, 2424 } }, 2425 }}); 2426 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2427 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2428 }; 2429 } 2430 2431 // 2432 // reading from xitdb 2433 // 2434 2435 // read just `Fields`, a subset of `T.Record`, from the record with event id 2436 // `id`, or null when there is none 2437 pub fn readRecordSubset( 2438 comptime T: type, 2439 comptime Fields: type, 2440 comptime DB: type, 2441 comptime hash_kind: hash.HashKind, 2442 haxy_moment: DB.HashMap(.read_only), 2443 arena: *std.heap.ArenaAllocator, 2444 id: []const u8, 2445 ) !?Fields { 2446 comptime assertFieldSubset(Fields, T.Record); 2447 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2448 const records = try DB.HashMap(.read_only).init(records_cursor); 2449 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2450 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2451 } 2452 2453 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2454 const info = @typeInfo(Sub).@"struct"; 2455 for (info.field_names, info.field_types) |field_name, field_type| { 2456 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2457 const FullField = @FieldType(Full, field_name); 2458 if (@typeInfo(field_type) == .@"struct") { 2459 assertFieldSubset(field_type, FullField); 2460 } else if (field_type != FullField) { 2461 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2462 } 2463 } 2464 } 2465 2466 pub fn read( 2467 comptime T: type, 2468 comptime DB: type, 2469 comptime hash_kind: hash.HashKind, 2470 arena: *std.heap.ArenaAllocator, 2471 map: DB.HashMap(.read_only), 2472 ) !T { 2473 var event: T = undefined; 2474 switch (@typeInfo(T)) { 2475 .@"struct" => |struct_info| { 2476 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2477 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2478 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2479 } 2480 }, 2481 else => @compileError("read expects a struct"), 2482 } 2483 return event; 2484 } 2485 2486 fn readField( 2487 comptime Field: type, 2488 comptime DB: type, 2489 comptime hash_kind: hash.HashKind, 2490 arena: *std.heap.ArenaAllocator, 2491 cursor_maybe: ?DB.Cursor(.read_only), 2492 ) !Field { 2493 if (@typeInfo(Field) == .optional) { 2494 // a missing key or a null union payload is null 2495 const cursor = cursor_maybe orelse return null; 2496 if (cursor.slot().tag == .none) return null; 2497 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2498 } 2499 const cursor = cursor_maybe orelse return error.NotFound; 2500 switch (@typeInfo(Field)) { 2501 .pointer => |pointer_info| { 2502 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2503 @compileError("unsupported read field type: " ++ @typeName(Field)); 2504 } 2505 return try cursor.readBytesAlloc(arena.allocator(), null); 2506 }, 2507 .array => |array_info| { 2508 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2509 var bytes: Field = undefined; 2510 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2511 return bytes; 2512 }, 2513 .bool => { 2514 var buffer: [5]u8 = undefined; 2515 const bytes = try cursor.readBytesObject(&buffer); 2516 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2517 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2518 if (std.mem.eql(u8, bytes.value, "true")) return true; 2519 if (std.mem.eql(u8, bytes.value, "false")) return false; 2520 return error.InvalidBool; 2521 }, 2522 .int => |int_info| return switch (int_info.signedness) { 2523 .unsigned => @intCast(try cursor.readUint()), 2524 .signed => @intCast(try cursor.readInt()), 2525 }, 2526 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2527 .@"union" => |union_info| { 2528 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2529 switch (cursor.slot().tag) { 2530 .bytes, .short_bytes => { 2531 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2532 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2533 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2534 return @unionInit(Field, variant_name, {}); 2535 } 2536 } 2537 return error.InvalidUnion; 2538 }, 2539 .hash_map => { 2540 const variants = try DB.HashMap(.read_only).init(cursor); 2541 var iter = try variants.iterator(); 2542 const entry = (try iter.next()) orelse return error.InvalidUnion; 2543 const pair = try entry.readKeyValuePair(); 2544 if (try iter.next() != null) return error.InvalidUnion; 2545 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2546 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2547 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2548 } 2549 } 2550 return error.InvalidUnion; 2551 }, 2552 else => return error.InvalidUnion, 2553 } 2554 }, 2555 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2556 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2557 } 2558 } 2559 2560 // whether two events carry the same data 2561 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2562 switch (@typeInfo(T)) { 2563 .@"struct" => |struct_info| { 2564 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2565 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2566 } 2567 }, 2568 else => @compileError("fieldsEqual expects a struct"), 2569 } 2570 2571 return true; 2572 } 2573 2574 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2575 switch (@typeInfo(Field)) { 2576 .pointer => |pointer_info| { 2577 if (pointer_info.size == .slice and pointer_info.child == u8) { 2578 return std.mem.eql(u8, a, b); 2579 } else { 2580 @compileError("unsupported field type: " ++ @typeName(Field)); 2581 } 2582 }, 2583 .array => |array_info| { 2584 if (array_info.child == u8) { 2585 return std.mem.eql(u8, &a, &b); 2586 } else { 2587 @compileError("unsupported field type: " ++ @typeName(Field)); 2588 } 2589 }, 2590 .void => return true, 2591 .bool, .int, .@"enum" => return a == b, 2592 .@"union" => { 2593 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2594 return switch (a) { 2595 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2596 }; 2597 }, 2598 .@"struct" => return fieldsEqual(Field, a, b), 2599 .optional => |optional_info| { 2600 if (a) |a_value| { 2601 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2602 return false; 2603 } 2604 return b == null; 2605 }, 2606 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2607 } 2608 } 2609 2610 // 2611 // writing to xitdb 2612 // 2613 2614 pub fn upsert( 2615 comptime T: type, 2616 comptime DB: type, 2617 comptime hash_kind: hash.HashKind, 2618 map: DB.HashMap(.read_write), 2619 event: T, 2620 ) !void { 2621 switch (@typeInfo(T)) { 2622 .@"struct" => |struct_info| { 2623 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2624 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2625 } 2626 }, 2627 else => @compileError("upsert expects a struct"), 2628 } 2629 } 2630 2631 fn upsertField( 2632 comptime DB: type, 2633 comptime hash_kind: hash.HashKind, 2634 map: DB.HashMap(.read_write), 2635 comptime field_name: []const u8, 2636 comptime Field: type, 2637 value: Field, 2638 ) !void { 2639 const key = hash.hashInt(hash_kind, field_name); 2640 2641 switch (@typeInfo(Field)) { 2642 .pointer => |pointer_info| { 2643 if (pointer_info.size == .slice and pointer_info.child == u8) { 2644 try upsertBytes(DB, hash_kind, map, key, value); 2645 } else { 2646 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2647 } 2648 }, 2649 .array => |array_info| { 2650 if (array_info.child == u8) { 2651 try upsertBytes(DB, hash_kind, map, key, &value); 2652 } else { 2653 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2654 } 2655 }, 2656 .int => |int_info| switch (int_info.signedness) { 2657 .unsigned => { 2658 if (try map.getCursor(key)) |value_cursor| { 2659 if (try value_cursor.readUint() == value) { 2660 return; 2661 } 2662 } 2663 2664 try map.put(key, .{ .uint = value }); 2665 }, 2666 .signed => { 2667 if (try map.getCursor(key)) |value_cursor| { 2668 if (try value_cursor.readInt() == value) { 2669 return; 2670 } 2671 } 2672 2673 try map.put(key, .{ .int = value }); 2674 }, 2675 }, 2676 .bool => { 2677 const bytes = if (value) "true" else "false"; 2678 if (try map.getCursor(key)) |value_cursor| { 2679 var buffer: [5]u8 = undefined; 2680 const existing = try value_cursor.readBytesObject(&buffer); 2681 if (existing.format_tag) |format_tag| { 2682 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2683 return; 2684 } 2685 } 2686 } 2687 2688 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2689 }, 2690 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2691 .@"union" => switch (value) { 2692 inline else => |payload, tag| { 2693 if (@TypeOf(payload) == void) { 2694 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2695 } else { 2696 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2697 if (try map.getCursor(key)) |cursor| { 2698 switch (cursor.slot().tag) { 2699 .hash_map => { 2700 const variants = try DB.HashMap(.read_only).init(cursor); 2701 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2702 }, 2703 else => try map.put(key, .{ .slot = null }), 2704 } 2705 } 2706 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2707 if (@typeInfo(@TypeOf(payload)) == .optional) { 2708 // keep the variant even when its payload is null 2709 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2710 } 2711 if (try variants.getCursor(tag_key)) |cursor| { 2712 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2713 } 2714 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2715 } 2716 }, 2717 }, 2718 .optional => |optional_info| { 2719 // a missing key is null 2720 if (value) |child| { 2721 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2722 } else { 2723 _ = try map.remove(key); 2724 } 2725 }, 2726 .@"struct" => try upsert( 2727 Field, 2728 DB, 2729 hash_kind, 2730 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2731 value, 2732 ), 2733 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2734 } 2735 } 2736 2737 fn upsertBytes( 2738 comptime DB: type, 2739 comptime hash_kind: hash.HashKind, 2740 map: DB.HashMap(.read_write), 2741 key: hash.HashInt(hash_kind), 2742 value: []const u8, 2743 ) !void { 2744 var existing_cursor_maybe = try map.getCursor(key); 2745 if (existing_cursor_maybe) |*existing_cursor| { 2746 if (try bytesEqual(DB, existing_cursor, value)) { 2747 return; 2748 } 2749 } 2750 2751 try map.put(key, .{ .bytes = value }); 2752 } 2753 2754 fn bytesEqual( 2755 comptime DB: type, 2756 cursor: *DB.Cursor(.read_only), 2757 value: []const u8, 2758 ) !bool { 2759 switch (cursor.slot().tag) { 2760 .bytes, .short_bytes => {}, 2761 else => return false, 2762 } 2763 var read_buffer: [1024]u8 = undefined; 2764 var reader = try cursor.reader(&read_buffer); 2765 if (reader.size != value.len) { 2766 return false; 2767 } 2768 2769 var chunk_buffer: [1024]u8 = undefined; 2770 var offset: usize = 0; 2771 while (offset < value.len) { 2772 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2773 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2774 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2775 return false; 2776 } 2777 offset += chunk_len; 2778 } 2779 2780 return true; 2781 } 2782 2783 // 2784 // CommitIterator 2785 // 2786 // differs from xit's ObjectIterator in a few ways: 2787 // 2788 // 1. iterates parents first, rather than children first 2789 // 2. `next` only returns the object id, not the full Object 2790 // 3. stores its temporary state in a file on disk to avoid OOMs 2791 // 2792 2793 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2794 return struct { 2795 const DB = EventDB(repo_opts.hash); 2796 // a plain file is used for the scratch db because each write outside 2797 // a transaction is synced anyway, so buffering would gain nothing 2798 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2799 const db_name = "haxy-repo-events.db"; 2800 2801 repo_dir: std.Io.Dir, 2802 db_file: std.Io.File, 2803 db: *TempDB, 2804 // map of each object id to its children 2805 parent_to_children: TempDB.HashMap(.read_write), 2806 // tracking pending parents is necessary because a child can only 2807 // be returned after all of its unconsumed parents have been returned 2808 child_to_pending_parents: TempDB.HashMap(.read_write), 2809 // queue of object ids that are ready to be returned from `next` 2810 ready_queue: TempDB.ArrayList(.read_write), 2811 ready_queue_index: u64, 2812 // the object id at the tip of this branch 2813 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2814 // the object id furthest back in the history that hasn't been consumed 2815 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2816 2817 pub fn init( 2818 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2819 io: std.Io, 2820 allocator: std.mem.Allocator, 2821 consumed_object_ids: DB.HashMap(.read_only), 2822 ref: rf.Ref, 2823 ) !CommitIterator(repo_kind, repo_opts) { 2824 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2825 errdefer { 2826 db_file.close(io); 2827 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2828 } 2829 2830 // cursors point at the db, so it needs a stable address 2831 const db_ptr = try allocator.create(TempDB); 2832 errdefer allocator.destroy(db_ptr); 2833 // the db is scratch state that gets deleted after iteration, so 2834 // there is nothing worth fsyncing 2835 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2836 2837 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2838 2839 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2840 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2841 2842 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2843 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2844 2845 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2846 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2847 2848 var self = CommitIterator(repo_kind, repo_opts){ 2849 .repo_dir = state.core.repo_dir, 2850 .db_file = db_file, 2851 .db = db_ptr, 2852 .parent_to_children = parent_to_children, 2853 .child_to_pending_parents = child_to_pending_parents, 2854 .ready_queue = ready_queue, 2855 .ready_queue_index = 0, 2856 .newest_object_id = null, 2857 .oldest_object_id = null, 2858 }; 2859 errdefer self.deinit(io, allocator); 2860 2861 try self.collect(state, io, allocator, consumed_object_ids, ref); 2862 2863 return self; 2864 } 2865 2866 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2867 self.db_file.close(io); 2868 self.repo_dir.deleteFile(io, db_name) catch {}; 2869 allocator.destroy(self.db); 2870 } 2871 2872 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2873 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2874 2875 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2876 self.ready_queue_index += 1; 2877 2878 try self.enqueueChildren(&oid); 2879 return oid; 2880 } 2881 2882 fn collect( 2883 self: *CommitIterator(repo_kind, repo_opts), 2884 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2885 io: std.Io, 2886 allocator: std.mem.Allocator, 2887 consumed_object_ids: DB.HashMap(.read_only), 2888 ref: rf.Ref, 2889 ) !void { 2890 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2891 2892 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2893 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2894 var walk_queue_index: u64 = 0; 2895 2896 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2897 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2898 2899 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2900 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2901 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2902 try walk_queue.append(.{ .bytes = &head_oid }); 2903 2904 while (walk_queue_index < try walk_queue.count()) { 2905 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2906 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2907 2908 walk_queue_index += 1; 2909 2910 // if we've seen this object id, skip it 2911 if (null != try seen_object_ids.getCursor(oid_int)) { 2912 continue; 2913 } 2914 2915 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2916 2917 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2918 defer commit_object.deinit(); 2919 2920 // if this object id has already been consumed, skip it 2921 if (null != try consumed_object_ids.getCursor(oid_int)) { 2922 continue; 2923 } 2924 2925 if (self.newest_object_id == null) self.newest_object_id = oid; 2926 self.oldest_object_id = oid; 2927 2928 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2929 var pending_parent_count: u64 = 0; 2930 for (parent_oids) |*parent_oid| { 2931 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2932 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2933 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2934 2935 // if this object id has already been consumed, skip it 2936 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2937 continue; 2938 } 2939 2940 // if this object id hasn't already been seen, add it to the walk queue 2941 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2942 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2943 } 2944 2945 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2946 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2947 try children.put(oid_int, .{ .bytes = &oid }); 2948 pending_parent_count += 1; 2949 } 2950 2951 if (pending_parent_count == 0) { 2952 try self.ready_queue.append(.{ .bytes = &oid }); 2953 } else { 2954 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2955 } 2956 } 2957 } 2958 2959 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2960 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2961 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2962 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2963 var children_iter = try children.iterator(); 2964 2965 while (try children_iter.next()) |*child_cursor| { 2966 const kv_pair = try child_cursor.readKeyValuePair(); 2967 const child_oid_int = kv_pair.hash; 2968 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2969 const pending_parent_count = try pending_parent_cursor.readUint(); 2970 2971 if (pending_parent_count <= 1) { 2972 _ = try self.child_to_pending_parents.remove(child_oid_int); 2973 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2974 try self.ready_queue.append(.{ .bytes = &child_oid }); 2975 } else { 2976 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2977 } 2978 } 2979 } 2980 2981 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2982 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2983 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2984 _ = try oid_cursor.readBytes(&oid); 2985 return oid; 2986 } 2987 }; 2988 } 2989