╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭ find file ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ ╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │ │ │http│ ssh │ │ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2138 } 2139 2140 // create a bare repo with `hash_kind` and register it in its owner's user repo 2141 pub fn createRepo( 2142 io: std.Io, 2143 allocator: std.mem.Allocator, 2144 users_dir: []const u8, 2145 owner_id: *const [event_id_size]u8, 2146 owner: CommitAuthor, 2147 name: []const u8, 2148 description: []const u8, 2149 read_access: Repo.Access, 2150 hash_kind: hash.HashKind, 2151 ) !RepoLocation { 2152 try Repo.validateName(name); 2153 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2154 defer user_repo.deinit(io, allocator); 2155 if (try userMoment(&user_repo)) |moment| { 2156 var arena = std.heap.ArenaAllocator.init(allocator); 2157 defer arena.deinit(); 2158 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2159 } 2160 2161 var id_bytes: [event_id_size]u8 = undefined; 2162 io.random(&id_bytes); 2163 2164 // the directory comes first so a listed repo always has one 2165 { 2166 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2167 defer allocator.free(path); 2168 switch (hash_kind) { 2169 inline else => |kind| { 2170 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2171 defer repo.deinit(io, allocator); 2172 }, 2173 } 2174 } 2175 2176 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2177 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2178 } 2179 2180 // change the name, description, read access, and tab roles of the repo 2181 // named `old_name` in its owner's user repo 2182 pub fn updateRepo( 2183 io: std.Io, 2184 allocator: std.mem.Allocator, 2185 users_dir: []const u8, 2186 owner_id: *const [event_id_size]u8, 2187 author: CommitAuthor, 2188 old_name: []const u8, 2189 name: []const u8, 2190 description: []const u8, 2191 read_access: Repo.Access, 2192 discuss_role: ?Repo.Role, 2193 issue_role: ?Repo.Role, 2194 patch_role: ?Repo.Role, 2195 ) !void { 2196 try Repo.validateName(name); 2197 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2198 defer user_repo.deinit(io, allocator); 2199 var arena = std.heap.ArenaAllocator.init(allocator); 2200 defer arena.deinit(); 2201 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2202 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2203 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2204 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2205 } 2206 2207 var event = found.repo.event; 2208 event.name = name; 2209 event.description = description; 2210 event.read_access = read_access; 2211 event.discuss_role = discuss_role; 2212 event.issue_role = issue_role; 2213 event.patch_role = patch_role; 2214 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2215 .id = std.fmt.bytesToHex(found.event_id, .lower), 2216 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2217 .author = author, 2218 .event = .{ .repo = event }, 2219 }}); 2220 } 2221 2222 // remove the repo `repo_id` from its owner's user repo, then its dir. tombstone 2223 // first so a missing repo never remains visible 2224 pub fn deleteRepo( 2225 io: std.Io, 2226 allocator: std.mem.Allocator, 2227 users_dir: []const u8, 2228 owner_id: *const [event_id_size]u8, 2229 repo_id: *const [event_id_size]u8, 2230 author: CommitAuthor, 2231 ) !void { 2232 { 2233 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2234 defer user_repo.deinit(io, allocator); 2235 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, repo_id, .repo, author); 2236 } 2237 const path = try repoPath(allocator, users_dir, owner_id, repo_id); 2238 defer allocator.free(path); 2239 try std.Io.Dir.cwd().deleteTree(io, path); 2240 } 2241 2242 // grant `user_id` `role` on the repo `repo_id` in its owner's user repo, 2243 // replacing any role they held 2244 pub fn grantRole( 2245 io: std.Io, 2246 allocator: std.mem.Allocator, 2247 users_dir: []const u8, 2248 owner_id: *const [event_id_size]u8, 2249 repo_id: *const [event_id_size]u8, 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 const supported = [_][]const u8{ "ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384" }; 2457 for (supported) |name| { 2458 if (std.mem.eql(u8, key_type, name)) break; 2459 } else return error.UnsupportedKey; 2460 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, &fingerprint, key); 2461 } 2462 2463 // remove the user's ssh key with this fingerprint. removing a key they don't 2464 // hold writes nothing. 2465 pub fn removeUserKey( 2466 io: std.Io, 2467 allocator: std.mem.Allocator, 2468 users_dir: []const u8, 2469 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2470 user_id: *const [event_id_size]u8, 2471 fingerprint: *const [User.fingerprint_len]u8, 2472 ) !void { 2473 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, fingerprint, null); 2474 } 2475 2476 // rewrite the user's ssh keys with `added` appended, or without the key with 2477 // `fingerprint` when nothing is added 2478 fn writeUserKeys( 2479 io: std.Io, 2480 allocator: std.mem.Allocator, 2481 users_dir: []const u8, 2482 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2483 user_id: *const [event_id_size]u8, 2484 fingerprint: *const [User.fingerprint_len]u8, 2485 added: ?[]const u8, 2486 ) !void { 2487 var arena = std.heap.ArenaAllocator.init(allocator); 2488 defer arena.deinit(); 2489 const moment = try currentMoment(admin_repo_opts, admin_repo); 2490 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2491 if (user.removed) return error.NotFound; 2492 2493 var keys: std.ArrayList(u8) = .empty; 2494 var count: usize = 0; 2495 var held = false; 2496 var lines = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 2497 while (lines.next()) |line| { 2498 const line_fingerprint = User.fingerprintOfKey(line) orelse continue; 2499 if (std.mem.eql(u8, &line_fingerprint, fingerprint)) { 2500 held = true; 2501 if (added == null) continue; 2502 } 2503 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2504 try keys.appendSlice(arena.allocator(), line); 2505 count += 1; 2506 } 2507 if (added) |key| { 2508 if (held) return error.KeyAdded; 2509 if (count >= User.ssh_key_max_count) return error.TooManyKeys; 2510 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2511 try keys.appendSlice(arena.allocator(), key); 2512 } else if (!held) return; 2513 2514 var event = user.event; 2515 event.ssh_keys = keys.items; 2516 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2517 .id = std.fmt.bytesToHex(user_id.*, .lower), 2518 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2519 .author = .{ .name = event.name, .email = event.email }, 2520 .event = .{ .user = event }, 2521 }}); 2522 } 2523 2524 // consume a new repo's event into its owner's user repo and mark it active 2525 fn writeRepoEvent( 2526 io: std.Io, 2527 allocator: std.mem.Allocator, 2528 users_dir: []const u8, 2529 user_repo: *rp.Repo(.xit, user_repo_opts), 2530 owner_id: *const [event_id_size]u8, 2531 owner: CommitAuthor, 2532 id_bytes: *const [event_id_size]u8, 2533 name: []const u8, 2534 description: []const u8, 2535 read_access: Repo.Access, 2536 ) !void { 2537 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2538 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2539 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2540 .timestamp = timestamp, 2541 .author = owner, 2542 .event = .{ .repo = .{ 2543 .user_id = std.fmt.bytesToHex(owner_id.*, .lower), 2544 .name = name, 2545 .description = description, 2546 .read_access = read_access, 2547 } }, 2548 }}); 2549 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2550 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2551 }; 2552 } 2553 2554 // 2555 // reading from xitdb 2556 // 2557 2558 // read just `Fields`, a subset of `T.Record`, from the record with event id 2559 // `id`, or null when there is none 2560 pub fn readRecordSubset( 2561 comptime T: type, 2562 comptime Fields: type, 2563 comptime DB: type, 2564 comptime hash_kind: hash.HashKind, 2565 haxy_moment: DB.HashMap(.read_only), 2566 arena: *std.heap.ArenaAllocator, 2567 id: []const u8, 2568 ) !?Fields { 2569 comptime assertFieldSubset(Fields, T.Record); 2570 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2571 const records = try DB.HashMap(.read_only).init(records_cursor); 2572 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2573 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2574 } 2575 2576 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2577 const info = @typeInfo(Sub).@"struct"; 2578 for (info.field_names, info.field_types) |field_name, field_type| { 2579 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2580 const FullField = @FieldType(Full, field_name); 2581 if (@typeInfo(field_type) == .@"struct") { 2582 assertFieldSubset(field_type, FullField); 2583 } else if (field_type != FullField) { 2584 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2585 } 2586 } 2587 } 2588 2589 pub fn read( 2590 comptime T: type, 2591 comptime DB: type, 2592 comptime hash_kind: hash.HashKind, 2593 arena: *std.heap.ArenaAllocator, 2594 map: DB.HashMap(.read_only), 2595 ) !T { 2596 var event: T = undefined; 2597 switch (@typeInfo(T)) { 2598 .@"struct" => |struct_info| { 2599 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2600 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2601 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2602 } 2603 }, 2604 else => @compileError("read expects a struct"), 2605 } 2606 return event; 2607 } 2608 2609 fn readField( 2610 comptime Field: type, 2611 comptime DB: type, 2612 comptime hash_kind: hash.HashKind, 2613 arena: *std.heap.ArenaAllocator, 2614 cursor_maybe: ?DB.Cursor(.read_only), 2615 ) !Field { 2616 if (@typeInfo(Field) == .optional) { 2617 // a missing key or a null union payload is null 2618 const cursor = cursor_maybe orelse return null; 2619 if (cursor.slot().tag == .none) return null; 2620 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2621 } 2622 const cursor = cursor_maybe orelse return error.NotFound; 2623 switch (@typeInfo(Field)) { 2624 .pointer => |pointer_info| { 2625 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2626 @compileError("unsupported read field type: " ++ @typeName(Field)); 2627 } 2628 return try cursor.readBytesAlloc(arena.allocator(), null); 2629 }, 2630 .array => |array_info| { 2631 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2632 var bytes: Field = undefined; 2633 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2634 return bytes; 2635 }, 2636 .bool => { 2637 var buffer: [5]u8 = undefined; 2638 const bytes = try cursor.readBytesObject(&buffer); 2639 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2640 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2641 if (std.mem.eql(u8, bytes.value, "true")) return true; 2642 if (std.mem.eql(u8, bytes.value, "false")) return false; 2643 return error.InvalidBool; 2644 }, 2645 .int => |int_info| return switch (int_info.signedness) { 2646 .unsigned => @intCast(try cursor.readUint()), 2647 .signed => @intCast(try cursor.readInt()), 2648 }, 2649 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2650 .@"union" => |union_info| { 2651 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2652 switch (cursor.slot().tag) { 2653 .bytes, .short_bytes => { 2654 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2655 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2656 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2657 return @unionInit(Field, variant_name, {}); 2658 } 2659 } 2660 return error.InvalidUnion; 2661 }, 2662 .hash_map => { 2663 const variants = try DB.HashMap(.read_only).init(cursor); 2664 var iter = try variants.iterator(); 2665 const entry = (try iter.next()) orelse return error.InvalidUnion; 2666 const pair = try entry.readKeyValuePair(); 2667 if (try iter.next() != null) return error.InvalidUnion; 2668 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2669 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2670 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2671 } 2672 } 2673 return error.InvalidUnion; 2674 }, 2675 else => return error.InvalidUnion, 2676 } 2677 }, 2678 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2679 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2680 } 2681 } 2682 2683 // whether two events carry the same data 2684 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2685 switch (@typeInfo(T)) { 2686 .@"struct" => |struct_info| { 2687 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2688 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2689 } 2690 }, 2691 else => @compileError("fieldsEqual expects a struct"), 2692 } 2693 2694 return true; 2695 } 2696 2697 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2698 switch (@typeInfo(Field)) { 2699 .pointer => |pointer_info| { 2700 if (pointer_info.size == .slice and pointer_info.child == u8) { 2701 return std.mem.eql(u8, a, b); 2702 } else { 2703 @compileError("unsupported field type: " ++ @typeName(Field)); 2704 } 2705 }, 2706 .array => |array_info| { 2707 if (array_info.child == u8) { 2708 return std.mem.eql(u8, &a, &b); 2709 } else { 2710 @compileError("unsupported field type: " ++ @typeName(Field)); 2711 } 2712 }, 2713 .void => return true, 2714 .bool, .int, .@"enum" => return a == b, 2715 .@"union" => { 2716 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2717 return switch (a) { 2718 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2719 }; 2720 }, 2721 .@"struct" => return fieldsEqual(Field, a, b), 2722 .optional => |optional_info| { 2723 if (a) |a_value| { 2724 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2725 return false; 2726 } 2727 return b == null; 2728 }, 2729 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2730 } 2731 } 2732 2733 // 2734 // writing to xitdb 2735 // 2736 2737 pub fn upsert( 2738 comptime T: type, 2739 comptime DB: type, 2740 comptime hash_kind: hash.HashKind, 2741 map: DB.HashMap(.read_write), 2742 event: T, 2743 ) !void { 2744 switch (@typeInfo(T)) { 2745 .@"struct" => |struct_info| { 2746 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2747 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2748 } 2749 }, 2750 else => @compileError("upsert expects a struct"), 2751 } 2752 } 2753 2754 fn upsertField( 2755 comptime DB: type, 2756 comptime hash_kind: hash.HashKind, 2757 map: DB.HashMap(.read_write), 2758 comptime field_name: []const u8, 2759 comptime Field: type, 2760 value: Field, 2761 ) !void { 2762 const key = hash.hashInt(hash_kind, field_name); 2763 2764 switch (@typeInfo(Field)) { 2765 .pointer => |pointer_info| { 2766 if (pointer_info.size == .slice and pointer_info.child == u8) { 2767 try upsertBytes(DB, hash_kind, map, key, value); 2768 } else { 2769 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2770 } 2771 }, 2772 .array => |array_info| { 2773 if (array_info.child == u8) { 2774 try upsertBytes(DB, hash_kind, map, key, &value); 2775 } else { 2776 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2777 } 2778 }, 2779 .int => |int_info| switch (int_info.signedness) { 2780 .unsigned => { 2781 if (try map.getCursor(key)) |value_cursor| { 2782 if (try value_cursor.readUint() == value) { 2783 return; 2784 } 2785 } 2786 2787 try map.put(key, .{ .uint = value }); 2788 }, 2789 .signed => { 2790 if (try map.getCursor(key)) |value_cursor| { 2791 if (try value_cursor.readInt() == value) { 2792 return; 2793 } 2794 } 2795 2796 try map.put(key, .{ .int = value }); 2797 }, 2798 }, 2799 .bool => { 2800 const bytes = if (value) "true" else "false"; 2801 if (try map.getCursor(key)) |value_cursor| { 2802 var buffer: [5]u8 = undefined; 2803 const existing = try value_cursor.readBytesObject(&buffer); 2804 if (existing.format_tag) |format_tag| { 2805 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2806 return; 2807 } 2808 } 2809 } 2810 2811 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2812 }, 2813 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2814 .@"union" => switch (value) { 2815 inline else => |payload, tag| { 2816 if (@TypeOf(payload) == void) { 2817 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2818 } else { 2819 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2820 if (try map.getCursor(key)) |cursor| { 2821 switch (cursor.slot().tag) { 2822 .hash_map => { 2823 const variants = try DB.HashMap(.read_only).init(cursor); 2824 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2825 }, 2826 else => try map.put(key, .{ .slot = null }), 2827 } 2828 } 2829 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2830 if (@typeInfo(@TypeOf(payload)) == .optional) { 2831 // keep the variant even when its payload is null 2832 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2833 } 2834 if (try variants.getCursor(tag_key)) |cursor| { 2835 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2836 } 2837 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2838 } 2839 }, 2840 }, 2841 .optional => |optional_info| { 2842 // a missing key is null 2843 if (value) |child| { 2844 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2845 } else { 2846 _ = try map.remove(key); 2847 } 2848 }, 2849 .@"struct" => try upsert( 2850 Field, 2851 DB, 2852 hash_kind, 2853 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2854 value, 2855 ), 2856 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2857 } 2858 } 2859 2860 fn upsertBytes( 2861 comptime DB: type, 2862 comptime hash_kind: hash.HashKind, 2863 map: DB.HashMap(.read_write), 2864 key: hash.HashInt(hash_kind), 2865 value: []const u8, 2866 ) !void { 2867 var existing_cursor_maybe = try map.getCursor(key); 2868 if (existing_cursor_maybe) |*existing_cursor| { 2869 if (try bytesEqual(DB, existing_cursor, value)) { 2870 return; 2871 } 2872 } 2873 2874 try map.put(key, .{ .bytes = value }); 2875 } 2876 2877 fn bytesEqual( 2878 comptime DB: type, 2879 cursor: *DB.Cursor(.read_only), 2880 value: []const u8, 2881 ) !bool { 2882 switch (cursor.slot().tag) { 2883 .bytes, .short_bytes => {}, 2884 else => return false, 2885 } 2886 var read_buffer: [1024]u8 = undefined; 2887 var reader = try cursor.reader(&read_buffer); 2888 if (reader.size != value.len) { 2889 return false; 2890 } 2891 2892 var chunk_buffer: [1024]u8 = undefined; 2893 var offset: usize = 0; 2894 while (offset < value.len) { 2895 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2896 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2897 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2898 return false; 2899 } 2900 offset += chunk_len; 2901 } 2902 2903 return true; 2904 } 2905 2906 // 2907 // CommitIterator 2908 // 2909 // differs from xit's ObjectIterator in a few ways: 2910 // 2911 // 1. iterates parents first, rather than children first 2912 // 2. `next` only returns the object id, not the full Object 2913 // 3. stores its temporary state in a file on disk to avoid OOMs 2914 // 2915 2916 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2917 return struct { 2918 const DB = EventDB(repo_opts.hash); 2919 // a plain file is used for the scratch db because each write outside 2920 // a transaction is synced anyway, so buffering would gain nothing 2921 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2922 const db_name = "haxy-repo-events.db"; 2923 2924 repo_dir: std.Io.Dir, 2925 db_file: std.Io.File, 2926 db: *TempDB, 2927 // map of each object id to its children 2928 parent_to_children: TempDB.HashMap(.read_write), 2929 // tracking pending parents is necessary because a child can only 2930 // be returned after all of its unconsumed parents have been returned 2931 child_to_pending_parents: TempDB.HashMap(.read_write), 2932 // queue of object ids that are ready to be returned from `next` 2933 ready_queue: TempDB.ArrayList(.read_write), 2934 ready_queue_index: u64, 2935 // the object id at the tip of this branch 2936 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2937 // the object id furthest back in the history that hasn't been consumed 2938 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2939 2940 pub fn init( 2941 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2942 io: std.Io, 2943 allocator: std.mem.Allocator, 2944 consumed_object_ids: DB.HashMap(.read_only), 2945 ref: rf.Ref, 2946 ) !CommitIterator(repo_kind, repo_opts) { 2947 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2948 errdefer { 2949 db_file.close(io); 2950 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2951 } 2952 2953 // cursors point at the db, so it needs a stable address 2954 const db_ptr = try allocator.create(TempDB); 2955 errdefer allocator.destroy(db_ptr); 2956 // the db is scratch state that gets deleted after iteration, so 2957 // there is nothing worth fsyncing 2958 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2959 2960 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2961 2962 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2963 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2964 2965 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2966 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2967 2968 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2969 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2970 2971 var self = CommitIterator(repo_kind, repo_opts){ 2972 .repo_dir = state.core.repo_dir, 2973 .db_file = db_file, 2974 .db = db_ptr, 2975 .parent_to_children = parent_to_children, 2976 .child_to_pending_parents = child_to_pending_parents, 2977 .ready_queue = ready_queue, 2978 .ready_queue_index = 0, 2979 .newest_object_id = null, 2980 .oldest_object_id = null, 2981 }; 2982 errdefer self.deinit(io, allocator); 2983 2984 try self.collect(state, io, allocator, consumed_object_ids, ref); 2985 2986 return self; 2987 } 2988 2989 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2990 self.db_file.close(io); 2991 self.repo_dir.deleteFile(io, db_name) catch {}; 2992 allocator.destroy(self.db); 2993 } 2994 2995 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2996 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2997 2998 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2999 self.ready_queue_index += 1; 3000 3001 try self.enqueueChildren(&oid); 3002 return oid; 3003 } 3004 3005 fn collect( 3006 self: *CommitIterator(repo_kind, repo_opts), 3007 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 3008 io: std.Io, 3009 allocator: std.mem.Allocator, 3010 consumed_object_ids: DB.HashMap(.read_only), 3011 ref: rf.Ref, 3012 ) !void { 3013 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 3014 3015 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 3016 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 3017 var walk_queue_index: u64 = 0; 3018 3019 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 3020 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 3021 3022 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 3023 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 3024 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 3025 try walk_queue.append(.{ .bytes = &head_oid }); 3026 3027 while (walk_queue_index < try walk_queue.count()) { 3028 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 3029 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 3030 3031 walk_queue_index += 1; 3032 3033 // if we've seen this object id, skip it 3034 if (null != try seen_object_ids.getCursor(oid_int)) { 3035 continue; 3036 } 3037 3038 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 3039 3040 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 3041 defer commit_object.deinit(); 3042 3043 // if this object id has already been consumed, skip it 3044 if (null != try consumed_object_ids.getCursor(oid_int)) { 3045 continue; 3046 } 3047 3048 if (self.newest_object_id == null) self.newest_object_id = oid; 3049 self.oldest_object_id = oid; 3050 3051 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 3052 var pending_parent_count: u64 = 0; 3053 for (parent_oids) |*parent_oid| { 3054 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 3055 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 3056 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 3057 3058 // if this object id has already been consumed, skip it 3059 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 3060 continue; 3061 } 3062 3063 // if this object id hasn't already been seen, add it to the walk queue 3064 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 3065 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 3066 } 3067 3068 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 3069 const children = try TempDB.HashSet(.read_write).init(children_cursor); 3070 try children.put(oid_int, .{ .bytes = &oid }); 3071 pending_parent_count += 1; 3072 } 3073 3074 if (pending_parent_count == 0) { 3075 try self.ready_queue.append(.{ .bytes = &oid }); 3076 } else { 3077 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 3078 } 3079 } 3080 } 3081 3082 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 3083 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 3084 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 3085 const children = try TempDB.HashSet(.read_only).init(children_cursor); 3086 var children_iter = try children.iterator(); 3087 3088 while (try children_iter.next()) |*child_cursor| { 3089 const kv_pair = try child_cursor.readKeyValuePair(); 3090 const child_oid_int = kv_pair.hash; 3091 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 3092 const pending_parent_count = try pending_parent_cursor.readUint(); 3093 3094 if (pending_parent_count <= 1) { 3095 _ = try self.child_to_pending_parents.remove(child_oid_int); 3096 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 3097 try self.ready_queue.append(.{ .bytes = &child_oid }); 3098 } else { 3099 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 3100 } 3101 } 3102 } 3103 3104 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 3105 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 3106 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 3107 _ = try oid_cursor.readBytes(&oid); 3108 return oid; 3109 } 3110 }; 3111 } 3112