╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
2011 repo_name: []const u8, 2012 create_options_maybe: ?CreateRepoOptions, 2013 ) !?RepoLocation { 2014 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 2015 error.RepoNotFound => return null, 2016 else => |e| return e, 2017 }; 2018 defer admin_repo.deinit(io, allocator); 2019 2020 var arena = std.heap.ArenaAllocator.init(allocator); 2021 defer arena.deinit(); 2022 2023 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 2024 2025 // an unknown owner can't own a repo, so the push is rejected 2026 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 2027 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 2028 defer user_repo.deinit(io, allocator); 2029 2030 // an already-registered repo reuses its event id, so a re-push (or a clone) 2031 // lands in the same repo 2032 if (try userMoment(&user_repo)) |moment| { 2033 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 2034 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 2035 } 2036 } 2037 2038 const create_options = create_options_maybe orelse return null; 2039 2040 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 2041 2042 var id_bytes: [event_id_size]u8 = undefined; 2043 io.random(&id_bytes); 2044 try writeRepoEvent(io, allocator, users_dir, &user_repo, &owner_user_id, .{ .name = owner.event.name, .email = owner.event.email }, &id_bytes, repo_name, "", create_options.read_access); 2045 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 2046 } 2047 2048 // create a bare repo with `hash_kind` and register it in its owner's user repo 2049 pub fn createRepo( 2050 io: std.Io, 2051 allocator: std.mem.Allocator, 2052 users_dir: []const u8, 2053 owner_id: *const [event_id_size]u8, 2054 owner: CommitAuthor, 2055 name: []const u8, 2056 description: []const u8, 2057 read_access: Repo.Access, 2058 hash_kind: hash.HashKind, 2059 ) !RepoLocation { 2060 try Repo.validateName(name); 2061 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2062 defer user_repo.deinit(io, allocator); 2063 if (try userMoment(&user_repo)) |moment| { 2064 var arena = std.heap.ArenaAllocator.init(allocator); 2065 defer arena.deinit(); 2066 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2067 } 2068 2069 var id_bytes: [event_id_size]u8 = undefined; 2070 io.random(&id_bytes); 2071 2072 // the directory comes first so a listed repo always has one 2073 { 2074 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2075 defer allocator.free(path); 2076 switch (hash_kind) { 2077 inline else => |kind| { 2078 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2079 defer repo.deinit(io, allocator); 2080 }, 2081 } 2082 } 2083 2084 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2085 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2086 } 2087 2088 // change the name, description, read access, and tab roles of the repo 2089 // named `old_name` in its owner's user repo 2090 pub fn updateRepo( 2091 io: std.Io, 2092 allocator: std.mem.Allocator, 2093 users_dir: []const u8, 2094 owner_id: *const [event_id_size]u8, 2095 author: CommitAuthor, 2096 old_name: []const u8, 2097 name: []const u8, 2098 description: []const u8, 2099 read_access: Repo.Access, 2100 discuss_role: ?Repo.Role, 2101 issue_role: ?Repo.Role, 2102 patch_role: ?Repo.Role, 2103 ) !void { 2104 try Repo.validateName(name); 2105 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2106 defer user_repo.deinit(io, allocator); 2107 var arena = std.heap.ArenaAllocator.init(allocator); 2108 defer arena.deinit(); 2109 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2110 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2111 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2112 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2113 } 2114 2115 var event = found.repo.event; 2116 event.name = name; 2117 event.description = description; 2118 event.read_access = read_access; 2119 event.discuss_role = discuss_role; 2120 event.issue_role = issue_role; 2121 event.patch_role = patch_role; 2122 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2123 .id = std.fmt.bytesToHex(found.event_id, .lower), 2124 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2125 .author = author, 2126 .event = .{ .repo = event }, 2127 }}); 2128 } 2129 2130 // grant `user_id` `role` on the repo `repo_id` in its owner's user repo, 2131 // replacing any role they held 2132 pub fn grantRole( 2133 io: std.Io, 2134 allocator: std.mem.Allocator, 2135 users_dir: []const u8, 2136 owner_id: *const [event_id_size]u8, 2137 repo_id: *const [event_id_size]u8, 2138 user_id: *const [event_id_size]u8, 2139 role: Repo.Role, 2140 author: CommitAuthor, 2141 ) !void { 2142 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2143 defer user_repo.deinit(io, allocator); 2144 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2145 .id = std.fmt.bytesToHex(Grant.idOf(repo_id, user_id), .lower), 2146 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2147 .author = author, 2148 .event = .{ .grant = .{ .target_id = std.fmt.bytesToHex(repo_id.*, .lower), .user_id = std.fmt.bytesToHex(user_id.*, .lower), .role = role } }, 2149 }}); 2150 } 2151 2152 // revoke `user_id`'s grant on the repo `repo_id` in its owner's user repo 2153 pub fn revokeRole( 2154 io: std.Io, 2155 allocator: std.mem.Allocator, 2156 users_dir: []const u8, 2157 owner_id: *const [event_id_size]u8, 2158 repo_id: *const [event_id_size]u8, 2159 user_id: *const [event_id_size]u8, 2160 author: CommitAuthor, 2161 ) !void { 2162 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2163 defer user_repo.deinit(io, allocator); 2164 // a revoked grant stays in the kind index, which is all `remove` checks 2165 { 2166 var arena = std.heap.ArenaAllocator.init(allocator); 2167 defer arena.deinit(); 2168 const moment = (try userMoment(&user_repo)) orelse return error.EventNotFound; 2169 if (try Grant.readRole(UserDB, user_repo_opts.hash, moment, &arena, repo_id, user_id) == null) return error.EventNotFound; 2170 } 2171 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, &Grant.idOf(repo_id, user_id), .grant, author); 2172 } 2173 2174 // create a user and their user repo, returning the new user's id 2175 pub fn createUser( 2176 io: std.Io, 2177 allocator: std.mem.Allocator, 2178 users_dir: []const u8, 2179 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2180 name: []const u8, 2181 email: []const u8, 2182 password: []const u8, 2183 password_again: []const u8, 2184 ) ![event_id_size]u8 { 2185 try User.validateName(name); 2186 if (email.len == 0) return error.EmailEmpty; 2187 if (password.len == 0) return error.PasswordEmpty; 2188 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2189 // a fresh admin repo has no moment until its first event 2190 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2191 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2192 var arena = std.heap.ArenaAllocator.init(allocator); 2193 defer arena.deinit(); 2194 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2195 } else |err| switch (err) { 2196 error.NotFound => {}, 2197 else => |e| return e, 2198 } 2199 2200 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2201 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2202 2203 var id_bytes: [event_id_size]u8 = undefined; 2204 io.random(&id_bytes); 2205 2206 // the user repo comes first so a listed user can always create repos 2207 { 2208 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2209 defer allocator.free(path); 2210 var user_repo = try initUserRepo(io, allocator, path); 2211 defer user_repo.deinit(io, allocator); 2212 } 2213 2214 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2215 .id = std.fmt.bytesToHex(id_bytes, .lower), 2216 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2217 .author = .{ .name = name, .email = email }, 2218 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2219 }}); 2220 return id_bytes; 2221 } 2222 2223 // change a user's email, and their password when the password fields are 2224 // filled in 2225 pub fn updateUser( 2226 io: std.Io, 2227 allocator: std.mem.Allocator, 2228 users_dir: []const u8, 2229 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2230 user_id: *const [event_id_size]u8, 2231 email: []const u8, 2232 current_password: []const u8, 2233 new_password: []const u8, 2234 new_password_again: []const u8, 2235 ) !void { 2236 if (email.len == 0) return error.EmailEmpty; 2237 var arena = std.heap.ArenaAllocator.init(allocator); 2238 defer arena.deinit(); 2239 const moment = try currentMoment(admin_repo_opts, admin_repo); 2240 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2241 if (user.removed) return error.NotFound; 2242 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; 2243 2244 var event = user.event; 2245 event.email = email; 2246 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2247 if (current_password.len + new_password.len + new_password_again.len > 0) { 2248 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2249 if (new_password.len == 0) return error.PasswordEmpty; 2250 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2251 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2252 } 2253 2254 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2255 .id = std.fmt.bytesToHex(user_id.*, .lower), 2256 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2257 .author = .{ .name = event.name, .email = email }, 2258 .event = .{ .user = event }, 2259 }}); 2260 } 2261 2262 // consume a new repo's event into its owner's user repo and mark it active 2263 fn writeRepoEvent( 2264 io: std.Io, 2265 allocator: std.mem.Allocator, 2266 users_dir: []const u8, 2267 user_repo: *rp.Repo(.xit, user_repo_opts), 2268 owner_id: *const [event_id_size]u8, 2269 owner: CommitAuthor, 2270 id_bytes: *const [event_id_size]u8, 2271 name: []const u8, 2272 description: []const u8, 2273 read_access: Repo.Access, 2274 ) !void { 2275 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2276 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2277 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2278 .timestamp = timestamp, 2279 .author = owner, 2280 .event = .{ .repo = .{ 2281 .user_id = std.fmt.bytesToHex(owner_id.*, .lower), 2282 .name = name, 2283 .description = description, 2284 .read_access = read_access, 2285 } }, 2286 }}); 2287 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2288 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2289 }; 2290 } 2291 2292 // 2293 // reading from xitdb 2294 // 2295 2296 // read just `Fields`, a subset of `T.Record`, from the record with event id 2297 // `id`, or null when there is none 2298 pub fn readRecordSubset( 2299 comptime T: type, 2300 comptime Fields: type, 2301 comptime DB: type, 2302 comptime hash_kind: hash.HashKind, 2303 haxy_moment: DB.HashMap(.read_only), 2304 arena: *std.heap.ArenaAllocator, 2305 id: []const u8, 2306 ) !?Fields { 2307 comptime assertFieldSubset(Fields, T.Record); 2308 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2309 const records = try DB.HashMap(.read_only).init(records_cursor); 2310 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2311 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2312 } 2313 2314 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2315 const info = @typeInfo(Sub).@"struct"; 2316 for (info.field_names, info.field_types) |field_name, field_type| { 2317 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2318 const FullField = @FieldType(Full, field_name); 2319 if (@typeInfo(field_type) == .@"struct") { 2320 assertFieldSubset(field_type, FullField); 2321 } else if (field_type != FullField) { 2322 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2323 } 2324 } 2325 } 2326 2327 pub fn read( 2328 comptime T: type, 2329 comptime DB: type, 2330 comptime hash_kind: hash.HashKind, 2331 arena: *std.heap.ArenaAllocator, 2332 map: DB.HashMap(.read_only), 2333 ) !T { 2334 var event: T = undefined; 2335 switch (@typeInfo(T)) { 2336 .@"struct" => |struct_info| { 2337 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2338 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2339 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2340 } 2341 }, 2342 else => @compileError("read expects a struct"), 2343 } 2344 return event; 2345 } 2346 2347 fn readField( 2348 comptime Field: type, 2349 comptime DB: type, 2350 comptime hash_kind: hash.HashKind, 2351 arena: *std.heap.ArenaAllocator, 2352 cursor_maybe: ?DB.Cursor(.read_only), 2353 ) !Field { 2354 if (@typeInfo(Field) == .optional) { 2355 // a missing key or a null union payload is null 2356 const cursor = cursor_maybe orelse return null; 2357 if (cursor.slot().tag == .none) return null; 2358 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2359 } 2360 const cursor = cursor_maybe orelse return error.NotFound; 2361 switch (@typeInfo(Field)) { 2362 .pointer => |pointer_info| { 2363 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2364 @compileError("unsupported read field type: " ++ @typeName(Field)); 2365 } 2366 return try cursor.readBytesAlloc(arena.allocator(), null); 2367 }, 2368 .array => |array_info| { 2369 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2370 var bytes: Field = undefined; 2371 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2372 return bytes; 2373 }, 2374 .bool => { 2375 var buffer: [5]u8 = undefined; 2376 const bytes = try cursor.readBytesObject(&buffer); 2377 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2378 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2379 if (std.mem.eql(u8, bytes.value, "true")) return true; 2380 if (std.mem.eql(u8, bytes.value, "false")) return false; 2381 return error.InvalidBool; 2382 }, 2383 .int => |int_info| return switch (int_info.signedness) { 2384 .unsigned => @intCast(try cursor.readUint()), 2385 .signed => @intCast(try cursor.readInt()), 2386 }, 2387 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2388 .@"union" => |union_info| { 2389 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2390 switch (cursor.slot().tag) { 2391 .bytes, .short_bytes => { 2392 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2393 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2394 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2395 return @unionInit(Field, variant_name, {}); 2396 } 2397 } 2398 return error.InvalidUnion; 2399 }, 2400 .hash_map => { 2401 const variants = try DB.HashMap(.read_only).init(cursor); 2402 var iter = try variants.iterator(); 2403 const entry = (try iter.next()) orelse return error.InvalidUnion; 2404 const pair = try entry.readKeyValuePair(); 2405 if (try iter.next() != null) return error.InvalidUnion; 2406 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2407 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2408 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2409 } 2410 } 2411 return error.InvalidUnion; 2412 }, 2413 else => return error.InvalidUnion, 2414 } 2415 }, 2416 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2417 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2418 } 2419 } 2420 2421 // whether two events carry the same data 2422 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2423 switch (@typeInfo(T)) { 2424 .@"struct" => |struct_info| { 2425 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2426 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2427 } 2428 }, 2429 else => @compileError("fieldsEqual expects a struct"), 2430 } 2431 2432 return true; 2433 } 2434 2435 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2436 switch (@typeInfo(Field)) { 2437 .pointer => |pointer_info| { 2438 if (pointer_info.size == .slice and pointer_info.child == u8) { 2439 return std.mem.eql(u8, a, b); 2440 } else { 2441 @compileError("unsupported field type: " ++ @typeName(Field)); 2442 } 2443 }, 2444 .array => |array_info| { 2445 if (array_info.child == u8) { 2446 return std.mem.eql(u8, &a, &b); 2447 } else { 2448 @compileError("unsupported field type: " ++ @typeName(Field)); 2449 } 2450 }, 2451 .void => return true, 2452 .bool, .int, .@"enum" => return a == b, 2453 .@"union" => { 2454 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2455 return switch (a) { 2456 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2457 }; 2458 }, 2459 .@"struct" => return fieldsEqual(Field, a, b), 2460 .optional => |optional_info| { 2461 if (a) |a_value| { 2462 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2463 return false; 2464 } 2465 return b == null; 2466 }, 2467 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2468 } 2469 } 2470 2471 // 2472 // writing to xitdb 2473 // 2474 2475 pub fn upsert( 2476 comptime T: type, 2477 comptime DB: type, 2478 comptime hash_kind: hash.HashKind, 2479 map: DB.HashMap(.read_write), 2480 event: T, 2481 ) !void { 2482 switch (@typeInfo(T)) { 2483 .@"struct" => |struct_info| { 2484 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2485 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2486 } 2487 }, 2488 else => @compileError("upsert expects a struct"), 2489 } 2490 } 2491 2492 fn upsertField( 2493 comptime DB: type, 2494 comptime hash_kind: hash.HashKind, 2495 map: DB.HashMap(.read_write), 2496 comptime field_name: []const u8, 2497 comptime Field: type, 2498 value: Field, 2499 ) !void { 2500 const key = hash.hashInt(hash_kind, field_name); 2501 2502 switch (@typeInfo(Field)) { 2503 .pointer => |pointer_info| { 2504 if (pointer_info.size == .slice and pointer_info.child == u8) { 2505 try upsertBytes(DB, hash_kind, map, key, value); 2506 } else { 2507 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2508 } 2509 }, 2510 .array => |array_info| { 2511 if (array_info.child == u8) { 2512 try upsertBytes(DB, hash_kind, map, key, &value); 2513 } else { 2514 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2515 } 2516 }, 2517 .int => |int_info| switch (int_info.signedness) { 2518 .unsigned => { 2519 if (try map.getCursor(key)) |value_cursor| { 2520 if (try value_cursor.readUint() == value) { 2521 return; 2522 } 2523 } 2524 2525 try map.put(key, .{ .uint = value }); 2526 }, 2527 .signed => { 2528 if (try map.getCursor(key)) |value_cursor| { 2529 if (try value_cursor.readInt() == value) { 2530 return; 2531 } 2532 } 2533 2534 try map.put(key, .{ .int = value }); 2535 }, 2536 }, 2537 .bool => { 2538 const bytes = if (value) "true" else "false"; 2539 if (try map.getCursor(key)) |value_cursor| { 2540 var buffer: [5]u8 = undefined; 2541 const existing = try value_cursor.readBytesObject(&buffer); 2542 if (existing.format_tag) |format_tag| { 2543 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2544 return; 2545 } 2546 } 2547 } 2548 2549 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2550 }, 2551 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2552 .@"union" => switch (value) { 2553 inline else => |payload, tag| { 2554 if (@TypeOf(payload) == void) { 2555 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2556 } else { 2557 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2558 if (try map.getCursor(key)) |cursor| { 2559 switch (cursor.slot().tag) { 2560 .hash_map => { 2561 const variants = try DB.HashMap(.read_only).init(cursor); 2562 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2563 }, 2564 else => try map.put(key, .{ .slot = null }), 2565 } 2566 } 2567 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2568 if (@typeInfo(@TypeOf(payload)) == .optional) { 2569 // keep the variant even when its payload is null 2570 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2571 } 2572 if (try variants.getCursor(tag_key)) |cursor| { 2573 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2574 } 2575 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2576 } 2577 }, 2578 }, 2579 .optional => |optional_info| { 2580 // a missing key is null 2581 if (value) |child| { 2582 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2583 } else { 2584 _ = try map.remove(key); 2585 } 2586 }, 2587 .@"struct" => try upsert( 2588 Field, 2589 DB, 2590 hash_kind, 2591 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2592 value, 2593 ), 2594 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2595 } 2596 } 2597 2598 fn upsertBytes( 2599 comptime DB: type, 2600 comptime hash_kind: hash.HashKind, 2601 map: DB.HashMap(.read_write), 2602 key: hash.HashInt(hash_kind), 2603 value: []const u8, 2604 ) !void { 2605 var existing_cursor_maybe = try map.getCursor(key); 2606 if (existing_cursor_maybe) |*existing_cursor| { 2607 if (try bytesEqual(DB, existing_cursor, value)) { 2608 return; 2609 } 2610 } 2611 2612 try map.put(key, .{ .bytes = value }); 2613 } 2614 2615 fn bytesEqual( 2616 comptime DB: type, 2617 cursor: *DB.Cursor(.read_only), 2618 value: []const u8, 2619 ) !bool { 2620 switch (cursor.slot().tag) { 2621 .bytes, .short_bytes => {}, 2622 else => return false, 2623 } 2624 var read_buffer: [1024]u8 = undefined; 2625 var reader = try cursor.reader(&read_buffer); 2626 if (reader.size != value.len) { 2627 return false; 2628 } 2629 2630 var chunk_buffer: [1024]u8 = undefined; 2631 var offset: usize = 0; 2632 while (offset < value.len) { 2633 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2634 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2635 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2636 return false; 2637 } 2638 offset += chunk_len; 2639 } 2640 2641 return true; 2642 } 2643 2644 // 2645 // CommitIterator 2646 // 2647 // differs from xit's ObjectIterator in a few ways: 2648 // 2649 // 1. iterates parents first, rather than children first 2650 // 2. `next` only returns the object id, not the full Object 2651 // 3. stores its temporary state in a file on disk to avoid OOMs 2652 // 2653 2654 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2655 return struct { 2656 const DB = EventDB(repo_opts.hash); 2657 // a plain file is used for the scratch db because each write outside 2658 // a transaction is synced anyway, so buffering would gain nothing 2659 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2660 const db_name = "haxy-repo-events.db"; 2661 2662 repo_dir: std.Io.Dir, 2663 db_file: std.Io.File, 2664 db: *TempDB, 2665 // map of each object id to its children 2666 parent_to_children: TempDB.HashMap(.read_write), 2667 // tracking pending parents is necessary because a child can only 2668 // be returned after all of its unconsumed parents have been returned 2669 child_to_pending_parents: TempDB.HashMap(.read_write), 2670 // queue of object ids that are ready to be returned from `next` 2671 ready_queue: TempDB.ArrayList(.read_write), 2672 ready_queue_index: u64, 2673 // the object id at the tip of this branch 2674 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2675 // the object id furthest back in the history that hasn't been consumed 2676 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2677 2678 pub fn init( 2679 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2680 io: std.Io, 2681 allocator: std.mem.Allocator, 2682 consumed_object_ids: DB.HashMap(.read_only), 2683 ref: rf.Ref, 2684 ) !CommitIterator(repo_kind, repo_opts) { 2685 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2686 errdefer { 2687 db_file.close(io); 2688 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2689 } 2690 2691 // cursors point at the db, so it needs a stable address 2692 const db_ptr = try allocator.create(TempDB); 2693 errdefer allocator.destroy(db_ptr); 2694 // the db is scratch state that gets deleted after iteration, so 2695 // there is nothing worth fsyncing 2696 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2697 2698 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2699 2700 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2701 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2702 2703 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2704 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2705 2706 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2707 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2708 2709 var self = CommitIterator(repo_kind, repo_opts){ 2710 .repo_dir = state.core.repo_dir, 2711 .db_file = db_file, 2712 .db = db_ptr, 2713 .parent_to_children = parent_to_children, 2714 .child_to_pending_parents = child_to_pending_parents, 2715 .ready_queue = ready_queue, 2716 .ready_queue_index = 0, 2717 .newest_object_id = null, 2718 .oldest_object_id = null, 2719 }; 2720 errdefer self.deinit(io, allocator); 2721 2722 try self.collect(state, io, allocator, consumed_object_ids, ref); 2723 2724 return self; 2725 } 2726 2727 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2728 self.db_file.close(io); 2729 self.repo_dir.deleteFile(io, db_name) catch {}; 2730 allocator.destroy(self.db); 2731 } 2732 2733 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2734 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2735 2736 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2737 self.ready_queue_index += 1; 2738 2739 try self.enqueueChildren(&oid); 2740 return oid; 2741 } 2742 2743 fn collect( 2744 self: *CommitIterator(repo_kind, repo_opts), 2745 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2746 io: std.Io, 2747 allocator: std.mem.Allocator, 2748 consumed_object_ids: DB.HashMap(.read_only), 2749 ref: rf.Ref, 2750 ) !void { 2751 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2752 2753 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2754 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2755 var walk_queue_index: u64 = 0; 2756 2757 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2758 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2759 2760 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2761 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2762 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2763 try walk_queue.append(.{ .bytes = &head_oid }); 2764 2765 while (walk_queue_index < try walk_queue.count()) { 2766 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2767 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2768 2769 walk_queue_index += 1; 2770 2771 // if we've seen this object id, skip it 2772 if (null != try seen_object_ids.getCursor(oid_int)) { 2773 continue; 2774 } 2775 2776 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2777 2778 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2779 defer commit_object.deinit(); 2780 2781 // if this object id has already been consumed, skip it 2782 if (null != try consumed_object_ids.getCursor(oid_int)) { 2783 continue; 2784 } 2785 2786 if (self.newest_object_id == null) self.newest_object_id = oid; 2787 self.oldest_object_id = oid; 2788 2789 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2790 var pending_parent_count: u64 = 0; 2791 for (parent_oids) |*parent_oid| { 2792 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2793 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2794 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2795 2796 // if this object id has already been consumed, skip it 2797 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2798 continue; 2799 } 2800 2801 // if this object id hasn't already been seen, add it to the walk queue 2802 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2803 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2804 } 2805 2806 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2807 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2808 try children.put(oid_int, .{ .bytes = &oid }); 2809 pending_parent_count += 1; 2810 } 2811 2812 if (pending_parent_count == 0) { 2813 try self.ready_queue.append(.{ .bytes = &oid }); 2814 } else { 2815 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2816 } 2817 } 2818 } 2819 2820 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2821 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2822 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2823 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2824 var children_iter = try children.iterator(); 2825 2826 while (try children_iter.next()) |*child_cursor| { 2827 const kv_pair = try child_cursor.readKeyValuePair(); 2828 const child_oid_int = kv_pair.hash; 2829 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2830 const pending_parent_count = try pending_parent_cursor.readUint(); 2831 2832 if (pending_parent_count <= 1) { 2833 _ = try self.child_to_pending_parents.remove(child_oid_int); 2834 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2835 try self.ready_queue.append(.{ .bytes = &child_oid }); 2836 } else { 2837 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2838 } 2839 } 2840 } 2841 2842 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2843 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2844 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2845 _ = try oid_cursor.readBytes(&oid); 2846 return oid; 2847 } 2848 }; 2849 } 2850