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