╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1316 io, 1317 allocator, 1318 event, 1319 &trees.head, 1320 author, 1321 committer, 1322 commit_object.content.commit.metadata.timestamp, 1323 ); 1324 } 1325 1326 break :blk .{ 1327 .event = event, 1328 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1329 .created_order = event_order, 1330 .updated_order = event_order, 1331 .event_oid = &event_oid, 1332 .base_tree_oid = &trees.base, 1333 .head_tree_oid = &trees.head, 1334 .patch_oid = &patch_oid, 1335 .commit_count = PatchRev.commitCount(repo_kind, repo_opts, read_state, io, allocator, event.base_oid, event.source_oid) catch null, 1336 }; 1337 } else null; 1338 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1339 }, 1340 .patch => |event_maybe| { 1341 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 1342 .event = event, 1343 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1344 .created_timestamp = commit_object.content.commit.metadata.timestamp, 1345 .created_order = event_order, 1346 .updated_order = event_order, 1347 } else null; 1348 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1349 }, 1350 } 1351 } 1352 1353 // the current object id is now the last one 1354 last_object_id_maybe = repo_event_oid; 1355 1356 // prevent any of the data created above from being mutated by future iterations of this loop 1357 try db.freeze(); 1358 } 1359 1360 if (last_object_id_maybe) |*last_object_id| { 1361 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1362 } 1363 1364 return true; 1365 } 1366 1367 // the conflicted records of one kind, keyed by the same order key its id set 1368 // uses, so this doubles as the index the conflicts view lists and counts. every 1369 // value under an entry is a slot reference to a structure that already exists: 1370 // 1371 // <order key> -> conflict entry 1372 // conflicted-fields the conflicting field names, space separated 1373 // base-record the merge base's whole record 1374 // their-record the merged-in side's whole record 1375 // their-field->oid that side's field name to commit map 1376 // 1377 // our own value is the live record and our commit is in the kind's oid map, so 1378 // neither is repeated here. 1379 pub const conflicted_fields_key = "conflicted-fields"; 1380 pub const base_record_key = "base-record"; 1381 pub const their_record_key = "their-record"; 1382 pub const their_field_to_oid_key = "their-field->oid"; 1383 1384 // record the commit against every field this event changes. a merge passes no 1385 // oid, since each field's winner may come from a different side. 1386 pub fn writeOid( 1387 comptime T: type, 1388 comptime DB: type, 1389 comptime hash_kind: hash.HashKind, 1390 id_to_field_to_oid: DB.HashMap(.read_write), 1391 record_key: hash.HashInt(hash_kind), 1392 existing_maybe: ?T, 1393 event: T, 1394 event_oid: ?[]const u8, 1395 ) !void { 1396 const oid = event_oid orelse return; 1397 1398 // created only once a field actually changes 1399 var field_oids: ?DB.SortedMap(.read_write) = null; 1400 1401 const info = @typeInfo(T).@"struct"; 1402 inline for (info.field_names, info.field_types) |field_name, field_type| { 1403 const changed = if (existing_maybe) |existing| 1404 !fieldEqual(field_type, @field(existing, field_name), @field(event, field_name)) 1405 else 1406 true; 1407 if (changed) { 1408 if (field_oids == null) { 1409 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1410 } 1411 if (field_oids) |map| try map.put(field_name, .{ .bytes = oid }); 1412 } 1413 } 1414 } 1415 1416 // the whole field list, space separated, is the longest it can get 1417 fn conflictedFieldsMaxLen(comptime T: type) usize { 1418 var len: usize = 0; 1419 for (@typeInfo(T).@"struct".field_names) |name| len += name.len + 1; 1420 return len; 1421 } 1422 1423 pub const MergePolicy = enum { 1424 field_conflicts, 1425 target_wins, 1426 }; 1427 1428 // what a three-way merge did with a field 1429 pub const FieldMerge = enum { 1430 // the target's value stands, because neither side changed it, both made the 1431 // same change, or only the target changed it 1432 kept, 1433 parent, 1434 conflicted, 1435 }; 1436 1437 // three-way merge each field. one only the parent changed takes the parent's 1438 // value; one both sides changed differently keeps the target's. a missing 1439 // baseline makes every differing field a conflict. 1440 fn mergeFields( 1441 comptime T: type, 1442 baseline_maybe: ?T, 1443 target: T, 1444 parent: T, 1445 outcome: *[@typeInfo(T).@"struct".field_names.len]FieldMerge, 1446 ) T { 1447 var merged = target; 1448 1449 const info = @typeInfo(T).@"struct"; 1450 inline for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { 1451 const target_value = @field(target, field_name); 1452 const parent_value = @field(parent, field_name); 1453 1454 if (!fieldEqual(field_type, target_value, parent_value)) { 1455 outcome[i] = if (baseline_maybe) |baseline| blk: { 1456 const baseline_value = @field(baseline, field_name); 1457 if (fieldEqual(field_type, target_value, baseline_value)) { 1458 @field(merged, field_name) = parent_value; 1459 break :blk .parent; 1460 } 1461 // only the target changed it 1462 if (fieldEqual(field_type, parent_value, baseline_value)) break :blk .kept; 1463 break :blk .conflicted; 1464 } else .conflicted; 1465 } 1466 } 1467 1468 return merged; 1469 } 1470 1471 // three-way merge of one kind's records from a merge parent. kinds that expose 1472 // conflicts merge field by field; the others take one whole record. the result 1473 // goes through the kind's `consume`, which re-derives the indexes from it. a 1474 // removal carries over unless the other side changed the record, so a merge 1475 // never fails. 1476 pub fn merge( 1477 comptime T: type, 1478 comptime DB: type, 1479 comptime hash_kind: hash.HashKind, 1480 allocator: std.mem.Allocator, 1481 haxy_moment: DB.HashMap(.read_write), 1482 parent_moment: DB.HashMap(.read_only), 1483 baseline_moment: DB.HashMap(.read_only), 1484 ) !void { 1485 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1486 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1487 1488 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1489 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1490 1491 var baseline_records: ?DB.HashMap(.read_only) = null; 1492 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1493 baseline_records = try DB.HashMap(.read_only).init(cursor); 1494 } 1495 1496 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1497 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1498 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1499 switch (comptime T.merge_policy) { 1500 .field_conflicts => { 1501 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1502 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1503 } 1504 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1505 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1506 } 1507 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1508 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1509 } 1510 }, 1511 .target_wins => {}, 1512 } 1513 1514 var arena = std.heap.ArenaAllocator.init(allocator); 1515 defer arena.deinit(); 1516 1517 var iter = try parent_set.iteratorFromIndex(0); 1518 while (try iter.next()) |kv_pair_cursor| { 1519 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1520 const record_key = hash.hashInt(hash_kind, &event_id); 1521 1522 _ = arena.reset(.retain_capacity); 1523 1524 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1525 const parent_slot = parent_record_cursor.slot(); 1526 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1527 1528 // the parent left this record alone 1529 if (baseline_slot) |slot| { 1530 if (slot.eql(parent_slot)) continue; 1531 } 1532 1533 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1534 1535 // re-derived every iteration, since `consume` writes through its own 1536 // handles 1537 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1538 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1539 1540 // a record the target doesn't have arrives wholesale from the parent 1541 var outcome: [@typeInfo(T).@"struct".field_names.len]FieldMerge = @splat(.parent); 1542 var merged = parent_record; 1543 1544 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1545 // both sides share the change 1546 if (target_record_cursor.slot().eql(parent_slot)) continue; 1547 1548 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1549 1550 var baseline_record: ?T.Record = null; 1551 if (baseline_records) |map| { 1552 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1553 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1554 } 1555 } 1556 1557 switch (comptime T.merge_policy) { 1558 .field_conflicts => { 1559 outcome = @splat(.kept); 1560 merged = target_record; 1561 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1562 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1563 if (comptime @hasDecl(T, "resolveMerge")) { 1564 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1565 } 1566 1567 // merge the removed state separately from serialized fields. removal 1568 // carries over an unchanged record, while an edit or restoration 1569 // keeps it active. 1570 merged.removed = if (target_record.removed == parent_record.removed) 1571 target_record.removed 1572 else if (baseline_record) |baseline| blk: { 1573 const active = if (!target_record.removed) target_record else parent_record; 1574 if (active.removed != baseline.removed) break :blk false; 1575 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1576 break :blk true; 1577 } else false; 1578 }, 1579 .target_wins => { 1580 // an uncontested parent change carries over. if both sides 1581 // changed the record, the target wins as a whole, except that 1582 // an edit or restoration wins over a removal. 1583 const target_changed = if (baseline_slot) |slot| 1584 !target_record_cursor.slot().eql(slot) 1585 else 1586 true; 1587 merged = if (!target_changed) 1588 parent_record 1589 else if (target_record.removed != parent_record.removed) 1590 if (target_record.removed) parent_record else target_record 1591 else 1592 target_record; 1593 }, 1594 } 1595 } 1596 1597 // the index is unique, so a key the target gave to a different record 1598 // leaves this one out rather than stranding that one behind a name it 1599 // no longer owns 1600 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1601 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1602 const name_index = try DB.SortedMap(.read_write).init(name_index_cursor); 1603 if (try name_index.getCursor(merged.event.name)) |owner_cursor| { 1604 var owner_id: [event_id_size]u8 = undefined; 1605 _ = try owner_cursor.readBytes(&owner_id); 1606 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1607 } 1608 } 1609 1610 // `consume` sets no oids, since each field's winner may come from 1611 // a different side 1612 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1613 1614 switch (comptime T.merge_policy) { 1615 .field_conflicts => {}, 1616 .target_wins => continue, 1617 } 1618 1619 // removed records do not carry field conflicts 1620 if (merged.removed) continue; 1621 1622 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1623 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1624 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1625 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1626 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1627 1628 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1629 if (parent_id_to_field_to_oid) |map| { 1630 if (try map.getCursor(record_key)) |field_oids_cursor| { 1631 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1632 } 1633 } 1634 // created only once a field actually comes from the parent 1635 var field_oids: ?DB.SortedMap(.read_write) = null; 1636 1637 // the fields both sides changed differently, space separated 1638 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1639 var conflicted_len: usize = 0; 1640 1641 inline for (@typeInfo(T).@"struct".field_names, 0..) |field_name, i| { 1642 switch (outcome[i]) { 1643 // the target's value stands, so its oid does too 1644 .kept => {}, 1645 // the parent set this value, so its commit takes the field. a 1646 // parent with no oid took its own value from a merge, leaving 1647 // the field unattributed rather than crediting the target's 1648 // commit for a value it no longer holds. 1649 .parent => { 1650 if (field_oids == null) { 1651 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1652 } 1653 const map = field_oids orelse unreachable; 1654 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field_name) else null; 1655 if (parent_oid) |oid_cursor| { 1656 try map.put(field_name, .{ .slot = oid_cursor.slot() }); 1657 } else { 1658 _ = try map.remove(field_name); 1659 } 1660 }, 1661 .conflicted => { 1662 if (conflicted_len > 0) { 1663 conflicted_fields[conflicted_len] = ' '; 1664 conflicted_len += 1; 1665 } 1666 @memcpy(conflicted_fields[conflicted_len..][0..field_name.len], field_name); 1667 conflicted_len += field_name.len; 1668 }, 1669 } 1670 } 1671 1672 if (conflicted_len > 0) { 1673 // each side's whole record is stored by reference, so the view can 1674 // show any of them or take theirs wholesale 1675 _ = try conflicts.remove(&merged_key); 1676 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1677 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1678 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1679 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1680 if (parent_field_oids) |map| { 1681 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1682 } 1683 continue; 1684 } 1685 1686 // created_order never changes, so the parent keys this record's conflict 1687 // identically, and it carries over when the target has none, unless the 1688 // parent's entry is unchanged from the baseline, meaning the target 1689 // inherited it too and resolving it removed it here. 1690 if (parent_conflicts) |map| { 1691 if (null == try conflicts.getCursor(&merged_key)) { 1692 if (try map.getSlot(&merged_key)) |conflict_slot| { 1693 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1694 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1695 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1696 } 1697 } 1698 } 1699 } 1700 } 1701 1702 // a comment, attachment or assignment a write names under a thread 1703 pub const ThreadChild = union(enum) { 1704 comment: *const [event_id_size]u8, 1705 attach: *const [event_id_size]u8, 1706 assign: *const [event_id_size]u8, 1707 }; 1708 1709 // whether `thread_id` names a thread of `thread_kind` in the repo's events, and 1710 // `child`, when given, belongs to it. a caller's url can claim any kind for any 1711 // id, so every write under a thread checks its claim here first. 1712 pub fn threadHolds( 1713 comptime repo_kind: rp.RepoKind, 1714 comptime repo_opts: rp.RepoOpts(repo_kind), 1715 io: std.Io, 1716 allocator: std.mem.Allocator, 1717 repo: *rp.Repo(repo_kind, repo_opts), 1718 thread_kind: EventKind, 1719 thread_id: *const [event_id_size]u8, 1720 child_maybe: ?ThreadChild, 1721 ) !bool { 1722 const DB = EventDB(repo_opts.hash); 1723 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1724 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1725 const moment = (if (event_db_maybe) |*event_db| 1726 currentMomentFromDb(repo_opts.hash, event_db.db) 1727 else if (repo_kind == .git) 1728 return false 1729 else 1730 currentMoment(repo_opts, repo)) catch return false; 1731 1732 // only these kinds are threads 1733 switch (thread_kind) { 1734 .discuss, .issue, .patch => {}, 1735 else => return false, 1736 } 1737 const kinds_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return false; 1738 const kinds = try DB.HashMap(.read_only).init(kinds_cursor); 1739 if ((try readEventKind(repo_opts.hash, kinds, thread_id)) != thread_kind) return false; 1740 1741 const child = child_maybe orelse return true; 1742 var arena = std.heap.ArenaAllocator.init(allocator); 1743 defer arena.deinit(); 1744 const thread_id_hex = std.fmt.bytesToHex(thread_id.*, .lower); 1745 switch (child) { 1746 .comment => |id| { 1747 const comment = (try readRecordSubset(Comment, struct { event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1748 return std.mem.eql(u8, &comment.event.thread_id, &thread_id_hex); 1749 }, 1750 .attach => |id| { 1751 const attachment = (try readRecordSubset(Attachment, struct { event: struct { target_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1752 return std.mem.eql(u8, &attachment.event.target_id, &thread_id_hex); 1753 }, 1754 // only an active assignment can be removed 1755 .assign => |id| { 1756 const assignment = (try readRecordSubset(Assignment, struct { removed: bool, event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1757 return !assignment.removed and std.mem.eql(u8, &assignment.event.thread_id, &thread_id_hex); 1758 }, 1759 } 1760 } 1761 1762 // remove an event a thread's page names: the thread itself, or a comment, 1763 // attachment or assignment, which must belong to it 1764 pub fn removeInThread( 1765 host: Host, 1766 comptime repo_kind: rp.RepoKind, 1767 comptime repo_opts: rp.RepoOpts(repo_kind), 1768 io: std.Io, 1769 allocator: std.mem.Allocator, 1770 repo: *rp.Repo(repo_kind, repo_opts), 1771 thread_kind: EventKind, 1772 thread_id: *const [event_id_size]u8, 1773 kind: EventKind, 1774 id: *const [event_id_size]u8, 1775 author: CommitAuthor, 1776 ) !void { 1777 const child_maybe: ?ThreadChild = switch (kind) { 1778 .comment => .{ .comment = id }, 1779 .attach => .{ .attach = id }, 1780 .assign => .{ .assign = id }, 1781 else => null, 1782 }; 1783 if (child_maybe) |child| { 1784 if (!try threadHolds(repo_kind, repo_opts, io, allocator, repo, thread_kind, thread_id, child)) return error.EventNotFound; 1785 } 1786 try remove(host, .repo, repo_kind, repo_opts, io, allocator, repo, id, kind, author); 1787 } 1788 1789 pub fn readFromRepo( 1790 comptime T: type, 1791 comptime repo_kind: rp.RepoKind, 1792 comptime repo_opts: rp.RepoOpts(repo_kind), 1793 io: std.Io, 1794 allocator: std.mem.Allocator, 1795 arena: *std.heap.ArenaAllocator, 1796 repo: *rp.Repo(repo_kind, repo_opts), 1797 id: *const [event_id_size]u8, 1798 ) !?T.Record { 1799 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1800 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1801 const moment = (if (event_db_maybe) |*event_db| 1802 currentMomentFromDb(repo_opts.hash, event_db.db) 1803 else if (repo_kind == .git) 1804 return null 1805 else 1806 currentMoment(repo_opts, repo)) catch return null; 1807 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1808 } 1809 1810 pub fn currentMoment( 1811 comptime repo_opts: rp.RepoOpts(.xit), 1812 repo: *rp.Repo(.xit, repo_opts), 1813 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1814 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1815 } 1816 1817 pub fn currentMomentFromDb( 1818 comptime hash_kind: hash.HashKind, 1819 db: *EventDB(hash_kind), 1820 ) !EventDB(hash_kind).HashMap(.read_only) { 1821 const DB = EventDB(hash_kind); 1822 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1823 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1824 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1825 return try currentMomentFromRepoMoment(hash_kind, moment); 1826 } 1827 1828 pub fn currentMomentFromRepoMoment( 1829 comptime hash_kind: hash.HashKind, 1830 moment: EventDB(hash_kind).HashMap(.read_only), 1831 ) !EventDB(hash_kind).HashMap(.read_only) { 1832 const DB = EventDB(hash_kind); 1833 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1834 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1835 _ = try last_object_id_cursor.readBytes(&last_object_id); 1836 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1837 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1838 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1839 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1840 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1841 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1842 } 1843 1844 // build a sorted-set key from an order and event id. big-endian order makes 1845 // byte order match numeric order; the event id breaks ties. 1846 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1847 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1848 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1849 @memcpy(key[@sizeOf(u64)..], event_id); 1850 return key; 1851 } 1852 1853 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1854 return orderKey(std.math.maxInt(u64) - order, event_id); 1855 } 1856 1857 pub fn removedRecord( 1858 comptime T: type, 1859 comptime DB: type, 1860 comptime hash_kind: hash.HashKind, 1861 haxy_moment: DB.HashMap(.read_only), 1862 existing_maybe: ?T, 1863 ) !T { 1864 var record = existing_maybe orelse return error.EventNotFound; 1865 record.removed = true; 1866 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1867 record.updated_order = try order_cursor.readUint(); 1868 return record; 1869 } 1870 1871 // add or refresh one entry in the global logical-event index 1872 pub fn indexEvent( 1873 comptime DB: type, 1874 comptime hash_kind: hash.HashKind, 1875 haxy_moment: DB.HashMap(.read_write), 1876 event_id: *const [event_id_size]u8, 1877 kind: EventKind, 1878 existing_maybe: anytype, 1879 record: anytype, 1880 ) !void { 1881 const event_key = hash.hashInt(hash_kind, event_id); 1882 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1883 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1884 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1885 1886 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1887 const active = try DB.SortedSet(.read_write).init(active_cursor); 1888 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1889 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1890 1891 if (existing_maybe) |existing| { 1892 const old_key = orderKeyDesc(existing.updated_order, event_id); 1893 _ = try active.remove(&old_key); 1894 _ = try removed_set.remove(&old_key); 1895 } 1896 1897 const order_key = orderKeyDesc(record.updated_order, event_id); 1898 if (record.removed) { 1899 try removed_set.put(&order_key); 1900 } else { 1901 try active.put(&order_key); 1902 } 1903 } 1904 1905 pub fn touchThread( 1906 comptime DB: type, 1907 comptime hash_kind: hash.HashKind, 1908 haxy_moment: DB.HashMap(.read_write), 1909 thread_id: *const [event_id_size]u8, 1910 order: u64, 1911 arena: *std.heap.ArenaAllocator, 1912 ) !void { 1913 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1914 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1915 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1916 switch (kind) { 1917 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1918 else => {}, 1919 } 1920 } 1921 1922 pub fn readEventKind( 1923 comptime hash_kind: hash.HashKind, 1924 kind_map: anytype, 1925 id: *const [event_id_size]u8, 1926 ) !?EventKind { 1927 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1928 var buffer: [64]u8 = undefined; 1929 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1930 } 1931 1932 // the email of the event's author, or null when the id names no authored event 1933 // of this kind 1934 pub fn readAuthorEmail( 1935 comptime repo_kind: rp.RepoKind, 1936 comptime repo_opts: rp.RepoOpts(repo_kind), 1937 io: std.Io, 1938 allocator: std.mem.Allocator, 1939 arena: *std.heap.ArenaAllocator, 1940 repo: *rp.Repo(repo_kind, repo_opts), 1941 kind: EventKind, 1942 id: *const [event_id_size]u8, 1943 ) !?[]const u8 { 1944 const record_map_key = switch (kind) { 1945 .discuss => Discussion.record_map_key, 1946 .issue => Issue.record_map_key, 1947 .comment => Comment.record_map_key, 1948 .attach => Attachment.record_map_key, 1949 .assign => Assignment.record_map_key, 1950 .patchrev => PatchRev.record_map_key, 1951 .patch => Patch.record_map_key, 1952 .user, .repo, .fork, .grant, .notify => return null, 1953 }; 1954 1955 const DB = EventDB(repo_opts.hash); 1956 var event_db_maybe: ?LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 1957 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1958 const moment = (if (event_db_maybe) |*event_db| 1959 currentMomentFromDb(repo_opts.hash, event_db.db) 1960 else if (repo_kind == .git) 1961 return null 1962 else 1963 currentMoment(repo_opts, repo)) catch return null; 1964 1965 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1966 const records = try DB.HashMap(.read_only).init(records_cursor); 1967 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1968 const record = try DB.HashMap(.read_only).init(record_cursor); 1969 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1970 } 1971 1972 // the event id embedded in a set entry's order key 1973 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1974 var cursor = kv_pair_cursor; 1975 const kv_pair = try cursor.readKeyValuePair(); 1976 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1977 _ = try kv_pair.key_cursor.readBytes(&order_key); 1978 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1979 } 1980 1981 // split a pushed "<owner>:<repo>" path into its two components, or null if it 1982 // isn't exactly two non-empty parts with no "/". 1983 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1984 if (std.mem.indexOfScalar(u8, path, '/') != null) return null; 1985 var it = std.mem.splitScalar(u8, path, ':'); 1986 const owner = it.next() orelse return null; 1987 const name = it.next() orelse return null; 1988 if (it.next() != null) return null; 1989 if (owner.len == 0 or name.len == 0) return null; 1990 1991 return .{ .owner = owner, .name = name }; 1992 } 1993 1994 pub const CreateRepoOptions = struct { 1995 read_access: Repo.Access = .private, 1996 }; 1997 1998 // the ids that locate a repo's on-disk directory 1999 pub const RepoLocation = struct { 2000 owner_id: [event_id_size]u8, 2001 repo_id: [event_id_size]u8, 2002 }; 2003 2004 // resolve a pushed `<owner>:<repo>` to the ids that locate its on-disk directory 2005 pub fn resolveOrCreateRepo( 2006 io: std.Io, 2007 allocator: std.mem.Allocator, 2008 users_dir: []const u8, 2009 admin_repo_path: []const u8, 2010 owner_name: []const u8, 2011 repo_name: []const u8, 2012 create_options_maybe: ?CreateRepoOptions, 2013 ) !?RepoLocation { 2014 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 2015 error.RepoNotFound => return null, 2016 else => |e| return e, 2017 }; 2018 defer admin_repo.deinit(io, allocator); 2019 2020 var arena = std.heap.ArenaAllocator.init(allocator); 2021 defer arena.deinit(); 2022 2023 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 2024 2025 // an unknown owner can't own a repo, so the push is rejected 2026 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 2027 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 2028 defer user_repo.deinit(io, allocator); 2029 2030 // an already-registered repo reuses its event id, so a re-push (or a clone) 2031 // lands in the same repo 2032 if (try userMoment(&user_repo)) |moment| { 2033 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 2034 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 2035 } 2036 } 2037 2038 const create_options = create_options_maybe orelse return null; 2039 2040 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 2041 2042 var id_bytes: [event_id_size]u8 = undefined; 2043 io.random(&id_bytes); 2044 try writeRepoEvent(io, allocator, users_dir, &user_repo, &owner_user_id, .{ .name = owner.event.name, .email = owner.event.email }, &id_bytes, repo_name, "", create_options.read_access); 2045 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 2046 } 2047 2048 // create a bare repo with `hash_kind` and register it in its owner's user repo 2049 pub fn createRepo( 2050 io: std.Io, 2051 allocator: std.mem.Allocator, 2052 users_dir: []const u8, 2053 owner_id: *const [event_id_size]u8, 2054 owner: CommitAuthor, 2055 name: []const u8, 2056 description: []const u8, 2057 read_access: Repo.Access, 2058 hash_kind: hash.HashKind, 2059 ) !RepoLocation { 2060 try Repo.validateName(name); 2061 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2062 defer user_repo.deinit(io, allocator); 2063 if (try userMoment(&user_repo)) |moment| { 2064 var arena = std.heap.ArenaAllocator.init(allocator); 2065 defer arena.deinit(); 2066 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2067 } 2068 2069 var id_bytes: [event_id_size]u8 = undefined; 2070 io.random(&id_bytes); 2071 2072 // the directory comes first so a listed repo always has one 2073 { 2074 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2075 defer allocator.free(path); 2076 switch (hash_kind) { 2077 inline else => |kind| { 2078 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2079 defer repo.deinit(io, allocator); 2080 }, 2081 } 2082 } 2083 2084 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2085 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2086 } 2087 2088 // change the name, description, read access, and tab roles of the repo 2089 // named `old_name` in its owner's user repo 2090 pub fn updateRepo( 2091 io: std.Io, 2092 allocator: std.mem.Allocator, 2093 users_dir: []const u8, 2094 owner_id: *const [event_id_size]u8, 2095 author: CommitAuthor, 2096 old_name: []const u8, 2097 name: []const u8, 2098 description: []const u8, 2099 read_access: Repo.Access, 2100 discuss_role: ?Repo.Role, 2101 issue_role: ?Repo.Role, 2102 patch_role: ?Repo.Role, 2103 ) !void { 2104 try Repo.validateName(name); 2105 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2106 defer user_repo.deinit(io, allocator); 2107 var arena = std.heap.ArenaAllocator.init(allocator); 2108 defer arena.deinit(); 2109 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2110 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2111 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2112 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2113 } 2114 2115 var event = found.repo.event; 2116 event.name = name; 2117 event.description = description; 2118 event.read_access = read_access; 2119 event.discuss_role = discuss_role; 2120 event.issue_role = issue_role; 2121 event.patch_role = patch_role; 2122 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2123 .id = std.fmt.bytesToHex(found.event_id, .lower), 2124 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2125 .author = author, 2126 .event = .{ .repo = event }, 2127 }}); 2128 } 2129 2130 // grant `user_id` `role` on the repo `repo_id` in its owner's user repo, 2131 // replacing any role they held 2132 pub fn grantRole( 2133 io: std.Io, 2134 allocator: std.mem.Allocator, 2135 users_dir: []const u8, 2136 owner_id: *const [event_id_size]u8, 2137 repo_id: *const [event_id_size]u8, 2138 user_id: *const [event_id_size]u8, 2139 role: Repo.Role, 2140 author: CommitAuthor, 2141 ) !void { 2142 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2143 defer user_repo.deinit(io, allocator); 2144 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2145 .id = std.fmt.bytesToHex(Grant.idOf(repo_id, user_id), .lower), 2146 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2147 .author = author, 2148 .event = .{ .grant = .{ .target_id = std.fmt.bytesToHex(repo_id.*, .lower), .user_id = std.fmt.bytesToHex(user_id.*, .lower), .role = role } }, 2149 }}); 2150 } 2151 2152 // revoke `user_id`'s grant on the repo `repo_id` in its owner's user repo 2153 pub fn revokeRole( 2154 io: std.Io, 2155 allocator: std.mem.Allocator, 2156 users_dir: []const u8, 2157 owner_id: *const [event_id_size]u8, 2158 repo_id: *const [event_id_size]u8, 2159 user_id: *const [event_id_size]u8, 2160 author: CommitAuthor, 2161 ) !void { 2162 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2163 defer user_repo.deinit(io, allocator); 2164 // a revoked grant stays in the kind index, which is all `remove` checks 2165 { 2166 var arena = std.heap.ArenaAllocator.init(allocator); 2167 defer arena.deinit(); 2168 const moment = (try userMoment(&user_repo)) orelse return error.EventNotFound; 2169 if (try Grant.readRole(UserDB, user_repo_opts.hash, moment, &arena, repo_id, user_id) == null) return error.EventNotFound; 2170 } 2171 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, &Grant.idOf(repo_id, user_id), .grant, author); 2172 } 2173 2174 // create a user and their user repo, returning the new user's id 2175 pub fn createUser( 2176 io: std.Io, 2177 allocator: std.mem.Allocator, 2178 users_dir: []const u8, 2179 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2180 name: []const u8, 2181 email: []const u8, 2182 password: []const u8, 2183 password_again: []const u8, 2184 ) ![event_id_size]u8 { 2185 try User.validateName(name); 2186 if (email.len == 0) return error.EmailEmpty; 2187 if (password.len == 0) return error.PasswordEmpty; 2188 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2189 // a fresh admin repo has no moment until its first event 2190 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2191 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2192 var arena = std.heap.ArenaAllocator.init(allocator); 2193 defer arena.deinit(); 2194 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2195 } else |err| switch (err) { 2196 error.NotFound => {}, 2197 else => |e| return e, 2198 } 2199 2200 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2201 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2202 2203 var id_bytes: [event_id_size]u8 = undefined; 2204 io.random(&id_bytes); 2205 2206 // the user repo comes first so a listed user can always create repos 2207 { 2208 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2209 defer allocator.free(path); 2210 var user_repo = try initUserRepo(io, allocator, path); 2211 defer user_repo.deinit(io, allocator); 2212 } 2213 2214 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2215 .id = std.fmt.bytesToHex(id_bytes, .lower), 2216 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2217 .author = .{ .name = name, .email = email }, 2218 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2219 }}); 2220 return id_bytes; 2221 } 2222 2223 // change a user's email, and their password when the password fields are 2224 // filled in 2225 pub fn updateUser( 2226 io: std.Io, 2227 allocator: std.mem.Allocator, 2228 users_dir: []const u8, 2229 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2230 user_id: *const [event_id_size]u8, 2231 email: []const u8, 2232 current_password: []const u8, 2233 new_password: []const u8, 2234 new_password_again: []const u8, 2235 ) !void { 2236 if (email.len == 0) return error.EmailEmpty; 2237 var arena = std.heap.ArenaAllocator.init(allocator); 2238 defer arena.deinit(); 2239 const moment = try currentMoment(admin_repo_opts, admin_repo); 2240 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2241 if (user.removed) return error.NotFound; 2242 if (!std.mem.eql(u8, email, user.event.email) and try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2243 2244 var event = user.event; 2245 event.email = email; 2246 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2247 if (current_password.len + new_password.len + new_password_again.len > 0) { 2248 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2249 if (new_password.len == 0) return error.PasswordEmpty; 2250 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2251 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2252 } 2253 2254 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2255 .id = std.fmt.bytesToHex(user_id.*, .lower), 2256 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2257 .author = .{ .name = event.name, .email = email }, 2258 .event = .{ .user = event }, 2259 }}); 2260 } 2261 2262 // add an authorized_keys line to the user's ssh keys 2263 pub fn addUserKey( 2264 io: std.Io, 2265 allocator: std.mem.Allocator, 2266 users_dir: []const u8, 2267 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2268 user_id: *const [event_id_size]u8, 2269 key_text: []const u8, 2270 ) !void { 2271 const key = std.mem.trim(u8, key_text, " \t\r"); 2272 // the keys are stored one per line 2273 if (std.mem.indexOfScalar(u8, key, '\n') != null) return error.InvalidKey; 2274 const fingerprint = User.fingerprintOfKey(key) orelse return error.InvalidKey; 2275 // the key types the ssh server verifies 2276 const key_type = std.mem.sliceTo(key, ' '); 2277 if (!std.mem.eql(u8, key_type, "ssh-ed25519") and !std.mem.eql(u8, key_type, "ssh-rsa")) return error.UnsupportedKey; 2278 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, &fingerprint, key); 2279 } 2280 2281 // remove the user's ssh key with this fingerprint. removing a key they don't 2282 // hold writes nothing. 2283 pub fn removeUserKey( 2284 io: std.Io, 2285 allocator: std.mem.Allocator, 2286 users_dir: []const u8, 2287 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2288 user_id: *const [event_id_size]u8, 2289 fingerprint: *const [User.fingerprint_len]u8, 2290 ) !void { 2291 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, fingerprint, null); 2292 } 2293 2294 // rewrite the user's ssh keys with `added` appended, or without the key with 2295 // `fingerprint` when nothing is added 2296 fn writeUserKeys( 2297 io: std.Io, 2298 allocator: std.mem.Allocator, 2299 users_dir: []const u8, 2300 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2301 user_id: *const [event_id_size]u8, 2302 fingerprint: *const [User.fingerprint_len]u8, 2303 added: ?[]const u8, 2304 ) !void { 2305 var arena = std.heap.ArenaAllocator.init(allocator); 2306 defer arena.deinit(); 2307 const moment = try currentMoment(admin_repo_opts, admin_repo); 2308 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2309 if (user.removed) return error.NotFound; 2310 2311 var keys: std.ArrayList(u8) = .empty; 2312 var held = false; 2313 var lines = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 2314 while (lines.next()) |line| { 2315 const line_fingerprint = User.fingerprintOfKey(line) orelse continue; 2316 if (std.mem.eql(u8, &line_fingerprint, fingerprint)) { 2317 held = true; 2318 if (added == null) continue; 2319 } 2320 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2321 try keys.appendSlice(arena.allocator(), line); 2322 } 2323 if (added) |key| { 2324 if (held) return error.KeyAdded; 2325 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2326 try keys.appendSlice(arena.allocator(), key); 2327 } else if (!held) return; 2328 2329 var event = user.event; 2330 event.ssh_keys = keys.items; 2331 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2332 .id = std.fmt.bytesToHex(user_id.*, .lower), 2333 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2334 .author = .{ .name = event.name, .email = event.email }, 2335 .event = .{ .user = event }, 2336 }}); 2337 } 2338 2339 // consume a new repo's event into its owner's user repo and mark it active 2340 fn writeRepoEvent( 2341 io: std.Io, 2342 allocator: std.mem.Allocator, 2343 users_dir: []const u8, 2344 user_repo: *rp.Repo(.xit, user_repo_opts), 2345 owner_id: *const [event_id_size]u8, 2346 owner: CommitAuthor, 2347 id_bytes: *const [event_id_size]u8, 2348 name: []const u8, 2349 description: []const u8, 2350 read_access: Repo.Access, 2351 ) !void { 2352 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2353 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2354 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2355 .timestamp = timestamp, 2356 .author = owner, 2357 .event = .{ .repo = .{ 2358 .user_id = std.fmt.bytesToHex(owner_id.*, .lower), 2359 .name = name, 2360 .description = description, 2361 .read_access = read_access, 2362 } }, 2363 }}); 2364 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2365 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2366 }; 2367 } 2368 2369 // 2370 // reading from xitdb 2371 // 2372 2373 // read just `Fields`, a subset of `T.Record`, from the record with event id 2374 // `id`, or null when there is none 2375 pub fn readRecordSubset( 2376 comptime T: type, 2377 comptime Fields: type, 2378 comptime DB: type, 2379 comptime hash_kind: hash.HashKind, 2380 haxy_moment: DB.HashMap(.read_only), 2381 arena: *std.heap.ArenaAllocator, 2382 id: []const u8, 2383 ) !?Fields { 2384 comptime assertFieldSubset(Fields, T.Record); 2385 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2386 const records = try DB.HashMap(.read_only).init(records_cursor); 2387 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2388 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2389 } 2390 2391 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2392 const info = @typeInfo(Sub).@"struct"; 2393 for (info.field_names, info.field_types) |field_name, field_type| { 2394 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2395 const FullField = @FieldType(Full, field_name); 2396 if (@typeInfo(field_type) == .@"struct") { 2397 assertFieldSubset(field_type, FullField); 2398 } else if (field_type != FullField) { 2399 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2400 } 2401 } 2402 } 2403 2404 pub fn read( 2405 comptime T: type, 2406 comptime DB: type, 2407 comptime hash_kind: hash.HashKind, 2408 arena: *std.heap.ArenaAllocator, 2409 map: DB.HashMap(.read_only), 2410 ) !T { 2411 var event: T = undefined; 2412 switch (@typeInfo(T)) { 2413 .@"struct" => |struct_info| { 2414 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2415 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2416 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2417 } 2418 }, 2419 else => @compileError("read expects a struct"), 2420 } 2421 return event; 2422 } 2423 2424 fn readField( 2425 comptime Field: type, 2426 comptime DB: type, 2427 comptime hash_kind: hash.HashKind, 2428 arena: *std.heap.ArenaAllocator, 2429 cursor_maybe: ?DB.Cursor(.read_only), 2430 ) !Field { 2431 if (@typeInfo(Field) == .optional) { 2432 // a missing key or a null union payload is null 2433 const cursor = cursor_maybe orelse return null; 2434 if (cursor.slot().tag == .none) return null; 2435 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2436 } 2437 const cursor = cursor_maybe orelse return error.NotFound; 2438 switch (@typeInfo(Field)) { 2439 .pointer => |pointer_info| { 2440 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2441 @compileError("unsupported read field type: " ++ @typeName(Field)); 2442 } 2443 return try cursor.readBytesAlloc(arena.allocator(), null); 2444 }, 2445 .array => |array_info| { 2446 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2447 var bytes: Field = undefined; 2448 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2449 return bytes; 2450 }, 2451 .bool => { 2452 var buffer: [5]u8 = undefined; 2453 const bytes = try cursor.readBytesObject(&buffer); 2454 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2455 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2456 if (std.mem.eql(u8, bytes.value, "true")) return true; 2457 if (std.mem.eql(u8, bytes.value, "false")) return false; 2458 return error.InvalidBool; 2459 }, 2460 .int => |int_info| return switch (int_info.signedness) { 2461 .unsigned => @intCast(try cursor.readUint()), 2462 .signed => @intCast(try cursor.readInt()), 2463 }, 2464 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2465 .@"union" => |union_info| { 2466 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2467 switch (cursor.slot().tag) { 2468 .bytes, .short_bytes => { 2469 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2470 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2471 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2472 return @unionInit(Field, variant_name, {}); 2473 } 2474 } 2475 return error.InvalidUnion; 2476 }, 2477 .hash_map => { 2478 const variants = try DB.HashMap(.read_only).init(cursor); 2479 var iter = try variants.iterator(); 2480 const entry = (try iter.next()) orelse return error.InvalidUnion; 2481 const pair = try entry.readKeyValuePair(); 2482 if (try iter.next() != null) return error.InvalidUnion; 2483 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2484 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2485 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2486 } 2487 } 2488 return error.InvalidUnion; 2489 }, 2490 else => return error.InvalidUnion, 2491 } 2492 }, 2493 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2494 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2495 } 2496 } 2497 2498 // whether two events carry the same data 2499 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2500 switch (@typeInfo(T)) { 2501 .@"struct" => |struct_info| { 2502 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2503 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2504 } 2505 }, 2506 else => @compileError("fieldsEqual expects a struct"), 2507 } 2508 2509 return true; 2510 } 2511 2512 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2513 switch (@typeInfo(Field)) { 2514 .pointer => |pointer_info| { 2515 if (pointer_info.size == .slice and pointer_info.child == u8) { 2516 return std.mem.eql(u8, a, b); 2517 } else { 2518 @compileError("unsupported field type: " ++ @typeName(Field)); 2519 } 2520 }, 2521 .array => |array_info| { 2522 if (array_info.child == u8) { 2523 return std.mem.eql(u8, &a, &b); 2524 } else { 2525 @compileError("unsupported field type: " ++ @typeName(Field)); 2526 } 2527 }, 2528 .void => return true, 2529 .bool, .int, .@"enum" => return a == b, 2530 .@"union" => { 2531 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2532 return switch (a) { 2533 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2534 }; 2535 }, 2536 .@"struct" => return fieldsEqual(Field, a, b), 2537 .optional => |optional_info| { 2538 if (a) |a_value| { 2539 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2540 return false; 2541 } 2542 return b == null; 2543 }, 2544 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2545 } 2546 } 2547 2548 // 2549 // writing to xitdb 2550 // 2551 2552 pub fn upsert( 2553 comptime T: type, 2554 comptime DB: type, 2555 comptime hash_kind: hash.HashKind, 2556 map: DB.HashMap(.read_write), 2557 event: T, 2558 ) !void { 2559 switch (@typeInfo(T)) { 2560 .@"struct" => |struct_info| { 2561 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2562 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2563 } 2564 }, 2565 else => @compileError("upsert expects a struct"), 2566 } 2567 } 2568 2569 fn upsertField( 2570 comptime DB: type, 2571 comptime hash_kind: hash.HashKind, 2572 map: DB.HashMap(.read_write), 2573 comptime field_name: []const u8, 2574 comptime Field: type, 2575 value: Field, 2576 ) !void { 2577 const key = hash.hashInt(hash_kind, field_name); 2578 2579 switch (@typeInfo(Field)) { 2580 .pointer => |pointer_info| { 2581 if (pointer_info.size == .slice and pointer_info.child == u8) { 2582 try upsertBytes(DB, hash_kind, map, key, value); 2583 } else { 2584 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2585 } 2586 }, 2587 .array => |array_info| { 2588 if (array_info.child == u8) { 2589 try upsertBytes(DB, hash_kind, map, key, &value); 2590 } else { 2591 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2592 } 2593 }, 2594 .int => |int_info| switch (int_info.signedness) { 2595 .unsigned => { 2596 if (try map.getCursor(key)) |value_cursor| { 2597 if (try value_cursor.readUint() == value) { 2598 return; 2599 } 2600 } 2601 2602 try map.put(key, .{ .uint = value }); 2603 }, 2604 .signed => { 2605 if (try map.getCursor(key)) |value_cursor| { 2606 if (try value_cursor.readInt() == value) { 2607 return; 2608 } 2609 } 2610 2611 try map.put(key, .{ .int = value }); 2612 }, 2613 }, 2614 .bool => { 2615 const bytes = if (value) "true" else "false"; 2616 if (try map.getCursor(key)) |value_cursor| { 2617 var buffer: [5]u8 = undefined; 2618 const existing = try value_cursor.readBytesObject(&buffer); 2619 if (existing.format_tag) |format_tag| { 2620 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2621 return; 2622 } 2623 } 2624 } 2625 2626 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2627 }, 2628 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2629 .@"union" => switch (value) { 2630 inline else => |payload, tag| { 2631 if (@TypeOf(payload) == void) { 2632 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2633 } else { 2634 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2635 if (try map.getCursor(key)) |cursor| { 2636 switch (cursor.slot().tag) { 2637 .hash_map => { 2638 const variants = try DB.HashMap(.read_only).init(cursor); 2639 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2640 }, 2641 else => try map.put(key, .{ .slot = null }), 2642 } 2643 } 2644 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2645 if (@typeInfo(@TypeOf(payload)) == .optional) { 2646 // keep the variant even when its payload is null 2647 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2648 } 2649 if (try variants.getCursor(tag_key)) |cursor| { 2650 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2651 } 2652 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2653 } 2654 }, 2655 }, 2656 .optional => |optional_info| { 2657 // a missing key is null 2658 if (value) |child| { 2659 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2660 } else { 2661 _ = try map.remove(key); 2662 } 2663 }, 2664 .@"struct" => try upsert( 2665 Field, 2666 DB, 2667 hash_kind, 2668 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2669 value, 2670 ), 2671 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2672 } 2673 } 2674 2675 fn upsertBytes( 2676 comptime DB: type, 2677 comptime hash_kind: hash.HashKind, 2678 map: DB.HashMap(.read_write), 2679 key: hash.HashInt(hash_kind), 2680 value: []const u8, 2681 ) !void { 2682 var existing_cursor_maybe = try map.getCursor(key); 2683 if (existing_cursor_maybe) |*existing_cursor| { 2684 if (try bytesEqual(DB, existing_cursor, value)) { 2685 return; 2686 } 2687 } 2688 2689 try map.put(key, .{ .bytes = value }); 2690 } 2691 2692 fn bytesEqual( 2693 comptime DB: type, 2694 cursor: *DB.Cursor(.read_only), 2695 value: []const u8, 2696 ) !bool { 2697 switch (cursor.slot().tag) { 2698 .bytes, .short_bytes => {}, 2699 else => return false, 2700 } 2701 var read_buffer: [1024]u8 = undefined; 2702 var reader = try cursor.reader(&read_buffer); 2703 if (reader.size != value.len) { 2704 return false; 2705 } 2706 2707 var chunk_buffer: [1024]u8 = undefined; 2708 var offset: usize = 0; 2709 while (offset < value.len) { 2710 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2711 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2712 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2713 return false; 2714 } 2715 offset += chunk_len; 2716 } 2717 2718 return true; 2719 } 2720 2721 // 2722 // CommitIterator 2723 // 2724 // differs from xit's ObjectIterator in a few ways: 2725 // 2726 // 1. iterates parents first, rather than children first 2727 // 2. `next` only returns the object id, not the full Object 2728 // 3. stores its temporary state in a file on disk to avoid OOMs 2729 // 2730 2731 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2732 return struct { 2733 const DB = EventDB(repo_opts.hash); 2734 // a plain file is used for the scratch db because each write outside 2735 // a transaction is synced anyway, so buffering would gain nothing 2736 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2737 const db_name = "haxy-repo-events.db"; 2738 2739 repo_dir: std.Io.Dir, 2740 db_file: std.Io.File, 2741 db: *TempDB, 2742 // map of each object id to its children 2743 parent_to_children: TempDB.HashMap(.read_write), 2744 // tracking pending parents is necessary because a child can only 2745 // be returned after all of its unconsumed parents have been returned 2746 child_to_pending_parents: TempDB.HashMap(.read_write), 2747 // queue of object ids that are ready to be returned from `next` 2748 ready_queue: TempDB.ArrayList(.read_write), 2749 ready_queue_index: u64, 2750 // the object id at the tip of this branch 2751 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2752 // the object id furthest back in the history that hasn't been consumed 2753 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2754 2755 pub fn init( 2756 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2757 io: std.Io, 2758 allocator: std.mem.Allocator, 2759 consumed_object_ids: DB.HashMap(.read_only), 2760 ref: rf.Ref, 2761 ) !CommitIterator(repo_kind, repo_opts) { 2762 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2763 errdefer { 2764 db_file.close(io); 2765 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2766 } 2767 2768 // cursors point at the db, so it needs a stable address 2769 const db_ptr = try allocator.create(TempDB); 2770 errdefer allocator.destroy(db_ptr); 2771 // the db is scratch state that gets deleted after iteration, so 2772 // there is nothing worth fsyncing 2773 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2774 2775 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2776 2777 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2778 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2779 2780 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2781 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2782 2783 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2784 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2785 2786 var self = CommitIterator(repo_kind, repo_opts){ 2787 .repo_dir = state.core.repo_dir, 2788 .db_file = db_file, 2789 .db = db_ptr, 2790 .parent_to_children = parent_to_children, 2791 .child_to_pending_parents = child_to_pending_parents, 2792 .ready_queue = ready_queue, 2793 .ready_queue_index = 0, 2794 .newest_object_id = null, 2795 .oldest_object_id = null, 2796 }; 2797 errdefer self.deinit(io, allocator); 2798 2799 try self.collect(state, io, allocator, consumed_object_ids, ref); 2800 2801 return self; 2802 } 2803 2804 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2805 self.db_file.close(io); 2806 self.repo_dir.deleteFile(io, db_name) catch {}; 2807 allocator.destroy(self.db); 2808 } 2809 2810 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2811 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2812 2813 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2814 self.ready_queue_index += 1; 2815 2816 try self.enqueueChildren(&oid); 2817 return oid; 2818 } 2819 2820 fn collect( 2821 self: *CommitIterator(repo_kind, repo_opts), 2822 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2823 io: std.Io, 2824 allocator: std.mem.Allocator, 2825 consumed_object_ids: DB.HashMap(.read_only), 2826 ref: rf.Ref, 2827 ) !void { 2828 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2829 2830 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2831 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2832 var walk_queue_index: u64 = 0; 2833 2834 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2835 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2836 2837 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2838 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2839 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2840 try walk_queue.append(.{ .bytes = &head_oid }); 2841 2842 while (walk_queue_index < try walk_queue.count()) { 2843 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2844 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2845 2846 walk_queue_index += 1; 2847 2848 // if we've seen this object id, skip it 2849 if (null != try seen_object_ids.getCursor(oid_int)) { 2850 continue; 2851 } 2852 2853 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2854 2855 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2856 defer commit_object.deinit(); 2857 2858 // if this object id has already been consumed, skip it 2859 if (null != try consumed_object_ids.getCursor(oid_int)) { 2860 continue; 2861 } 2862 2863 if (self.newest_object_id == null) self.newest_object_id = oid; 2864 self.oldest_object_id = oid; 2865 2866 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2867 var pending_parent_count: u64 = 0; 2868 for (parent_oids) |*parent_oid| { 2869 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2870 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2871 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2872 2873 // if this object id has already been consumed, skip it 2874 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2875 continue; 2876 } 2877 2878 // if this object id hasn't already been seen, add it to the walk queue 2879 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2880 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2881 } 2882 2883 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2884 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2885 try children.put(oid_int, .{ .bytes = &oid }); 2886 pending_parent_count += 1; 2887 } 2888 2889 if (pending_parent_count == 0) { 2890 try self.ready_queue.append(.{ .bytes = &oid }); 2891 } else { 2892 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2893 } 2894 } 2895 } 2896 2897 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2898 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2899 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2900 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2901 var children_iter = try children.iterator(); 2902 2903 while (try children_iter.next()) |*child_cursor| { 2904 const kv_pair = try child_cursor.readKeyValuePair(); 2905 const child_oid_int = kv_pair.hash; 2906 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2907 const pending_parent_count = try pending_parent_cursor.readUint(); 2908 2909 if (pending_parent_count <= 1) { 2910 _ = try self.child_to_pending_parents.remove(child_oid_int); 2911 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2912 try self.ready_queue.append(.{ .bytes = &child_oid }); 2913 } else { 2914 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2915 } 2916 } 2917 } 2918 2919 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2920 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2921 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2922 _ = try oid_cursor.readBytes(&oid); 2923 return oid; 2924 } 2925 }; 2926 } 2927