╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1908 @memcpy(key[@sizeOf(u64)..], event_id); 1909 return key; 1910 } 1911 1912 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1913 return orderKey(std.math.maxInt(u64) - order, event_id); 1914 } 1915 1916 pub fn removedRecord( 1917 comptime T: type, 1918 comptime DB: type, 1919 comptime hash_kind: hash.HashKind, 1920 haxy_moment: DB.HashMap(.read_only), 1921 existing_maybe: ?T, 1922 ) !T { 1923 var record = existing_maybe orelse return error.EventNotFound; 1924 record.removed = true; 1925 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1926 record.updated_order = try order_cursor.readUint(); 1927 return record; 1928 } 1929 1930 // add or refresh one entry in the global logical-event index 1931 pub fn indexEvent( 1932 comptime DB: type, 1933 comptime hash_kind: hash.HashKind, 1934 haxy_moment: DB.HashMap(.read_write), 1935 event_id: *const [event_id_size]u8, 1936 kind: EventKind, 1937 existing_maybe: anytype, 1938 record: anytype, 1939 ) !void { 1940 const event_key = hash.hashInt(hash_kind, event_id); 1941 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1942 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1943 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1944 1945 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1946 const active = try DB.SortedSet(.read_write).init(active_cursor); 1947 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1948 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1949 1950 if (existing_maybe) |existing| { 1951 const old_key = orderKeyDesc(existing.updated_order, event_id); 1952 _ = try active.remove(&old_key); 1953 _ = try removed_set.remove(&old_key); 1954 } 1955 1956 const order_key = orderKeyDesc(record.updated_order, event_id); 1957 if (record.removed) { 1958 try removed_set.put(&order_key); 1959 } else { 1960 try active.put(&order_key); 1961 } 1962 } 1963 1964 pub fn touchThread( 1965 comptime DB: type, 1966 comptime hash_kind: hash.HashKind, 1967 haxy_moment: DB.HashMap(.read_write), 1968 thread_id: *const [event_id_size]u8, 1969 order: u64, 1970 arena: *std.heap.ArenaAllocator, 1971 ) !void { 1972 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1973 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1974 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1975 switch (kind) { 1976 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1977 else => {}, 1978 } 1979 } 1980 1981 pub fn readEventKind( 1982 comptime hash_kind: hash.HashKind, 1983 kind_map: anytype, 1984 id: *const [event_id_size]u8, 1985 ) !?EventKind { 1986 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1987 var buffer: [64]u8 = undefined; 1988 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1989 } 1990 1991 // the email of the event's author, or null when the id names no authored event 1992 // of this kind 1993 pub fn readAuthorEmail( 1994 comptime repo_kind: rp.RepoKind, 1995 comptime repo_opts: rp.RepoOpts(repo_kind), 1996 io: std.Io, 1997 allocator: std.mem.Allocator, 1998 arena: *std.heap.ArenaAllocator, 1999 repo: *rp.Repo(repo_kind, repo_opts), 2000 kind: EventKind, 2001 id: *const [event_id_size]u8, 2002 ) !?[]const u8 { 2003 const record_map_key = switch (kind) { 2004 .discuss => Discussion.record_map_key, 2005 .issue => Issue.record_map_key, 2006 .comment => Comment.record_map_key, 2007 .attach => Attachment.record_map_key, 2008 .assign => Assignment.record_map_key, 2009 .patchrev => PatchRev.record_map_key, 2010 .patch => Patch.record_map_key, 2011 .user, .repo, .fork, .grant, .notify => return null, 2012 }; 2013 2014 const DB = EventDB(repo_opts.hash); 2015 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 2016 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 2017 const moment = (if (event_db_maybe) |*event_db| 2018 currentMomentFromDb(repo_opts.hash, event_db.db) 2019 else if (repo_kind == .git) 2020 return null 2021 else 2022 currentMoment(repo_opts, repo)) catch return null; 2023 2024 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 2025 const records = try DB.HashMap(.read_only).init(records_cursor); 2026 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 2027 const record = try DB.HashMap(.read_only).init(record_cursor); 2028 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 2029 } 2030 2031 // the event id embedded in a set entry's order key 2032 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 2033 var cursor = kv_pair_cursor; 2034 const kv_pair = try cursor.readKeyValuePair(); 2035 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 2036 _ = try kv_pair.key_cursor.readBytes(&order_key); 2037 return order_key[@sizeOf(u64)..][0..event_id_size].*; 2038 } 2039 2040 // split a pushed "<owner>:<repo>" path into its two components, or null if it 2041 // isn't exactly two non-empty parts with no "/". 2042 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 2043 if (std.mem.indexOfScalar(u8, path, '/') != null) return null; 2044 var it = std.mem.splitScalar(u8, path, ':'); 2045 const owner = it.next() orelse return null; 2046 const name = it.next() orelse return null; 2047 if (it.next() != null) return null; 2048 if (owner.len == 0 or name.len == 0) return null; 2049 2050 return .{ .owner = owner, .name = name }; 2051 } 2052 2053 pub const CreateRepoOptions = struct { 2054 read_access: Repo.Access = .private, 2055 }; 2056 2057 // the ids that locate a repo's on-disk directory 2058 pub const RepoLocation = struct { 2059 owner_id: [event_id_size]u8, 2060 repo_id: [event_id_size]u8, 2061 }; 2062 2063 // resolve a pushed `<owner>:<repo>` to the ids that locate its on-disk directory 2064 pub fn resolveOrCreateRepo( 2065 io: std.Io, 2066 allocator: std.mem.Allocator, 2067 users_dir: []const u8, 2068 admin_repo_path: []const u8, 2069 owner_name: []const u8, 2070 repo_name: []const u8, 2071 create_options_maybe: ?CreateRepoOptions, 2072 ) !?RepoLocation { 2073 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 2074 error.RepoNotFound => return null, 2075 else => |e| return e, 2076 }; 2077 defer admin_repo.deinit(io, allocator); 2078 2079 var arena = std.heap.ArenaAllocator.init(allocator); 2080 defer arena.deinit(); 2081 2082 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 2083 2084 // an unknown owner can't own a repo, so the push is rejected 2085 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 2086 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 2087 defer user_repo.deinit(io, allocator); 2088 2089 // an already-registered repo reuses its event id, so a re-push (or a clone) 2090 // lands in the same repo 2091 if (try userMoment(&user_repo)) |moment| { 2092 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 2093 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 2094 } 2095 } 2096 2097 const create_options = create_options_maybe orelse return null; 2098 2099 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 2100 2101 var id_bytes: [event_id_size]u8 = undefined; 2102 io.random(&id_bytes); 2103 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); 2104 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 2105 } 2106 2107 // create a bare repo with `hash_kind` and register it in its owner's user repo 2108 pub fn createRepo( 2109 io: std.Io, 2110 allocator: std.mem.Allocator, 2111 users_dir: []const u8, 2112 owner_id: *const [event_id_size]u8, 2113 owner: CommitAuthor, 2114 name: []const u8, 2115 description: []const u8, 2116 read_access: Repo.Access, 2117 hash_kind: hash.HashKind, 2118 ) !RepoLocation { 2119 try Repo.validateName(name); 2120 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2121 defer user_repo.deinit(io, allocator); 2122 if (try userMoment(&user_repo)) |moment| { 2123 var arena = std.heap.ArenaAllocator.init(allocator); 2124 defer arena.deinit(); 2125 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2126 } 2127 2128 var id_bytes: [event_id_size]u8 = undefined; 2129 io.random(&id_bytes); 2130 2131 // the directory comes first so a listed repo always has one 2132 { 2133 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2134 defer allocator.free(path); 2135 switch (hash_kind) { 2136 inline else => |kind| { 2137 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2138 defer repo.deinit(io, allocator); 2139 }, 2140 } 2141 } 2142 2143 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2144 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2145 } 2146 2147 // change the name, description, read access, and tab roles of the repo 2148 // named `old_name` in its owner's user repo 2149 pub fn updateRepo( 2150 io: std.Io, 2151 allocator: std.mem.Allocator, 2152 users_dir: []const u8, 2153 owner_id: *const [event_id_size]u8, 2154 author: CommitAuthor, 2155 old_name: []const u8, 2156 name: []const u8, 2157 description: []const u8, 2158 read_access: Repo.Access, 2159 discuss_role: ?Repo.Role, 2160 issue_role: ?Repo.Role, 2161 patch_role: ?Repo.Role, 2162 ) !void { 2163 try Repo.validateName(name); 2164 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2165 defer user_repo.deinit(io, allocator); 2166 var arena = std.heap.ArenaAllocator.init(allocator); 2167 defer arena.deinit(); 2168 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2169 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2170 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2171 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2172 } 2173 2174 var event = found.repo.event; 2175 event.name = name; 2176 event.description = description; 2177 event.read_access = read_access; 2178 event.discuss_role = discuss_role; 2179 event.issue_role = issue_role; 2180 event.patch_role = patch_role; 2181 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2182 .id = std.fmt.bytesToHex(found.event_id, .lower), 2183 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2184 .author = author, 2185 .event = .{ .repo = event }, 2186 }}); 2187 } 2188 2189 // grant `user_id` `role` on the repo `repo_id` in its owner's user repo, 2190 // replacing any role they held 2191 pub fn grantRole( 2192 io: std.Io, 2193 allocator: std.mem.Allocator, 2194 users_dir: []const u8, 2195 owner_id: *const [event_id_size]u8, 2196 repo_id: *const [event_id_size]u8, 2197 user_id: *const [event_id_size]u8, 2198 role: Repo.Role, 2199 author: CommitAuthor, 2200 ) !void { 2201 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2202 defer user_repo.deinit(io, allocator); 2203 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2204 .id = std.fmt.bytesToHex(Grant.idOf(repo_id, user_id), .lower), 2205 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2206 .author = author, 2207 .event = .{ .grant = .{ .target_id = std.fmt.bytesToHex(repo_id.*, .lower), .user_id = std.fmt.bytesToHex(user_id.*, .lower), .role = role } }, 2208 }}); 2209 } 2210 2211 // revoke `user_id`'s grant on the repo `repo_id` in its owner's user repo 2212 pub fn revokeRole( 2213 io: std.Io, 2214 allocator: std.mem.Allocator, 2215 users_dir: []const u8, 2216 owner_id: *const [event_id_size]u8, 2217 repo_id: *const [event_id_size]u8, 2218 user_id: *const [event_id_size]u8, 2219 author: CommitAuthor, 2220 ) !void { 2221 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2222 defer user_repo.deinit(io, allocator); 2223 // a revoked grant stays in the kind index, which is all `remove` checks 2224 { 2225 var arena = std.heap.ArenaAllocator.init(allocator); 2226 defer arena.deinit(); 2227 const moment = (try userMoment(&user_repo)) orelse return error.EventNotFound; 2228 if (try Grant.readRole(UserDB, user_repo_opts.hash, moment, &arena, repo_id, user_id) == null) return error.EventNotFound; 2229 } 2230 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, &Grant.idOf(repo_id, user_id), .grant, author); 2231 } 2232 2233 // add `branch` to the protected branches of the repo `repo_id` in its owner's 2234 // user repo, or take it out when `protect` is false. taking out a branch that 2235 // isn't protected writes nothing. 2236 pub fn protectBranch( 2237 io: std.Io, 2238 allocator: std.mem.Allocator, 2239 users_dir: []const u8, 2240 owner_id: *const [event_id_size]u8, 2241 repo_id: *const [event_id_size]u8, 2242 branch: []const u8, 2243 protect: bool, 2244 author: CommitAuthor, 2245 ) !void { 2246 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2247 defer user_repo.deinit(io, allocator); 2248 var arena = std.heap.ArenaAllocator.init(allocator); 2249 defer arena.deinit(); 2250 const aa = arena.allocator(); 2251 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2252 const repo = (try Repo.readById(UserDB, user_repo_opts.hash, moment, &arena, repo_id)) orelse return error.NotFound; 2253 if (repo.removed) return error.NotFound; 2254 2255 var branches: std.ArrayList(u8) = .empty; 2256 var count: usize = 0; 2257 var held = false; 2258 for (try repo.event.protectedBranchNames(aa)) |name| { 2259 if (std.mem.eql(u8, name, branch)) { 2260 held = true; 2261 if (!protect) continue; 2262 } 2263 if (branches.items.len > 0) try branches.append(aa, '\n'); 2264 try branches.appendSlice(aa, name); 2265 count += 1; 2266 } 2267 if (protect) { 2268 if (held) return error.BranchProtected; 2269 if (count >= Repo.protected_branch_max_count) return error.TooManyProtectedBranches; 2270 if (branches.items.len > 0) try branches.append(aa, '\n'); 2271 try branches.appendSlice(aa, branch); 2272 } else if (!held) return; 2273 2274 var event = repo.event; 2275 event.protected_branches = branches.items; 2276 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2277 .id = std.fmt.bytesToHex(repo_id.*, .lower), 2278 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2279 .author = author, 2280 .event = .{ .repo = event }, 2281 }}); 2282 } 2283 2284 // create a user and their user repo, returning the new user's id 2285 pub fn createUser( 2286 io: std.Io, 2287 allocator: std.mem.Allocator, 2288 users_dir: []const u8, 2289 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2290 name: []const u8, 2291 email: []const u8, 2292 password: []const u8, 2293 password_again: []const u8, 2294 ) ![event_id_size]u8 { 2295 try User.validateName(name); 2296 if (email.len == 0) return error.EmailEmpty; 2297 if (password.len == 0) return error.PasswordEmpty; 2298 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2299 // a fresh admin repo has no moment until its first event 2300 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2301 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2302 var arena = std.heap.ArenaAllocator.init(allocator); 2303 defer arena.deinit(); 2304 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2305 } else |err| switch (err) { 2306 error.NotFound => {}, 2307 else => |e| return e, 2308 } 2309 2310 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2311 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2312 2313 var id_bytes: [event_id_size]u8 = undefined; 2314 io.random(&id_bytes); 2315 2316 // the user repo comes first so a listed user can always create repos 2317 { 2318 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2319 defer allocator.free(path); 2320 var user_repo = try initUserRepo(io, allocator, path); 2321 defer user_repo.deinit(io, allocator); 2322 } 2323 2324 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2325 .id = std.fmt.bytesToHex(id_bytes, .lower), 2326 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2327 .author = .{ .name = name, .email = email }, 2328 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2329 }}); 2330 return id_bytes; 2331 } 2332 2333 // change a user's email, and their password when the password fields are 2334 // filled in 2335 pub fn updateUser( 2336 io: std.Io, 2337 allocator: std.mem.Allocator, 2338 users_dir: []const u8, 2339 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2340 user_id: *const [event_id_size]u8, 2341 email: []const u8, 2342 current_password: []const u8, 2343 new_password: []const u8, 2344 new_password_again: []const u8, 2345 ) !void { 2346 if (email.len == 0) return error.EmailEmpty; 2347 var arena = std.heap.ArenaAllocator.init(allocator); 2348 defer arena.deinit(); 2349 const moment = try currentMoment(admin_repo_opts, admin_repo); 2350 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2351 if (user.removed) return error.NotFound; 2352 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; 2353 2354 var event = user.event; 2355 event.email = email; 2356 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2357 if (current_password.len + new_password.len + new_password_again.len > 0) { 2358 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2359 if (new_password.len == 0) return error.PasswordEmpty; 2360 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2361 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2362 } 2363 2364 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2365 .id = std.fmt.bytesToHex(user_id.*, .lower), 2366 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2367 .author = .{ .name = event.name, .email = email }, 2368 .event = .{ .user = event }, 2369 }}); 2370 } 2371 2372 // add an authorized_keys line to the user's ssh keys 2373 pub fn addUserKey( 2374 io: std.Io, 2375 allocator: std.mem.Allocator, 2376 users_dir: []const u8, 2377 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2378 user_id: *const [event_id_size]u8, 2379 key_text: []const u8, 2380 ) !void { 2381 const key = std.mem.trim(u8, key_text, " \t\r"); 2382 // the keys are stored one per line 2383 if (std.mem.indexOfScalar(u8, key, '\n') != null) return error.InvalidKey; 2384 const fingerprint = User.fingerprintOfKey(key) orelse return error.InvalidKey; 2385 // the key types the ssh server verifies 2386 const key_type = std.mem.sliceTo(key, ' '); 2387 if (!std.mem.eql(u8, key_type, "ssh-ed25519") and !std.mem.eql(u8, key_type, "ssh-rsa")) return error.UnsupportedKey; 2388 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, &fingerprint, key); 2389 } 2390 2391 // remove the user's ssh key with this fingerprint. removing a key they don't 2392 // hold writes nothing. 2393 pub fn removeUserKey( 2394 io: std.Io, 2395 allocator: std.mem.Allocator, 2396 users_dir: []const u8, 2397 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2398 user_id: *const [event_id_size]u8, 2399 fingerprint: *const [User.fingerprint_len]u8, 2400 ) !void { 2401 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, fingerprint, null); 2402 } 2403 2404 // rewrite the user's ssh keys with `added` appended, or without the key with 2405 // `fingerprint` when nothing is added 2406 fn writeUserKeys( 2407 io: std.Io, 2408 allocator: std.mem.Allocator, 2409 users_dir: []const u8, 2410 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2411 user_id: *const [event_id_size]u8, 2412 fingerprint: *const [User.fingerprint_len]u8, 2413 added: ?[]const u8, 2414 ) !void { 2415 var arena = std.heap.ArenaAllocator.init(allocator); 2416 defer arena.deinit(); 2417 const moment = try currentMoment(admin_repo_opts, admin_repo); 2418 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2419 if (user.removed) return error.NotFound; 2420 2421 var keys: std.ArrayList(u8) = .empty; 2422 var count: usize = 0; 2423 var held = false; 2424 var lines = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 2425 while (lines.next()) |line| { 2426 const line_fingerprint = User.fingerprintOfKey(line) orelse continue; 2427 if (std.mem.eql(u8, &line_fingerprint, fingerprint)) { 2428 held = true; 2429 if (added == null) continue; 2430 } 2431 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2432 try keys.appendSlice(arena.allocator(), line); 2433 count += 1; 2434 } 2435 if (added) |key| { 2436 if (held) return error.KeyAdded; 2437 if (count >= User.ssh_key_max_count) return error.TooManyKeys; 2438 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2439 try keys.appendSlice(arena.allocator(), key); 2440 } else if (!held) return; 2441 2442 var event = user.event; 2443 event.ssh_keys = keys.items; 2444 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2445 .id = std.fmt.bytesToHex(user_id.*, .lower), 2446 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2447 .author = .{ .name = event.name, .email = event.email }, 2448 .event = .{ .user = event }, 2449 }}); 2450 } 2451 2452 // consume a new repo's event into its owner's user repo and mark it active 2453 fn writeRepoEvent( 2454 io: std.Io, 2455 allocator: std.mem.Allocator, 2456 users_dir: []const u8, 2457 user_repo: *rp.Repo(.xit, user_repo_opts), 2458 owner_id: *const [event_id_size]u8, 2459 owner: CommitAuthor, 2460 id_bytes: *const [event_id_size]u8, 2461 name: []const u8, 2462 description: []const u8, 2463 read_access: Repo.Access, 2464 ) !void { 2465 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2466 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2467 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2468 .timestamp = timestamp, 2469 .author = owner, 2470 .event = .{ .repo = .{ 2471 .user_id = std.fmt.bytesToHex(owner_id.*, .lower), 2472 .name = name, 2473 .description = description, 2474 .read_access = read_access, 2475 } }, 2476 }}); 2477 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2478 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2479 }; 2480 } 2481 2482 // 2483 // reading from xitdb 2484 // 2485 2486 // read just `Fields`, a subset of `T.Record`, from the record with event id 2487 // `id`, or null when there is none 2488 pub fn readRecordSubset( 2489 comptime T: type, 2490 comptime Fields: type, 2491 comptime DB: type, 2492 comptime hash_kind: hash.HashKind, 2493 haxy_moment: DB.HashMap(.read_only), 2494 arena: *std.heap.ArenaAllocator, 2495 id: []const u8, 2496 ) !?Fields { 2497 comptime assertFieldSubset(Fields, T.Record); 2498 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2499 const records = try DB.HashMap(.read_only).init(records_cursor); 2500 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2501 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2502 } 2503 2504 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2505 const info = @typeInfo(Sub).@"struct"; 2506 for (info.field_names, info.field_types) |field_name, field_type| { 2507 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2508 const FullField = @FieldType(Full, field_name); 2509 if (@typeInfo(field_type) == .@"struct") { 2510 assertFieldSubset(field_type, FullField); 2511 } else if (field_type != FullField) { 2512 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2513 } 2514 } 2515 } 2516 2517 pub fn read( 2518 comptime T: type, 2519 comptime DB: type, 2520 comptime hash_kind: hash.HashKind, 2521 arena: *std.heap.ArenaAllocator, 2522 map: DB.HashMap(.read_only), 2523 ) !T { 2524 var event: T = undefined; 2525 switch (@typeInfo(T)) { 2526 .@"struct" => |struct_info| { 2527 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2528 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2529 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2530 } 2531 }, 2532 else => @compileError("read expects a struct"), 2533 } 2534 return event; 2535 } 2536 2537 fn readField( 2538 comptime Field: type, 2539 comptime DB: type, 2540 comptime hash_kind: hash.HashKind, 2541 arena: *std.heap.ArenaAllocator, 2542 cursor_maybe: ?DB.Cursor(.read_only), 2543 ) !Field { 2544 if (@typeInfo(Field) == .optional) { 2545 // a missing key or a null union payload is null 2546 const cursor = cursor_maybe orelse return null; 2547 if (cursor.slot().tag == .none) return null; 2548 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2549 } 2550 const cursor = cursor_maybe orelse return error.NotFound; 2551 switch (@typeInfo(Field)) { 2552 .pointer => |pointer_info| { 2553 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2554 @compileError("unsupported read field type: " ++ @typeName(Field)); 2555 } 2556 return try cursor.readBytesAlloc(arena.allocator(), null); 2557 }, 2558 .array => |array_info| { 2559 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2560 var bytes: Field = undefined; 2561 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2562 return bytes; 2563 }, 2564 .bool => { 2565 var buffer: [5]u8 = undefined; 2566 const bytes = try cursor.readBytesObject(&buffer); 2567 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2568 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2569 if (std.mem.eql(u8, bytes.value, "true")) return true; 2570 if (std.mem.eql(u8, bytes.value, "false")) return false; 2571 return error.InvalidBool; 2572 }, 2573 .int => |int_info| return switch (int_info.signedness) { 2574 .unsigned => @intCast(try cursor.readUint()), 2575 .signed => @intCast(try cursor.readInt()), 2576 }, 2577 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2578 .@"union" => |union_info| { 2579 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2580 switch (cursor.slot().tag) { 2581 .bytes, .short_bytes => { 2582 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2583 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2584 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2585 return @unionInit(Field, variant_name, {}); 2586 } 2587 } 2588 return error.InvalidUnion; 2589 }, 2590 .hash_map => { 2591 const variants = try DB.HashMap(.read_only).init(cursor); 2592 var iter = try variants.iterator(); 2593 const entry = (try iter.next()) orelse return error.InvalidUnion; 2594 const pair = try entry.readKeyValuePair(); 2595 if (try iter.next() != null) return error.InvalidUnion; 2596 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2597 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2598 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2599 } 2600 } 2601 return error.InvalidUnion; 2602 }, 2603 else => return error.InvalidUnion, 2604 } 2605 }, 2606 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2607 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2608 } 2609 } 2610 2611 // whether two events carry the same data 2612 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2613 switch (@typeInfo(T)) { 2614 .@"struct" => |struct_info| { 2615 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2616 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2617 } 2618 }, 2619 else => @compileError("fieldsEqual expects a struct"), 2620 } 2621 2622 return true; 2623 } 2624 2625 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2626 switch (@typeInfo(Field)) { 2627 .pointer => |pointer_info| { 2628 if (pointer_info.size == .slice and pointer_info.child == u8) { 2629 return std.mem.eql(u8, a, b); 2630 } else { 2631 @compileError("unsupported field type: " ++ @typeName(Field)); 2632 } 2633 }, 2634 .array => |array_info| { 2635 if (array_info.child == u8) { 2636 return std.mem.eql(u8, &a, &b); 2637 } else { 2638 @compileError("unsupported field type: " ++ @typeName(Field)); 2639 } 2640 }, 2641 .void => return true, 2642 .bool, .int, .@"enum" => return a == b, 2643 .@"union" => { 2644 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2645 return switch (a) { 2646 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2647 }; 2648 }, 2649 .@"struct" => return fieldsEqual(Field, a, b), 2650 .optional => |optional_info| { 2651 if (a) |a_value| { 2652 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2653 return false; 2654 } 2655 return b == null; 2656 }, 2657 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2658 } 2659 } 2660 2661 // 2662 // writing to xitdb 2663 // 2664 2665 pub fn upsert( 2666 comptime T: type, 2667 comptime DB: type, 2668 comptime hash_kind: hash.HashKind, 2669 map: DB.HashMap(.read_write), 2670 event: T, 2671 ) !void { 2672 switch (@typeInfo(T)) { 2673 .@"struct" => |struct_info| { 2674 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2675 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2676 } 2677 }, 2678 else => @compileError("upsert expects a struct"), 2679 } 2680 } 2681 2682 fn upsertField( 2683 comptime DB: type, 2684 comptime hash_kind: hash.HashKind, 2685 map: DB.HashMap(.read_write), 2686 comptime field_name: []const u8, 2687 comptime Field: type, 2688 value: Field, 2689 ) !void { 2690 const key = hash.hashInt(hash_kind, field_name); 2691 2692 switch (@typeInfo(Field)) { 2693 .pointer => |pointer_info| { 2694 if (pointer_info.size == .slice and pointer_info.child == u8) { 2695 try upsertBytes(DB, hash_kind, map, key, value); 2696 } else { 2697 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2698 } 2699 }, 2700 .array => |array_info| { 2701 if (array_info.child == u8) { 2702 try upsertBytes(DB, hash_kind, map, key, &value); 2703 } else { 2704 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2705 } 2706 }, 2707 .int => |int_info| switch (int_info.signedness) { 2708 .unsigned => { 2709 if (try map.getCursor(key)) |value_cursor| { 2710 if (try value_cursor.readUint() == value) { 2711 return; 2712 } 2713 } 2714 2715 try map.put(key, .{ .uint = value }); 2716 }, 2717 .signed => { 2718 if (try map.getCursor(key)) |value_cursor| { 2719 if (try value_cursor.readInt() == value) { 2720 return; 2721 } 2722 } 2723 2724 try map.put(key, .{ .int = value }); 2725 }, 2726 }, 2727 .bool => { 2728 const bytes = if (value) "true" else "false"; 2729 if (try map.getCursor(key)) |value_cursor| { 2730 var buffer: [5]u8 = undefined; 2731 const existing = try value_cursor.readBytesObject(&buffer); 2732 if (existing.format_tag) |format_tag| { 2733 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2734 return; 2735 } 2736 } 2737 } 2738 2739 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2740 }, 2741 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2742 .@"union" => switch (value) { 2743 inline else => |payload, tag| { 2744 if (@TypeOf(payload) == void) { 2745 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2746 } else { 2747 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2748 if (try map.getCursor(key)) |cursor| { 2749 switch (cursor.slot().tag) { 2750 .hash_map => { 2751 const variants = try DB.HashMap(.read_only).init(cursor); 2752 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2753 }, 2754 else => try map.put(key, .{ .slot = null }), 2755 } 2756 } 2757 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2758 if (@typeInfo(@TypeOf(payload)) == .optional) { 2759 // keep the variant even when its payload is null 2760 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2761 } 2762 if (try variants.getCursor(tag_key)) |cursor| { 2763 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2764 } 2765 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2766 } 2767 }, 2768 }, 2769 .optional => |optional_info| { 2770 // a missing key is null 2771 if (value) |child| { 2772 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2773 } else { 2774 _ = try map.remove(key); 2775 } 2776 }, 2777 .@"struct" => try upsert( 2778 Field, 2779 DB, 2780 hash_kind, 2781 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2782 value, 2783 ), 2784 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2785 } 2786 } 2787 2788 fn upsertBytes( 2789 comptime DB: type, 2790 comptime hash_kind: hash.HashKind, 2791 map: DB.HashMap(.read_write), 2792 key: hash.HashInt(hash_kind), 2793 value: []const u8, 2794 ) !void { 2795 var existing_cursor_maybe = try map.getCursor(key); 2796 if (existing_cursor_maybe) |*existing_cursor| { 2797 if (try bytesEqual(DB, existing_cursor, value)) { 2798 return; 2799 } 2800 } 2801 2802 try map.put(key, .{ .bytes = value }); 2803 } 2804 2805 fn bytesEqual( 2806 comptime DB: type, 2807 cursor: *DB.Cursor(.read_only), 2808 value: []const u8, 2809 ) !bool { 2810 switch (cursor.slot().tag) { 2811 .bytes, .short_bytes => {}, 2812 else => return false, 2813 } 2814 var read_buffer: [1024]u8 = undefined; 2815 var reader = try cursor.reader(&read_buffer); 2816 if (reader.size != value.len) { 2817 return false; 2818 } 2819 2820 var chunk_buffer: [1024]u8 = undefined; 2821 var offset: usize = 0; 2822 while (offset < value.len) { 2823 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2824 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2825 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2826 return false; 2827 } 2828 offset += chunk_len; 2829 } 2830 2831 return true; 2832 } 2833 2834 // 2835 // CommitIterator 2836 // 2837 // differs from xit's ObjectIterator in a few ways: 2838 // 2839 // 1. iterates parents first, rather than children first 2840 // 2. `next` only returns the object id, not the full Object 2841 // 3. stores its temporary state in a file on disk to avoid OOMs 2842 // 2843 2844 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2845 return struct { 2846 const DB = EventDB(repo_opts.hash); 2847 // a plain file is used for the scratch db because each write outside 2848 // a transaction is synced anyway, so buffering would gain nothing 2849 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2850 const db_name = "haxy-repo-events.db"; 2851 2852 repo_dir: std.Io.Dir, 2853 db_file: std.Io.File, 2854 db: *TempDB, 2855 // map of each object id to its children 2856 parent_to_children: TempDB.HashMap(.read_write), 2857 // tracking pending parents is necessary because a child can only 2858 // be returned after all of its unconsumed parents have been returned 2859 child_to_pending_parents: TempDB.HashMap(.read_write), 2860 // queue of object ids that are ready to be returned from `next` 2861 ready_queue: TempDB.ArrayList(.read_write), 2862 ready_queue_index: u64, 2863 // the object id at the tip of this branch 2864 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2865 // the object id furthest back in the history that hasn't been consumed 2866 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2867 2868 pub fn init( 2869 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2870 io: std.Io, 2871 allocator: std.mem.Allocator, 2872 consumed_object_ids: DB.HashMap(.read_only), 2873 ref: rf.Ref, 2874 ) !CommitIterator(repo_kind, repo_opts) { 2875 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2876 errdefer { 2877 db_file.close(io); 2878 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2879 } 2880 2881 // cursors point at the db, so it needs a stable address 2882 const db_ptr = try allocator.create(TempDB); 2883 errdefer allocator.destroy(db_ptr); 2884 // the db is scratch state that gets deleted after iteration, so 2885 // there is nothing worth fsyncing 2886 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2887 2888 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2889 2890 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2891 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2892 2893 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2894 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2895 2896 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2897 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2898 2899 var self = CommitIterator(repo_kind, repo_opts){ 2900 .repo_dir = state.core.repo_dir, 2901 .db_file = db_file, 2902 .db = db_ptr, 2903 .parent_to_children = parent_to_children, 2904 .child_to_pending_parents = child_to_pending_parents, 2905 .ready_queue = ready_queue, 2906 .ready_queue_index = 0, 2907 .newest_object_id = null, 2908 .oldest_object_id = null, 2909 }; 2910 errdefer self.deinit(io, allocator); 2911 2912 try self.collect(state, io, allocator, consumed_object_ids, ref); 2913 2914 return self; 2915 } 2916 2917 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2918 self.db_file.close(io); 2919 self.repo_dir.deleteFile(io, db_name) catch {}; 2920 allocator.destroy(self.db); 2921 } 2922 2923 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2924 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2925 2926 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2927 self.ready_queue_index += 1; 2928 2929 try self.enqueueChildren(&oid); 2930 return oid; 2931 } 2932 2933 fn collect( 2934 self: *CommitIterator(repo_kind, repo_opts), 2935 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2936 io: std.Io, 2937 allocator: std.mem.Allocator, 2938 consumed_object_ids: DB.HashMap(.read_only), 2939 ref: rf.Ref, 2940 ) !void { 2941 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2942 2943 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2944 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2945 var walk_queue_index: u64 = 0; 2946 2947 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2948 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2949 2950 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2951 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2952 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2953 try walk_queue.append(.{ .bytes = &head_oid }); 2954 2955 while (walk_queue_index < try walk_queue.count()) { 2956 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2957 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2958 2959 walk_queue_index += 1; 2960 2961 // if we've seen this object id, skip it 2962 if (null != try seen_object_ids.getCursor(oid_int)) { 2963 continue; 2964 } 2965 2966 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2967 2968 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2969 defer commit_object.deinit(); 2970 2971 // if this object id has already been consumed, skip it 2972 if (null != try consumed_object_ids.getCursor(oid_int)) { 2973 continue; 2974 } 2975 2976 if (self.newest_object_id == null) self.newest_object_id = oid; 2977 self.oldest_object_id = oid; 2978 2979 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2980 var pending_parent_count: u64 = 0; 2981 for (parent_oids) |*parent_oid| { 2982 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2983 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2984 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2985 2986 // if this object id has already been consumed, skip it 2987 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2988 continue; 2989 } 2990 2991 // if this object id hasn't already been seen, add it to the walk queue 2992 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2993 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2994 } 2995 2996 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2997 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2998 try children.put(oid_int, .{ .bytes = &oid }); 2999 pending_parent_count += 1; 3000 } 3001 3002 if (pending_parent_count == 0) { 3003 try self.ready_queue.append(.{ .bytes = &oid }); 3004 } else { 3005 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 3006 } 3007 } 3008 } 3009 3010 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 3011 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 3012 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 3013 const children = try TempDB.HashSet(.read_only).init(children_cursor); 3014 var children_iter = try children.iterator(); 3015 3016 while (try children_iter.next()) |*child_cursor| { 3017 const kv_pair = try child_cursor.readKeyValuePair(); 3018 const child_oid_int = kv_pair.hash; 3019 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 3020 const pending_parent_count = try pending_parent_cursor.readUint(); 3021 3022 if (pending_parent_count <= 1) { 3023 _ = try self.child_to_pending_parents.remove(child_oid_int); 3024 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 3025 try self.ready_queue.append(.{ .bytes = &child_oid }); 3026 } else { 3027 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 3028 } 3029 } 3030 } 3031 3032 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 3033 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 3034 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 3035 _ = try oid_cursor.readBytes(&oid); 3036 return oid; 3037 } 3038 }; 3039 } 3040