╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const hash = xit.hash; 5 const mrg = xit.merge; 6 const obj = xit.object; 7 const rf = xit.ref; 8 9 pub const User = @import("event/User.zig"); 10 pub const Repo = @import("event/Repo.zig"); 11 pub const Issue = @import("event/Issue.zig"); 12 13 pub const event_id_size: usize = 32; 14 15 // the branch haxy events are committed to before being consumed 16 pub const events_ref: rf.Ref = .{ .kind = .head, .name = "haxy/meta" }; 17 18 pub const EventKind = enum { 19 user, 20 repo, 21 issue, 22 }; 23 24 pub const EventWithId = struct { 25 id: [event_id_size * 2]u8, 26 event: union(EventKind) { 27 user: ?User, 28 repo: ?Repo, 29 issue: ?Issue, 30 }, 31 32 pub fn jsonStringify(self: EventWithId, jw: anytype) !void { 33 try jw.beginObject(); 34 try jw.objectField("id"); 35 try jw.write(self.id); 36 try jw.objectField("kind"); 37 try jw.write(@tagName(self.event)); 38 try jw.objectField("data"); 39 switch (self.event) { 40 inline else => |event_maybe| try jw.write(event_maybe), 41 } 42 try jw.endObject(); 43 } 44 45 fn fromString(arena: *std.heap.ArenaAllocator, message: []const u8) !EventWithId { 46 const JsonEvent = struct { 47 id: [event_id_size * 2]u8, 48 kind: EventKind, 49 data: ?std.json.Value = null, 50 }; 51 const json_event = try std.json.parseFromSliceLeaky(JsonEvent, arena.allocator(), message, .{}); 52 return .{ 53 .id = json_event.id, 54 .event = switch (json_event.kind) { 55 .user => .{ 56 .user = if (json_event.data) |value| 57 try std.json.parseFromValueLeaky(User, arena.allocator(), value, .{}) 58 else 59 null, 60 }, 61 .repo => .{ 62 .repo = if (json_event.data) |value| 63 try std.json.parseFromValueLeaky(Repo, arena.allocator(), value, .{}) 64 else 65 null, 66 }, 67 .issue => .{ 68 .issue = if (json_event.data) |value| 69 try std.json.parseFromValueLeaky(Issue, arena.allocator(), value, .{}) 70 else 71 null, 72 }, 73 }, 74 }; 75 } 76 77 pub fn randomId(random: std.Random) [event_id_size]u8 { 78 var id_bytes: [event_id_size]u8 = undefined; 79 random.bytes(&id_bytes); 80 return id_bytes; 81 } 82 }; 83 84 pub fn consume( 85 comptime repo_opts: rp.RepoOpts(.xit), 86 io: std.Io, 87 allocator: std.mem.Allocator, 88 repo: *rp.Repo(.xit, repo_opts), 89 ref: rf.Ref, 90 ) !void { 91 const DB = rp.Repo(.xit, repo_opts).DB; 92 const State = rp.Repo(.xit, repo_opts).State; 93 94 const Ctx = struct { 95 core: *rp.Repo(.xit, repo_opts).Core, 96 io: std.Io, 97 allocator: std.mem.Allocator, 98 ref: rf.Ref, 99 100 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 101 var moment = try DB.HashMap(.read_write).init(cursor.*); 102 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 103 try consumeInTransaction(repo_opts, state, ctx.io, ctx.allocator, ctx.ref); 104 } 105 }; 106 107 try repo.core.db_file.lock(io, .exclusive); 108 defer repo.core.db_file.unlock(io); 109 110 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 111 try history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 112 .core = &repo.core, 113 .io = io, 114 .allocator = allocator, 115 .ref = ref, 116 }); 117 } 118 119 pub fn consumeInTransaction( 120 comptime repo_opts: rp.RepoOpts(.xit), 121 state: rp.Repo(.xit, repo_opts).State(.read_write), 122 io: std.Io, 123 allocator: std.mem.Allocator, 124 ref: rf.Ref, 125 ) !void { 126 const DB = rp.Repo(.xit, repo_opts).DB; 127 128 // the last_object_id represents the object id that was last consumed 129 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 130 if (try state.extra.moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id"))) |last_object_id_cursor| { 131 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 132 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 133 last_object_id_maybe = last_object_id_buffer; 134 } 135 136 // the list with all of haxy's state, including materialized views. 137 // the reason it is a list is so we can keep every previous haxy 138 // state, making it easy to revert to an older state if the user 139 // rebases some of the past commits. 140 const haxy_cursor = try state.extra.moment.putCursor(hash.hashInt(repo_opts.hash, "haxy")); 141 const haxy = try DB.ArrayList(.read_write).init(haxy_cursor); 142 143 // add a new item to the haxy list created above. 144 // we call the item haxy_moments. it is a map of object id to haxy moment. 145 // in other words, it maps each object id to a hash map containing the 146 // state that the database was in when that object id was consumed. 147 var haxy_moments_cursor = try haxy.appendCursor(); 148 // use the previous haxy_moments as the basis for this one if it exists 149 if (try haxy.getCursor(-2)) |last_haxy_moments_cursor| { 150 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 151 } 152 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 153 154 var commit_iter = try CommitIterator(repo_opts).init(state.readOnly(), io, allocator, haxy_moments.readOnly(), ref); 155 defer commit_iter.deinit(io, allocator); 156 157 // if there are no events to process, look at the oid at HEAD and update 158 // the last_object_id to point to it. this is important in situations 159 // where we do a merge and then force-push to remove the merge. see the 160 // merge test for an example. 161 if (commit_iter.newest_object_id == null) { 162 const head_oid_hex = (try rf.readRecur(.xit, repo_opts, state.readOnly(), io, .{ .ref = ref })) orelse return error.OidNotFound; 163 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 164 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 165 166 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 167 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 168 169 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 170 const moment_index = try moment_index_cursor.readUint(); 171 172 try haxy.slice(moment_index + 1); 173 try state.extra.moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = &head_oid }); 174 return; 175 } 176 177 // if this branch was rebased and force pushed, we need to detect that and 178 // properly revert the haxy state to the last valid state. we detect this 179 // by simply asking if the last event is a descendent of the last event 180 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 181 if (last_object_id_maybe) |*last_object_id| { 182 var is_rebased = false; 183 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 184 185 _ = mrg.getDescendent( 186 .xit, 187 repo_opts, 188 state.readOnly(), 189 io, 190 allocator, 191 &std.fmt.bytesToHex(last_object_id, .lower), 192 &std.fmt.bytesToHex(&newest_object_id, .lower), 193 ) catch |err| switch (err) { 194 error.DescendentNotFound => is_rebased = true, 195 else => |e| return e, 196 }; 197 198 if (is_rebased) { 199 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 200 var oldest_object = try obj.Object(.xit, repo_opts, .full).init(state.readOnly(), io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 201 defer oldest_object.deinit(); 202 203 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 204 switch (parent_oids.len) { 205 0 => { 206 // the branch was rebased all the way to the very beginning. 207 // we have a repo event with no parent, which means it is now 208 // the very first event. all we need to do is set the haxy list 209 // to be empty and make a new haxy_moments map to work with. 210 211 try haxy.slice(0); 212 haxy_moments_cursor = try haxy.appendCursor(); 213 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 214 215 last_object_id_maybe = null; 216 }, 217 1 => { 218 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 219 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 220 221 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 222 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 223 224 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 225 const old_moment_index = try old_moment_index_cursor.readUint(); 226 227 // resize the haxy list so we truncate all the moments that were 228 // created after the parent_oid was consumed 229 try haxy.slice(old_moment_index + 1); 230 231 // make a new haxy moment and set its initial value to the last haxy moment 232 haxy_moments_cursor = try haxy.appendCursor(); 233 const old_haxy_moments_cursor = try haxy.getCursor(old_moment_index) orelse return error.CursorNotFound; 234 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 235 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 236 237 last_object_id_maybe = oid; 238 }, 239 else => return error.UnexpectedParentCount, 240 } 241 } 242 } 243 244 while (try commit_iter.next()) |repo_event_oid| { 245 var commit_object = try obj.Object(.xit, repo_opts, .full).init(state.readOnly(), io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 246 defer commit_object.deinit(); 247 248 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 249 250 // create a moment for this object id 251 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 252 253 // if there was a previous object id, set this haxy moment's initial value to it. 254 // this efficiently "clones" the map so we make further modifications based on it. 255 if (parent_oids.len > 0) { 256 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 257 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 258 259 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 260 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 261 } 262 263 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 264 265 // merge changes from every parent after the first parent. the common 266 // ancestor is the baseline, so a later parent only contributes values 267 // it changed relative to the merge base. 268 if (parent_oids.len > 1) { 269 for (parent_oids[1..]) |*parent_oid| { 270 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 271 _ = try std.fmt.hexToBytes(&oid, parent_oid); 272 273 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 274 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 275 276 const baseline_oid_hex = try mrg.commonAncestor(.xit, repo_opts, state.readOnly(), io, allocator, &parent_oids[0], parent_oid); 277 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 278 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 279 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 280 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 281 282 try mergeChangedMapEntries(DB, haxy_moment, parent_haxy_moment, baseline_haxy_moment, true); 283 } 284 } 285 286 // associate this moment with the index it will first appear at in the haxy list. 287 // this will be important later so we can truncate that list if the user ever 288 // rebases starting at this object id. 289 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy.count() - 1 }); 290 291 // consume the event unless it's a merge commit 292 if (parent_oids.len <= 1) { 293 var arena = std.heap.ArenaAllocator.init(allocator); 294 defer arena.deinit(); 295 296 // read the message from the commit 297 try commit_object.object_reader.seekTo(commit_object.content.commit.message_position); 298 const message = try commit_object.object_reader.interface.allocRemaining(arena.allocator(), .unlimited); 299 300 const event_with_id = try EventWithId.fromString(&arena, message); 301 302 // get the id of the current event as bytes 303 var current_event_id: [event_id_size]u8 = undefined; 304 _ = try std.fmt.hexToBytes(&current_event_id, &event_with_id.id); 305 306 switch (event_with_id.event) { 307 .user => |event_maybe| try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena), 308 .repo => |event_maybe| try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena), 309 .issue => |event_maybe| try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe), 310 } 311 } 312 313 // the current object id is now the last one 314 last_object_id_maybe = repo_event_oid; 315 316 // prevent any of the data created above from being mutated by future iterations of this loop 317 try state.core.db.freeze(); 318 } 319 320 if (last_object_id_maybe) |*last_object_id| { 321 try state.extra.moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = last_object_id }); 322 } 323 } 324 325 pub fn currentMoment( 326 comptime repo_opts: rp.RepoOpts(.xit), 327 repo: *rp.Repo(.xit, repo_opts), 328 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 329 const DB = rp.Repo(.xit, repo_opts).DB; 330 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 331 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 332 const moment = try DB.HashMap(.read_only).init(moment_cursor); 333 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 334 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 335 _ = try last_object_id_cursor.readBytes(&last_object_id); 336 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 337 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 338 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 339 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 340 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 341 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 342 } 343 344 // commit each event as a JSON message on the events branch, then consume them 345 // into the database 346 pub fn commitAndConsume( 347 comptime repo_opts: rp.RepoOpts(.xit), 348 io: std.Io, 349 allocator: std.mem.Allocator, 350 repo: *rp.Repo(.xit, repo_opts), 351 ref: rf.Ref, 352 events: []const EventWithId, 353 ) !void { 354 var json: std.Io.Writer.Allocating = .init(allocator); 355 defer json.deinit(); 356 357 for (events) |event| { 358 json.clearRetainingCapacity(); 359 try std.json.Stringify.value(event, .{}, &json.writer); 360 _ = try repo.commitAtRef(io, allocator, .{ .message = json.written() }, null, ref); 361 } 362 363 try consume(repo_opts, io, allocator, repo, ref); 364 } 365 366 // 367 // reading from xitdb 368 // 369 370 pub fn read( 371 comptime T: type, 372 comptime DB: type, 373 comptime hash_kind: hash.HashKind, 374 arena: *std.heap.ArenaAllocator, 375 map: DB.HashMap(.read_only), 376 ) !T { 377 var event: T = undefined; 378 379 switch (@typeInfo(T)) { 380 .@"struct" => |struct_info| { 381 inline for (struct_info.fields) |field| { 382 switch (@typeInfo(field.type)) { 383 .pointer => |pointer_info| { 384 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 385 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 386 } else { 387 @compileError("unsupported read field type: " ++ @typeName(field.type)); 388 } 389 }, 390 .array => |array_info| { 391 if (array_info.child == u8) { 392 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 393 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 394 @memcpy(@field(event, field.name)[0..], bytes); 395 } else { 396 @compileError("unsupported read field type: " ++ @typeName(field.type)); 397 } 398 }, 399 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 400 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 401 } 402 } 403 }, 404 else => @compileError("read expects a struct"), 405 } 406 407 return event; 408 } 409 410 fn readBytes( 411 comptime DB: type, 412 comptime hash_kind: hash.HashKind, 413 allocator: std.mem.Allocator, 414 map: DB.HashMap(.read_only), 415 field_name: []const u8, 416 ) ![]const u8 { 417 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 418 return try cursor.readBytesAlloc(allocator, null); 419 } 420 421 fn readBool( 422 comptime DB: type, 423 comptime hash_kind: hash.HashKind, 424 map: DB.HashMap(.read_only), 425 field_name: []const u8, 426 ) !bool { 427 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 428 var buffer: [5]u8 = undefined; 429 const bytes = try cursor.readBytesObject(&buffer); 430 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 431 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 432 if (std.mem.eql(u8, bytes.value, "true")) return true; 433 if (std.mem.eql(u8, bytes.value, "false")) return false; 434 return error.InvalidBool; 435 } 436 437 // 438 // writing to xitdb 439 // 440 441 pub fn upsert( 442 comptime T: type, 443 comptime DB: type, 444 comptime hash_kind: hash.HashKind, 445 map: DB.HashMap(.read_write), 446 event: T, 447 ) !void { 448 switch (@typeInfo(T)) { 449 .@"struct" => |struct_info| { 450 inline for (struct_info.fields) |field| { 451 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 452 } 453 }, 454 else => @compileError("upsert expects a struct"), 455 } 456 } 457 458 fn mergeChangedMapEntries( 459 comptime DB: type, 460 target: DB.HashMap(.read_write), 461 parent: DB.HashMap(.read_only), 462 baseline: DB.HashMap(.read_only), 463 comptime is_top_level: bool, 464 ) !void { 465 var parent_iter = try parent.iterator(); 466 while (try parent_iter.next()) |kv_pair_cursor| { 467 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 468 469 const baseline_value_cursor = try baseline.getCursor(kv_pair.hash) orelse { 470 if ((try target.getCursor(kv_pair.hash)) != null) { 471 return error.MergeConflict; 472 } 473 474 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 475 continue; 476 }; 477 478 const tag = kv_pair.value_cursor.slot().tag; 479 480 if (tag != baseline_value_cursor.slot().tag) { 481 return error.UnexpectedTag; 482 } 483 484 if (kv_pair.value_cursor.slot().value == baseline_value_cursor.slot().value) { 485 continue; 486 } 487 488 if (tag == .hash_map) { 489 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 490 if (target_existing_cursor.slot().tag != .hash_map) { 491 return error.MergeConflict; 492 } 493 494 const target_child_cursor = try target.putCursor(kv_pair.hash); 495 const target_child = try DB.HashMap(.read_write).init(target_child_cursor); 496 const parent_child = try DB.HashMap(.read_only).init(kv_pair.value_cursor); 497 const baseline_child = try DB.HashMap(.read_only).init(baseline_value_cursor); 498 try mergeChangedMapEntries(DB, target_child, parent_child, baseline_child, false); 499 } else if (is_top_level) { 500 // the moment-index is a top-level key in the haxy moment 501 // and is not a map. we don't want to do any merge of this. 502 continue; 503 } else { 504 const target_value_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 505 if (target_value_cursor.slot().value != baseline_value_cursor.slot().value) { 506 return error.MergeConflict; 507 } 508 509 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 510 } 511 } 512 } 513 514 fn upsertField( 515 comptime DB: type, 516 comptime hash_kind: hash.HashKind, 517 map: DB.HashMap(.read_write), 518 comptime field_name: []const u8, 519 comptime Field: type, 520 value: Field, 521 ) !void { 522 const key = hash.hashInt(hash_kind, field_name); 523 524 switch (@typeInfo(Field)) { 525 .pointer => |pointer_info| { 526 if (pointer_info.size == .slice and pointer_info.child == u8) { 527 try upsertBytes(DB, hash_kind, map, key, value); 528 } else { 529 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 530 } 531 }, 532 .array => |array_info| { 533 if (array_info.child == u8) { 534 try upsertBytes(DB, hash_kind, map, key, &value); 535 } else { 536 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 537 } 538 }, 539 .int => |int_info| switch (int_info.signedness) { 540 .unsigned => { 541 if (try map.getCursor(key)) |value_cursor| { 542 if (try value_cursor.readUint() == value) { 543 return; 544 } 545 } 546 547 try map.put(key, .{ .uint = value }); 548 }, 549 .signed => { 550 if (try map.getCursor(key)) |value_cursor| { 551 if (try value_cursor.readInt() == value) { 552 return; 553 } 554 } 555 556 try map.put(key, .{ .int = value }); 557 }, 558 }, 559 .bool => { 560 const bytes = if (value) "true" else "false"; 561 if (try map.getCursor(key)) |value_cursor| { 562 var buffer: [5]u8 = undefined; 563 const existing = try value_cursor.readBytesObject(&buffer); 564 if (existing.format_tag) |format_tag| { 565 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 566 return; 567 } 568 } 569 } 570 571 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 572 }, 573 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 574 } 575 } 576 577 fn upsertBytes( 578 comptime DB: type, 579 comptime hash_kind: hash.HashKind, 580 map: DB.HashMap(.read_write), 581 key: hash.HashInt(hash_kind), 582 value: []const u8, 583 ) !void { 584 var existing_cursor_maybe = try map.getCursor(key); 585 if (existing_cursor_maybe) |*existing_cursor| { 586 if (try bytesEqual(DB, existing_cursor, value)) { 587 return; 588 } 589 } 590 591 var value_cursor = try map.putCursor(key); 592 var write_buffer: [1024]u8 = undefined; 593 var writer = try value_cursor.writer(&write_buffer); 594 try writer.interface.writeAll(value); 595 try writer.finish(); 596 } 597 598 fn bytesEqual( 599 comptime DB: type, 600 cursor: *DB.Cursor(.read_only), 601 value: []const u8, 602 ) !bool { 603 var read_buffer: [1024]u8 = undefined; 604 var reader = try cursor.reader(&read_buffer); 605 if (reader.size != value.len) { 606 return false; 607 } 608 609 var chunk_buffer: [1024]u8 = undefined; 610 var offset: usize = 0; 611 while (offset < value.len) { 612 const chunk_len = @min(chunk_buffer.len, value.len - offset); 613 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 614 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 615 return false; 616 } 617 offset += chunk_len; 618 } 619 620 return true; 621 } 622 623 // 624 // CommitIterator 625 // 626 // differs from xit's ObjectIterator in a few ways: 627 // 628 // 1. iterates parents first, rather than children first 629 // 2. `next` only returns the object id, not the full Object 630 // 3. stores its temporary state in a file on disk to avoid OOMs 631 // 632 633 pub fn CommitIterator(comptime repo_opts: rp.RepoOpts(.xit)) type { 634 return struct { 635 const DB = rp.Repo(.xit, repo_opts).DB; 636 const db_name = "haxy-repo-events.db"; 637 638 repo_dir: std.Io.Dir, 639 db_file: std.Io.File, 640 db: *DB, 641 // map of each object id to its children 642 parent_to_children: DB.HashMap(.read_write), 643 // tracking pending parents is necessary because a child can only 644 // be returned after all of its unconsumed parents have been returned 645 child_to_pending_parents: DB.HashMap(.read_write), 646 // queue of object ids that are ready to be returned from `next` 647 ready_queue: DB.ArrayList(.read_write), 648 ready_queue_index: u64, 649 // the object id at the tip of this branch 650 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 651 // the object id furthest back in the history that hasn't been consumed 652 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 653 654 pub fn init( 655 state: rp.Repo(.xit, repo_opts).State(.read_only), 656 io: std.Io, 657 allocator: std.mem.Allocator, 658 consumed_object_ids: DB.HashMap(.read_only), 659 ref: rf.Ref, 660 ) !CommitIterator(repo_opts) { 661 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 662 errdefer { 663 db_file.close(io); 664 state.core.repo_dir.deleteFile(io, db_name) catch {}; 665 } 666 667 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 668 errdefer allocator.destroy(buffer_ptr); 669 670 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 671 errdefer buffer_ptr.deinit(); 672 673 const db_ptr = try allocator.create(DB); 674 errdefer allocator.destroy(db_ptr); 675 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr }); 676 677 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 678 679 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 680 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 681 682 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 683 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 684 685 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 686 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 687 688 var self = CommitIterator(repo_opts){ 689 .repo_dir = state.core.repo_dir, 690 .db_file = db_file, 691 .db = db_ptr, 692 .parent_to_children = parent_to_children, 693 .child_to_pending_parents = child_to_pending_parents, 694 .ready_queue = ready_queue, 695 .ready_queue_index = 0, 696 .newest_object_id = null, 697 .oldest_object_id = null, 698 }; 699 errdefer self.deinit(io, allocator); 700 701 try self.collect(state, io, allocator, consumed_object_ids, ref); 702 703 return self; 704 } 705 706 pub fn deinit(self: *CommitIterator(repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 707 self.db_file.close(io); 708 self.db.core.memory.buffer.deinit(); 709 allocator.destroy(self.db.core.memory.buffer); 710 self.repo_dir.deleteFile(io, db_name) catch {}; 711 allocator.destroy(self.db); 712 } 713 714 pub fn next(self: *CommitIterator(repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 715 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 716 717 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 718 self.ready_queue_index += 1; 719 720 try self.enqueueChildren(&oid); 721 return oid; 722 } 723 724 fn collect( 725 self: *CommitIterator(repo_opts), 726 state: rp.Repo(.xit, repo_opts).State(.read_only), 727 io: std.Io, 728 allocator: std.mem.Allocator, 729 consumed_object_ids: DB.HashMap(.read_only), 730 ref: rf.Ref, 731 ) !void { 732 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 733 734 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 735 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 736 var walk_queue_index: u64 = 0; 737 738 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 739 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 740 741 const head_oid_hex = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 742 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 743 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 744 try walk_queue.append(.{ .bytes = &head_oid }); 745 746 while (walk_queue_index < try walk_queue.count()) { 747 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 748 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 749 750 walk_queue_index += 1; 751 752 // if we've seen this object id, skip it 753 if (null != try seen_object_ids.getCursor(oid_int)) { 754 continue; 755 } 756 757 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 758 759 var commit_object = try obj.Object(.xit, repo_opts, .full).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 760 defer commit_object.deinit(); 761 762 // if this object id has already been consumed, skip it 763 if (null != try consumed_object_ids.getCursor(oid_int)) { 764 continue; 765 } 766 767 if (self.newest_object_id == null) self.newest_object_id = oid; 768 self.oldest_object_id = oid; 769 770 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 771 var pending_parent_count: u64 = 0; 772 for (parent_oids) |*parent_oid| { 773 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 774 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 775 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 776 777 // if this object id has already been consumed, skip it 778 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 779 continue; 780 } 781 782 // if this object id hasn't already been seen, add it to the walk queue 783 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 784 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 785 } 786 787 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 788 const children = try DB.HashSet(.read_write).init(children_cursor); 789 try children.put(oid_int, .{ .bytes = &oid }); 790 pending_parent_count += 1; 791 } 792 793 if (pending_parent_count == 0) { 794 try self.ready_queue.append(.{ .bytes = &oid }); 795 } else { 796 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 797 } 798 } 799 } 800 801 fn enqueueChildren(self: *CommitIterator(repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 802 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 803 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 804 const children = try DB.HashSet(.read_only).init(children_cursor); 805 var children_iter = try children.iterator(); 806 807 while (try children_iter.next()) |*child_cursor| { 808 const kv_pair = try child_cursor.readKeyValuePair(); 809 const child_oid_int = kv_pair.hash; 810 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 811 const pending_parent_count = try pending_parent_cursor.readUint(); 812 813 if (pending_parent_count <= 1) { 814 _ = try self.child_to_pending_parents.remove(child_oid_int); 815 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 816 try self.ready_queue.append(.{ .bytes = &child_oid }); 817 } else { 818 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 819 } 820 } 821 } 822 823 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 824 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 825 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 826 _ = try oid_cursor.readBytes(&oid); 827 return oid; 828 } 829 }; 830 } 831