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