╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const hash = xit.hash; 5 const mrg = xit.merge; 6 const obj = xit.object; 7 const rf = xit.ref; 8 const pch = @import("patch.zig"); 9 10 pub const User = @import("event/User.zig"); 11 pub const Repo = @import("event/Repo.zig"); 12 pub const Fork = @import("event/Fork.zig"); 13 pub const Issue = @import("event/Issue.zig"); 14 pub const Discussion = @import("event/Discussion.zig"); 15 pub const Comment = @import("event/Comment.zig"); 16 pub const Attachment = @import("event/Attachment.zig"); 17 pub const Patch = @import("event/Patch.zig"); 18 pub const PatchRev = @import("event/PatchRev.zig"); 19 20 // the most bytes an event's serialized form may hold 21 pub const max_event_size: usize = 100 * 1024; 22 23 // the branch haxy events are committed to before being consumed 24 pub const events_ref: rf.Ref = .{ .kind = .head, .name = "haxy/events" }; 25 26 pub const materialized_key = "haxy"; 27 pub const last_object_id_key = "haxy-last-object-id"; 28 29 // options + db type for the admin repo 30 pub const admin_repo_opts: rp.RepoOpts(.xit) = .{}; 31 pub const AdminDB = rp.Repo(.xit, admin_repo_opts).DB; 32 33 // the xitdb type events are stored in. it only depends on the hash kind, so 34 // this matches the db of any xit repo using that hash kind. 35 pub fn EventDB(comptime hash_kind: hash.HashKind) type { 36 return rp.Repo(.xit, .{ .hash = hash_kind }).DB; 37 } 38 39 // the email between a commit author line's angle brackets, or null 40 pub fn authorEmail(author_line: []const u8) ?[]const u8 { 41 const open_bracket = std.mem.indexOfScalar(u8, author_line, '<') orelse return null; 42 const close_bracket = std.mem.indexOfScalarPos(u8, author_line, open_bracket + 1, '>') orelse return null; 43 return author_line[open_bracket + 1 .. close_bracket]; 44 } 45 46 // build a `T` by copying its fields, by name, out of `source` 47 pub fn project(comptime T: type, source: anytype) T { 48 var result: T = undefined; 49 inline for (std.meta.fields(T)) |field| { 50 @field(result, field.name) = @field(source, field.name); 51 } 52 return result; 53 } 54 55 pub const EventKind = enum { 56 user, 57 repo, 58 fork, 59 issue, 60 discuss, 61 comment, 62 attach, 63 patchrev, 64 patch, 65 }; 66 67 pub const RepoRole = enum { 68 admin, 69 repo, 70 fork, 71 72 fn allows(self: RepoRole, kind: EventKind) bool { 73 return switch (self) { 74 .admin => switch (kind) { 75 .user, .repo, .fork => true, 76 else => false, 77 }, 78 .repo => switch (kind) { 79 .issue, .discuss, .comment, .attach, .patchrev, .patch => true, 80 else => false, 81 }, 82 .fork => switch (kind) { 83 .patchrev, .patch => true, 84 else => false, 85 }, 86 }; 87 } 88 }; 89 90 // every logical event's kind and update-ordered active/removed id sets 91 pub const event_index_key = "event-id->kind"; 92 pub const active_event_id_set_key = "active-event-id-set"; 93 pub const removed_event_id_set_key = "removed-event-id-set"; 94 const event_order_key = "event-order"; 95 96 pub fn titleValid(title: []const u8) bool { 97 return std.mem.trim(u8, title, " \t\r\n").len != 0; 98 } 99 100 // a null payload removes the record 101 pub const Event = union(EventKind) { 102 user: ?User, 103 repo: ?Repo, 104 fork: ?Fork, 105 issue: ?Issue, 106 discuss: ?Discussion, 107 comment: ?Comment, 108 attach: ?Attachment, 109 patchrev: ?PatchRev, 110 patch: ?Patch, 111 }; 112 113 // a file committed alongside its event 114 pub const Blob = struct { 115 name: []const u8, 116 size: u64, 117 reader: *std.Io.Reader, 118 }; 119 120 // an entry in the fresh tree carried by one event commit 121 pub const EventTreeEntry = union(enum) { 122 blob: Blob, 123 tree: struct { 124 name: []const u8, 125 oid: []const u8, 126 }, 127 }; 128 129 // who a commit is attributed to 130 pub const CommitAuthor = struct { 131 name: []const u8, 132 email: []const u8, 133 }; 134 135 pub const event_id_size: usize = 16; 136 137 pub fn parseEventId(id: []const u8) ![event_id_size]u8 { 138 var bytes: [event_id_size]u8 = undefined; 139 _ = try std.fmt.hexToBytes(&bytes, id); 140 if (!std.mem.eql(u8, id, &std.fmt.bytesToHex(bytes, .lower))) return error.InvalidEventId; 141 return bytes; 142 } 143 144 pub const EventWithId = struct { 145 id: [event_id_size * 2]u8, 146 event: Event, 147 timestamp: u64 = 0, // not serialized, because it comes from the commit timestamp 148 author: CommitAuthor, // not serialized, because it goes in the commit author line 149 tree_entries: []const EventTreeEntry = &.{}, // not serialized, because they go in the commit tree 150 151 pub fn jsonStringify(self: EventWithId, jw: anytype) !void { 152 try jw.beginObject(); 153 try jw.objectField("id"); 154 try jw.write(self.id); 155 try jw.objectField("kind"); 156 try jw.write(@tagName(self.event)); 157 try jw.objectField("data"); 158 switch (self.event) { 159 inline else => |event_maybe| try jw.write(event_maybe), 160 } 161 try jw.endObject(); 162 } 163 164 fn fromString(arena: *std.heap.ArenaAllocator, message: []const u8) !EventWithId { 165 const JsonEvent = struct { 166 id: [event_id_size * 2]u8, 167 kind: EventKind, 168 data: ?std.json.Value = null, 169 }; 170 const json_event = try std.json.parseFromSliceLeaky(JsonEvent, arena.allocator(), message, .{ .ignore_unknown_fields = true }); 171 return .{ 172 .id = json_event.id, 173 // unused when reading; the author lives in the commit 174 .author = .{ .name = "", .email = "" }, 175 .event = switch (json_event.kind) { 176 .user => .{ 177 .user = if (json_event.data) |value| 178 try std.json.parseFromValueLeaky(User, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 179 else 180 null, 181 }, 182 .repo => .{ 183 .repo = if (json_event.data) |value| 184 try std.json.parseFromValueLeaky(Repo, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 185 else 186 null, 187 }, 188 .fork => .{ 189 .fork = if (json_event.data) |value| 190 try std.json.parseFromValueLeaky(Fork, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 191 else 192 null, 193 }, 194 .issue => .{ 195 .issue = if (json_event.data) |value| 196 try std.json.parseFromValueLeaky(Issue, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 197 else 198 null, 199 }, 200 .discuss => .{ 201 .discuss = if (json_event.data) |value| 202 try std.json.parseFromValueLeaky(Discussion, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 203 else 204 null, 205 }, 206 .comment => .{ 207 .comment = if (json_event.data) |value| 208 try std.json.parseFromValueLeaky(Comment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 209 else 210 null, 211 }, 212 .attach => .{ 213 .attach = if (json_event.data) |value| 214 try std.json.parseFromValueLeaky(Attachment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 215 else 216 null, 217 }, 218 .patch => .{ 219 .patch = if (json_event.data) |value| 220 try std.json.parseFromValueLeaky(Patch, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 221 else 222 null, 223 }, 224 .patchrev => .{ 225 .patchrev = if (json_event.data) |value| 226 try std.json.parseFromValueLeaky(PatchRev, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 227 else 228 null, 229 }, 230 }, 231 }; 232 } 233 234 pub fn randomId(random: std.Random) [event_id_size]u8 { 235 var id_bytes: [event_id_size]u8 = undefined; 236 random.bytes(&id_bytes); 237 return id_bytes; 238 } 239 }; 240 241 // remove an event by emitting a null payload 242 pub fn remove( 243 comptime role: RepoRole, 244 comptime repo_kind: rp.RepoKind, 245 comptime repo_opts: rp.RepoOpts(repo_kind), 246 io: std.Io, 247 allocator: std.mem.Allocator, 248 repo: *rp.Repo(repo_kind, repo_opts), 249 id: *const [event_id_size]u8, 250 kind: EventKind, 251 author: CommitAuthor, 252 ) !void { 253 const DB = EventDB(repo_opts.hash); 254 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; 255 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 256 const moment = (if (event_db_maybe) |*event_db| 257 currentMomentFromDb(repo_opts.hash, event_db.db) 258 else if (repo_kind == .git) 259 return error.EventNotFound 260 else 261 currentMoment(repo_opts, repo)) catch return error.EventNotFound; 262 const kind_map_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return error.EventNotFound; 263 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 264 const stored_kind = (try readEventKind(repo_opts.hash, kind_map, id)) orelse return error.EventNotFound; 265 if (stored_kind != kind) return error.EventNotFound; 266 if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 267 event_db_maybe = null; 268 269 const event: Event = switch (kind) { 270 .user => .{ .user = null }, 271 .repo => .{ .repo = null }, 272 .fork => .{ .fork = null }, 273 .issue => .{ .issue = null }, 274 .discuss => .{ .discuss = null }, 275 .comment => .{ .comment = null }, 276 .attach => .{ .attach = null }, 277 .patchrev => .{ .patchrev = null }, 278 .patch => .{ .patch = null }, 279 }; 280 try consume(role, repo_kind, repo_opts, io, allocator, repo, events_ref, &.{.{ 281 .id = std.fmt.bytesToHex(id.*, .lower), 282 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 283 .author = author, 284 .event = event, 285 }}); 286 } 287 288 // commit `events` (if any) as JSON commit messages on `ref`, then consume the 289 // events on `ref` into the db the repo's views read: the repo's own db for a 290 // xit repo, or the standalone event db next to a git repo. for a xit repo the 291 // commits and the consume run in one transaction. 292 pub fn consume( 293 comptime role: RepoRole, 294 comptime repo_kind: rp.RepoKind, 295 comptime repo_opts: rp.RepoOpts(repo_kind), 296 io: std.Io, 297 allocator: std.mem.Allocator, 298 repo: *rp.Repo(repo_kind, repo_opts), 299 ref: rf.Ref, 300 events: []const EventWithId, 301 ) !void { 302 for (events) |event| { 303 if (!role.allows(std.meta.activeTag(event.event))) return error.EventKindNotAllowed; 304 } 305 306 var resolved_remote_name: ?[]u8 = null; 307 defer if (resolved_remote_name) |name| allocator.free(name); 308 309 // a branch that only exists on a remote is consumed from its remote-tracking 310 // ref, while commits go on the local branch, continuing from the remote tip 311 // so a cloned repo's local branch stays connected to the server history 312 const resolved_ref: rf.Ref, const first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8 = blk: { 313 if (null != try repo.readRef(io, ref)) break :blk .{ ref, null }; 314 var remotes = try repo.listRemotes(io, allocator); 315 defer remotes.deinit(); 316 for (remotes.sections.keys()) |remote_name| { 317 const remote_ref: rf.Ref = .{ .kind = .{ .remote = remote_name }, .name = ref.name }; 318 if (try repo.readRef(io, remote_ref)) |oid| { 319 if (events.len > 0) break :blk .{ ref, .{oid} }; 320 const name = try allocator.dupe(u8, remote_name); 321 resolved_remote_name = name; 322 break :blk .{ rf.Ref{ .kind = .{ .remote = name }, .name = ref.name }, null }; 323 } 324 } 325 if (events.len > 0) break :blk .{ ref, null }; 326 // the branch is gone (or never existed): drop any db from a previous 327 // sync rather than serving its issues indefinitely 328 if (repo_kind == .git) try LocalEventDB(repo_opts.hash).delete(io, repo.core.repo_dir); 329 return; 330 }; 331 332 switch (repo_kind) { 333 .git => { 334 try commitEvents(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, ref, events, first_parent_oids); 335 336 var event_db = try LocalEventDB(repo_opts.hash).open(io, allocator, repo.core.repo_dir); 337 defer event_db.deinit(io, allocator); 338 339 try event_db.consume(repo_kind, repo_opts, io, allocator, repo, resolved_ref); 340 }, 341 .xit => { 342 const DB = rp.Repo(.xit, repo_opts).DB; 343 const State = rp.Repo(.xit, repo_opts).State; 344 345 const Ctx = struct { 346 core: *rp.Repo(.xit, repo_opts).Core, 347 io: std.Io, 348 allocator: std.mem.Allocator, 349 ref: rf.Ref, 350 events: []const EventWithId, 351 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 352 353 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 354 var moment = try DB.HashMap(.read_write).init(cursor.*); 355 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 356 357 try commitEvents(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.ref, ctx.events, ctx.first_parent_oids); 358 if (!try consumeInTransaction(role, .xit, repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 359 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "event" }); 360 } 361 }; 362 363 try repo.core.db_file.lock(io, .exclusive); 364 defer repo.core.db_file.unlock(io); 365 366 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 367 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 368 .core = &repo.core, 369 .io = io, 370 .allocator = allocator, 371 .ref = resolved_ref, 372 .events = events, 373 .first_parent_oids = first_parent_oids, 374 }) catch |err| switch (err) { 375 error.CancelTransaction => {}, 376 else => |e| return e, 377 }; 378 }, 379 } 380 } 381 382 // merge the remote events ref into the local events ref without touching head, 383 // the index, or the worktree 384 pub fn mergeEvents( 385 comptime repo_kind: rp.RepoKind, 386 comptime repo_opts: rp.RepoOpts(repo_kind), 387 io: std.Io, 388 allocator: std.mem.Allocator, 389 repo: *rp.Repo(repo_kind, repo_opts), 390 remote_ref: rf.Ref, 391 ) !void { 392 switch (repo_kind) { 393 .git => _ = try mergeEventsInTransaction(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, remote_ref), 394 .xit => { 395 const DB = rp.Repo(.xit, repo_opts).DB; 396 const State = rp.Repo(.xit, repo_opts).State; 397 398 const Ctx = struct { 399 core: *rp.Repo(.xit, repo_opts).Core, 400 io: std.Io, 401 allocator: std.mem.Allocator, 402 remote_ref: rf.Ref, 403 404 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 405 var moment = try DB.HashMap(.read_write).init(cursor.*); 406 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 407 if (!try mergeEventsInTransaction(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.remote_ref)) return error.CancelTransaction; 408 try xit.undo.writeMessage(repo_opts, state, .{ .custom = "event" }); 409 } 410 }; 411 412 try repo.core.db_file.lock(io, .exclusive); 413 defer repo.core.db_file.unlock(io); 414 415 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 416 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 417 .core = &repo.core, 418 .io = io, 419 .allocator = allocator, 420 .remote_ref = remote_ref, 421 }) catch |err| switch (err) { 422 error.CancelTransaction => {}, 423 else => |e| return e, 424 }; 425 }, 426 } 427 } 428 429 fn mergeEventsInTransaction( 430 comptime repo_kind: rp.RepoKind, 431 comptime repo_opts: rp.RepoOpts(repo_kind), 432 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 433 io: std.Io, 434 allocator: std.mem.Allocator, 435 remote_ref: rf.Ref, 436 ) !bool { 437 const remote_oid = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = remote_ref })) orelse return false; 438 const local_oid_maybe = try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = events_ref }); 439 440 var ref_path_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 441 const ref_path = try events_ref.toPath(&ref_path_buffer); 442 const local_oid = local_oid_maybe orelse { 443 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 444 return true; 445 }; 446 if (std.mem.eql(u8, &local_oid, &remote_oid)) return false; 447 448 const ancestor_maybe: ?[hash.hexLen(repo_opts.hash)]u8 = mrg.commonAncestor(repo_kind, repo_opts, state.readOnly(), io, allocator, &local_oid, &remote_oid) catch |err| switch (err) { 449 error.NoCommonAncestor => null, 450 else => return err, 451 }; 452 if (ancestor_maybe) |ancestor| { 453 if (std.mem.eql(u8, &ancestor, &remote_oid)) return false; 454 if (std.mem.eql(u8, &ancestor, &local_oid)) { 455 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 456 return true; 457 } 458 } 459 460 const parent_oids = [_][hash.hexLen(repo_opts.hash)]u8{ local_oid, remote_oid }; 461 var tree = try obj.Tree.init(allocator); 462 defer tree.deinit(); 463 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 464 .message = "merge events", 465 .parent_oids = &parent_oids, 466 }, &tree, events_ref); 467 return true; 468 } 469 470 // the file an attach event carries: the one entry in its commit's tree. the 471 // name and oid are allocated in `arena`. 472 fn attachedFile( 473 comptime repo_kind: rp.RepoKind, 474 comptime repo_opts: rp.RepoOpts(repo_kind), 475 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 476 io: std.Io, 477 allocator: std.mem.Allocator, 478 arena: *std.heap.ArenaAllocator, 479 tree_oid: *const [hash.hexLen(repo_opts.hash)]u8, 480 ) !struct { name: []const u8, oid: []const u8 } { 481 var tree_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, tree_oid); 482 defer tree_object.deinit(); 483 484 const entries = switch (tree_object.content) { 485 .tree => |tree| tree.entries, 486 else => return error.InvalidAttachment, 487 }; 488 if (entries.count() != 1) return error.InvalidAttachment; 489 const entry = entries.values()[0]; 490 if (entry.isTree()) return error.InvalidAttachment; 491 const name = entries.keys()[0]; 492 if (!Attachment.nameValid(name)) return error.InvalidAttachment; 493 494 const oid = std.fmt.bytesToHex(entry.oid, .lower); 495 var object_reader = try obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, &oid); 496 defer object_reader.deinit(); 497 if (object_reader.header().kind != .blob) return error.InvalidAttachment; 498 499 return .{ 500 .name = try arena.allocator().dupe(u8, name), 501 .oid = try arena.allocator().dupe(u8, &oid), 502 }; 503 } 504 505 fn commitIdentity(line: []const u8) ![]const u8 { 506 const close = std.mem.indexOfScalar(u8, line, '>') orelse return error.AuthorNotFound; 507 return line[0 .. close + 1]; 508 } 509 510 // commit each event as a JSON commit message on `ref` through `state`, so a 511 // xit repo can write them inside an already-open transaction 512 pub fn commitEvents( 513 comptime repo_kind: rp.RepoKind, 514 comptime repo_opts: rp.RepoOpts(repo_kind), 515 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 516 io: std.Io, 517 allocator: std.mem.Allocator, 518 ref: rf.Ref, 519 events: []const EventWithId, 520 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 521 ) !void { 522 var parent_oids: ?[]const [hash.hexLen(repo_opts.hash)]u8 = if (first_parent_oids) |*oids| oids else null; 523 524 var json: std.Io.Writer.Allocating = .init(allocator); 525 defer json.deinit(); 526 527 for (events) |event| { 528 json.clearRetainingCapacity(); 529 try std.json.Stringify.value(event, .{}, &json.writer); 530 if (json.written().len > max_event_size) return error.EventTooLarge; 531 const author = try std.fmt.allocPrint(allocator, "{s} <{s}>", .{ event.author.name, event.author.email }); 532 defer allocator.free(author); 533 534 // every event gets a fresh tree 535 var tree = try obj.Tree.init(allocator); 536 defer tree.deinit(); 537 for (event.tree_entries) |entry| { 538 switch (entry) { 539 .blob => |blob| { 540 var oid_bytes = [_]u8{0} ** hash.byteLen(repo_opts.hash); 541 try obj.writeObject(repo_kind, repo_opts, state, io, allocator, blob.reader, .{ .kind = .blob, .size = blob.size }, &oid_bytes); 542 try tree.addBlobEntry(.{ .content = .{ .unix_permission = 0o644, .object_type = .regular_file } }, blob.name, &oid_bytes); 543 }, 544 .tree => |nested| { 545 var oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 546 _ = try std.fmt.hexToBytes(&oid_bytes, nested.oid); 547 if (!std.mem.eql(u8, nested.oid, &std.fmt.bytesToHex(oid_bytes, .lower))) return error.InvalidTreeObject; 548 try tree.addTreeEntry(nested.name, &oid_bytes); 549 }, 550 } 551 } 552 553 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 554 .author = author, 555 .message = json.written(), 556 .timestamp = event.timestamp, 557 .parent_oids = parent_oids, 558 .allow_empty = true, 559 }, &tree, ref); 560 // later events parent on the ref's new tip 561 parent_oids = null; 562 } 563 } 564 565 pub const PushProgress = struct { 566 response: *xit.net_server_receive_pack.Response, 567 writer: *std.Io.Writer, 568 count: usize = 0, 569 total: usize = 0, 570 571 pub fn run(self: *PushProgress, _: std.Io, event: rp.ProgressEvent) !void { 572 switch (event) { 573 .start => |start| { 574 if (start.kind != .writing_patch) return; 575 self.total = start.estimated_total_items; 576 self.count = 0; 577 }, 578 .complete_one => |kind| { 579 if (kind != .writing_patch) return; 580 self.count += 1; 581 }, 582 .end => |kind| { 583 if (kind != .writing_patch) return; 584 }, 585 else => return, 586 } 587 var buffer: [128]u8 = undefined; 588 const percent = if (self.total == 0) 100 else @as(u128, self.count) * 100 / self.total; 589 const text = try std.fmt.bufPrint(&buffer, "Processing commits: {d}% ({d}/{d}){s}", .{ percent, self.count, self.total, if (event == .end) "\n" else "\r" }); 590 try self.response.progress(self.writer, text); 591 } 592 }; 593 594 // prepare all reachable commits, including history received before patch 595 // generation was enabled. this shares the receive-pack transaction. 596 pub fn writeReceivedPatches( 597 comptime repo_opts: rp.RepoOpts(.xit), 598 state: rp.Repo(.xit, repo_opts).State(.read_write), 599 io: std.Io, 600 allocator: std.mem.Allocator, 601 response: *xit.net_server_receive_pack.Response, 602 writer: *std.Io.Writer, 603 ) !void { 604 try response.progress(writer, "Processing commits...\n"); 605 var config = try xit.config.Config(.xit, repo_opts).init(state.readOnly(), io, allocator); 606 defer config.deinit(); 607 try config.add(state, io, .{ .name = "merge.algorithm", .value = "patch" }); 608 609 var iter = try obj.ObjectIterator(.xit, repo_opts).init(state.readOnly(), io, allocator, .{ .kind = .commit }); 610 defer iter.deinit(); 611 var refs = try rf.AllRefIterator(.xit, repo_opts).init(state.readOnly(), allocator); 612 defer refs.deinit(); 613 while (try refs.next()) |ref| { 614 if (try rf.readRecur(.xit, repo_opts, state.readOnly(), io, .{ .ref = ref })) |oid| { 615 try iter.include(&oid); 616 } 617 } 618 var progress = PushProgress{ .response = response, .writer = writer }; 619 try xit.patch.writePatches(repo_opts, state, io, allocator, &iter, &progress); 620 } 621 622 // serve a receive-pack and consume any events it pushed to the events branch, 623 // all in one transaction: the push and the views derived from it commit 624 // atomically, and a failed consume cancels the push 625 pub fn receivePackAndConsume( 626 comptime repo_opts: rp.RepoOpts(.xit), 627 io: std.Io, 628 allocator: std.mem.Allocator, 629 repo: *rp.Repo(.xit, repo_opts), 630 reader: *std.Io.Reader, 631 writer: *std.Io.Writer, 632 options: xit.net_server_receive_pack.Options, 633 repo_root_path: []const u8, 634 error_writer: *std.Io.Writer, 635 ) !void { 636 const DB = rp.Repo(.xit, repo_opts).DB; 637 const State = rp.Repo(.xit, repo_opts).State; 638 639 var response = xit.net_server_receive_pack.Response.init(allocator); 640 defer response.deinit(); 641 642 const Ctx = struct { 643 core: *rp.Repo(.xit, repo_opts).Core, 644 io: std.Io, 645 allocator: std.mem.Allocator, 646 reader: *std.Io.Reader, 647 writer: *std.Io.Writer, 648 options: xit.net_server_receive_pack.Options, 649 response: *xit.net_server_receive_pack.Response, 650 repo_root_path: []const u8, 651 error_writer: *std.Io.Writer, 652 653 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 654 var moment = try DB.HashMap(.read_write).init(cursor.*); 655 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 656 var updates = xit.net_server_receive_pack.AppliedRefUpdates.init(ctx.allocator); 657 defer updates.deinit(); 658 var receive_options = ctx.options; 659 receive_options.applied_ref_updates = &updates; 660 receive_options.deferred_response = ctx.response; 661 try xit.net_server_receive_pack.run(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.reader, ctx.writer, receive_options); 662 try writeReceivedPatches(repo_opts, state, ctx.io, ctx.allocator, ctx.response, ctx.writer); 663 664 // a repo without an events branch has no events to consume. a 665 // no-op consume must not cancel here, since the push shares the 666 // transaction and must commit regardless. 667 if (null != try rf.readRecur(.xit, repo_opts, state.readOnly(), ctx.io, .{ .ref = events_ref })) { 668 _ = try consumeInTransaction(.repo, .xit, repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, events_ref); 669 try pch.detectMerged(repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.repo_root_path, updates.items.items, ctx.error_writer); 670 } 671 try xit.undo.writeMessage(repo_opts, state, .push); 672 } 673 }; 674 675 try repo.core.db_file.lock(io, .exclusive); 676 defer repo.core.db_file.unlock(io); 677 678 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 679 history.appendContext( 680 .{ .slot = try history.getSlot(-1) }, 681 Ctx{ 682 .core = &repo.core, 683 .io = io, 684 .allocator = allocator, 685 .reader = reader, 686 .writer = writer, 687 .options = options, 688 .response = &response, 689 .repo_root_path = repo_root_path, 690 .error_writer = error_writer, 691 }, 692 ) catch |err| { 693 response.finish(writer, @errorName(err)) catch {}; 694 if (err == error.CancelTransaction) return; 695 return err; 696 }; 697 698 try response.finish(writer, null); 699 } 700 701 // a standalone event db holding events consumed from a local repo's events 702 // branch. it lives inside the repo dir but is not part of the repo's own data, 703 // so viewing a repo never mutates it. 704 pub fn LocalEventDB(comptime hash_kind: hash.HashKind) type { 705 return struct { 706 file: std.Io.File, 707 buffer: *std.Io.Writer.Allocating, 708 db: *EventDB(hash_kind), 709 710 const db_name = "haxy"; 711 const Self = @This(); 712 713 // open the db in `repo_dir` for writing, creating it if it doesn't exist 714 pub fn open(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !Self { 715 const file = try repo_dir.createFile(io, db_name, .{ .truncate = false, .read = true, .lock = .exclusive }); 716 return fromFile(io, allocator, file); 717 } 718 719 // open the db in `repo_dir` for reading, or null if it doesn't exist 720 pub fn openReadOnly(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !?Self { 721 const file = repo_dir.openFile(io, db_name, .{ .mode = .read_write, .lock = .shared }) catch |err| switch (err) { 722 error.FileNotFound => return null, 723 else => |e| return e, 724 }; 725 return try fromFile(io, allocator, file); 726 } 727 728 // remove the db from `repo_dir`, so a repo whose events branch 729 // disappeared doesn't keep showing stale issues 730 pub fn delete(io: std.Io, repo_dir: std.Io.Dir) !void { 731 repo_dir.deleteFile(io, db_name) catch |err| switch (err) { 732 error.FileNotFound => {}, 733 else => |e| return e, 734 }; 735 } 736 737 fn fromFile(io: std.Io, allocator: std.mem.Allocator, file: std.Io.File) !Self { 738 errdefer file.close(io); 739 740 const buffer = try allocator.create(std.Io.Writer.Allocating); 741 errdefer allocator.destroy(buffer); 742 buffer.* = std.Io.Writer.Allocating.init(allocator); 743 errdefer buffer.deinit(); 744 745 const db = try allocator.create(EventDB(hash_kind)); 746 errdefer allocator.destroy(db); 747 db.* = try EventDB(hash_kind).init(.{ .io = io, .file = file, .buffer = buffer }); 748 749 return .{ .file = file, .buffer = buffer, .db = db }; 750 } 751 752 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 753 self.file.close(io); 754 self.buffer.deinit(); 755 allocator.destroy(self.buffer); 756 allocator.destroy(self.db); 757 } 758 759 // consume the events on `repo`'s `ref` into this db. the db must come 760 // from `open`, whose handle holds the exclusive lock guarding the 761 // transaction. 762 pub fn consume( 763 self: *Self, 764 comptime repo_kind: rp.RepoKind, 765 comptime repo_opts: rp.RepoOpts(repo_kind), 766 io: std.Io, 767 allocator: std.mem.Allocator, 768 repo: *rp.Repo(repo_kind, repo_opts), 769 ref: rf.Ref, 770 ) !void { 771 comptime if (repo_opts.hash != hash_kind) @compileError("the repo must use the db's hash kind"); 772 const DB = EventDB(hash_kind); 773 774 const Ctx = struct { 775 repo: *rp.Repo(repo_kind, repo_opts), 776 db: *DB, 777 io: std.Io, 778 allocator: std.mem.Allocator, 779 ref: rf.Ref, 780 781 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 782 var moment = try DB.HashMap(.read_write).init(cursor.*); 783 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{} }; 784 if (!try consumeInTransaction(.repo, repo_kind, repo_opts, state, ctx.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 785 } 786 }; 787 788 const history = try DB.ArrayList(.read_write).init(self.db.rootCursor()); 789 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 790 .repo = repo, 791 .db = self.db, 792 .io = io, 793 .allocator = allocator, 794 .ref = ref, 795 }) catch |err| switch (err) { 796 error.CancelTransaction => {}, 797 else => |e| return e, 798 }; 799 } 800 }; 801 } 802 803 // consume the events on `ref` into the db `moment` writes to, returning false 804 // if there was nothing to do. events are read from `state`'s repo, which 805 // needn't be the repo backing the db — that's how a local (possibly 806 // git-backed) repo's events land in a standalone db. 807 pub fn consumeInTransaction( 808 comptime role: RepoRole, 809 comptime repo_kind: rp.RepoKind, 810 comptime repo_opts: rp.RepoOpts(repo_kind), 811 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 812 db: *EventDB(repo_opts.hash), 813 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 814 io: std.Io, 815 allocator: std.mem.Allocator, 816 ref: rf.Ref, 817 ) !bool { 818 const DB = EventDB(repo_opts.hash); 819 const read_state = state.readOnly(); 820 821 // the last_object_id represents the object id that was last consumed 822 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 823 if (try moment.getCursor(hash.hashInt(repo_opts.hash, last_object_id_key))) |last_object_id_cursor| { 824 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 825 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 826 last_object_id_maybe = last_object_id_buffer; 827 } 828 829 // the tip was already consumed, so there is nothing to do 830 if (last_object_id_maybe) |*last_object_id| { 831 const tip_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 832 var tip: [hash.byteLen(repo_opts.hash)]u8 = undefined; 833 _ = try std.fmt.hexToBytes(&tip, &tip_hex); 834 if (std.mem.eql(u8, last_object_id, &tip)) return false; 835 } 836 837 // the list with all of haxy's state, including materialized views. 838 // the reason it is a list is so we can keep every previous haxy 839 // state, making it easy to revert to an older state if the user 840 // rebases some of the past commits. 841 const haxy_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, materialized_key)); 842 const haxy = try DB.ArrayList(.read_write).init(haxy_cursor); 843 844 // add a new item to the haxy list created above. 845 // we call the item haxy_moments. it is a map of object id to haxy moment. 846 // in other words, it maps each object id to a hash map containing the 847 // state that the database was in when that object id was consumed. 848 var haxy_moments_cursor = try haxy.appendCursor(); 849 // use the previous haxy_moments as the basis for this one if it exists 850 if (try haxy.getCursor(-2)) |last_haxy_moments_cursor| { 851 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 852 } 853 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 854 855 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 856 defer commit_iter.deinit(io, allocator); 857 858 // if there are no events to process, look at the oid at HEAD and update 859 // the last_object_id to point to it. this is important in situations 860 // where we do a merge and then force-push to remove the merge. see the 861 // merge test for an example. 862 if (commit_iter.newest_object_id == null) { 863 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 864 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 865 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 866 867 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 868 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 869 870 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 871 const moment_index = try moment_index_cursor.readUint(); 872 873 try haxy.slice(moment_index + 1); 874 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = &head_oid }); 875 return true; 876 } 877 878 // if this branch was rebased and force pushed, we need to detect that and 879 // properly revert the haxy state to the last valid state. we detect this 880 // by simply asking if the last event is a descendent of the last event 881 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 882 if (last_object_id_maybe) |*last_object_id| { 883 var is_rebased = false; 884 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 885 886 _ = mrg.getDescendent( 887 repo_kind, 888 repo_opts, 889 read_state, 890 io, 891 allocator, 892 &std.fmt.bytesToHex(last_object_id, .lower), 893 &std.fmt.bytesToHex(&newest_object_id, .lower), 894 ) catch |err| switch (err) { 895 error.DescendentNotFound => is_rebased = true, 896 else => |e| return e, 897 }; 898 899 if (is_rebased) { 900 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 901 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 902 defer oldest_object.deinit(); 903 904 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 905 switch (parent_oids.len) { 906 0 => { 907 // the branch was rebased all the way to the very beginning. 908 // we have a repo event with no parent, which means it is now 909 // the very first event. all we need to do is set the haxy list 910 // to be empty and make a new haxy_moments map to work with. 911 912 try haxy.slice(0); 913 haxy_moments_cursor = try haxy.appendCursor(); 914 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 915 916 last_object_id_maybe = null; 917 }, 918 1 => { 919 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 920 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 921 922 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 923 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 924 925 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 926 const old_moment_index = try old_moment_index_cursor.readUint(); 927 928 // resize the haxy list so we truncate all the moments that were 929 // created after the parent_oid was consumed 930 try haxy.slice(old_moment_index + 1); 931 932 // make a new haxy moment and set its initial value to the last haxy moment 933 haxy_moments_cursor = try haxy.appendCursor(); 934 const old_haxy_moments_cursor = try haxy.getCursor(old_moment_index) orelse return error.CursorNotFound; 935 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 936 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 937 938 last_object_id_maybe = oid; 939 }, 940 else => return error.UnexpectedParentCount, 941 } 942 } 943 } 944 945 while (try commit_iter.next()) |repo_event_oid| { 946 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 947 defer commit_object.deinit(); 948 949 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 950 951 // create a moment for this object id 952 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 953 954 // if there was a previous object id, set this haxy moment's initial value to it. 955 // this efficiently "clones" the map so we make further modifications based on it. 956 if (parent_oids.len > 0) { 957 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 958 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 959 960 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 961 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 962 } 963 964 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 965 966 // graph generation gives every event a causal order independent of 967 // commit timestamps. concurrent events tie-break by id in their index. 968 var event_order: u64 = 1; 969 for (parent_oids) |*parent_oid| { 970 var parent_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 971 _ = try std.fmt.hexToBytes(&parent_id, parent_oid); 972 const parent_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &parent_id)) orelse return error.CursorNotFound; 973 const parent = try DB.HashMap(.read_only).init(parent_cursor); 974 const parent_order_cursor = try parent.getCursor(hash.hashInt(repo_opts.hash, event_order_key)) orelse return error.CursorNotFound; 975 const parent_order = try parent_order_cursor.readUint(); 976 event_order = @max(event_order, parent_order +| 1); 977 } 978 try haxy_moment.put(hash.hashInt(repo_opts.hash, event_order_key), .{ .uint = event_order }); 979 980 // merge changes from every parent after the first parent. the common 981 // ancestor is the baseline, so a later parent only contributes records 982 // it changed relative to the merge base. only the record maps are 983 // merged; every other view is derived from them, and each kind's 984 // `consume` re-derives its own as the winning records are written. 985 if (parent_oids.len > 1) { 986 for (parent_oids[1..]) |*parent_oid| { 987 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 988 _ = try std.fmt.hexToBytes(&oid, parent_oid); 989 990 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 991 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 992 993 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 994 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 995 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 996 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 997 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 998 999 inline for (std.meta.fields(Event)) |field| { 1000 const T = @typeInfo(field.type).optional.child; 1001 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 1002 } 1003 } 1004 } 1005 1006 // associate this moment with the index it will first appear at in the haxy list. 1007 // this will be important later so we can truncate that list if the user ever 1008 // rebases starting at this object id. 1009 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy.count() - 1 }); 1010 1011 // consume the event unless it's a merge commit 1012 if (parent_oids.len <= 1) { 1013 var arena = std.heap.ArenaAllocator.init(allocator); 1014 defer arena.deinit(); 1015 1016 // read the message from the commit 1017 var message: std.ArrayList(u8) = .empty; 1018 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 1019 1020 const event_with_id = try EventWithId.fromString(&arena, message.items); 1021 if (!role.allows(std.meta.activeTag(event_with_id.event))) return error.EventKindNotAllowed; 1022 1023 const current_event_id = try parseEventId(&event_with_id.id); 1024 1025 // wrap the payload into the record `consume` stores, with its 1026 // commit-derived fields; on update, `consume` preserves the 1027 // existing record's 1028 switch (event_with_id.event) { 1029 .user => |event_maybe| { 1030 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1031 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1032 }, 1033 .repo => |event_maybe| { 1034 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1035 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1036 }, 1037 .fork => |event_maybe| { 1038 const record_maybe: ?Fork.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1039 try Fork.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1040 }, 1041 .issue => |event_maybe| { 1042 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 1043 .event = event, 1044 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1045 .created_order = event_order, 1046 .updated_order = event_order, 1047 } else null; 1048 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1049 }, 1050 .discuss => |event_maybe| { 1051 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 1052 .event = event, 1053 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1054 .created_order = event_order, 1055 .updated_order = event_order, 1056 } else null; 1057 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1058 }, 1059 .comment => |event_maybe| { 1060 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 1061 .event = event, 1062 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1063 .created_order = event_order, 1064 .updated_order = event_order, 1065 } else null; 1066 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1067 }, 1068 .attach => |event_maybe| { 1069 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 1070 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 1071 break :blk .{ 1072 .event = event, 1073 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1074 .created_order = event_order, 1075 .updated_order = event_order, 1076 .name = entry.name, 1077 .blob_oid = entry.oid, 1078 }; 1079 } else null; 1080 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1081 }, 1082 .patchrev => |event_maybe| { 1083 const record_maybe: ?PatchRev.Record = if (event_maybe) |event| blk: { 1084 const trees = try PatchRev.readTrees(repo_kind, repo_opts, read_state, io, allocator, &commit_object.content.commit.tree); 1085 const existing_maybe = try PatchRev.readById(DB, repo_opts.hash, haxy_moment.readOnly(), &arena, &current_event_id); 1086 const event_oid = std.fmt.bytesToHex(repo_event_oid, .lower); 1087 1088 var patch_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1089 if (existing_maybe) |existing| { 1090 if (existing.patch_oid.len != patch_oid.len) return error.InvalidPatch; 1091 @memcpy(&patch_oid, existing.patch_oid); 1092 } else { 1093 const author = try commitIdentity(commit_object.content.commit.metadata.author orelse return error.AuthorNotFound); 1094 const committer = try commitIdentity(commit_object.content.commit.metadata.committer orelse author); 1095 patch_oid = try PatchRev.writeSquashCommit( 1096 repo_kind, 1097 repo_opts, 1098 state, 1099 io, 1100 allocator, 1101 event, 1102 &trees.head, 1103 author, 1104 committer, 1105 commit_object.content.commit.metadata.timestamp, 1106 ); 1107 } 1108 1109 break :blk .{ 1110 .event = event, 1111 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1112 .created_order = event_order, 1113 .updated_order = event_order, 1114 .event_oid = &event_oid, 1115 .base_tree_oid = &trees.base, 1116 .head_tree_oid = &trees.head, 1117 .patch_oid = &patch_oid, 1118 }; 1119 } else null; 1120 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1121 }, 1122 .patch => |event_maybe| { 1123 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 1124 .event = event, 1125 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1126 .created_order = event_order, 1127 .updated_order = event_order, 1128 } else null; 1129 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1130 }, 1131 } 1132 } 1133 1134 // the current object id is now the last one 1135 last_object_id_maybe = repo_event_oid; 1136 1137 // prevent any of the data created above from being mutated by future iterations of this loop 1138 try db.freeze(); 1139 } 1140 1141 if (last_object_id_maybe) |*last_object_id| { 1142 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1143 } 1144 1145 return true; 1146 } 1147 1148 // the conflicted records of one kind, keyed by the same order key its id set 1149 // uses, so this doubles as the index the conflicts view lists and counts. every 1150 // value under an entry is a slot reference to a structure that already exists: 1151 // 1152 // <order key> -> conflict entry 1153 // conflicted-fields the conflicting field names, space separated 1154 // base-record the merge base's whole record 1155 // their-record the merged-in side's whole record 1156 // their-field->oid that side's field name to commit map 1157 // 1158 // our own value is the live record and our commit is in the kind's oid map, so 1159 // neither is repeated here. 1160 pub const conflicted_fields_key = "conflicted-fields"; 1161 pub const base_record_key = "base-record"; 1162 pub const their_record_key = "their-record"; 1163 pub const their_field_to_oid_key = "their-field->oid"; 1164 1165 // record the commit against every field this event changes. a merge passes no 1166 // oid, since each field's winner may come from a different side. 1167 pub fn writeOid( 1168 comptime T: type, 1169 comptime DB: type, 1170 comptime hash_kind: hash.HashKind, 1171 id_to_field_to_oid: DB.HashMap(.read_write), 1172 record_key: hash.HashInt(hash_kind), 1173 existing_maybe: ?T, 1174 event: T, 1175 event_oid: ?[]const u8, 1176 ) !void { 1177 const oid = event_oid orelse return; 1178 1179 // created only once a field actually changes 1180 var field_oids: ?DB.SortedMap(.read_write) = null; 1181 1182 inline for (std.meta.fields(T)) |field| { 1183 const changed = if (existing_maybe) |existing| 1184 !fieldEqual(field.type, @field(existing, field.name), @field(event, field.name)) 1185 else 1186 true; 1187 if (changed) { 1188 if (field_oids == null) { 1189 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1190 } 1191 if (field_oids) |map| try map.put(field.name, .{ .bytes = oid }); 1192 } 1193 } 1194 } 1195 1196 // the whole field list, space separated, is the longest it can get 1197 fn conflictedFieldsMaxLen(comptime T: type) usize { 1198 var len: usize = 0; 1199 for (std.meta.fields(T)) |field| len += field.name.len + 1; 1200 return len; 1201 } 1202 1203 pub const MergePolicy = enum { 1204 field_conflicts, 1205 target_wins, 1206 }; 1207 1208 // what a three-way merge did with a field 1209 pub const FieldMerge = enum { 1210 // the target's value stands, because neither side changed it, both made the 1211 // same change, or only the target changed it 1212 kept, 1213 parent, 1214 conflicted, 1215 }; 1216 1217 // three-way merge each field. one only the parent changed takes the parent's 1218 // value; one both sides changed differently keeps the target's. a missing 1219 // baseline makes every differing field a conflict. 1220 fn mergeFields( 1221 comptime T: type, 1222 baseline_maybe: ?T, 1223 target: T, 1224 parent: T, 1225 outcome: *[std.meta.fields(T).len]FieldMerge, 1226 ) T { 1227 var merged = target; 1228 1229 inline for (std.meta.fields(T), 0..) |field, i| { 1230 const target_value = @field(target, field.name); 1231 const parent_value = @field(parent, field.name); 1232 1233 if (!fieldEqual(field.type, target_value, parent_value)) { 1234 outcome[i] = if (baseline_maybe) |baseline| blk: { 1235 const baseline_value = @field(baseline, field.name); 1236 if (fieldEqual(field.type, target_value, baseline_value)) { 1237 @field(merged, field.name) = parent_value; 1238 break :blk .parent; 1239 } 1240 // only the target changed it 1241 if (fieldEqual(field.type, parent_value, baseline_value)) break :blk .kept; 1242 break :blk .conflicted; 1243 } else .conflicted; 1244 } 1245 } 1246 1247 return merged; 1248 } 1249 1250 // three-way merge of one kind's records from a merge parent. kinds that expose 1251 // conflicts merge field by field; the others take one whole record. the result 1252 // goes through the kind's `consume`, which re-derives the indexes from it. a 1253 // removal carries over unless the other side changed the record, so a merge 1254 // never fails. 1255 pub fn merge( 1256 comptime T: type, 1257 comptime DB: type, 1258 comptime hash_kind: hash.HashKind, 1259 allocator: std.mem.Allocator, 1260 haxy_moment: DB.HashMap(.read_write), 1261 parent_moment: DB.HashMap(.read_only), 1262 baseline_moment: DB.HashMap(.read_only), 1263 ) !void { 1264 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1265 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1266 1267 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1268 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1269 1270 var baseline_records: ?DB.HashMap(.read_only) = null; 1271 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1272 baseline_records = try DB.HashMap(.read_only).init(cursor); 1273 } 1274 1275 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1276 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1277 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1278 switch (comptime T.merge_policy) { 1279 .field_conflicts => { 1280 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1281 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1282 } 1283 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1284 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1285 } 1286 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1287 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1288 } 1289 }, 1290 .target_wins => {}, 1291 } 1292 1293 var arena = std.heap.ArenaAllocator.init(allocator); 1294 defer arena.deinit(); 1295 1296 var iter = try parent_set.iteratorFromIndex(0); 1297 while (try iter.next()) |kv_pair_cursor| { 1298 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1299 const record_key = hash.hashInt(hash_kind, &event_id); 1300 1301 _ = arena.reset(.retain_capacity); 1302 1303 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1304 const parent_slot = parent_record_cursor.slot(); 1305 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1306 1307 // the parent left this record alone 1308 if (baseline_slot) |slot| { 1309 if (slot.eql(parent_slot)) continue; 1310 } 1311 1312 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1313 1314 // re-derived every iteration, since `consume` writes through its own 1315 // handles 1316 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1317 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1318 1319 // a record the target doesn't have arrives wholesale from the parent 1320 var outcome: [std.meta.fields(T).len]FieldMerge = @splat(.parent); 1321 var merged = parent_record; 1322 1323 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1324 // both sides share the change 1325 if (target_record_cursor.slot().eql(parent_slot)) continue; 1326 1327 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1328 1329 var baseline_record: ?T.Record = null; 1330 if (baseline_records) |map| { 1331 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1332 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1333 } 1334 } 1335 1336 switch (comptime T.merge_policy) { 1337 .field_conflicts => { 1338 outcome = @splat(.kept); 1339 merged = target_record; 1340 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1341 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1342 if (comptime @hasDecl(T, "resolveMerge")) { 1343 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1344 } 1345 1346 // merge the removed state separately from serialized fields. removal 1347 // carries over an unchanged record, while an edit or restoration 1348 // keeps it active. 1349 merged.removed = if (target_record.removed == parent_record.removed) 1350 target_record.removed 1351 else if (baseline_record) |baseline| blk: { 1352 const active = if (!target_record.removed) target_record else parent_record; 1353 if (active.removed != baseline.removed) break :blk false; 1354 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1355 break :blk true; 1356 } else false; 1357 }, 1358 .target_wins => { 1359 // an uncontested parent change carries over. if both sides 1360 // changed the record, the target wins as a whole, except that 1361 // an edit or restoration wins over a removal. 1362 const target_changed = if (baseline_slot) |slot| 1363 !target_record_cursor.slot().eql(slot) 1364 else 1365 true; 1366 merged = if (!target_changed) 1367 parent_record 1368 else if (target_record.removed != parent_record.removed) 1369 if (target_record.removed) parent_record else target_record 1370 else 1371 target_record; 1372 }, 1373 } 1374 } 1375 1376 // the index is unique, so a key the target gave to a different record 1377 // leaves this one out rather than stranding that one behind a name it 1378 // no longer owns 1379 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1380 const index_key = try merged.indexKey(arena.allocator()); 1381 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1382 const name_index = try DB.HashMap(.read_write).init(name_index_cursor); 1383 if (try name_index.getCursor(hash.hashInt(hash_kind, index_key))) |owner_cursor| { 1384 var owner_id: [event_id_size]u8 = undefined; 1385 _ = try owner_cursor.readBytes(&owner_id); 1386 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1387 } 1388 } 1389 1390 // `consume` sets no oids, since each field's winner may come from 1391 // a different side 1392 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1393 1394 switch (comptime T.merge_policy) { 1395 .field_conflicts => {}, 1396 .target_wins => continue, 1397 } 1398 1399 // removed records do not carry field conflicts 1400 if (merged.removed) continue; 1401 1402 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1403 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1404 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1405 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1406 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1407 1408 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1409 if (parent_id_to_field_to_oid) |map| { 1410 if (try map.getCursor(record_key)) |field_oids_cursor| { 1411 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1412 } 1413 } 1414 // created only once a field actually comes from the parent 1415 var field_oids: ?DB.SortedMap(.read_write) = null; 1416 1417 // the fields both sides changed differently, space separated 1418 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1419 var conflicted_len: usize = 0; 1420 1421 inline for (std.meta.fields(T), 0..) |field, i| { 1422 switch (outcome[i]) { 1423 // the target's value stands, so its oid does too 1424 .kept => {}, 1425 // the parent set this value, so its commit takes the field. a 1426 // parent with no oid took its own value from a merge, leaving 1427 // the field unattributed rather than crediting the target's 1428 // commit for a value it no longer holds. 1429 .parent => { 1430 if (field_oids == null) { 1431 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1432 } 1433 const map = field_oids orelse unreachable; 1434 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1435 if (parent_oid) |oid_cursor| { 1436 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1437 } else { 1438 _ = try map.remove(field.name); 1439 } 1440 }, 1441 .conflicted => { 1442 if (conflicted_len > 0) { 1443 conflicted_fields[conflicted_len] = ' '; 1444 conflicted_len += 1; 1445 } 1446 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1447 conflicted_len += field.name.len; 1448 }, 1449 } 1450 } 1451 1452 if (conflicted_len > 0) { 1453 // each side's whole record is stored by reference, so the view can 1454 // show any of them or take theirs wholesale 1455 _ = try conflicts.remove(&merged_key); 1456 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1457 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1458 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1459 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1460 if (parent_field_oids) |map| { 1461 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1462 } 1463 continue; 1464 } 1465 1466 // created_order never changes, so the parent keys this record's conflict 1467 // identically, and it carries over when the target has none, unless the 1468 // parent's entry is unchanged from the baseline, meaning the target 1469 // inherited it too and resolving it removed it here. 1470 if (parent_conflicts) |map| { 1471 if (null == try conflicts.getCursor(&merged_key)) { 1472 if (try map.getSlot(&merged_key)) |conflict_slot| { 1473 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1474 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1475 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1476 } 1477 } 1478 } 1479 } 1480 } 1481 1482 pub fn currentMoment( 1483 comptime repo_opts: rp.RepoOpts(.xit), 1484 repo: *rp.Repo(.xit, repo_opts), 1485 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1486 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1487 } 1488 1489 pub fn currentMomentFromDb( 1490 comptime hash_kind: hash.HashKind, 1491 db: *EventDB(hash_kind), 1492 ) !EventDB(hash_kind).HashMap(.read_only) { 1493 const DB = EventDB(hash_kind); 1494 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1495 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1496 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1497 return try currentMomentFromRepoMoment(hash_kind, moment); 1498 } 1499 1500 pub fn currentMomentFromRepoMoment( 1501 comptime hash_kind: hash.HashKind, 1502 moment: EventDB(hash_kind).HashMap(.read_only), 1503 ) !EventDB(hash_kind).HashMap(.read_only) { 1504 const DB = EventDB(hash_kind); 1505 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1506 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1507 _ = try last_object_id_cursor.readBytes(&last_object_id); 1508 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, materialized_key)) orelse return error.NotFound; 1509 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 1510 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 1511 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1512 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1513 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1514 } 1515 1516 // build a sorted-set key from an order and event id. big-endian order makes 1517 // byte order match numeric order; the event id breaks ties. 1518 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1519 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1520 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1521 @memcpy(key[@sizeOf(u64)..], event_id); 1522 return key; 1523 } 1524 1525 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1526 return orderKey(std.math.maxInt(u64) - order, event_id); 1527 } 1528 1529 pub fn removedRecord( 1530 comptime T: type, 1531 comptime DB: type, 1532 comptime hash_kind: hash.HashKind, 1533 haxy_moment: DB.HashMap(.read_only), 1534 existing_maybe: ?T, 1535 ) !T { 1536 var record = existing_maybe orelse return error.EventNotFound; 1537 record.removed = true; 1538 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1539 record.updated_order = try order_cursor.readUint(); 1540 return record; 1541 } 1542 1543 // add or refresh one entry in the global logical-event index 1544 pub fn indexEvent( 1545 comptime DB: type, 1546 comptime hash_kind: hash.HashKind, 1547 haxy_moment: DB.HashMap(.read_write), 1548 event_id: *const [event_id_size]u8, 1549 kind: EventKind, 1550 existing_maybe: anytype, 1551 record: anytype, 1552 ) !void { 1553 const event_key = hash.hashInt(hash_kind, event_id); 1554 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1555 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1556 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1557 1558 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1559 const active = try DB.SortedSet(.read_write).init(active_cursor); 1560 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1561 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1562 1563 if (existing_maybe) |existing| { 1564 const old_key = orderKeyDesc(existing.updated_order, event_id); 1565 _ = try active.remove(&old_key); 1566 _ = try removed_set.remove(&old_key); 1567 } 1568 1569 const order_key = orderKeyDesc(record.updated_order, event_id); 1570 if (record.removed) { 1571 try removed_set.put(&order_key); 1572 } else { 1573 try active.put(&order_key); 1574 } 1575 } 1576 1577 pub fn touchThread( 1578 comptime DB: type, 1579 comptime hash_kind: hash.HashKind, 1580 haxy_moment: DB.HashMap(.read_write), 1581 thread_id: *const [event_id_size]u8, 1582 order: u64, 1583 arena: *std.heap.ArenaAllocator, 1584 ) !void { 1585 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1586 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1587 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1588 switch (kind) { 1589 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1590 else => {}, 1591 } 1592 } 1593 1594 pub fn readEventKind( 1595 comptime hash_kind: hash.HashKind, 1596 kind_map: anytype, 1597 id: *const [event_id_size]u8, 1598 ) !?EventKind { 1599 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1600 var buffer: [64]u8 = undefined; 1601 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1602 } 1603 1604 // the event id embedded in a set entry's order key 1605 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1606 var cursor = kv_pair_cursor; 1607 const kv_pair = try cursor.readKeyValuePair(); 1608 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1609 _ = try kv_pair.key_cursor.readBytes(&order_key); 1610 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1611 } 1612 1613 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1614 // isn't exactly two non-empty segments. 1615 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1616 var it = std.mem.splitScalar(u8, path, '/'); 1617 const owner = it.next() orelse return null; 1618 const name = it.next() orelse return null; 1619 if (it.next() != null) return null; 1620 if (owner.len == 0 or name.len == 0) return null; 1621 1622 return .{ .owner = owner, .name = name }; 1623 } 1624 1625 pub const CreateRepoOptions = struct { 1626 read_access: Repo.Access = .private, 1627 }; 1628 1629 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1630 // directory under the repos dir 1631 pub fn resolveOrCreateRepo( 1632 io: std.Io, 1633 allocator: std.mem.Allocator, 1634 admin_repo_path: []const u8, 1635 owner_name: []const u8, 1636 repo_name: []const u8, 1637 create_options_maybe: ?CreateRepoOptions, 1638 ) !?[event_id_size * 2]u8 { 1639 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1640 error.RepoNotFound => return null, 1641 else => |e| return e, 1642 }; 1643 defer repo.deinit(io, allocator); 1644 1645 var arena = std.heap.ArenaAllocator.init(allocator); 1646 defer arena.deinit(); 1647 1648 const moment = try currentMoment(admin_repo_opts, &repo); 1649 1650 // an already-registered repo reuses its event id, so a re-push (or a clone) 1651 // lands in the same repo 1652 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1653 return std.fmt.bytesToHex(found.event_id, .lower); 1654 } 1655 1656 const create_options = create_options_maybe orelse return null; 1657 1658 // the new repo is owned by the named user, read from the name index; an 1659 // unknown owner can't own a repo, so the push is rejected 1660 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1661 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1662 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1663 var owner_user_id: [event_id_size]u8 = undefined; 1664 _ = try owner_id_cursor.readBytes(&owner_user_id); 1665 1666 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1667 1668 var id_bytes: [event_id_size]u8 = undefined; 1669 io.random(&id_bytes); 1670 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1671 1672 try consume(.admin, .xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1673 .id = event_id_hex, 1674 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1675 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1676 .event = .{ .repo = .{ 1677 .user_id = &owner_user_id, 1678 .name = repo_name, 1679 .description = "", 1680 .read_access = create_options.read_access, 1681 } }, 1682 }}); 1683 1684 return event_id_hex; 1685 } 1686 1687 // 1688 // reading from xitdb 1689 // 1690 1691 pub fn read( 1692 comptime T: type, 1693 comptime DB: type, 1694 comptime hash_kind: hash.HashKind, 1695 arena: *std.heap.ArenaAllocator, 1696 map: DB.HashMap(.read_only), 1697 ) !T { 1698 var event: T = undefined; 1699 1700 switch (@typeInfo(T)) { 1701 .@"struct" => |struct_info| { 1702 inline for (struct_info.fields) |field| { 1703 switch (@typeInfo(field.type)) { 1704 .pointer => |pointer_info| { 1705 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 1706 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1707 } else { 1708 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1709 } 1710 }, 1711 .array => |array_info| { 1712 if (array_info.child == u8) { 1713 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1714 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 1715 @memcpy(@field(event, field.name)[0..], bytes); 1716 } else { 1717 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1718 } 1719 }, 1720 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 1721 .int => |int_info| switch (int_info.signedness) { 1722 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 1723 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 1724 }, 1725 .@"enum" => { 1726 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1727 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 1728 }, 1729 .@"union" => { 1730 if (!@hasDecl(field.type, "decode")) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1731 @field(event, field.name) = try field.type.decode(try readBytes(DB, hash_kind, arena.allocator(), map, field.name)); 1732 }, 1733 .optional => |optional_info| { 1734 // a missing key is null 1735 if (try map.getCursor(hash.hashInt(hash_kind, field.name))) |cursor| { 1736 if (optional_info.child == []const u8) { 1737 @field(event, field.name) = try cursor.readBytesAlloc(arena.allocator(), null); 1738 } else switch (@typeInfo(optional_info.child)) { 1739 .array => |array_info| { 1740 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1741 var bytes: optional_info.child = undefined; 1742 const value = try cursor.readBytes(&bytes); 1743 if (value.len != bytes.len) return error.InvalidByteArrayLength; 1744 @field(event, field.name) = bytes; 1745 }, 1746 .@"struct" => @field(event, field.name) = try read( 1747 optional_info.child, 1748 DB, 1749 hash_kind, 1750 arena, 1751 try DB.HashMap(.read_only).init(cursor), 1752 ), 1753 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1754 } 1755 } else { 1756 @field(event, field.name) = null; 1757 } 1758 }, 1759 .@"struct" => { 1760 const cursor = try map.getCursor(hash.hashInt(hash_kind, field.name)) orelse return error.NotFound; 1761 @field(event, field.name) = try read( 1762 field.type, 1763 DB, 1764 hash_kind, 1765 arena, 1766 try DB.HashMap(.read_only).init(cursor), 1767 ); 1768 }, 1769 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1770 } 1771 } 1772 }, 1773 else => @compileError("read expects a struct"), 1774 } 1775 1776 return event; 1777 } 1778 1779 // whether two events carry the same data 1780 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1781 switch (@typeInfo(T)) { 1782 .@"struct" => |struct_info| { 1783 inline for (struct_info.fields) |field| { 1784 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1785 } 1786 }, 1787 else => @compileError("fieldsEqual expects a struct"), 1788 } 1789 1790 return true; 1791 } 1792 1793 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1794 switch (@typeInfo(Field)) { 1795 .pointer => |pointer_info| { 1796 if (pointer_info.size == .slice and pointer_info.child == u8) { 1797 return std.mem.eql(u8, a, b); 1798 } else { 1799 @compileError("unsupported field type: " ++ @typeName(Field)); 1800 } 1801 }, 1802 .array => |array_info| { 1803 if (array_info.child == u8) { 1804 return std.mem.eql(u8, &a, &b); 1805 } else { 1806 @compileError("unsupported field type: " ++ @typeName(Field)); 1807 } 1808 }, 1809 .void => return true, 1810 .bool, .int, .@"enum" => return a == b, 1811 .@"union" => { 1812 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1813 return switch (a) { 1814 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 1815 }; 1816 }, 1817 .@"struct" => return fieldsEqual(Field, a, b), 1818 .optional => |optional_info| { 1819 if (a) |a_value| { 1820 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 1821 return false; 1822 } 1823 return b == null; 1824 }, 1825 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1826 } 1827 } 1828 1829 fn readBytes( 1830 comptime DB: type, 1831 comptime hash_kind: hash.HashKind, 1832 allocator: std.mem.Allocator, 1833 map: DB.HashMap(.read_only), 1834 field_name: []const u8, 1835 ) ![]const u8 { 1836 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1837 return try cursor.readBytesAlloc(allocator, null); 1838 } 1839 1840 fn readUint( 1841 comptime DB: type, 1842 comptime hash_kind: hash.HashKind, 1843 map: DB.HashMap(.read_only), 1844 field_name: []const u8, 1845 ) !u64 { 1846 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1847 return try cursor.readUint(); 1848 } 1849 1850 fn readInt( 1851 comptime DB: type, 1852 comptime hash_kind: hash.HashKind, 1853 map: DB.HashMap(.read_only), 1854 field_name: []const u8, 1855 ) !i64 { 1856 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1857 return try cursor.readInt(); 1858 } 1859 1860 fn readBool( 1861 comptime DB: type, 1862 comptime hash_kind: hash.HashKind, 1863 map: DB.HashMap(.read_only), 1864 field_name: []const u8, 1865 ) !bool { 1866 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1867 var buffer: [5]u8 = undefined; 1868 const bytes = try cursor.readBytesObject(&buffer); 1869 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1870 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1871 if (std.mem.eql(u8, bytes.value, "true")) return true; 1872 if (std.mem.eql(u8, bytes.value, "false")) return false; 1873 return error.InvalidBool; 1874 } 1875 1876 // 1877 // writing to xitdb 1878 // 1879 1880 pub fn upsert( 1881 comptime T: type, 1882 comptime DB: type, 1883 comptime hash_kind: hash.HashKind, 1884 map: DB.HashMap(.read_write), 1885 event: T, 1886 ) !void { 1887 switch (@typeInfo(T)) { 1888 .@"struct" => |struct_info| { 1889 inline for (struct_info.fields) |field| { 1890 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1891 } 1892 }, 1893 else => @compileError("upsert expects a struct"), 1894 } 1895 } 1896 1897 fn upsertField( 1898 comptime DB: type, 1899 comptime hash_kind: hash.HashKind, 1900 map: DB.HashMap(.read_write), 1901 comptime field_name: []const u8, 1902 comptime Field: type, 1903 value: Field, 1904 ) !void { 1905 const key = hash.hashInt(hash_kind, field_name); 1906 1907 switch (@typeInfo(Field)) { 1908 .pointer => |pointer_info| { 1909 if (pointer_info.size == .slice and pointer_info.child == u8) { 1910 try upsertBytes(DB, hash_kind, map, key, value); 1911 } else { 1912 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1913 } 1914 }, 1915 .array => |array_info| { 1916 if (array_info.child == u8) { 1917 try upsertBytes(DB, hash_kind, map, key, &value); 1918 } else { 1919 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1920 } 1921 }, 1922 .int => |int_info| switch (int_info.signedness) { 1923 .unsigned => { 1924 if (try map.getCursor(key)) |value_cursor| { 1925 if (try value_cursor.readUint() == value) { 1926 return; 1927 } 1928 } 1929 1930 try map.put(key, .{ .uint = value }); 1931 }, 1932 .signed => { 1933 if (try map.getCursor(key)) |value_cursor| { 1934 if (try value_cursor.readInt() == value) { 1935 return; 1936 } 1937 } 1938 1939 try map.put(key, .{ .int = value }); 1940 }, 1941 }, 1942 .bool => { 1943 const bytes = if (value) "true" else "false"; 1944 if (try map.getCursor(key)) |value_cursor| { 1945 var buffer: [5]u8 = undefined; 1946 const existing = try value_cursor.readBytesObject(&buffer); 1947 if (existing.format_tag) |format_tag| { 1948 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1949 return; 1950 } 1951 } 1952 } 1953 1954 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1955 }, 1956 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1957 .@"union" => { 1958 if (!@hasDecl(Field, "encode") or !@hasDecl(Field, "max_encoded_len")) { 1959 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1960 } 1961 var buffer: [Field.max_encoded_len]u8 = undefined; 1962 try upsertBytes(DB, hash_kind, map, key, try value.encode(&buffer)); 1963 }, 1964 .optional => |optional_info| { 1965 // a missing key is null 1966 if (value) |child| { 1967 if (optional_info.child == []const u8) { 1968 try upsertBytes(DB, hash_kind, map, key, child); 1969 } else switch (@typeInfo(optional_info.child)) { 1970 .array => |array_info| { 1971 if (array_info.child != u8) @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1972 try upsertBytes(DB, hash_kind, map, key, &child); 1973 }, 1974 .@"struct" => try upsert( 1975 optional_info.child, 1976 DB, 1977 hash_kind, 1978 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1979 child, 1980 ), 1981 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1982 } 1983 } else { 1984 _ = try map.remove(key); 1985 } 1986 }, 1987 .@"struct" => try upsert( 1988 Field, 1989 DB, 1990 hash_kind, 1991 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1992 value, 1993 ), 1994 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1995 } 1996 } 1997 1998 fn upsertBytes( 1999 comptime DB: type, 2000 comptime hash_kind: hash.HashKind, 2001 map: DB.HashMap(.read_write), 2002 key: hash.HashInt(hash_kind), 2003 value: []const u8, 2004 ) !void { 2005 var existing_cursor_maybe = try map.getCursor(key); 2006 if (existing_cursor_maybe) |*existing_cursor| { 2007 if (try bytesEqual(DB, existing_cursor, value)) { 2008 return; 2009 } 2010 } 2011 2012 var value_cursor = try map.putCursor(key); 2013 var write_buffer: [1024]u8 = undefined; 2014 var writer = try value_cursor.writer(&write_buffer); 2015 try writer.interface.writeAll(value); 2016 try writer.finish(); 2017 } 2018 2019 fn bytesEqual( 2020 comptime DB: type, 2021 cursor: *DB.Cursor(.read_only), 2022 value: []const u8, 2023 ) !bool { 2024 var read_buffer: [1024]u8 = undefined; 2025 var reader = try cursor.reader(&read_buffer); 2026 if (reader.size != value.len) { 2027 return false; 2028 } 2029 2030 var chunk_buffer: [1024]u8 = undefined; 2031 var offset: usize = 0; 2032 while (offset < value.len) { 2033 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2034 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2035 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2036 return false; 2037 } 2038 offset += chunk_len; 2039 } 2040 2041 return true; 2042 } 2043 2044 // 2045 // CommitIterator 2046 // 2047 // differs from xit's ObjectIterator in a few ways: 2048 // 2049 // 1. iterates parents first, rather than children first 2050 // 2. `next` only returns the object id, not the full Object 2051 // 3. stores its temporary state in a file on disk to avoid OOMs 2052 // 2053 2054 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2055 return struct { 2056 const DB = EventDB(repo_opts.hash); 2057 const db_name = "haxy-repo-events.db"; 2058 2059 repo_dir: std.Io.Dir, 2060 db_file: std.Io.File, 2061 db: *DB, 2062 // map of each object id to its children 2063 parent_to_children: DB.HashMap(.read_write), 2064 // tracking pending parents is necessary because a child can only 2065 // be returned after all of its unconsumed parents have been returned 2066 child_to_pending_parents: DB.HashMap(.read_write), 2067 // queue of object ids that are ready to be returned from `next` 2068 ready_queue: DB.ArrayList(.read_write), 2069 ready_queue_index: u64, 2070 // the object id at the tip of this branch 2071 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2072 // the object id furthest back in the history that hasn't been consumed 2073 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2074 2075 pub fn init( 2076 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2077 io: std.Io, 2078 allocator: std.mem.Allocator, 2079 consumed_object_ids: DB.HashMap(.read_only), 2080 ref: rf.Ref, 2081 ) !CommitIterator(repo_kind, repo_opts) { 2082 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2083 errdefer { 2084 db_file.close(io); 2085 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2086 } 2087 2088 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 2089 errdefer allocator.destroy(buffer_ptr); 2090 2091 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 2092 errdefer buffer_ptr.deinit(); 2093 2094 const db_ptr = try allocator.create(DB); 2095 errdefer allocator.destroy(db_ptr); 2096 // the db is scratch state that gets deleted after iteration, so 2097 // there is nothing worth fsyncing 2098 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 2099 2100 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 2101 2102 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2103 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 2104 2105 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2106 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2107 2108 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2109 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 2110 2111 var self = CommitIterator(repo_kind, repo_opts){ 2112 .repo_dir = state.core.repo_dir, 2113 .db_file = db_file, 2114 .db = db_ptr, 2115 .parent_to_children = parent_to_children, 2116 .child_to_pending_parents = child_to_pending_parents, 2117 .ready_queue = ready_queue, 2118 .ready_queue_index = 0, 2119 .newest_object_id = null, 2120 .oldest_object_id = null, 2121 }; 2122 errdefer self.deinit(io, allocator); 2123 2124 try self.collect(state, io, allocator, consumed_object_ids, ref); 2125 2126 return self; 2127 } 2128 2129 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2130 self.db_file.close(io); 2131 self.db.core.memory.buffer.deinit(); 2132 allocator.destroy(self.db.core.memory.buffer); 2133 self.repo_dir.deleteFile(io, db_name) catch {}; 2134 allocator.destroy(self.db); 2135 } 2136 2137 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2138 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2139 2140 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2141 self.ready_queue_index += 1; 2142 2143 try self.enqueueChildren(&oid); 2144 return oid; 2145 } 2146 2147 fn collect( 2148 self: *CommitIterator(repo_kind, repo_opts), 2149 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2150 io: std.Io, 2151 allocator: std.mem.Allocator, 2152 consumed_object_ids: DB.HashMap(.read_only), 2153 ref: rf.Ref, 2154 ) !void { 2155 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 2156 2157 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2158 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 2159 var walk_queue_index: u64 = 0; 2160 2161 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2162 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 2163 2164 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2165 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2166 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2167 try walk_queue.append(.{ .bytes = &head_oid }); 2168 2169 while (walk_queue_index < try walk_queue.count()) { 2170 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2171 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2172 2173 walk_queue_index += 1; 2174 2175 // if we've seen this object id, skip it 2176 if (null != try seen_object_ids.getCursor(oid_int)) { 2177 continue; 2178 } 2179 2180 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2181 2182 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2183 defer commit_object.deinit(); 2184 2185 // if this object id has already been consumed, skip it 2186 if (null != try consumed_object_ids.getCursor(oid_int)) { 2187 continue; 2188 } 2189 2190 if (self.newest_object_id == null) self.newest_object_id = oid; 2191 self.oldest_object_id = oid; 2192 2193 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2194 var pending_parent_count: u64 = 0; 2195 for (parent_oids) |*parent_oid| { 2196 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2197 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2198 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2199 2200 // if this object id has already been consumed, skip it 2201 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2202 continue; 2203 } 2204 2205 // if this object id hasn't already been seen, add it to the walk queue 2206 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2207 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2208 } 2209 2210 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2211 const children = try DB.HashSet(.read_write).init(children_cursor); 2212 try children.put(oid_int, .{ .bytes = &oid }); 2213 pending_parent_count += 1; 2214 } 2215 2216 if (pending_parent_count == 0) { 2217 try self.ready_queue.append(.{ .bytes = &oid }); 2218 } else { 2219 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2220 } 2221 } 2222 } 2223 2224 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2225 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2226 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2227 const children = try DB.HashSet(.read_only).init(children_cursor); 2228 var children_iter = try children.iterator(); 2229 2230 while (try children_iter.next()) |*child_cursor| { 2231 const kv_pair = try child_cursor.readKeyValuePair(); 2232 const child_oid_int = kv_pair.hash; 2233 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2234 const pending_parent_count = try pending_parent_cursor.readUint(); 2235 2236 if (pending_parent_count <= 1) { 2237 _ = try self.child_to_pending_parents.remove(child_oid_int); 2238 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2239 try self.ready_queue.append(.{ .bytes = &child_oid }); 2240 } else { 2241 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2242 } 2243 } 2244 } 2245 2246 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2247 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2248 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2249 _ = try oid_cursor.readBytes(&oid); 2250 return oid; 2251 } 2252 }; 2253 } 2254