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