╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
188 if (last_object_id_maybe) |*last_object_id| { 189 var is_rebased = false; 190 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 191 192 _ = mrg.getDescendent( 193 .xit, 194 repo_opts, 195 state.readOnly(), 196 io, 197 allocator, 198 &std.fmt.bytesToHex(last_object_id, .lower), 199 &std.fmt.bytesToHex(&newest_object_id, .lower), 200 ) catch |err| switch (err) { 201 error.DescendentNotFound => is_rebased = true, 202 else => |e| return e, 203 }; 204 205 if (is_rebased) { 206 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 207 var oldest_object = try obj.Object(.xit, repo_opts, .full).init(state.readOnly(), io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 208 defer oldest_object.deinit(); 209 210 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 211 switch (parent_oids.len) { 212 0 => { 213 // the branch was rebased all the way to the very beginning. 214 // we have a repo event with no parent, which means it is now 215 // the very first event. all we need to do is set the haxy list 216 // to be empty and make a new haxy_moments map to work with. 217 218 try haxy.slice(0); 219 haxy_moments_cursor = try haxy.appendCursor(); 220 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 221 222 last_object_id_maybe = null; 223 }, 224 1 => { 225 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 226 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 227 228 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 229 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 230 231 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 232 const old_moment_index = try old_moment_index_cursor.readUint(); 233 234 // resize the haxy list so we truncate all the moments that were 235 // created after the parent_oid was consumed 236 try haxy.slice(old_moment_index + 1); 237 238 // make a new haxy moment and set its initial value to the last haxy moment 239 haxy_moments_cursor = try haxy.appendCursor(); 240 const old_haxy_moments_cursor = try haxy.getCursor(old_moment_index) orelse return error.CursorNotFound; 241 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 242 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 243 244 last_object_id_maybe = oid; 245 }, 246 else => return error.UnexpectedParentCount, 247 } 248 } 249 } 250 251 while (try commit_iter.next()) |repo_event_oid| { 252 var commit_object = try obj.Object(.xit, repo_opts, .full).init(state.readOnly(), io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 253 defer commit_object.deinit(); 254 255 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 256 257 // create a moment for this object id 258 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 259 260 // if there was a previous object id, set this haxy moment's initial value to it. 261 // this efficiently "clones" the map so we make further modifications based on it. 262 if (parent_oids.len > 0) { 263 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 264 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 265 266 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 267 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 268 } 269 270 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 271 272 // merge changes from every parent after the first parent. the common 273 // ancestor is the baseline, so a later parent only contributes values 274 // it changed relative to the merge base. 275 if (parent_oids.len > 1) { 276 for (parent_oids[1..]) |*parent_oid| { 277 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 278 _ = try std.fmt.hexToBytes(&oid, parent_oid); 279 280 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 281 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 282 283 const baseline_oid_hex = try mrg.commonAncestor(.xit, repo_opts, state.readOnly(), io, allocator, &parent_oids[0], parent_oid); 284 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 285 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 286 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 287 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 288 289 try mergeChangedMapEntries(DB, haxy_moment, parent_haxy_moment, baseline_haxy_moment, true); 290 } 291 } 292 293 // associate this moment with the index it will first appear at in the haxy list. 294 // this will be important later so we can truncate that list if the user ever 295 // rebases starting at this object id. 296 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy.count() - 1 }); 297 298 // consume the event unless it's a merge commit 299 if (parent_oids.len <= 1) { 300 var arena = std.heap.ArenaAllocator.init(allocator); 301 defer arena.deinit(); 302 303 // read the message from the commit 304 try commit_object.object_reader.seekTo(commit_object.content.commit.message_position); 305 const message = try commit_object.object_reader.interface.allocRemaining(arena.allocator(), .unlimited); 306 307 const event_with_id = try EventWithId.fromString(&arena, message); 308 309 // get the id of the current event as bytes 310 var current_event_id: [event_id_size]u8 = undefined; 311 _ = try std.fmt.hexToBytes(&current_event_id, &event_with_id.id); 312 313 switch (event_with_id.event) { 314 .user => |event_maybe| try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena), 315 .repo => |event_maybe| try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe, &arena), 316 .issue => |event_maybe| try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, event_maybe), 317 } 318 } 319 320 // the current object id is now the last one 321 last_object_id_maybe = repo_event_oid; 322 323 // prevent any of the data created above from being mutated by future iterations of this loop 324 try state.core.db.freeze(); 325 } 326 327 if (last_object_id_maybe) |*last_object_id| { 328 try state.extra.moment.put(hash.hashInt(repo_opts.hash, "haxy-last-object-id"), .{ .bytes = last_object_id }); 329 } 330 } 331 332 pub fn currentMoment( 333 comptime repo_opts: rp.RepoOpts(.xit), 334 repo: *rp.Repo(.xit, repo_opts), 335 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 336 const DB = rp.Repo(.xit, repo_opts).DB; 337 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 338 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 339 const moment = try DB.HashMap(.read_only).init(moment_cursor); 340 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 341 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 342 _ = try last_object_id_cursor.readBytes(&last_object_id); 343 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 344 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 345 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 346 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 347 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 348 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 349 } 350 351 pub fn commitAndConsume( 352 comptime repo_opts: rp.RepoOpts(.xit), 353 io: std.Io, 354 allocator: std.mem.Allocator, 355 repo: *rp.Repo(.xit, repo_opts), 356 ref: rf.Ref, 357 events: []const EventWithId, 358 ) !void { 359 var json: std.Io.Writer.Allocating = .init(allocator); 360 defer json.deinit(); 361 362 for (events) |event| { 363 json.clearRetainingCapacity(); 364 try std.json.Stringify.value(event, .{}, &json.writer); 365 _ = try repo.commitAtRef(io, allocator, .{ .message = json.written() }, null, ref); 366 } 367 368 try consume(repo_opts, io, allocator, repo, ref); 369 } 370 371 // split a pushed "<owner>/<repo>" path into its two components, or null if it 372 // isn't exactly two non-empty segments. 373 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 374 var it = std.mem.splitScalar(u8, path, '/'); 375 const owner = it.next() orelse return null; 376 const name = it.next() orelse return null; 377 if (it.next() != null) return null; 378 if (owner.len == 0 or name.len == 0) return null; 379 380 return .{ .owner = owner, .name = name }; 381 } 382 383 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 384 // directory under the repos dir 385 pub fn resolveOrCreateRepo( 386 io: std.Io, 387 allocator: std.mem.Allocator, 388 admin_repo_path: []const u8, 389 owner_name: []const u8, 390 repo_name: []const u8, 391 create_if_missing: bool, 392 ) !?[event_id_size * 2]u8 { 393 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 394 error.RepoNotFound => return null, 395 else => |e| return e, 396 }; 397 defer repo.deinit(io, allocator); 398 399 var arena = std.heap.ArenaAllocator.init(allocator); 400 defer arena.deinit(); 401 402 const moment = try currentMoment(admin_repo_opts, &repo); 403 404 // an already-registered repo reuses its event id, so a re-push (or a clone) 405 // lands in the same repo 406 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 407 return std.fmt.bytesToHex(found.event_id, .lower); 408 } 409 410 if (!create_if_missing) return null; 411 412 // the new repo is owned by the named user, read from the name index; an 413 // unknown owner can't own a repo, so the push is rejected 414 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 415 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 416 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 417 var owner_user_id: [event_id_size]u8 = undefined; 418 _ = try owner_id_cursor.readBytes(&owner_user_id); 419 420 var id_bytes: [event_id_size]u8 = undefined; 421 io.random(&id_bytes); 422 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 423 424 try commitAndConsume(admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 425 .id = event_id_hex, 426 .event = .{ .repo = .{ 427 .user_id = &owner_user_id, 428 .name = repo_name, 429 .description = "", 430 .enable_issue = true, 431 } }, 432 }}); 433 434 return event_id_hex; 435 } 436 437 // 438 // reading from xitdb 439 // 440 441 pub fn read( 442 comptime T: type, 443 comptime DB: type, 444 comptime hash_kind: hash.HashKind, 445 arena: *std.heap.ArenaAllocator, 446 map: DB.HashMap(.read_only), 447 ) !T { 448 var event: T = undefined; 449 450 switch (@typeInfo(T)) { 451 .@"struct" => |struct_info| { 452 inline for (struct_info.fields) |field| { 453 switch (@typeInfo(field.type)) { 454 .pointer => |pointer_info| { 455 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 456 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 457 } else { 458 @compileError("unsupported read field type: " ++ @typeName(field.type)); 459 } 460 }, 461 .array => |array_info| { 462 if (array_info.child == u8) { 463 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 464 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 465 @memcpy(@field(event, field.name)[0..], bytes); 466 } else { 467 @compileError("unsupported read field type: " ++ @typeName(field.type)); 468 } 469 }, 470 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 471 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 472 } 473 } 474 }, 475 else => @compileError("read expects a struct"), 476 } 477 478 return event; 479 } 480 481 fn readBytes( 482 comptime DB: type, 483 comptime hash_kind: hash.HashKind, 484 allocator: std.mem.Allocator, 485 map: DB.HashMap(.read_only), 486 field_name: []const u8, 487 ) ![]const u8 { 488 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 489 return try cursor.readBytesAlloc(allocator, null); 490 } 491 492 fn readBool( 493 comptime DB: type, 494 comptime hash_kind: hash.HashKind, 495 map: DB.HashMap(.read_only), 496 field_name: []const u8, 497 ) !bool { 498 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 499 var buffer: [5]u8 = undefined; 500 const bytes = try cursor.readBytesObject(&buffer); 501 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 502 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 503 if (std.mem.eql(u8, bytes.value, "true")) return true; 504 if (std.mem.eql(u8, bytes.value, "false")) return false; 505 return error.InvalidBool; 506 } 507 508 // 509 // writing to xitdb 510 // 511 512 pub fn upsert( 513 comptime T: type, 514 comptime DB: type, 515 comptime hash_kind: hash.HashKind, 516 map: DB.HashMap(.read_write), 517 event: T, 518 ) !void { 519 switch (@typeInfo(T)) { 520 .@"struct" => |struct_info| { 521 inline for (struct_info.fields) |field| { 522 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 523 } 524 }, 525 else => @compileError("upsert expects a struct"), 526 } 527 } 528 529 fn mergeChangedMapEntries( 530 comptime DB: type, 531 target: DB.HashMap(.read_write), 532 parent: DB.HashMap(.read_only), 533 baseline: DB.HashMap(.read_only), 534 comptime is_top_level: bool, 535 ) !void { 536 var parent_iter = try parent.iterator(); 537 while (try parent_iter.next()) |kv_pair_cursor| { 538 const kv_pair = try kv_pair_cursor.readKeyValuePair(); 539 540 const baseline_value_cursor = try baseline.getCursor(kv_pair.hash) orelse { 541 if ((try target.getCursor(kv_pair.hash)) != null) { 542 return error.MergeConflict; 543 } 544 545 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 546 continue; 547 }; 548 549 const tag = kv_pair.value_cursor.slot().tag; 550 551 if (tag != baseline_value_cursor.slot().tag) { 552 return error.UnexpectedTag; 553 } 554 555 if (kv_pair.value_cursor.slot().value == baseline_value_cursor.slot().value) { 556 continue; 557 } 558 559 if (tag == .hash_map) { 560 const target_existing_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 561 if (target_existing_cursor.slot().tag != .hash_map) { 562 return error.MergeConflict; 563 } 564 565 const target_child_cursor = try target.putCursor(kv_pair.hash); 566 const target_child = try DB.HashMap(.read_write).init(target_child_cursor); 567 const parent_child = try DB.HashMap(.read_only).init(kv_pair.value_cursor); 568 const baseline_child = try DB.HashMap(.read_only).init(baseline_value_cursor); 569 try mergeChangedMapEntries(DB, target_child, parent_child, baseline_child, false); 570 } else if (is_top_level) { 571 // the moment-index is a top-level key in the haxy moment 572 // and is not a map. we don't want to do any merge of this. 573 continue; 574 } else { 575 const target_value_cursor = try target.getCursor(kv_pair.hash) orelse return error.MergeConflict; 576 if (target_value_cursor.slot().value != baseline_value_cursor.slot().value) { 577 return error.MergeConflict; 578 } 579 580 try target.put(kv_pair.hash, .{ .slot = kv_pair.value_cursor.slot() }); 581 } 582 } 583 } 584 585 fn upsertField( 586 comptime DB: type, 587 comptime hash_kind: hash.HashKind, 588 map: DB.HashMap(.read_write), 589 comptime field_name: []const u8, 590 comptime Field: type, 591 value: Field, 592 ) !void { 593 const key = hash.hashInt(hash_kind, field_name); 594 595 switch (@typeInfo(Field)) { 596 .pointer => |pointer_info| { 597 if (pointer_info.size == .slice and pointer_info.child == u8) { 598 try upsertBytes(DB, hash_kind, map, key, value); 599 } else { 600 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 601 } 602 }, 603 .array => |array_info| { 604 if (array_info.child == u8) { 605 try upsertBytes(DB, hash_kind, map, key, &value); 606 } else { 607 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 608 } 609 }, 610 .int => |int_info| switch (int_info.signedness) { 611 .unsigned => { 612 if (try map.getCursor(key)) |value_cursor| { 613 if (try value_cursor.readUint() == value) { 614 return; 615 } 616 } 617 618 try map.put(key, .{ .uint = value }); 619 }, 620 .signed => { 621 if (try map.getCursor(key)) |value_cursor| { 622 if (try value_cursor.readInt() == value) { 623 return; 624 } 625 } 626 627 try map.put(key, .{ .int = value }); 628 }, 629 }, 630 .bool => { 631 const bytes = if (value) "true" else "false"; 632 if (try map.getCursor(key)) |value_cursor| { 633 var buffer: [5]u8 = undefined; 634 const existing = try value_cursor.readBytesObject(&buffer); 635 if (existing.format_tag) |format_tag| { 636 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 637 return; 638 } 639 } 640 } 641 642 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 643 }, 644 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 645 } 646 } 647 648 fn upsertBytes( 649 comptime DB: type, 650 comptime hash_kind: hash.HashKind, 651 map: DB.HashMap(.read_write), 652 key: hash.HashInt(hash_kind), 653 value: []const u8, 654 ) !void { 655 var existing_cursor_maybe = try map.getCursor(key); 656 if (existing_cursor_maybe) |*existing_cursor| { 657 if (try bytesEqual(DB, existing_cursor, value)) { 658 return; 659 } 660 } 661 662 var value_cursor = try map.putCursor(key); 663 var write_buffer: [1024]u8 = undefined; 664 var writer = try value_cursor.writer(&write_buffer); 665 try writer.interface.writeAll(value); 666 try writer.finish(); 667 } 668 669 fn bytesEqual( 670 comptime DB: type, 671 cursor: *DB.Cursor(.read_only), 672 value: []const u8, 673 ) !bool { 674 var read_buffer: [1024]u8 = undefined; 675 var reader = try cursor.reader(&read_buffer); 676 if (reader.size != value.len) { 677 return false; 678 } 679 680 var chunk_buffer: [1024]u8 = undefined; 681 var offset: usize = 0; 682 while (offset < value.len) { 683 const chunk_len = @min(chunk_buffer.len, value.len - offset); 684 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 685 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 686 return false; 687 } 688 offset += chunk_len; 689 } 690 691 return true; 692 } 693 694 // 695 // CommitIterator 696 // 697 // differs from xit's ObjectIterator in a few ways: 698 // 699 // 1. iterates parents first, rather than children first 700 // 2. `next` only returns the object id, not the full Object 701 // 3. stores its temporary state in a file on disk to avoid OOMs 702 // 703 704 pub fn CommitIterator(comptime repo_opts: rp.RepoOpts(.xit)) type { 705 return struct { 706 const DB = rp.Repo(.xit, repo_opts).DB; 707 const db_name = "haxy-repo-events.db"; 708 709 repo_dir: std.Io.Dir, 710 db_file: std.Io.File, 711 db: *DB, 712 // map of each object id to its children 713 parent_to_children: DB.HashMap(.read_write), 714 // tracking pending parents is necessary because a child can only 715 // be returned after all of its unconsumed parents have been returned 716 child_to_pending_parents: DB.HashMap(.read_write), 717 // queue of object ids that are ready to be returned from `next` 718 ready_queue: DB.ArrayList(.read_write), 719 ready_queue_index: u64, 720 // the object id at the tip of this branch 721 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 722 // the object id furthest back in the history that hasn't been consumed 723 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 724 725 pub fn init( 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 ) !CommitIterator(repo_opts) { 732 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 733 errdefer { 734 db_file.close(io); 735 state.core.repo_dir.deleteFile(io, db_name) catch {}; 736 } 737 738 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 739 errdefer allocator.destroy(buffer_ptr); 740 741 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 742 errdefer buffer_ptr.deinit(); 743 744 const db_ptr = try allocator.create(DB); 745 errdefer allocator.destroy(db_ptr); 746 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr }); 747 748 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 749 750 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 751 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 752 753 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 754 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 755 756 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 757 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 758 759 var self = CommitIterator(repo_opts){ 760 .repo_dir = state.core.repo_dir, 761 .db_file = db_file, 762 .db = db_ptr, 763 .parent_to_children = parent_to_children, 764 .child_to_pending_parents = child_to_pending_parents, 765 .ready_queue = ready_queue, 766 .ready_queue_index = 0, 767 .newest_object_id = null, 768 .oldest_object_id = null, 769 }; 770 errdefer self.deinit(io, allocator); 771 772 try self.collect(state, io, allocator, consumed_object_ids, ref); 773 774 return self; 775 } 776 777 pub fn deinit(self: *CommitIterator(repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 778 self.db_file.close(io); 779 self.db.core.memory.buffer.deinit(); 780 allocator.destroy(self.db.core.memory.buffer); 781 self.repo_dir.deleteFile(io, db_name) catch {}; 782 allocator.destroy(self.db); 783 } 784 785 pub fn next(self: *CommitIterator(repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 786 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 787 788 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 789 self.ready_queue_index += 1; 790 791 try self.enqueueChildren(&oid); 792 return oid; 793 } 794 795 fn collect( 796 self: *CommitIterator(repo_opts), 797 state: rp.Repo(.xit, repo_opts).State(.read_only), 798 io: std.Io, 799 allocator: std.mem.Allocator, 800 consumed_object_ids: DB.HashMap(.read_only), 801 ref: rf.Ref, 802 ) !void { 803 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 804 805 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 806 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 807 var walk_queue_index: u64 = 0; 808 809 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 810 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 811 812 const head_oid_hex = (try rf.readRecur(.xit, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 813 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 814 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 815 try walk_queue.append(.{ .bytes = &head_oid }); 816 817 while (walk_queue_index < try walk_queue.count()) { 818 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 819 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 820 821 walk_queue_index += 1; 822 823 // if we've seen this object id, skip it 824 if (null != try seen_object_ids.getCursor(oid_int)) { 825 continue; 826 } 827 828 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 829 830 var commit_object = try obj.Object(.xit, repo_opts, .full).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 831 defer commit_object.deinit(); 832 833 // if this object id has already been consumed, skip it 834 if (null != try consumed_object_ids.getCursor(oid_int)) { 835 continue; 836 } 837 838 if (self.newest_object_id == null) self.newest_object_id = oid; 839 self.oldest_object_id = oid; 840 841 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 842 var pending_parent_count: u64 = 0; 843 for (parent_oids) |*parent_oid| { 844 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 845 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 846 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 847 848 // if this object id has already been consumed, skip it 849 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 850 continue; 851 } 852 853 // if this object id hasn't already been seen, add it to the walk queue 854 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 855 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 856 } 857 858 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 859 const children = try DB.HashSet(.read_write).init(children_cursor); 860 try children.put(oid_int, .{ .bytes = &oid }); 861 pending_parent_count += 1; 862 } 863 864 if (pending_parent_count == 0) { 865 try self.ready_queue.append(.{ .bytes = &oid }); 866 } else { 867 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 868 } 869 } 870 } 871 872 fn enqueueChildren(self: *CommitIterator(repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 873 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 874 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 875 const children = try DB.HashSet(.read_only).init(children_cursor); 876 var children_iter = try children.iterator(); 877 878 while (try children_iter.next()) |*child_cursor| { 879 const kv_pair = try child_cursor.readKeyValuePair(); 880 const child_oid_int = kv_pair.hash; 881 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 882 const pending_parent_count = try pending_parent_cursor.readUint(); 883 884 if (pending_parent_count <= 1) { 885 _ = try self.child_to_pending_parents.remove(child_oid_int); 886 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 887 try self.ready_queue.append(.{ .bytes = &child_oid }); 888 } else { 889 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 890 } 891 } 892 } 893 894 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 895 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 896 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 897 _ = try oid_cursor.readBytes(&oid); 898 return oid; 899 } 900 }; 901 } 902