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