╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const hash = xit.hash; 5 const mrg = xit.merge; 6 const obj = xit.object; 7 const rf = xit.ref; 8 9 pub const User = @import("event/User.zig"); 10 pub const Repo = @import("event/Repo.zig"); 11 pub const Issue = @import("event/Issue.zig"); 12 13 pub const event_id_size: usize = 32; 14 15 // the branch haxy events are committed to before being consumed 16 pub const events_ref: rf.Ref = .{ .kind = .head, .name = "haxy/events" }; 17 18 // options + db type for *the admin repo* — the single event store that holds 19 // users, repos, issues, etc. the functions below stay parameterized over 20 // repo_opts because they also operate on individual repos in the repos dir, 21 // which may use different options 22 pub const admin_repo_opts: rp.RepoOpts(.xit) = .{}; 23 pub const AdminDB = rp.Repo(.xit, admin_repo_opts).DB; 24 25 // the xitdb type events are stored in. it only depends on the hash kind, so 26 // this matches the db of any xit repo using that hash kind. 27 pub fn EventDB(comptime hash_kind: hash.HashKind) type { 28 return rp.Repo(.xit, .{ .hash = hash_kind }).DB; 29 } 30 31 pub const EventKind = enum { 32 user, 33 repo, 34 issue, 35 }; 36 37 pub const EventWithId = struct { 38 id: [event_id_size * 2]u8, 39 event: union(EventKind) { 40 user: ?User, 41 repo: ?Repo, 42 issue: ?Issue, 43 }, 44 timestamp: u64 = 0, // not serialized, because it comes from the commit timestamp 45 46 pub fn jsonStringify(self: EventWithId, jw: anytype) !void { 47 try jw.beginObject(); 48 try jw.objectField("id"); 49 try jw.write(self.id); 50 try jw.objectField("kind"); 51 try jw.write(@tagName(self.event)); 52 try jw.objectField("data"); 53 switch (self.event) { 54 inline else => |event_maybe| try jw.write(event_maybe), 55 } 56 try jw.endObject(); 57 } 58 59 fn fromString(arena: *std.heap.ArenaAllocator, message: []const u8) !EventWithId { 60 const JsonEvent = struct { 61 id: [event_id_size * 2]u8, 62 kind: EventKind, 63 data: ?std.json.Value = null, 64 }; 65 const json_event = try std.json.parseFromSliceLeaky(JsonEvent, arena.allocator(), message, .{}); 66 return .{ 67 .id = json_event.id, 68 .event = switch (json_event.kind) { 69 .user => .{ 70 .user = if (json_event.data) |value| 71 try std.json.parseFromValueLeaky(User, arena.allocator(), value, .{}) 72 else 73 null, 74 }, 75 .repo => .{ 76 .repo = if (json_event.data) |value| 77 try std.json.parseFromValueLeaky(Repo, arena.allocator(), value, .{}) 78 else 79 null, 80 }, 81 .issue => .{ 82 .issue = if (json_event.data) |value| 83 try std.json.parseFromValueLeaky(Issue, arena.allocator(), value, .{}) 84 else 85 null, 86 }, 87 }, 88 }; 89 } 90 91 pub fn randomId(random: std.Random) [event_id_size]u8 { 92 var id_bytes: [event_id_size]u8 = undefined; 93 random.bytes(&id_bytes); 94 return id_bytes; 95 } 96 }; 97 98 pub fn consume( 99 comptime repo_opts: rp.RepoOpts(.xit), 100 io: std.Io, 101 allocator: std.mem.Allocator, 102 repo: *rp.Repo(.xit, repo_opts), 103 ref: rf.Ref, 104 ) !void { 105 const DB = rp.Repo(.xit, repo_opts).DB; 106 const State = rp.Repo(.xit, repo_opts).State; 107 108 const Ctx = struct { 109 core: *rp.Repo(.xit, repo_opts).Core, 110 io: std.Io, 111 allocator: std.mem.Allocator, 112 ref: rf.Ref, 113 114 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 115 var moment = try DB.HashMap(.read_write).init(cursor.*); 116 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 117 try consumeInTransaction(.xit, repo_opts, state.readOnly(), &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.ref); 118 } 119 }; 120 121 try repo.core.db_file.lock(io, .exclusive); 122 defer repo.core.db_file.unlock(io); 123 124 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 125 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 126 .core = &repo.core, 127 .io = io, 128 .allocator = allocator, 129 .ref = ref, 130 }); 131 } 132 133 // a standalone event db holding events consumed from a local repo's events 134 // branch. it lives inside the repo dir but is not part of the repo's own data, 135 // so viewing a repo never mutates it. 136 pub fn LocalEventDB(comptime hash_kind: hash.HashKind) type { 137 return struct { 138 file: std.Io.File, 139 buffer: *std.Io.Writer.Allocating, 140 db: *EventDB(hash_kind), 141 142 const db_name = "haxy"; 143 const Self = @This(); 144 145 // open the db in `repo_dir`, creating it if it doesn't exist 146 pub fn create(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !Self { 147 const file = try repo_dir.createFile(io, db_name, .{ .truncate = false, .read = true, .lock = .exclusive }); 148 return fromFile(io, allocator, file); 149 } 150 151 // open the db in `repo_dir` for reading, or null if it doesn't exist 152 pub fn open(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !?Self { 153 const file = repo_dir.openFile(io, db_name, .{ .mode = .read_write, .lock = .shared }) catch |err| switch (err) { 154 error.FileNotFound => return null, 155 else => |e| return e, 156 }; 157 return try fromFile(io, allocator, file); 158 } 159 160 // remove the db from `repo_dir`, so a repo whose events branch 161 // disappeared doesn't keep showing stale issues 162 pub fn delete(io: std.Io, repo_dir: std.Io.Dir) !void { 163 repo_dir.deleteFile(io, db_name) catch |err| switch (err) { 164 error.FileNotFound => {}, 165 else => |e| return e, 166 }; 167 } 168 169 fn fromFile(io: std.Io, allocator: std.mem.Allocator, file: std.Io.File) !Self { 170 errdefer file.close(io); 171 172 const buffer = try allocator.create(std.Io.Writer.Allocating); 173 errdefer allocator.destroy(buffer); 174 buffer.* = std.Io.Writer.Allocating.init(allocator); 175 errdefer buffer.deinit(); 176 177 const db = try allocator.create(EventDB(hash_kind)); 178 errdefer allocator.destroy(db); 179 db.* = try EventDB(hash_kind).init(.{ .io = io, .file = file, .buffer = buffer }); 180 181 return .{ .file = file, .buffer = buffer, .db = db }; 182 } 183 184 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 185 self.file.close(io); 186 self.buffer.deinit(); 187 allocator.destroy(self.buffer); 188 allocator.destroy(self.db); 189 } 190 191 // consume the events on `repo`'s `ref` into this db. the db must come 192 // from `create`, whose handle holds the exclusive lock guarding the 193 // transaction. 194 pub fn consume( 195 self: *Self, 196 comptime repo_kind: rp.RepoKind, 197 comptime repo_opts: rp.RepoOpts(repo_kind), 198 io: std.Io, 199 allocator: std.mem.Allocator, 200 repo: *rp.Repo(repo_kind, repo_opts), 201 ref: rf.Ref, 202 ) !void { 203 comptime if (repo_opts.hash != hash_kind) @compileError("the repo must use the db's hash kind"); 204 const DB = EventDB(hash_kind); 205 206 const Ctx = struct { 207 repo: *rp.Repo(repo_kind, repo_opts), 208 db: *DB, 209 io: std.Io, 210 allocator: std.mem.Allocator, 211 ref: rf.Ref, 212 213 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 214 var moment = try DB.HashMap(.read_write).init(cursor.*); 215 var repo_moment = try ctx.repo.core.latestMoment(); 216 const read_state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &ctx.repo.core, .extra = .{ .moment = &repo_moment } }; 217 try consumeInTransaction(repo_kind, repo_opts, read_state, ctx.db, &moment, ctx.io, ctx.allocator, ctx.ref); 218 } 219 }; 220 221 const history = try DB.ArrayList(.read_write).init(self.db.rootCursor()); 222 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 223 .repo = repo, 224 .db = self.db, 225 .io = io, 226 .allocator = allocator, 227 .ref = ref, 228 }); 229 } 230 }; 231 } 232 233 // bring a local repo's event db up to date with its events branch 234 pub fn syncLocalEvents( 235 comptime repo_kind: rp.RepoKind, 236 comptime repo_opts: rp.RepoOpts(repo_kind), 237 io: std.Io, 238 allocator: std.mem.Allocator, 239 repo: *rp.Repo(repo_kind, repo_opts), 240 ) !void { 241 var remotes = try repo.listRemotes(io, allocator); 242 defer remotes.deinit(); 243 244 const ref: rf.Ref, const tip: [hash.hexLen(repo_opts.hash)]u8 = blk: { 245 if (try repo.readRef(io, events_ref)) |oid| break :blk .{ events_ref, oid }; 246 for (remotes.sections.keys()) |remote_name| { 247 const remote_ref: rf.Ref = .{ .kind = .{ .remote = remote_name }, .name = events_ref.name }; 248 if (try repo.readRef(io, remote_ref)) |oid| break :blk .{ remote_ref, oid }; 249 } 250 // the branch is gone (or never existed): drop any db from a previous 251 // sync rather than serving its issues indefinitely 252 try LocalEventDB(repo_opts.hash).delete(io, repo.core.repo_dir); 253 return; 254 }; 255 256 var event_db = try LocalEventDB(repo_opts.hash).create(io, allocator, repo.core.repo_dir); 257 defer event_db.deinit(io, allocator); 258 259 if (try lastConsumedOid(repo_opts.hash, event_db.db)) |last_oid| { 260 var tip_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 261 _ = try std.fmt.hexToBytes(&tip_bytes, &tip); 262 if (std.mem.eql(u8, &last_oid, &tip_bytes)) return; 263 } 264 265 try event_db.consume(repo_kind, repo_opts, io, allocator, repo, ref); 266 } 267 268 // consume the events on `ref` into the db `moment` writes to. events are read 269 // from `read_state`'s repo, which needn't be the repo backing the db — that's 270 // how a local (possibly git-backed) repo's events land in a standalone db. 271 pub fn consumeInTransaction( 272 comptime repo_kind: rp.RepoKind, 273 comptime repo_opts: rp.RepoOpts(repo_kind), 274 read_state: rp.Repo(repo_kind, repo_opts).State(.read_only), 275 db: *EventDB(repo_opts.hash), 276 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 277 io: std.Io, 278 allocator: std.mem.Allocator, 279 ref: rf.Ref, 280 ) !void { 281 const DB = EventDB(repo_opts.hash); 282 283 // the last_object_id represents the object id that was last consumed 284 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 285 if (try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id"))) |last_object_id_cursor| { 286 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 287 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 288 last_object_id_maybe = last_object_id_buffer; 289 } 290 291 // the list with all of haxy's state, including materialized views. 292 // the reason it is a list is so we can keep every previous haxy 293 // state, making it easy to revert to an older state if the user 294 // rebases some of the past commits. 295 const haxy_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, "haxy")); 296 const haxy = try DB.ArrayList(.read_write).init(haxy_cursor); 297 298 // add a new item to the haxy list created above. 299 // we call the item haxy_moments. it is a map of object id to haxy moment. 300 // in other words, it maps each object id to a hash map containing the 301 // state that the database was in when that object id was consumed. 302 var haxy_moments_cursor = try haxy.appendCursor(); 303 // use the previous haxy_moments as the basis for this one if it exists 304 if (try haxy.getCursor(-2)) |last_haxy_moments_cursor| { 305 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 306 } 307 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 308 309 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 310 defer commit_iter.deinit(io, allocator); 311 312 // if there are no events to process, look at the oid at HEAD and update 313 // the last_object_id to point to it. this is important in situations 314 // where we do a merge and then force-push to remove the merge. see the 315 // merge test for an example. 316 if (commit_iter.newest_object_id == null) { 317 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 318 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 319 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 320 321 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 322 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 323 324 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 325 const moment_index = try moment_index_cursor.readUint(); 326 327 try haxy.slice(moment_index + 1); 328 try moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = &head_oid }); 329 return; 330 } 331 332 // if this branch was rebased and force pushed, we need to detect that and 333 // properly revert the haxy state to the last valid state. we detect this 334 // by simply asking if the last event is a descendent of the last event 335 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 336 if (last_object_id_maybe) |*last_object_id| { 337 var is_rebased = false; 338 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 339 340 _ = mrg.getDescendent( 341 repo_kind, 342 repo_opts, 343 read_state, 344 io, 345 allocator, 346 &std.fmt.bytesToHex(last_object_id, .lower), 347 &std.fmt.bytesToHex(&newest_object_id, .lower), 348 ) catch |err| switch (err) { 349 error.DescendentNotFound => is_rebased = true, 350 else => |e| return e, 351 }; 352 353 if (is_rebased) { 354 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 355 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 356 defer oldest_object.deinit(); 357 358 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 359 switch (parent_oids.len) { 360 0 => { 361 // the branch was rebased all the way to the very beginning. 362 // we have a repo event with no parent, which means it is now 363 // the very first event. all we need to do is set the haxy list 364 // to be empty and make a new haxy_moments map to work with. 365 366 try haxy.slice(0); 367 haxy_moments_cursor = try haxy.appendCursor(); 368 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 369 370 last_object_id_maybe = null; 371 }, 372 1 => { 373 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 374 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 375 376 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 377 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 378 379 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 380 const old_moment_index = try old_moment_index_cursor.readUint(); 381 382 // resize the haxy list so we truncate all the moments that were 383 // created after the parent_oid was consumed 384 try haxy.slice(old_moment_index + 1); 385 386 // make a new haxy moment and set its initial value to the last haxy moment 387 haxy_moments_cursor = try haxy.appendCursor(); 388 const old_haxy_moments_cursor = try haxy.getCursor(old_moment_index) orelse return error.CursorNotFound; 389 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 390 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 391 392 last_object_id_maybe = oid; 393 }, 394 else => return error.UnexpectedParentCount, 395 } 396 } 397 } 398 399 while (try commit_iter.next()) |repo_event_oid| { 400 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 401 defer commit_object.deinit(); 402 403 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 404 405 // create a moment for this object id 406 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 407 408 // if there was a previous object id, set this haxy moment's initial value to it. 409 // this efficiently "clones" the map so we make further modifications based on it. 410 if (parent_oids.len > 0) { 411 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 412 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 413 414 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 415 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 416 } 417 418 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 419 420 // merge changes from every parent after the first parent. the common 421 // ancestor is the baseline, so a later parent only contributes values 422 // it changed relative to the merge base. 423 if (parent_oids.len > 1) { 424 for (parent_oids[1..]) |*parent_oid| { 425 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 426 _ = try std.fmt.hexToBytes(&oid, parent_oid); 427 428 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 429 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 430 431 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 432 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 433 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 434 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 435 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 436 437 try mergeChangedMapEntries(DB, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment, true); 438 } 439 } 440 441 // associate this moment with the index it will first appear at in the haxy list. 442 // this will be important later so we can truncate that list if the user ever 443 // rebases starting at this object id. 444 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy.count() - 1 }); 445 446 // consume the event unless it's a merge commit 447 if (parent_oids.len <= 1) { 448 var arena = std.heap.ArenaAllocator.init(allocator); 449 defer arena.deinit(); 450 451 // read the message from the commit 452 try commit_object.object_reader.seekTo(commit_object.content.commit.message_position); 453 const message = try commit_object.object_reader.interface.allocRemaining(arena.allocator(), .unlimited); 454 455 const event_with_id = try EventWithId.fromString(&arena, message); 456 457 // get the id of the current event as bytes 458 var current_event_id: [event_id_size]u8 = undefined; 459 _ = try std.fmt.hexToBytes(&current_event_id, &event_with_id.id); 460 461 const created_ts = commit_object.content.commit.metadata.timestamp; 462 463 switch (event_with_id.event) { 464 .user => |event_maybe| try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena, created_ts), 465 .repo => |event_maybe| try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena, created_ts), 466 .issue => |event_maybe| try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena, created_ts), 467 } 468 } 469 470 // the current object id is now the last one 471 last_object_id_maybe = repo_event_oid; 472 473 // prevent any of the data created above from being mutated by future iterations of this loop 474 try db.freeze(); 475 } 476 477 if (last_object_id_maybe) |*last_object_id| { 478 try moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = last_object_id }); 479 } 480 } 481 482 pub fn currentMoment( 483 comptime repo_opts: rp.RepoOpts(.xit), 484 repo: *rp.Repo(.xit, repo_opts), 485 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 486 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 487 } 488 489 // the oid of the last event commit consumed into `db`, or null before any 490 // consume completed 491 fn lastConsumedOid( 492 comptime hash_kind: hash.HashKind, 493 db: *EventDB(hash_kind), 494 ) !?[hash.byteLen(hash_kind)]u8 { 495 const DB = EventDB(hash_kind); 496 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 497 const moment_cursor = try history.getCursor(-1) orelse return null; 498 const moment = try DB.HashMap(.read_only).init(moment_cursor); 499 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy-last-object-id")) orelse return null; 500 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 501 _ = try last_object_id_cursor.readBytes(&last_object_id); 502 return last_object_id; 503 } 504 505 pub fn currentMomentFromDb( 506 comptime hash_kind: hash.HashKind, 507 db: *EventDB(hash_kind), 508 ) !EventDB(hash_kind).HashMap(.read_only) { 509 const DB = EventDB(hash_kind); 510 const last_object_id = (try lastConsumedOid(hash_kind, db)) orelse return error.NotFound; 511 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 512 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 513 const moment = try DB.HashMap(.read_only).init(moment_cursor); 514 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, "haxy")) orelse return error.NotFound; 515 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 516 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 517 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 518 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 519 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 520 } 521 522 pub fn commitAndConsume( 523 comptime repo_opts: rp.RepoOpts(.xit), 524 io: std.Io, 525 allocator: std.mem.Allocator, 526 repo: *rp.Repo(.xit, repo_opts), 527 ref: rf.Ref, 528 events: []const EventWithId, 529 ) !void { 530 var json: std.Io.Writer.Allocating = .init(allocator); 531 defer json.deinit(); 532 533 for (events) |event| { 534 json.clearRetainingCapacity(); 535 try std.json.Stringify.value(event, .{}, &json.writer); 536 _ = try repo.commitAtRef(io, allocator, .{ .message = json.written(), .timestamp = event.timestamp }, null, ref); 537 } 538 539 try consume(repo_opts, io, allocator, repo, ref); 540 } 541 542 // build the key for SortedSets sorted by timestamp. the big-endian timestamp 543 // makes byte order match creation order; the event id breaks ties and keeps 544 // keys unique within the same timestamp. 545 pub fn orderKey(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 546 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 547 std.mem.writeInt(u64, key[0..@sizeOf(u64)], timestamp, .big); 548 @memcpy(key[@sizeOf(u64)..], event_id); 549 return key; 550 } 551 552 // split a pushed "<owner>/<repo>" path into its two components, or null if it 553 // isn't exactly two non-empty segments. 554 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 555 var it = std.mem.splitScalar(u8, path, '/'); 556 const owner = it.next() orelse return null; 557 const name = it.next() orelse return null; 558 if (it.next() != null) return null; 559 if (owner.len == 0 or name.len == 0) return null; 560 561 return .{ .owner = owner, .name = name }; 562 } 563 564 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 565 // directory under the repos dir 566 pub fn resolveOrCreateRepo( 567 io: std.Io, 568 allocator: std.mem.Allocator, 569 admin_repo_path: []const u8, 570 owner_name: []const u8, 571 repo_name: []const u8, 572 create_if_missing: bool, 573 ) !?[event_id_size * 2]u8 { 574 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 575 error.RepoNotFound => return null, 576 else => |e| return e, 577 }; 578 defer repo.deinit(io, allocator); 579 580 var arena = std.heap.ArenaAllocator.init(allocator); 581 defer arena.deinit(); 582 583 const moment = try currentMoment(admin_repo_opts, &repo); 584 585 // an already-registered repo reuses its event id, so a re-push (or a clone) 586 // lands in the same repo 587 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 588 return std.fmt.bytesToHex(found.event_id, .lower); 589 } 590 591 if (!create_if_missing) return null; 592 593 // the new repo is owned by the named user, read from the name index; an 594 // unknown owner can't own a repo, so the push is rejected 595 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 596 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 597 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 598 var owner_user_id: [event_id_size]u8 = undefined; 599 _ = try owner_id_cursor.readBytes(&owner_user_id); 600 601 var id_bytes: [event_id_size]u8 = undefined; 602 io.random(&id_bytes); 603 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 604 605 try commitAndConsume(admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 606 .id = event_id_hex, 607 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 608 .event = .{ .repo = .{ 609 .user_id = &owner_user_id, 610 .name = repo_name, 611 .description = "", 612 .enable_issue = true, 613 } }, 614 }}); 615 616 return event_id_hex; 617 } 618 619 // 620 // reading from xitdb 621 // 622 623 pub fn read( 624 comptime T: type, 625 comptime DB: type, 626 comptime hash_kind: hash.HashKind, 627 arena: *std.heap.ArenaAllocator, 628 map: DB.HashMap(.read_only), 629 ) !T { 630 var event: T = undefined; 631 632 switch (@typeInfo(T)) { 633 .@"struct" => |struct_info| { 634 inline for (struct_info.fields) |field| { 635 switch (@typeInfo(field.type)) { 636 .pointer => |pointer_info| { 637 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 638 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 639 } else { 640 @compileError("unsupported read field type: " ++ @typeName(field.type)); 641 } 642 }, 643 .array => |array_info| { 644 if (array_info.child == u8) { 645 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 646 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 647 @memcpy(@field(event, field.name)[0..], bytes); 648 } else { 649 @compileError("unsupported read field type: " ++ @typeName(field.type)); 650 } 651 }, 652 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 653 .int => |int_info| switch (int_info.signedness) { 654 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 655 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 656 }, 657 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 658 } 659 } 660 }, 661 else => @compileError("read expects a struct"), 662 } 663 664 return event; 665 } 666 667 fn readBytes( 668 comptime DB: type, 669 comptime hash_kind: hash.HashKind, 670 allocator: std.mem.Allocator, 671 map: DB.HashMap(.read_only), 672 field_name: []const u8, 673 ) ![]const u8 { 674 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 675 return try cursor.readBytesAlloc(allocator, null); 676 } 677 678 fn readUint( 679 comptime DB: type, 680 comptime hash_kind: hash.HashKind, 681 map: DB.HashMap(.read_only), 682 field_name: []const u8, 683 ) !u64 { 684 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 685 return try cursor.readUint(); 686 } 687 688 fn readInt( 689 comptime DB: type, 690 comptime hash_kind: hash.HashKind, 691 map: DB.HashMap(.read_only), 692 field_name: []const u8, 693 ) !i64 { 694 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 695 return try cursor.readInt(); 696 } 697 698 fn readBool( 699 comptime DB: type, 700 comptime hash_kind: hash.HashKind, 701 map: DB.HashMap(.read_only), 702 field_name: []const u8, 703 ) !bool { 704 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 705 var buffer: [5]u8 = undefined; 706 const bytes = try cursor.readBytesObject(&buffer); 707 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 708 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 709 if (std.mem.eql(u8, bytes.value, "true")) return true; 710 if (std.mem.eql(u8, bytes.value, "false")) return false; 711 return error.InvalidBool; 712 } 713 714 // 715 // writing to xitdb 716 // 717 718 pub fn upsert( 719 comptime T: type, 720 comptime DB: type, 721 comptime hash_kind: hash.HashKind, 722 map: DB.HashMap(.read_write), 723 event: T, 724 ) !void { 725 switch (@typeInfo(T)) { 726 .@"struct" => |struct_info| { 727 inline for (struct_info.fields) |field| { 728 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 729 } 730 }, 731 else => @compileError("upsert expects a struct"), 732 } 733 } 734 735 fn mergeChangedMapEntries( 736 comptime DB: type, 737 allocator: std.mem.Allocator, 738 target: DB.HashMap(.read_write), 739 parent: DB.HashMap(.read_only), 740 baseline: DB.HashMap(.read_only), 741 comptime is_top_level: bool, 742 ) !void { 743 var parent_iter = try parent.iterator(); 744 while (try parent_iter.next()) |kv_pair_cursor| { 745 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 746 747 const baseline_value_cursor = try baseline.getCursor(kv_pair.hash) orelse { 748 if ((try target.getCursor(kv_pair.hash)) != null) { 749 return error.MergeConflict; 750 } 751 752 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 753 continue; 754 }; 755 756 const tag = kv_pair.value_cursor.slot().tag; 757 758 if (tag != baseline_value_cursor.slot().tag) { 759 return error.UnexpectedTag; 760 } 761 762 if (kv_pair.value_cursor.slot().value == baseline_value_cursor.slot().value) { 763 continue; 764 } 765 766 if (tag == .hash_map) { 767 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 768 if (target_existing_cursor.slot().tag != .hash_map) { 769 return error.UnexpectedTag; 770 } 771 772 const target_child_cursor = try target.putCursor(kv_pair.hash); 773 const target_child = try DB.HashMap(.read_write).init(target_child_cursor); 774 const parent_child = try DB.HashMap(.read_only).init(kv_pair.value_cursor); 775 const baseline_child = try DB.HashMap(.read_only).init(baseline_value_cursor); 776 try mergeChangedMapEntries(DB, allocator, target_child, parent_child, baseline_child, false); 777 } else if (tag == .sorted_set) { 778 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 779 if (target_existing_cursor.slot().tag != .sorted_set) { 780 return error.UnexpectedTag; 781 } 782 783 const target_child_cursor = try target.putCursor(kv_pair.hash); 784 const target_child = try DB.SortedSet(.read_write).init(target_child_cursor); 785 const parent_child = try DB.SortedSet(.read_only).init(kv_pair.value_cursor); 786 const baseline_child = try DB.SortedSet(.read_only).init(baseline_value_cursor); 787 try mergeChangedSetEntries(DB, allocator, target_child, parent_child, baseline_child); 788 } else if (tag == .sorted_map) { 789 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 790 if (target_existing_cursor.slot().tag != .sorted_map) { 791 return error.UnexpectedTag; 792 } 793 794 const target_child_cursor = try target.putCursor(kv_pair.hash); 795 const target_child = try DB.SortedMap(.read_write).init(target_child_cursor); 796 const parent_child = try DB.SortedMap(.read_only).init(kv_pair.value_cursor); 797 const baseline_child = try DB.SortedMap(.read_only).init(baseline_value_cursor); 798 try mergeChangedSortedMapEntries(DB, allocator, target_child, parent_child, baseline_child); 799 } else if (is_top_level) { 800 // the moment-index is a top-level key in the haxy moment 801 // and is not a map. we don't want to do any merge of this. 802 continue; 803 } else { 804 const target_value_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 805 if (target_value_cursor.slot().tag != baseline_value_cursor.slot().tag) { 806 return error.UnexpectedTag; 807 } 808 if (target_value_cursor.slot().value != baseline_value_cursor.slot().value) { 809 return error.MergeConflict; 810 } 811 812 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 813 } 814 } 815 } 816 817 // three-way merge of a sorted map keyed by byte strings, like 818 // mergeChangedMapEntries but recursing into sorted-set values. 819 fn mergeChangedSortedMapEntries( 820 comptime DB: type, 821 allocator: std.mem.Allocator, 822 target: DB.SortedMap(.read_write), 823 parent: DB.SortedMap(.read_only), 824 baseline: DB.SortedMap(.read_only), 825 ) !void { 826 var parent_iter = try parent.iterator(); 827 while (try parent_iter.next()) |kv_pair_cursor| { 828 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 829 const key = try kv_pair.key_cursor.readBytesAlloc(allocator, null); 830 defer allocator.free(key); 831 832 const baseline_value_cursor = try baseline.getCursor(key) orelse { 833 if (try target.getCursor(key)) |target_existing_cursor| { 834 // both parents created this key. sets union (they hold 835 // independently added members); anything else conflicts. 836 const parent_tag = kv_pair.value_cursor.slot().tag; 837 if (target_existing_cursor.slot().tag != parent_tag) { 838 return error.UnexpectedTag; 839 } 840 if (parent_tag != .sorted_set) { 841 return error.MergeConflict; 842 } 843 844 const target_child_cursor = try target.putCursor(key); 845 const target_child = try DB.SortedSet(.read_write).init(target_child_cursor); 846 const parent_child = try DB.SortedSet(.read_only).init(kv_pair.value_cursor); 847 var set_iter = try parent_child.iterator(); 848 while (try set_iter.next()) |set_kv_cursor| { 849 const set_kv = try set_kv_cursor.readKeyValuePair(); 850 const set_key = try set_kv.key_cursor.readBytesAlloc(allocator, null); 851 defer allocator.free(set_key); 852 try target_child.put(set_key); 853 } 854 continue; 855 } 856 857 try target.put(key, .{ .slot = kv_pair.value_cursor.slot() }); 858 continue; 859 }; 860 861 const tag = kv_pair.value_cursor.slot().tag; 862 863 if (tag != baseline_value_cursor.slot().tag) { 864 return error.UnexpectedTag; 865 } 866 867 if (kv_pair.value_cursor.slot().value == baseline_value_cursor.slot().value) { 868 continue; 869 } 870 871 if (tag == .sorted_set) { 872 const target_existing_cursor = try target.getCursor(key) orelse return error.MergeConflict; 873 if (target_existing_cursor.slot().tag != .sorted_set) { 874 return error.UnexpectedTag; 875 } 876 877 const target_child_cursor = try target.putCursor(key); 878 const target_child = try DB.SortedSet(.read_write).init(target_child_cursor); 879 const parent_child = try DB.SortedSet(.read_only).init(kv_pair.value_cursor); 880 const baseline_child = try DB.SortedSet(.read_only).init(baseline_value_cursor); 881 try mergeChangedSetEntries(DB, allocator, target_child, parent_child, baseline_child); 882 } else { 883 const target_value_cursor = try target.getCursor(key) orelse return error.MergeConflict; 884 if (target_value_cursor.slot().tag != baseline_value_cursor.slot().tag) { 885 return error.UnexpectedTag; 886 } 887 if (target_value_cursor.slot().value != baseline_value_cursor.slot().value) { 888 return error.MergeConflict; 889 } 890 891 try target.put(key, .{ .slot = kv_pair.value_cursor.slot() }); 892 } 893 } 894 } 895 896 // three-way merge of a sorted set: apply the parent's changes relative to the 897 // baseline. keys have no values, so additions and removals can't conflict. 898 fn mergeChangedSetEntries( 899 comptime DB: type, 900 allocator: std.mem.Allocator, 901 target: DB.SortedSet(.read_write), 902 parent: DB.SortedSet(.read_only), 903 baseline: DB.SortedSet(.read_only), 904 ) !void { 905 var parent_iter = try parent.iterator(); 906 while (try parent_iter.next()) |kv_pair_cursor| { 907 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 908 const key = try kv_pair.key_cursor.readBytesAlloc(allocator, null); 909 defer allocator.free(key); 910 if (!try baseline.contains(key)) try target.put(key); 911 } 912 913 var baseline_iter = try baseline.iterator(); 914 while (try baseline_iter.next()) |kv_pair_cursor| { 915 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 916 const key = try kv_pair.key_cursor.readBytesAlloc(allocator, null); 917 defer allocator.free(key); 918 if (!try parent.contains(key)) _ = try target.remove(key); 919 } 920 } 921 922 fn upsertField( 923 comptime DB: type, 924 comptime hash_kind: hash.HashKind, 925 map: DB.HashMap(.read_write), 926 comptime field_name: []const u8, 927 comptime Field: type, 928 value: Field, 929 ) !void { 930 const key = hash.hashInt(hash_kind, field_name); 931 932 switch (@typeInfo(Field)) { 933 .pointer => |pointer_info| { 934 if (pointer_info.size == .slice and pointer_info.child == u8) { 935 try upsertBytes(DB, hash_kind, map, key, value); 936 } else { 937 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 938 } 939 }, 940 .array => |array_info| { 941 if (array_info.child == u8) { 942 try upsertBytes(DB, hash_kind, map, key, &value); 943 } else { 944 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 945 } 946 }, 947 .int => |int_info| switch (int_info.signedness) { 948 .unsigned => { 949 if (try map.getCursor(key)) |value_cursor| { 950 if (try value_cursor.readUint() == value) { 951 return; 952 } 953 } 954 955 try map.put(key, .{ .uint = value }); 956 }, 957 .signed => { 958 if (try map.getCursor(key)) |value_cursor| { 959 if (try value_cursor.readInt() == value) { 960 return; 961 } 962 } 963 964 try map.put(key, .{ .int = value }); 965 }, 966 }, 967 .bool => { 968 const bytes = if (value) "true" else "false"; 969 if (try map.getCursor(key)) |value_cursor| { 970 var buffer: [5]u8 = undefined; 971 const existing = try value_cursor.readBytesObject(&buffer); 972 if (existing.format_tag) |format_tag| { 973 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 974 return; 975 } 976 } 977 } 978 979 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 980 }, 981 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 982 } 983 } 984 985 fn upsertBytes( 986 comptime DB: type, 987 comptime hash_kind: hash.HashKind, 988 map: DB.HashMap(.read_write), 989 key: hash.HashInt(hash_kind), 990 value: []const u8, 991 ) !void { 992 var existing_cursor_maybe = try map.getCursor(key); 993 if (existing_cursor_maybe) |*existing_cursor| { 994 if (try bytesEqual(DB, existing_cursor, value)) { 995 return; 996 } 997 } 998 999 var value_cursor = try map.putCursor(key); 1000 var write_buffer: [1024]u8 = undefined; 1001 var writer = try value_cursor.writer(&write_buffer); 1002 try writer.interface.writeAll(value); 1003 try writer.finish(); 1004 } 1005 1006 fn bytesEqual( 1007 comptime DB: type, 1008 cursor: *DB.Cursor(.read_only), 1009 value: []const u8, 1010 ) !bool { 1011 var read_buffer: [1024]u8 = undefined; 1012 var reader = try cursor.reader(&read_buffer); 1013 if (reader.size != value.len) { 1014 return false; 1015 } 1016 1017 var chunk_buffer: [1024]u8 = undefined; 1018 var offset: usize = 0; 1019 while (offset < value.len) { 1020 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1021 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1022 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1023 return false; 1024 } 1025 offset += chunk_len; 1026 } 1027 1028 return true; 1029 } 1030 1031 // 1032 // CommitIterator 1033 // 1034 // differs from xit's ObjectIterator in a few ways: 1035 // 1036 // 1. iterates parents first, rather than children first 1037 // 2. `next` only returns the object id, not the full Object 1038 // 3. stores its temporary state in a file on disk to avoid OOMs 1039 // 1040 1041 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1042 return struct { 1043 const DB = EventDB(repo_opts.hash); 1044 const db_name = "haxy-repo-events.db"; 1045 1046 repo_dir: std.Io.Dir, 1047 db_file: std.Io.File, 1048 db: *DB, 1049 // map of each object id to its children 1050 parent_to_children: DB.HashMap(.read_write), 1051 // tracking pending parents is necessary because a child can only 1052 // be returned after all of its unconsumed parents have been returned 1053 child_to_pending_parents: DB.HashMap(.read_write), 1054 // queue of object ids that are ready to be returned from `next` 1055 ready_queue: DB.ArrayList(.read_write), 1056 ready_queue_index: u64, 1057 // the object id at the tip of this branch 1058 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1059 // the object id furthest back in the history that hasn't been consumed 1060 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1061 1062 pub fn init( 1063 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1064 io: std.Io, 1065 allocator: std.mem.Allocator, 1066 consumed_object_ids: DB.HashMap(.read_only), 1067 ref: rf.Ref, 1068 ) !CommitIterator(repo_kind, repo_opts) { 1069 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1070 errdefer { 1071 db_file.close(io); 1072 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1073 } 1074 1075 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1076 errdefer allocator.destroy(buffer_ptr); 1077 1078 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1079 errdefer buffer_ptr.deinit(); 1080 1081 const db_ptr = try allocator.create(DB); 1082 errdefer allocator.destroy(db_ptr); 1083 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr }); 1084 1085 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1086 1087 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1088 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1089 1090 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1091 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1092 1093 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1094 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1095 1096 var self = CommitIterator(repo_kind, repo_opts){ 1097 .repo_dir = state.core.repo_dir, 1098 .db_file = db_file, 1099 .db = db_ptr, 1100 .parent_to_children = parent_to_children, 1101 .child_to_pending_parents = child_to_pending_parents, 1102 .ready_queue = ready_queue, 1103 .ready_queue_index = 0, 1104 .newest_object_id = null, 1105 .oldest_object_id = null, 1106 }; 1107 errdefer self.deinit(io, allocator); 1108 1109 try self.collect(state, io, allocator, consumed_object_ids, ref); 1110 1111 return self; 1112 } 1113 1114 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1115 self.db_file.close(io); 1116 self.db.core.memory.buffer.deinit(); 1117 allocator.destroy(self.db.core.memory.buffer); 1118 self.repo_dir.deleteFile(io, db_name) catch {}; 1119 allocator.destroy(self.db); 1120 } 1121 1122 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 1123 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 1124 1125 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 1126 self.ready_queue_index += 1; 1127 1128 try self.enqueueChildren(&oid); 1129 return oid; 1130 } 1131 1132 fn collect( 1133 self: *CommitIterator(repo_kind, repo_opts), 1134 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1135 io: std.Io, 1136 allocator: std.mem.Allocator, 1137 consumed_object_ids: DB.HashMap(.read_only), 1138 ref: rf.Ref, 1139 ) !void { 1140 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 1141 1142 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 1143 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 1144 var walk_queue_index: u64 = 0; 1145 1146 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 1147 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 1148 1149 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1150 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1151 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1152 try walk_queue.append(.{ .bytes = &head_oid }); 1153 1154 while (walk_queue_index < try walk_queue.count()) { 1155 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 1156 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 1157 1158 walk_queue_index += 1; 1159 1160 // if we've seen this object id, skip it 1161 if (null != try seen_object_ids.getCursor(oid_int)) { 1162 continue; 1163 } 1164 1165 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 1166 1167 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 1168 defer commit_object.deinit(); 1169 1170 // if this object id has already been consumed, skip it 1171 if (null != try consumed_object_ids.getCursor(oid_int)) { 1172 continue; 1173 } 1174 1175 if (self.newest_object_id == null) self.newest_object_id = oid; 1176 self.oldest_object_id = oid; 1177 1178 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1179 var pending_parent_count: u64 = 0; 1180 for (parent_oids) |*parent_oid| { 1181 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1182 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 1183 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 1184 1185 // if this object id has already been consumed, skip it 1186 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 1187 continue; 1188 } 1189 1190 // if this object id hasn't already been seen, add it to the walk queue 1191 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 1192 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 1193 } 1194 1195 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 1196 const children = try DB.HashSet(.read_write).init(children_cursor); 1197 try children.put(oid_int, .{ .bytes = &oid }); 1198 pending_parent_count += 1; 1199 } 1200 1201 if (pending_parent_count == 0) { 1202 try self.ready_queue.append(.{ .bytes = &oid }); 1203 } else { 1204 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 1205 } 1206 } 1207 } 1208 1209 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 1210 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 1211 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 1212 const children = try DB.HashSet(.read_only).init(children_cursor); 1213 var children_iter = try children.iterator(); 1214 1215 while (try children_iter.next()) |*child_cursor| { 1216 const kv_pair = try child_cursor.readKeyValuePair(); 1217 const child_oid_int = kv_pair.hash; 1218 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 1219 const pending_parent_count = try pending_parent_cursor.readUint(); 1220 1221 if (pending_parent_count <= 1) { 1222 _ = try self.child_to_pending_parents.remove(child_oid_int); 1223 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 1224 try self.ready_queue.append(.{ .bytes = &child_oid }); 1225 } else { 1226 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 1227 } 1228 } 1229 } 1230 1231 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 1232 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 1233 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1234 _ = try oid_cursor.readBytes(&oid); 1235 return oid; 1236 } 1237 }; 1238 } 1239