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