╭ 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 // commit each event as a JSON commit message on `ref`, then consume them into 523 // the db the repo's views read: the repo's own db, or the standalone local 524 // event db when `is_local`. 525 pub fn commitAndConsume( 526 comptime repo_kind: rp.RepoKind, 527 comptime repo_opts: rp.RepoOpts(repo_kind), 528 io: std.Io, 529 allocator: std.mem.Allocator, 530 repo: *rp.Repo(repo_kind, repo_opts), 531 ref: rf.Ref, 532 events: []const EventWithId, 533 is_local: bool, 534 ) !void { 535 // a branch that only exists on a remote continues from the remote tip, 536 // so a cloned repo's local branch stays connected to the server history 537 const first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8 = blk: { 538 if (try repo.readRef(io, ref) != null) break :blk null; 539 var remotes = try repo.listRemotes(io, allocator); 540 defer remotes.deinit(); 541 for (remotes.sections.keys()) |remote_name| { 542 const remote_ref: rf.Ref = .{ .kind = .{ .remote = remote_name }, .name = ref.name }; 543 if (try repo.readRef(io, remote_ref)) |oid| break :blk .{oid}; 544 } 545 break :blk null; 546 }; 547 var parent_oids: ?[]const [hash.hexLen(repo_opts.hash)]u8 = if (first_parent_oids) |*oids| oids else null; 548 549 var json: std.Io.Writer.Allocating = .init(allocator); 550 defer json.deinit(); 551 552 for (events) |event| { 553 json.clearRetainingCapacity(); 554 try std.json.Stringify.value(event, .{}, &json.writer); 555 _ = try repo.commitAtRef(io, allocator, .{ .author = "haxy <user@haxy>", .message = json.written(), .timestamp = event.timestamp, .parent_oids = parent_oids }, null, ref); 556 // later events parent on the ref's new tip 557 parent_oids = null; 558 } 559 560 if (is_local) { 561 try syncLocalEvents(repo_kind, repo_opts, io, allocator, repo); 562 } else switch (repo_kind) { 563 .xit => try consume(repo_opts, io, allocator, repo, ref), 564 // server repos are always xit 565 .git => unreachable, 566 } 567 } 568 569 // build the key for SortedSets sorted by timestamp. the big-endian timestamp 570 // makes byte order match creation order; the event id breaks ties and keeps 571 // keys unique within the same timestamp. 572 pub fn orderKey(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 573 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 574 std.mem.writeInt(u64, key[0..@sizeOf(u64)], timestamp, .big); 575 @memcpy(key[@sizeOf(u64)..], event_id); 576 return key; 577 } 578 579 pub fn orderKeyDesc(timestamp: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 580 return orderKey(std.math.maxInt(u64) - timestamp, event_id); 581 } 582 583 // split a pushed "<owner>/<repo>" path into its two components, or null if it 584 // isn't exactly two non-empty segments. 585 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 586 var it = std.mem.splitScalar(u8, path, '/'); 587 const owner = it.next() orelse return null; 588 const name = it.next() orelse return null; 589 if (it.next() != null) return null; 590 if (owner.len == 0 or name.len == 0) return null; 591 592 return .{ .owner = owner, .name = name }; 593 } 594 595 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 596 // directory under the repos dir 597 pub fn resolveOrCreateRepo( 598 io: std.Io, 599 allocator: std.mem.Allocator, 600 admin_repo_path: []const u8, 601 owner_name: []const u8, 602 repo_name: []const u8, 603 create_if_missing: bool, 604 ) !?[event_id_size * 2]u8 { 605 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 606 error.RepoNotFound => return null, 607 else => |e| return e, 608 }; 609 defer repo.deinit(io, allocator); 610 611 var arena = std.heap.ArenaAllocator.init(allocator); 612 defer arena.deinit(); 613 614 const moment = try currentMoment(admin_repo_opts, &repo); 615 616 // an already-registered repo reuses its event id, so a re-push (or a clone) 617 // lands in the same repo 618 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 619 return std.fmt.bytesToHex(found.event_id, .lower); 620 } 621 622 if (!create_if_missing) return null; 623 624 // the new repo is owned by the named user, read from the name index; an 625 // unknown owner can't own a repo, so the push is rejected 626 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 627 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 628 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 629 var owner_user_id: [event_id_size]u8 = undefined; 630 _ = try owner_id_cursor.readBytes(&owner_user_id); 631 632 var id_bytes: [event_id_size]u8 = undefined; 633 io.random(&id_bytes); 634 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 635 636 try commitAndConsume(.xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 637 .id = event_id_hex, 638 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 639 .event = .{ .repo = .{ 640 .user_id = &owner_user_id, 641 .name = repo_name, 642 .description = "", 643 .enable_issue = true, 644 } }, 645 }}, false); 646 647 return event_id_hex; 648 } 649 650 // 651 // reading from xitdb 652 // 653 654 pub fn read( 655 comptime T: type, 656 comptime DB: type, 657 comptime hash_kind: hash.HashKind, 658 arena: *std.heap.ArenaAllocator, 659 map: DB.HashMap(.read_only), 660 ) !T { 661 var event: T = undefined; 662 663 switch (@typeInfo(T)) { 664 .@"struct" => |struct_info| { 665 inline for (struct_info.fields) |field| { 666 switch (@typeInfo(field.type)) { 667 .pointer => |pointer_info| { 668 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 669 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 670 } else { 671 @compileError("unsupported read field type: " ++ @typeName(field.type)); 672 } 673 }, 674 .array => |array_info| { 675 if (array_info.child == u8) { 676 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 677 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 678 @memcpy(@field(event, field.name)[0..], bytes); 679 } else { 680 @compileError("unsupported read field type: " ++ @typeName(field.type)); 681 } 682 }, 683 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 684 .int => |int_info| switch (int_info.signedness) { 685 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 686 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 687 }, 688 .@"enum" => { 689 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 690 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 691 }, 692 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 693 } 694 } 695 }, 696 else => @compileError("read expects a struct"), 697 } 698 699 return event; 700 } 701 702 fn readBytes( 703 comptime DB: type, 704 comptime hash_kind: hash.HashKind, 705 allocator: std.mem.Allocator, 706 map: DB.HashMap(.read_only), 707 field_name: []const u8, 708 ) ![]const u8 { 709 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 710 return try cursor.readBytesAlloc(allocator, null); 711 } 712 713 fn readUint( 714 comptime DB: type, 715 comptime hash_kind: hash.HashKind, 716 map: DB.HashMap(.read_only), 717 field_name: []const u8, 718 ) !u64 { 719 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 720 return try cursor.readUint(); 721 } 722 723 fn readInt( 724 comptime DB: type, 725 comptime hash_kind: hash.HashKind, 726 map: DB.HashMap(.read_only), 727 field_name: []const u8, 728 ) !i64 { 729 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 730 return try cursor.readInt(); 731 } 732 733 fn readBool( 734 comptime DB: type, 735 comptime hash_kind: hash.HashKind, 736 map: DB.HashMap(.read_only), 737 field_name: []const u8, 738 ) !bool { 739 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 740 var buffer: [5]u8 = undefined; 741 const bytes = try cursor.readBytesObject(&buffer); 742 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 743 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 744 if (std.mem.eql(u8, bytes.value, "true")) return true; 745 if (std.mem.eql(u8, bytes.value, "false")) return false; 746 return error.InvalidBool; 747 } 748 749 // 750 // writing to xitdb 751 // 752 753 pub fn upsert( 754 comptime T: type, 755 comptime DB: type, 756 comptime hash_kind: hash.HashKind, 757 map: DB.HashMap(.read_write), 758 event: T, 759 ) !void { 760 switch (@typeInfo(T)) { 761 .@"struct" => |struct_info| { 762 inline for (struct_info.fields) |field| { 763 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 764 } 765 }, 766 else => @compileError("upsert expects a struct"), 767 } 768 } 769 770 // three-way merge of a hash map 771 fn mergeChangedMapEntries( 772 comptime DB: type, 773 allocator: std.mem.Allocator, 774 target: DB.HashMap(.read_write), 775 parent: DB.HashMap(.read_only), 776 baseline: DB.HashMap(.read_only), 777 comptime is_top_level: bool, 778 ) !void { 779 var parent_iter = try parent.iterator(); 780 while (try parent_iter.next()) |kv_pair_cursor| { 781 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 782 783 const baseline_value_cursor = try baseline.getCursor(kv_pair.hash) orelse { 784 if ((try target.getCursor(kv_pair.hash)) != null) { 785 return error.MergeConflict; 786 } 787 788 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 789 continue; 790 }; 791 792 const tag = kv_pair.value_cursor.slot().tag; 793 794 if (tag != baseline_value_cursor.slot().tag) { 795 return error.UnexpectedTag; 796 } 797 798 if (kv_pair.value_cursor.slot().value == baseline_value_cursor.slot().value) { 799 continue; 800 } 801 802 if (tag == .hash_map) { 803 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 804 if (target_existing_cursor.slot().tag != .hash_map) { 805 return error.UnexpectedTag; 806 } 807 808 const target_child_cursor = try target.putCursor(kv_pair.hash); 809 const target_child = try DB.HashMap(.read_write).init(target_child_cursor); 810 const parent_child = try DB.HashMap(.read_only).init(kv_pair.value_cursor); 811 const baseline_child = try DB.HashMap(.read_only).init(baseline_value_cursor); 812 try mergeChangedMapEntries(DB, allocator, target_child, parent_child, baseline_child, false); 813 } else if (tag == .sorted_set) { 814 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 815 if (target_existing_cursor.slot().tag != .sorted_set) { 816 return error.UnexpectedTag; 817 } 818 819 const target_child_cursor = try target.putCursor(kv_pair.hash); 820 const target_child = try DB.SortedSet(.read_write).init(target_child_cursor); 821 const parent_child = try DB.SortedSet(.read_only).init(kv_pair.value_cursor); 822 const baseline_child = try DB.SortedSet(.read_only).init(baseline_value_cursor); 823 try mergeChangedSetEntries(DB, allocator, target_child, parent_child, baseline_child); 824 } else if (tag == .sorted_map) { 825 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 826 if (target_existing_cursor.slot().tag != .sorted_map) { 827 return error.UnexpectedTag; 828 } 829 830 const target_child_cursor = try target.putCursor(kv_pair.hash); 831 const target_child = try DB.SortedMap(.read_write).init(target_child_cursor); 832 const parent_child = try DB.SortedMap(.read_only).init(kv_pair.value_cursor); 833 const baseline_child = try DB.SortedMap(.read_only).init(baseline_value_cursor); 834 try mergeChangedSortedMapEntries(DB, allocator, target_child, parent_child, baseline_child); 835 } else if (is_top_level) { 836 // the moment-index is a top-level key in the haxy moment 837 // and is not a map. we don't want to do any merge of this. 838 continue; 839 } else { 840 const target_value_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 841 if (target_value_cursor.slot().tag != baseline_value_cursor.slot().tag) { 842 return error.UnexpectedTag; 843 } 844 if (target_value_cursor.slot().value != baseline_value_cursor.slot().value) { 845 return error.MergeConflict; 846 } 847 848 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 849 } 850 } 851 } 852 853 // three-way merge of a sorted map 854 fn mergeChangedSortedMapEntries( 855 comptime DB: type, 856 allocator: std.mem.Allocator, 857 target: DB.SortedMap(.read_write), 858 parent: DB.SortedMap(.read_only), 859 baseline: DB.SortedMap(.read_only), 860 ) !void { 861 var parent_iter = try parent.iterator(); 862 while (try parent_iter.next()) |kv_pair_cursor| { 863 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 864 const key = try kv_pair.key_cursor.readBytesAlloc(allocator, null); 865 defer allocator.free(key); 866 867 const baseline_value_cursor = try baseline.getCursor(key) orelse { 868 if (try target.getCursor(key)) |target_existing_cursor| { 869 // both parents created this key. sets union (they hold 870 // independently added members); anything else conflicts. 871 const parent_tag = kv_pair.value_cursor.slot().tag; 872 if (target_existing_cursor.slot().tag != parent_tag) { 873 return error.UnexpectedTag; 874 } 875 if (parent_tag != .sorted_set) { 876 return error.MergeConflict; 877 } 878 879 const target_child_cursor = try target.putCursor(key); 880 const target_child = try DB.SortedSet(.read_write).init(target_child_cursor); 881 const parent_child = try DB.SortedSet(.read_only).init(kv_pair.value_cursor); 882 var set_iter = try parent_child.iterator(); 883 while (try set_iter.next()) |set_kv_cursor| { 884 const set_kv = try set_kv_cursor.readKeyValuePair(); 885 const set_key = try set_kv.key_cursor.readBytesAlloc(allocator, null); 886 defer allocator.free(set_key); 887 try target_child.put(set_key); 888 } 889 continue; 890 } 891 892 try target.put(key, .{ .slot = kv_pair.value_cursor.slot() }); 893 continue; 894 }; 895 896 const tag = kv_pair.value_cursor.slot().tag; 897 898 if (tag != baseline_value_cursor.slot().tag) { 899 return error.UnexpectedTag; 900 } 901 902 if (kv_pair.value_cursor.slot().value == baseline_value_cursor.slot().value) { 903 continue; 904 } 905 906 if (tag == .sorted_set) { 907 const target_existing_cursor = try target.getCursor(key) orelse return error.MergeConflict; 908 if (target_existing_cursor.slot().tag != .sorted_set) { 909 return error.UnexpectedTag; 910 } 911 912 const target_child_cursor = try target.putCursor(key); 913 const target_child = try DB.SortedSet(.read_write).init(target_child_cursor); 914 const parent_child = try DB.SortedSet(.read_only).init(kv_pair.value_cursor); 915 const baseline_child = try DB.SortedSet(.read_only).init(baseline_value_cursor); 916 try mergeChangedSetEntries(DB, allocator, target_child, parent_child, baseline_child); 917 } else { 918 const target_value_cursor = try target.getCursor(key) orelse return error.MergeConflict; 919 if (target_value_cursor.slot().tag != baseline_value_cursor.slot().tag) { 920 return error.UnexpectedTag; 921 } 922 if (target_value_cursor.slot().value != baseline_value_cursor.slot().value) { 923 return error.MergeConflict; 924 } 925 926 try target.put(key, .{ .slot = kv_pair.value_cursor.slot() }); 927 } 928 } 929 } 930 931 // three-way merge of a sorted set: apply the parent's changes relative to the 932 // baseline. keys have no values, so additions and removals can't conflict. 933 fn mergeChangedSetEntries( 934 comptime DB: type, 935 allocator: std.mem.Allocator, 936 target: DB.SortedSet(.read_write), 937 parent: DB.SortedSet(.read_only), 938 baseline: DB.SortedSet(.read_only), 939 ) !void { 940 var parent_iter = try parent.iterator(); 941 while (try parent_iter.next()) |kv_pair_cursor| { 942 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 943 const key = try kv_pair.key_cursor.readBytesAlloc(allocator, null); 944 defer allocator.free(key); 945 if (!try baseline.contains(key)) try target.put(key); 946 } 947 948 var baseline_iter = try baseline.iterator(); 949 while (try baseline_iter.next()) |kv_pair_cursor| { 950 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 951 const key = try kv_pair.key_cursor.readBytesAlloc(allocator, null); 952 defer allocator.free(key); 953 if (!try parent.contains(key)) _ = try target.remove(key); 954 } 955 } 956 957 fn upsertField( 958 comptime DB: type, 959 comptime hash_kind: hash.HashKind, 960 map: DB.HashMap(.read_write), 961 comptime field_name: []const u8, 962 comptime Field: type, 963 value: Field, 964 ) !void { 965 const key = hash.hashInt(hash_kind, field_name); 966 967 switch (@typeInfo(Field)) { 968 .pointer => |pointer_info| { 969 if (pointer_info.size == .slice and pointer_info.child == u8) { 970 try upsertBytes(DB, hash_kind, map, key, value); 971 } else { 972 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 973 } 974 }, 975 .array => |array_info| { 976 if (array_info.child == u8) { 977 try upsertBytes(DB, hash_kind, map, key, &value); 978 } else { 979 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 980 } 981 }, 982 .int => |int_info| switch (int_info.signedness) { 983 .unsigned => { 984 if (try map.getCursor(key)) |value_cursor| { 985 if (try value_cursor.readUint() == value) { 986 return; 987 } 988 } 989 990 try map.put(key, .{ .uint = value }); 991 }, 992 .signed => { 993 if (try map.getCursor(key)) |value_cursor| { 994 if (try value_cursor.readInt() == value) { 995 return; 996 } 997 } 998 999 try map.put(key, .{ .int = value }); 1000 }, 1001 }, 1002 .bool => { 1003 const bytes = if (value) "true" else "false"; 1004 if (try map.getCursor(key)) |value_cursor| { 1005 var buffer: [5]u8 = undefined; 1006 const existing = try value_cursor.readBytesObject(&buffer); 1007 if (existing.format_tag) |format_tag| { 1008 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1009 return; 1010 } 1011 } 1012 } 1013 1014 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1015 }, 1016 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1017 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1018 } 1019 } 1020 1021 fn upsertBytes( 1022 comptime DB: type, 1023 comptime hash_kind: hash.HashKind, 1024 map: DB.HashMap(.read_write), 1025 key: hash.HashInt(hash_kind), 1026 value: []const u8, 1027 ) !void { 1028 var existing_cursor_maybe = try map.getCursor(key); 1029 if (existing_cursor_maybe) |*existing_cursor| { 1030 if (try bytesEqual(DB, existing_cursor, value)) { 1031 return; 1032 } 1033 } 1034 1035 var value_cursor = try map.putCursor(key); 1036 var write_buffer: [1024]u8 = undefined; 1037 var writer = try value_cursor.writer(&write_buffer); 1038 try writer.interface.writeAll(value); 1039 try writer.finish(); 1040 } 1041 1042 fn bytesEqual( 1043 comptime DB: type, 1044 cursor: *DB.Cursor(.read_only), 1045 value: []const u8, 1046 ) !bool { 1047 var read_buffer: [1024]u8 = undefined; 1048 var reader = try cursor.reader(&read_buffer); 1049 if (reader.size != value.len) { 1050 return false; 1051 } 1052 1053 var chunk_buffer: [1024]u8 = undefined; 1054 var offset: usize = 0; 1055 while (offset < value.len) { 1056 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1057 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1058 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1059 return false; 1060 } 1061 offset += chunk_len; 1062 } 1063 1064 return true; 1065 } 1066 1067 // 1068 // CommitIterator 1069 // 1070 // differs from xit's ObjectIterator in a few ways: 1071 // 1072 // 1. iterates parents first, rather than children first 1073 // 2. `next` only returns the object id, not the full Object 1074 // 3. stores its temporary state in a file on disk to avoid OOMs 1075 // 1076 1077 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1078 return struct { 1079 const DB = EventDB(repo_opts.hash); 1080 const db_name = "haxy-repo-events.db"; 1081 1082 repo_dir: std.Io.Dir, 1083 db_file: std.Io.File, 1084 db: *DB, 1085 // map of each object id to its children 1086 parent_to_children: DB.HashMap(.read_write), 1087 // tracking pending parents is necessary because a child can only 1088 // be returned after all of its unconsumed parents have been returned 1089 child_to_pending_parents: DB.HashMap(.read_write), 1090 // queue of object ids that are ready to be returned from `next` 1091 ready_queue: DB.ArrayList(.read_write), 1092 ready_queue_index: u64, 1093 // the object id at the tip of this branch 1094 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1095 // the object id furthest back in the history that hasn't been consumed 1096 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1097 1098 pub fn init( 1099 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1100 io: std.Io, 1101 allocator: std.mem.Allocator, 1102 consumed_object_ids: DB.HashMap(.read_only), 1103 ref: rf.Ref, 1104 ) !CommitIterator(repo_kind, repo_opts) { 1105 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1106 errdefer { 1107 db_file.close(io); 1108 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1109 } 1110 1111 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1112 errdefer allocator.destroy(buffer_ptr); 1113 1114 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1115 errdefer buffer_ptr.deinit(); 1116 1117 const db_ptr = try allocator.create(DB); 1118 errdefer allocator.destroy(db_ptr); 1119 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr }); 1120 1121 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1122 1123 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1124 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1125 1126 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1127 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1128 1129 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1130 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1131 1132 var self = CommitIterator(repo_kind, repo_opts){ 1133 .repo_dir = state.core.repo_dir, 1134 .db_file = db_file, 1135 .db = db_ptr, 1136 .parent_to_children = parent_to_children, 1137 .child_to_pending_parents = child_to_pending_parents, 1138 .ready_queue = ready_queue, 1139 .ready_queue_index = 0, 1140 .newest_object_id = null, 1141 .oldest_object_id = null, 1142 }; 1143 errdefer self.deinit(io, allocator); 1144 1145 try self.collect(state, io, allocator, consumed_object_ids, ref); 1146 1147 return self; 1148 } 1149 1150 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1151 self.db_file.close(io); 1152 self.db.core.memory.buffer.deinit(); 1153 allocator.destroy(self.db.core.memory.buffer); 1154 self.repo_dir.deleteFile(io, db_name) catch {}; 1155 allocator.destroy(self.db); 1156 } 1157 1158 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 1159 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 1160 1161 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 1162 self.ready_queue_index += 1; 1163 1164 try self.enqueueChildren(&oid); 1165 return oid; 1166 } 1167 1168 fn collect( 1169 self: *CommitIterator(repo_kind, repo_opts), 1170 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1171 io: std.Io, 1172 allocator: std.mem.Allocator, 1173 consumed_object_ids: DB.HashMap(.read_only), 1174 ref: rf.Ref, 1175 ) !void { 1176 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 1177 1178 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 1179 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 1180 var walk_queue_index: u64 = 0; 1181 1182 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 1183 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 1184 1185 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1186 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1187 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1188 try walk_queue.append(.{ .bytes = &head_oid }); 1189 1190 while (walk_queue_index < try walk_queue.count()) { 1191 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 1192 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 1193 1194 walk_queue_index += 1; 1195 1196 // if we've seen this object id, skip it 1197 if (null != try seen_object_ids.getCursor(oid_int)) { 1198 continue; 1199 } 1200 1201 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 1202 1203 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 1204 defer commit_object.deinit(); 1205 1206 // if this object id has already been consumed, skip it 1207 if (null != try consumed_object_ids.getCursor(oid_int)) { 1208 continue; 1209 } 1210 1211 if (self.newest_object_id == null) self.newest_object_id = oid; 1212 self.oldest_object_id = oid; 1213 1214 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1215 var pending_parent_count: u64 = 0; 1216 for (parent_oids) |*parent_oid| { 1217 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1218 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 1219 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 1220 1221 // if this object id has already been consumed, skip it 1222 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 1223 continue; 1224 } 1225 1226 // if this object id hasn't already been seen, add it to the walk queue 1227 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 1228 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 1229 } 1230 1231 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 1232 const children = try DB.HashSet(.read_write).init(children_cursor); 1233 try children.put(oid_int, .{ .bytes = &oid }); 1234 pending_parent_count += 1; 1235 } 1236 1237 if (pending_parent_count == 0) { 1238 try self.ready_queue.append(.{ .bytes = &oid }); 1239 } else { 1240 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 1241 } 1242 } 1243 } 1244 1245 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 1246 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 1247 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 1248 const children = try DB.HashSet(.read_only).init(children_cursor); 1249 var children_iter = try children.iterator(); 1250 1251 while (try children_iter.next()) |*child_cursor| { 1252 const kv_pair = try child_cursor.readKeyValuePair(); 1253 const child_oid_int = kv_pair.hash; 1254 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 1255 const pending_parent_count = try pending_parent_cursor.readUint(); 1256 1257 if (pending_parent_count <= 1) { 1258 _ = try self.child_to_pending_parents.remove(child_oid_int); 1259 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 1260 try self.ready_queue.append(.{ .bytes = &child_oid }); 1261 } else { 1262 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 1263 } 1264 } 1265 } 1266 1267 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 1268 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 1269 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1270 _ = try oid_cursor.readBytes(&oid); 1271 return oid; 1272 } 1273 }; 1274 } 1275