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