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