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