╭ 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 Grant = @import("event/Grant.zig"); 14 pub const Discussion = @import("event/Discussion.zig"); 15 pub const Issue = @import("event/Issue.zig"); 16 pub const Comment = @import("event/Comment.zig"); 17 pub const Attachment = @import("event/Attachment.zig"); 18 pub const Assignment = @import("event/Assignment.zig"); 19 pub const Patch = @import("event/Patch.zig"); 20 pub const PatchRev = @import("event/PatchRev.zig"); 21 22 // the most bytes an event's serialized form may hold 23 pub const max_event_size: usize = 100 * 1024; 24 25 // the branch haxy events are committed to before being consumed 26 pub const events_ref: rf.Ref = .{ .kind = .head, .name = "haxy/events" }; 27 28 pub const history_key = "haxy/history"; 29 pub const last_object_id_key = "haxy/last-object-id"; 30 31 // options + db type for the admin repo 32 pub const admin_repo_opts: rp.RepoOpts(.xit) = .{}; 33 pub const AdminDB = rp.Repo(.xit, admin_repo_opts).DB; 34 35 // options + db type for a user repo, which holds its user's repo, fork and grant events 36 pub const user_repo_opts: rp.RepoOpts(.xit) = .{}; 37 pub const UserDB = rp.Repo(.xit, user_repo_opts).DB; 38 39 // the admin repo's file the home page renders 40 pub const admin_about_path = "ABOUT.md"; 41 42 // create the admin repo with a master branch holding the default about page. 43 // pushes to master update its work dir. 44 pub fn initAdminRepo(io: std.Io, allocator: std.mem.Allocator, path: []const u8) !rp.Repo(.xit, admin_repo_opts) { 45 var repo = try rp.Repo(.xit, admin_repo_opts).init(io, allocator, .{ .path = path }); 46 errdefer repo.deinit(io, allocator); 47 try repo.addConfig(io, allocator, .{ .name = "receive.denycurrentbranch", .value = "updateInstead" }); 48 { 49 const file = try repo.core.work_dir.createFile(io, admin_about_path, .{}); 50 defer file.close(io); 51 try file.writeStreamingAll(io, "# HAXY\n\nWelcome to your Haxy instance!\n\nEdit `admin/ABOUT.md` in the server dir to change what this page says."); 52 } 53 try repo.add(io, allocator, &.{admin_about_path}); 54 _ = try repo.commit(io, allocator, .{ .author = "haxy <haxy@localhost>", .message = "init" }); 55 return repo; 56 } 57 58 // create a user's bare repo. its events branch starts with the first consume. 59 pub fn initUserRepo(io: std.Io, allocator: std.mem.Allocator, path: []const u8) !rp.Repo(.xit, user_repo_opts) { 60 return try rp.Repo(.xit, user_repo_opts).init(io, allocator, .{ .bare = true, .path = path }); 61 } 62 63 // a user repo's path, inside the user's dir 64 pub fn userRepoPath(allocator: std.mem.Allocator, users_dir: []const u8, user_id: *const [event_id_size]u8) ![]u8 { 65 return try std.Io.Dir.path.join(allocator, &.{ users_dir, &std.fmt.bytesToHex(user_id.*, .lower), "user" }); 66 } 67 68 // a repo's path, inside its owner's dir 69 pub fn repoPath(allocator: std.mem.Allocator, users_dir: []const u8, owner_id: []const u8, repo_id: []const u8) ![]u8 { 70 return try std.Io.Dir.path.join(allocator, &.{ users_dir, &std.fmt.bytesToHex(owner_id[0..event_id_size].*, .lower), "repos", &std.fmt.bytesToHex(repo_id[0..event_id_size].*, .lower) }); 71 } 72 73 // the ids a repo path names, or null for a path `repoPath` didn't build 74 pub fn parseRepoPath(users_dir: []const u8, path: []const u8) ?RepoLocation { 75 const repos_dir = std.Io.Dir.path.dirname(path) orelse return null; 76 if (!std.mem.eql(u8, std.Io.Dir.path.basename(repos_dir), "repos")) return null; 77 const owner_dir = std.Io.Dir.path.dirname(repos_dir) orelse return null; 78 if (!std.mem.eql(u8, std.Io.Dir.path.dirname(owner_dir) orelse return null, users_dir)) return null; 79 return .{ 80 .owner_id = parseEventId(std.Io.Dir.path.basename(owner_dir)) catch return null, 81 .repo_id = parseEventId(std.Io.Dir.path.basename(path)) catch return null, 82 }; 83 } 84 85 // the owner's repos newest activity first, as order keys 86 pub const recent_repo_id_set_key = "haxy/recent-repo-id-set"; 87 // each repo's activity time in that set 88 const repo_activity_time_key = "haxy/repo-id->activity-time"; 89 90 // a repo's activity time is rewritten at most once per window 91 pub const repo_activity_window_secs = 5 * 60; 92 93 // move a repo to `timestamp` in its owner's activity index, unless it moved within the window 94 pub fn bumpRepoActivity( 95 io: std.Io, 96 allocator: std.mem.Allocator, 97 users_dir: []const u8, 98 owner_id: *const [event_id_size]u8, 99 repo_id: *const [event_id_size]u8, 100 timestamp: u64, 101 ) !void { 102 const hash_kind = user_repo_opts.hash; 103 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return; 104 defer user_repo.deinit(io, allocator); 105 106 // a recent bump skips the transaction 107 if (try readActivityTime(try user_repo.core.latestMoment(), repo_id)) |time| { 108 if (timestamp -| time < repo_activity_window_secs) return; 109 } 110 111 const Ctx = struct { 112 repo_id: *const [event_id_size]u8, 113 timestamp: u64, 114 115 pub fn run(ctx: @This(), cursor: *UserDB.Cursor(.read_write)) !void { 116 const moment = try UserDB.HashMap(.read_write).init(cursor.*); 117 // reread so a concurrent bump can't leave its key behind 118 const old_time = try readActivityTime(moment.readOnly(), ctx.repo_id); 119 if (old_time) |time| { 120 if (ctx.timestamp -| time < repo_activity_window_secs) return error.CancelTransaction; 121 } 122 const recent = try UserDB.SortedSet(.read_write).init(try moment.putCursor(hash.hashInt(hash_kind, recent_repo_id_set_key))); 123 if (old_time) |time| _ = try recent.remove(&orderKeyDesc(time, ctx.repo_id)); 124 try recent.put(&orderKeyDesc(ctx.timestamp, ctx.repo_id)); 125 const times = try UserDB.HashMap(.read_write).init(try moment.putCursor(hash.hashInt(hash_kind, repo_activity_time_key))); 126 try times.put(hash.hashInt(hash_kind, ctx.repo_id), .{ .uint = ctx.timestamp }); 127 } 128 }; 129 130 try user_repo.core.db_file.lock(io, .exclusive); 131 defer user_repo.core.db_file.unlock(io); 132 133 const history = try UserDB.ArrayList(.read_write).init(user_repo.core.db.rootCursor()); 134 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ .repo_id = repo_id, .timestamp = timestamp }) catch |err| switch (err) { 135 error.CancelTransaction => {}, 136 else => |e| return e, 137 }; 138 } 139 140 // bump the repo at `repo_path` to now, logging rather than returning a failure 141 pub fn bumpRepoActivityAt(io: std.Io, allocator: std.mem.Allocator, users_dir: []const u8, repo_path: []const u8) void { 142 const location = parseRepoPath(users_dir, repo_path) orelse return; 143 const now: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 144 bumpRepoActivity(io, allocator, users_dir, &location.owner_id, &location.repo_id, now) catch |err| { 145 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 146 }; 147 } 148 149 fn readActivityTime(moment: UserDB.HashMap(.read_only), repo_id: *const [event_id_size]u8) !?u64 { 150 const times_cursor = try moment.getCursor(hash.hashInt(user_repo_opts.hash, repo_activity_time_key)) orelse return null; 151 const times = try UserDB.HashMap(.read_only).init(times_cursor); 152 const time_cursor = try times.getCursor(hash.hashInt(user_repo_opts.hash, repo_id)) orelse return null; 153 return try time_cursor.readUint(); 154 } 155 156 // open a user's repo, or null when it's missing 157 pub fn openUserRepo(io: std.Io, allocator: std.mem.Allocator, users_dir: []const u8, user_id: *const [event_id_size]u8) !?rp.Repo(.xit, user_repo_opts) { 158 const path = try userRepoPath(allocator, users_dir, user_id); 159 defer allocator.free(path); 160 return rp.Repo(.xit, user_repo_opts).open(io, allocator, .{ .path = path, .require_repo_root = true }) catch |err| switch (err) { 161 error.RepoNotFound, error.FileNotFound => null, 162 else => |e| e, 163 }; 164 } 165 166 // a user repo's moment, or null before its first event 167 pub fn userMoment(repo: *rp.Repo(.xit, user_repo_opts)) !?UserDB.HashMap(.read_only) { 168 return currentMoment(user_repo_opts, repo) catch |err| switch (err) { 169 error.NotFound => null, 170 else => |e| e, 171 }; 172 } 173 174 // read a repo by its owner's name and its name, from the owner's user repo, 175 // with the role `viewer_id` holds in it. a null viewer is logged out. 176 pub fn readRepoByOwnerAndName( 177 io: std.Io, 178 allocator: std.mem.Allocator, 179 arena: *std.heap.ArenaAllocator, 180 admin_moment: AdminDB.HashMap(.read_only), 181 users_dir: []const u8, 182 owner_name: []const u8, 183 repo_name: []const u8, 184 viewer_id: ?[event_id_size]u8, 185 ) !?Repo.RepoWithRole { 186 const owner_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 187 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_id)) orelse return null; 188 defer user_repo.deinit(io, allocator); 189 const moment = (try userMoment(&user_repo)) orelse return null; 190 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, arena, repo_name)) orelse return null; 191 return .{ 192 .repo = found.repo, 193 .event_id = found.event_id, 194 .role = try Repo.roleOf(UserDB, user_repo_opts.hash, moment, arena, found.repo, &found.event_id, viewer_id), 195 }; 196 } 197 198 // read a repo by its owner's id and its id, from the owner's user repo, with 199 // the role `viewer_id` holds in it. a null viewer is logged out. 200 pub fn readRepoById( 201 io: std.Io, 202 allocator: std.mem.Allocator, 203 arena: *std.heap.ArenaAllocator, 204 users_dir: []const u8, 205 owner_id: *const [event_id_size]u8, 206 repo_id: *const [event_id_size]u8, 207 viewer_id: ?[event_id_size]u8, 208 ) !?Repo.RepoWithRole { 209 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return null; 210 defer user_repo.deinit(io, allocator); 211 const moment = (try userMoment(&user_repo)) orelse return null; 212 const repo = (try Repo.readById(UserDB, user_repo_opts.hash, moment, arena, repo_id)) orelse return null; 213 return .{ 214 .repo = repo, 215 .event_id = repo_id.*, 216 .role = try Repo.roleOf(UserDB, user_repo_opts.hash, moment, arena, repo, repo_id, viewer_id), 217 }; 218 } 219 220 // a repo's active grants, from its owner's user repo 221 pub fn readRepoGrants( 222 io: std.Io, 223 allocator: std.mem.Allocator, 224 arena: *std.heap.ArenaAllocator, 225 users_dir: []const u8, 226 owner_id: *const [event_id_size]u8, 227 repo_id: *const [event_id_size]u8, 228 ) ![]const Grant { 229 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return &.{}; 230 defer user_repo.deinit(io, allocator); 231 const moment = (try userMoment(&user_repo)) orelse return &.{}; 232 return try Grant.readByTarget(UserDB, user_repo_opts.hash, moment, arena, repo_id); 233 } 234 235 // read a fork by its forker's id and its id, from the forker's user repo 236 pub fn readForkById( 237 io: std.Io, 238 allocator: std.mem.Allocator, 239 arena: *std.heap.ArenaAllocator, 240 users_dir: []const u8, 241 forker_id: *const [event_id_size]u8, 242 fork_id: *const [event_id_size]u8, 243 ) !?Fork.Record { 244 var user_repo = (try openUserRepo(io, allocator, users_dir, forker_id)) orelse return null; 245 defer user_repo.deinit(io, allocator); 246 const moment = (try userMoment(&user_repo)) orelse return null; 247 return try Fork.readById(UserDB, user_repo_opts.hash, moment, arena, fork_id); 248 } 249 250 // the xitdb type events are stored in. it only depends on the hash kind, so 251 // this matches the db of any xit repo using that hash kind. 252 pub fn EventDB(comptime hash_kind: hash.HashKind) type { 253 return rp.Repo(.xit, .{ .hash = hash_kind }).DB; 254 } 255 256 // the email between a commit author line's angle brackets, or null 257 pub fn authorEmail(author_line: []const u8) ?[]const u8 { 258 const open_bracket = std.mem.indexOfScalar(u8, author_line, '<') orelse return null; 259 const close_bracket = std.mem.indexOfScalarPos(u8, author_line, open_bracket + 1, '>') orelse return null; 260 return author_line[open_bracket + 1 .. close_bracket]; 261 } 262 263 // build a `T` by copying its fields, by name, out of `source` 264 pub fn project(comptime T: type, source: anytype) T { 265 var result: T = undefined; 266 inline for (@typeInfo(T).@"struct".field_names) |name| { 267 @field(result, name) = @field(source, name); 268 } 269 return result; 270 } 271 272 pub const EventKind = enum { 273 user, 274 repo, 275 fork, 276 grant, 277 discuss, 278 issue, 279 comment, 280 attach, 281 assign, 282 patchrev, 283 patch, 284 }; 285 286 pub const RepoRole = enum { 287 admin, 288 user, 289 repo, 290 fork, 291 292 fn allows(self: RepoRole, kind: EventKind) bool { 293 return switch (self) { 294 .admin => kind == .user, 295 .user => switch (kind) { 296 .repo, .fork, .grant => true, 297 else => false, 298 }, 299 .repo => switch (kind) { 300 .discuss, .issue, .comment, .attach, .assign, .patchrev, .patch => true, 301 else => false, 302 }, 303 .fork => switch (kind) { 304 .patchrev, .patch => true, 305 else => false, 306 }, 307 }; 308 } 309 }; 310 311 // every logical event's kind and update-ordered active/removed id sets 312 pub const event_index_key = "event-id->kind"; 313 pub const active_event_id_set_key = "active-event-id-set"; 314 pub const removed_event_id_set_key = "removed-event-id-set"; 315 const event_order_key = "event-order"; 316 317 pub fn titleValid(title: []const u8) bool { 318 return std.mem.trim(u8, title, " \t\r\n").len != 0; 319 } 320 321 // a null payload removes the record 322 pub const Event = union(EventKind) { 323 user: ?User, 324 repo: ?Repo, 325 fork: ?Fork, 326 grant: ?Grant, 327 discuss: ?Discussion, 328 issue: ?Issue, 329 comment: ?Comment, 330 attach: ?Attachment, 331 assign: ?Assignment, 332 patchrev: ?PatchRev, 333 patch: ?Patch, 334 }; 335 336 // a file committed alongside its event 337 pub const Blob = struct { 338 name: []const u8, 339 size: u64, 340 reader: *std.Io.Reader, 341 }; 342 343 // an entry in the fresh tree carried by one event commit 344 pub const EventTreeEntry = union(enum) { 345 blob: Blob, 346 tree: struct { 347 name: []const u8, 348 oid: []const u8, 349 }, 350 }; 351 352 pub const HostKind = enum { 353 local, 354 server, 355 }; 356 357 // where events are written, with the context only a server has 358 pub const Host = union(HostKind) { 359 local, 360 server: Server, 361 362 pub const Server = struct { 363 users_dir: []const u8, 364 }; 365 }; 366 367 // who a commit is attributed to 368 pub const CommitAuthor = struct { 369 name: []const u8, 370 email: []const u8, 371 }; 372 373 pub const event_id_size: usize = 16; 374 375 pub fn parseEventId(id: []const u8) ![event_id_size]u8 { 376 var bytes: [event_id_size]u8 = undefined; 377 _ = try std.fmt.hexToBytes(&bytes, id); 378 if (!std.mem.eql(u8, id, &std.fmt.bytesToHex(bytes, .lower))) return error.InvalidEventId; 379 return bytes; 380 } 381 382 pub const EventWithId = struct { 383 id: [event_id_size * 2]u8, 384 event: Event, 385 timestamp: u64 = 0, // not serialized, because it comes from the commit timestamp 386 author: CommitAuthor, // not serialized, because it goes in the commit author line 387 tree_entries: []const EventTreeEntry = &.{}, // not serialized, because they go in the commit tree 388 389 pub fn jsonStringify(self: EventWithId, jw: anytype) !void { 390 try jw.beginObject(); 391 try jw.objectField("id"); 392 try jw.write(self.id); 393 try jw.objectField("kind"); 394 try jw.write(@tagName(self.event)); 395 try jw.objectField("data"); 396 switch (self.event) { 397 inline else => |event_maybe| try jw.write(event_maybe), 398 } 399 try jw.endObject(); 400 } 401 402 fn fromString(arena: *std.heap.ArenaAllocator, message: []const u8) !EventWithId { 403 const JsonEvent = struct { 404 id: [event_id_size * 2]u8, 405 kind: EventKind, 406 data: ?std.json.Value = null, 407 }; 408 const json_event = try std.json.parseFromSliceLeaky(JsonEvent, arena.allocator(), message, .{ .ignore_unknown_fields = true }); 409 return .{ 410 .id = json_event.id, 411 // unused when reading; the author lives in the commit 412 .author = .{ .name = "", .email = "" }, 413 .event = switch (json_event.kind) { 414 .user => .{ 415 .user = if (json_event.data) |value| 416 try std.json.parseFromValueLeaky(User, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 417 else 418 null, 419 }, 420 .repo => .{ 421 .repo = if (json_event.data) |value| 422 try std.json.parseFromValueLeaky(Repo, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 423 else 424 null, 425 }, 426 .fork => .{ 427 .fork = if (json_event.data) |value| 428 try std.json.parseFromValueLeaky(Fork, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 429 else 430 null, 431 }, 432 .grant => .{ 433 .grant = if (json_event.data) |value| 434 try std.json.parseFromValueLeaky(Grant, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 435 else 436 null, 437 }, 438 .discuss => .{ 439 .discuss = if (json_event.data) |value| 440 try std.json.parseFromValueLeaky(Discussion, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 441 else 442 null, 443 }, 444 .issue => .{ 445 .issue = if (json_event.data) |value| 446 try std.json.parseFromValueLeaky(Issue, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 447 else 448 null, 449 }, 450 .comment => .{ 451 .comment = if (json_event.data) |value| 452 try std.json.parseFromValueLeaky(Comment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 453 else 454 null, 455 }, 456 .attach => .{ 457 .attach = if (json_event.data) |value| 458 try std.json.parseFromValueLeaky(Attachment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 459 else 460 null, 461 }, 462 .assign => .{ 463 .assign = if (json_event.data) |value| 464 try std.json.parseFromValueLeaky(Assignment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 465 else 466 null, 467 }, 468 .patch => .{ 469 .patch = if (json_event.data) |value| 470 try std.json.parseFromValueLeaky(Patch, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 471 else 472 null, 473 }, 474 .patchrev => .{ 475 .patchrev = if (json_event.data) |value| 476 try std.json.parseFromValueLeaky(PatchRev, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 477 else 478 null, 479 }, 480 }, 481 }; 482 } 483 484 pub fn randomId(random: std.Random) [event_id_size]u8 { 485 var id_bytes: [event_id_size]u8 = undefined; 486 random.bytes(&id_bytes); 487 return id_bytes; 488 } 489 }; 490 491 // remove an event by emitting a null payload 492 pub fn remove( 493 host: Host, 494 comptime role: RepoRole, 495 comptime repo_kind: rp.RepoKind, 496 comptime repo_opts: rp.RepoOpts(repo_kind), 497 io: std.Io, 498 allocator: std.mem.Allocator, 499 repo: *rp.Repo(repo_kind, repo_opts), 500 id: *const [event_id_size]u8, 501 kind: EventKind, 502 author: CommitAuthor, 503 ) !void { 504 const DB = EventDB(repo_opts.hash); 505 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; 506 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 507 const moment = (if (event_db_maybe) |*event_db| 508 currentMomentFromDb(repo_opts.hash, event_db.db) 509 else if (repo_kind == .git) 510 return error.EventNotFound 511 else 512 currentMoment(repo_opts, repo)) catch return error.EventNotFound; 513 const kind_map_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return error.EventNotFound; 514 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 515 const stored_kind = (try readEventKind(repo_opts.hash, kind_map, id)) orelse return error.EventNotFound; 516 if (stored_kind != kind) return error.EventNotFound; 517 if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 518 event_db_maybe = null; 519 520 const event: Event = switch (kind) { 521 .user => .{ .user = null }, 522 .repo => .{ .repo = null }, 523 .fork => .{ .fork = null }, 524 .grant => .{ .grant = null }, 525 .discuss => .{ .discuss = null }, 526 .issue => .{ .issue = null }, 527 .comment => .{ .comment = null }, 528 .attach => .{ .attach = null }, 529 .assign => .{ .assign = null }, 530 .patchrev => .{ .patchrev = null }, 531 .patch => .{ .patch = null }, 532 }; 533 try consume(host, role, repo_kind, repo_opts, io, allocator, repo, events_ref, &.{.{ 534 .id = std.fmt.bytesToHex(id.*, .lower), 535 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 536 .author = author, 537 .event = event, 538 }}); 539 } 540 541 pub const undo_action = "haxy/events"; 542 pub const merge_undo_action = "haxy/merge-events"; 543 544 // index that tracks the events consumed in a given haxy moment 545 pub const moment_index_to_event_id_set_key = "moment-index->event-id-set"; 546 547 // a haxy moment's own position in the haxy history 548 pub const moment_index_key = "moment-index"; 549 550 // a moment's key in the set map 551 fn momentIndexKey(comptime hash_kind: hash.HashKind, moment_index: u64) hash.HashInt(hash_kind) { 552 var buffer: [@sizeOf(u64)]u8 = undefined; 553 std.mem.writeInt(u64, &buffer, moment_index, .big); 554 return hash.hashInt(hash_kind, &buffer); 555 } 556 557 // the ids of the events a moment wrote, newest first, or null when it wrote none 558 pub fn momentEventIds( 559 comptime DB: type, 560 comptime hash_kind: hash.HashKind, 561 haxy_moment: DB.HashMap(.read_only), 562 moment_index: u64, 563 ) !?DB.SortedSet(.read_only) { 564 const sets_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, moment_index_to_event_id_set_key)) orelse return null; 565 const sets = try DB.HashMap(.read_only).init(sets_cursor); 566 const ids_cursor = try sets.getCursor(momentIndexKey(hash_kind, moment_index)) orelse return null; 567 return try DB.SortedSet(.read_only).init(ids_cursor); 568 } 569 570 // commit `events` (if any) as JSON commit messages on `ref`, then consume the 571 // events on `ref` into the db the repo's views read: the repo's own db for a 572 // xit repo, or the standalone event db next to a git repo. for a xit repo the 573 // commits and the consume run in one transaction, which also saves the 574 // mergeability of the patches the events touched. 575 pub fn consume( 576 host: Host, 577 comptime role: RepoRole, 578 comptime repo_kind: rp.RepoKind, 579 comptime repo_opts: rp.RepoOpts(repo_kind), 580 io: std.Io, 581 allocator: std.mem.Allocator, 582 repo: *rp.Repo(repo_kind, repo_opts), 583 ref: rf.Ref, 584 events: []const EventWithId, 585 ) !void { 586 for (events) |event| { 587 if (!role.allows(std.meta.activeTag(event.event))) return error.EventKindNotAllowed; 588 } 589 590 var resolved_remote_name: ?[]u8 = null; 591 defer if (resolved_remote_name) |name| allocator.free(name); 592 593 // a branch that only exists on a remote is consumed from its remote-tracking 594 // ref, while commits go on the local branch, continuing from the remote tip 595 // so a cloned repo's local branch stays connected to the server history 596 const resolved_ref: rf.Ref, const first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8 = blk: { 597 if (null != try repo.readRef(io, ref)) break :blk .{ ref, null }; 598 var remotes = try repo.listRemotes(io, allocator); 599 defer remotes.deinit(); 600 for (remotes.sections.keys()) |remote_name| { 601 const remote_ref: rf.Ref = .{ .kind = .{ .remote = remote_name }, .name = ref.name }; 602 if (try repo.readRef(io, remote_ref)) |oid| { 603 if (events.len > 0) break :blk .{ ref, .{oid} }; 604 const name = try allocator.dupe(u8, remote_name); 605 resolved_remote_name = name; 606 break :blk .{ rf.Ref{ .kind = .{ .remote = name }, .name = ref.name }, null }; 607 } 608 } 609 if (events.len > 0) break :blk .{ ref, null }; 610 // the branch is gone (or never existed): drop any db from a previous 611 // sync rather than serving its issues indefinitely 612 if (repo_kind == .git) try LocalEventDB(repo_opts.hash).delete(io, repo.core.repo_dir); 613 return; 614 }; 615 616 switch (repo_kind) { 617 .git => { 618 try commitEvents(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, ref, events, first_parent_oids); 619 620 var event_db = try LocalEventDB(repo_opts.hash).open(io, allocator, repo.core.repo_dir); 621 defer event_db.deinit(io, allocator); 622 623 try event_db.consume(repo_kind, repo_opts, io, allocator, repo, resolved_ref); 624 }, 625 .xit => { 626 const DB = rp.Repo(.xit, repo_opts).DB; 627 const State = rp.Repo(.xit, repo_opts).State; 628 var checks: pch.MergeCheckInputs(repo_opts) = .{}; 629 defer checks.deinit(io, allocator); 630 if (role == .repo and host == .server) { 631 checks.prepare(io, allocator, repo, host.server.users_dir, events) catch |err| { 632 std.log.warn("failed to prepare mergeability: {s}", .{@errorName(err)}); 633 }; 634 } 635 636 const Ctx = struct { 637 core: *rp.Repo(.xit, repo_opts).Core, 638 io: std.Io, 639 allocator: std.mem.Allocator, 640 ref: rf.Ref, 641 events: []const EventWithId, 642 checks: *pch.MergeCheckInputs(repo_opts), 643 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 644 645 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 646 var moment = try DB.HashMap(.read_write).init(cursor.*); 647 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 648 649 try commitEvents(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.ref, ctx.events, ctx.first_parent_oids); 650 if (!try consumeInTransaction(role, .xit, repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 651 _ = try ctx.checks.update(state, ctx.io, ctx.allocator); 652 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = undo_action } }); 653 } 654 }; 655 656 try repo.core.db_file.lock(io, .exclusive); 657 defer repo.core.db_file.unlock(io); 658 659 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 660 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 661 .core = &repo.core, 662 .io = io, 663 .allocator = allocator, 664 .ref = resolved_ref, 665 .events = events, 666 .checks = &checks, 667 .first_parent_oids = first_parent_oids, 668 }) catch |err| switch (err) { 669 error.CancelTransaction => return, 670 else => |e| return e, 671 }; 672 }, 673 } 674 675 // consuming an existing ref does not provide the set of changed patches 676 // explicit patch writes already saved their checks in the event transaction 677 if (role == .repo and repo_kind == .xit and host == .server and events.len == 0) { 678 pch.refreshOpenMergeability(repo_opts, io, allocator, repo, host.server.users_dir, null, null); 679 } 680 681 if (role == .repo and host == .server and events.len > 0) { 682 bumpRepoActivityAt(io, allocator, host.server.users_dir, repo.core.work_path); 683 } 684 } 685 686 // merge the remote events ref into the local events ref without touching head, 687 // the index, or the worktree 688 pub fn mergeEvents( 689 comptime repo_kind: rp.RepoKind, 690 comptime repo_opts: rp.RepoOpts(repo_kind), 691 io: std.Io, 692 allocator: std.mem.Allocator, 693 repo: *rp.Repo(repo_kind, repo_opts), 694 remote_ref: rf.Ref, 695 ) !void { 696 switch (repo_kind) { 697 .git => _ = try mergeEventsInTransaction(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, remote_ref), 698 .xit => { 699 const DB = rp.Repo(.xit, repo_opts).DB; 700 const State = rp.Repo(.xit, repo_opts).State; 701 702 const Ctx = struct { 703 core: *rp.Repo(.xit, repo_opts).Core, 704 io: std.Io, 705 allocator: std.mem.Allocator, 706 remote_ref: rf.Ref, 707 708 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 709 var moment = try DB.HashMap(.read_write).init(cursor.*); 710 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 711 if (!try mergeEventsInTransaction(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.remote_ref)) return error.CancelTransaction; 712 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = merge_undo_action } }); 713 } 714 }; 715 716 try repo.core.db_file.lock(io, .exclusive); 717 defer repo.core.db_file.unlock(io); 718 719 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 720 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 721 .core = &repo.core, 722 .io = io, 723 .allocator = allocator, 724 .remote_ref = remote_ref, 725 }) catch |err| switch (err) { 726 error.CancelTransaction => {}, 727 else => |e| return e, 728 }; 729 }, 730 } 731 } 732 733 fn mergeEventsInTransaction( 734 comptime repo_kind: rp.RepoKind, 735 comptime repo_opts: rp.RepoOpts(repo_kind), 736 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 737 io: std.Io, 738 allocator: std.mem.Allocator, 739 remote_ref: rf.Ref, 740 ) !bool { 741 const remote_oid = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = remote_ref })) orelse return false; 742 const local_oid_maybe = try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = events_ref }); 743 744 var ref_path_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 745 const ref_path = try events_ref.toPath(&ref_path_buffer); 746 const local_oid = local_oid_maybe orelse { 747 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 748 return true; 749 }; 750 if (std.mem.eql(u8, &local_oid, &remote_oid)) return false; 751 752 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) { 753 error.NoCommonAncestor => null, 754 else => return err, 755 }; 756 if (ancestor_maybe) |ancestor| { 757 if (std.mem.eql(u8, &ancestor, &remote_oid)) return false; 758 if (std.mem.eql(u8, &ancestor, &local_oid)) { 759 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 760 return true; 761 } 762 } 763 764 const parent_oids = [_][hash.hexLen(repo_opts.hash)]u8{ local_oid, remote_oid }; 765 var tree = try obj.Tree.init(allocator); 766 defer tree.deinit(); 767 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 768 .message = "merge events", 769 .parent_oids = &parent_oids, 770 }, &tree, events_ref); 771 return true; 772 } 773 774 // the file an attach event carries: the one entry in its commit's tree. the 775 // name and oid are allocated in `arena`. 776 fn attachedFile( 777 comptime repo_kind: rp.RepoKind, 778 comptime repo_opts: rp.RepoOpts(repo_kind), 779 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 780 io: std.Io, 781 allocator: std.mem.Allocator, 782 arena: *std.heap.ArenaAllocator, 783 tree_oid: *const [hash.hexLen(repo_opts.hash)]u8, 784 ) !struct { name: []const u8, oid: []const u8 } { 785 var tree_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, tree_oid); 786 defer tree_object.deinit(); 787 788 const entries = switch (tree_object.content) { 789 .tree => |tree| tree.entries, 790 else => return error.InvalidAttachment, 791 }; 792 if (entries.count() != 1) return error.InvalidAttachment; 793 const entry = entries.values()[0]; 794 if (entry.isTree()) return error.InvalidAttachment; 795 const name = entries.keys()[0]; 796 if (!Attachment.nameValid(name)) return error.InvalidAttachment; 797 798 const oid = std.fmt.bytesToHex(entry.oid, .lower); 799 var object_reader = try obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, &oid); 800 defer object_reader.deinit(); 801 if (object_reader.header().kind != .blob) return error.InvalidAttachment; 802 803 return .{ 804 .name = try arena.allocator().dupe(u8, name), 805 .oid = try arena.allocator().dupe(u8, &oid), 806 }; 807 } 808 809 fn commitIdentity(line: []const u8) ![]const u8 { 810 const close = std.mem.indexOfScalar(u8, line, '>') orelse return error.AuthorNotFound; 811 return line[0 .. close + 1]; 812 } 813 814 // commit each event as a JSON commit message on `ref` through `state`, so a 815 // xit repo can write them inside an already-open transaction 816 pub fn commitEvents( 817 comptime repo_kind: rp.RepoKind, 818 comptime repo_opts: rp.RepoOpts(repo_kind), 819 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 820 io: std.Io, 821 allocator: std.mem.Allocator, 822 ref: rf.Ref, 823 events: []const EventWithId, 824 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 825 ) !void { 826 var parent_oids: ?[]const [hash.hexLen(repo_opts.hash)]u8 = if (first_parent_oids) |*oids| oids else null; 827 828 var json: std.Io.Writer.Allocating = .init(allocator); 829 defer json.deinit(); 830 831 for (events) |event| { 832 json.clearRetainingCapacity(); 833 try std.json.Stringify.value(event, .{}, &json.writer); 834 if (json.written().len > max_event_size) return error.EventTooLarge; 835 const author = try allocator.print("{s} <{s}>", .{ event.author.name, event.author.email }); 836 defer allocator.free(author); 837 838 // every event gets a fresh tree 839 var tree = try obj.Tree.init(allocator); 840 defer tree.deinit(); 841 for (event.tree_entries) |entry| { 842 switch (entry) { 843 .blob => |blob| { 844 var oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = @splat(0); 845 try obj.writeObject(repo_kind, repo_opts, state, io, allocator, blob.reader, .{ .kind = .blob, .size = blob.size }, &oid_bytes); 846 try tree.addBlobEntry(.{ .content = .{ .unix_permission = 0o644, .object_type = .regular_file } }, blob.name, &oid_bytes); 847 }, 848 .tree => |nested| { 849 var oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 850 _ = try std.fmt.hexToBytes(&oid_bytes, nested.oid); 851 if (!std.mem.eql(u8, nested.oid, &std.fmt.bytesToHex(oid_bytes, .lower))) return error.InvalidTreeObject; 852 try tree.addTreeEntry(nested.name, &oid_bytes); 853 }, 854 } 855 } 856 857 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 858 .author = author, 859 .message = json.written(), 860 .timestamp = event.timestamp, 861 .parent_oids = parent_oids, 862 .allow_empty = true, 863 }, &tree, ref); 864 // later events parent on the ref's new tip 865 parent_oids = null; 866 } 867 } 868 869 // a standalone event db holding events consumed from a local repo's events 870 // branch. it lives inside the repo dir but is not part of the repo's own data, 871 // so viewing a repo never mutates it. 872 pub fn LocalEventDB(comptime hash_kind: hash.HashKind) type { 873 return struct { 874 file: std.Io.File, 875 buffer: *std.Io.Writer.Allocating, 876 db: *EventDB(hash_kind), 877 878 const db_name = "haxy"; 879 const Self = @This(); 880 881 // open the db in `repo_dir` for writing, creating it if it doesn't exist 882 pub fn open(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !Self { 883 const file = try repo_dir.createFile(io, db_name, .{ .truncate = false, .read = true, .lock = .exclusive }); 884 return fromFile(io, allocator, file); 885 } 886 887 // open the db in `repo_dir` for reading, or null if it doesn't exist 888 pub fn openReadOnly(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !?Self { 889 const file = repo_dir.openFile(io, db_name, .{ .mode = .read_write, .lock = .shared }) catch |err| switch (err) { 890 error.FileNotFound => return null, 891 else => |e| return e, 892 }; 893 return try fromFile(io, allocator, file); 894 } 895 896 // remove the db from `repo_dir`, so a repo whose events branch 897 // disappeared doesn't keep showing stale issues 898 pub fn delete(io: std.Io, repo_dir: std.Io.Dir) !void { 899 repo_dir.deleteFile(io, db_name) catch |err| switch (err) { 900 error.FileNotFound => {}, 901 else => |e| return e, 902 }; 903 } 904 905 fn fromFile(io: std.Io, allocator: std.mem.Allocator, file: std.Io.File) !Self { 906 errdefer file.close(io); 907 908 const buffer = try allocator.create(std.Io.Writer.Allocating); 909 errdefer allocator.destroy(buffer); 910 buffer.* = std.Io.Writer.Allocating.init(allocator); 911 errdefer buffer.deinit(); 912 913 const db = try allocator.create(EventDB(hash_kind)); 914 errdefer allocator.destroy(db); 915 db.* = try EventDB(hash_kind).init(.{ .io = io, .file = file, .buffer = buffer }); 916 917 return .{ .file = file, .buffer = buffer, .db = db }; 918 } 919 920 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 921 self.file.close(io); 922 self.buffer.deinit(); 923 allocator.destroy(self.buffer); 924 allocator.destroy(self.db); 925 } 926 927 // consume the events on `repo`'s `ref` into this db. the db must come 928 // from `open`, whose handle holds the exclusive lock guarding the 929 // transaction. 930 pub fn consume( 931 self: *Self, 932 comptime repo_kind: rp.RepoKind, 933 comptime repo_opts: rp.RepoOpts(repo_kind), 934 io: std.Io, 935 allocator: std.mem.Allocator, 936 repo: *rp.Repo(repo_kind, repo_opts), 937 ref: rf.Ref, 938 ) !void { 939 comptime if (repo_opts.hash != hash_kind) @compileError("the repo must use the db's hash kind"); 940 const DB = EventDB(hash_kind); 941 942 const Ctx = struct { 943 repo: *rp.Repo(repo_kind, repo_opts), 944 db: *DB, 945 io: std.Io, 946 allocator: std.mem.Allocator, 947 ref: rf.Ref, 948 949 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 950 var moment = try DB.HashMap(.read_write).init(cursor.*); 951 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{} }; 952 if (!try consumeInTransaction(.repo, repo_kind, repo_opts, state, ctx.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 953 } 954 }; 955 956 const history = try DB.ArrayList(.read_write).init(self.db.rootCursor()); 957 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 958 .repo = repo, 959 .db = self.db, 960 .io = io, 961 .allocator = allocator, 962 .ref = ref, 963 }) catch |err| switch (err) { 964 error.CancelTransaction => {}, 965 else => |e| return e, 966 }; 967 } 968 }; 969 } 970 971 // consume the events on `ref` into the db `moment` writes to, returning false 972 // if there was nothing to do. events are read from `state`'s repo, which 973 // needn't be the repo backing the db — that's how a local (possibly 974 // git-backed) repo's events land in a standalone db. 975 pub fn consumeInTransaction( 976 comptime role: RepoRole, 977 comptime repo_kind: rp.RepoKind, 978 comptime repo_opts: rp.RepoOpts(repo_kind), 979 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 980 db: *EventDB(repo_opts.hash), 981 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 982 io: std.Io, 983 allocator: std.mem.Allocator, 984 ref: rf.Ref, 985 ) !bool { 986 const DB = EventDB(repo_opts.hash); 987 const read_state = state.readOnly(); 988 989 // the last_object_id represents the object id that was last consumed 990 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 991 if (try moment.getCursor(hash.hashInt(repo_opts.hash, last_object_id_key))) |last_object_id_cursor| { 992 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 993 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 994 last_object_id_maybe = last_object_id_buffer; 995 } 996 997 // the tip was already consumed, so there is nothing to do 998 if (last_object_id_maybe) |*last_object_id| { 999 const tip_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1000 var tip: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1001 _ = try std.fmt.hexToBytes(&tip, &tip_hex); 1002 if (std.mem.eql(u8, last_object_id, &tip)) return false; 1003 } 1004 1005 // the list with all of haxy's state, including materialized views. 1006 // the reason it is a list is so we can keep every previous haxy 1007 // state, making it easy to revert to an older state if the user 1008 // rebases some of the past commits. 1009 const haxy_history_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, history_key)); 1010 const haxy_history = try DB.ArrayList(.read_write).init(haxy_history_cursor); 1011 1012 // add a new item to the haxy history list created above. 1013 // we call the item haxy_moments. it is a map of object id to haxy moment. 1014 // in other words, it maps each object id to a hash map containing the 1015 // state that the database was in when that object id was consumed. 1016 var haxy_moments_cursor = try haxy_history.appendCursor(); 1017 // use the previous haxy_moments as the basis for this one if it exists 1018 if (try haxy_history.getCursor(-2)) |last_haxy_moments_cursor| { 1019 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 1020 } 1021 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 1022 1023 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 1024 defer commit_iter.deinit(io, allocator); 1025 1026 // if there are no events to process, look at the oid at HEAD and update 1027 // the last_object_id to point to it. this is important in situations 1028 // where we do a merge and then force-push to remove the merge. see the 1029 // merge test for an example. 1030 if (commit_iter.newest_object_id == null) { 1031 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1032 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1033 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1034 1035 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 1036 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 1037 1038 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 1039 const moment_index = try moment_index_cursor.readUint(); 1040 1041 try haxy_history.slice(moment_index + 1); 1042 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = &head_oid }); 1043 return true; 1044 } 1045 1046 // if this branch was rebased and force pushed, we need to detect that and 1047 // properly revert the haxy state to the last valid state. we detect this 1048 // by simply asking if the last event is a descendent of the last event 1049 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 1050 if (last_object_id_maybe) |*last_object_id| { 1051 var is_rebased = false; 1052 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 1053 1054 _ = mrg.getDescendent( 1055 repo_kind, 1056 repo_opts, 1057 read_state, 1058 io, 1059 allocator, 1060 &std.fmt.bytesToHex(last_object_id, .lower), 1061 &std.fmt.bytesToHex(&newest_object_id, .lower), 1062 ) catch |err| switch (err) { 1063 error.DescendentNotFound => is_rebased = true, 1064 else => |e| return e, 1065 }; 1066 1067 if (is_rebased) { 1068 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 1069 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 1070 defer oldest_object.deinit(); 1071 1072 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1073 switch (parent_oids.len) { 1074 0 => { 1075 // the branch was rebased all the way to the very beginning. 1076 // we have a repo event with no parent, which means it is now 1077 // the very first event. all we need to do is set the haxy 1078 // history list to be empty and make a new haxy_moments map 1079 // to work with. 1080 1081 try haxy_history.slice(0); 1082 haxy_moments_cursor = try haxy_history.appendCursor(); 1083 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 1084 1085 last_object_id_maybe = null; 1086 }, 1087 1 => { 1088 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1089 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 1090 1091 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 1092 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 1093 1094 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 1095 const old_moment_index = try old_moment_index_cursor.readUint(); 1096 1097 // resize the haxy history list so we truncate all the 1098 // moments that were created after the parent_oid was consumed 1099 try haxy_history.slice(old_moment_index + 1); 1100 1101 // make a new haxy moment and set its initial value to the last haxy moment 1102 haxy_moments_cursor = try haxy_history.appendCursor(); 1103 const old_haxy_moments_cursor = try haxy_history.getCursor(old_moment_index) orelse return error.CursorNotFound; 1104 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 1105 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 1106 1107 last_object_id_maybe = oid; 1108 }, 1109 else => return error.UnexpectedParentCount, 1110 } 1111 } 1112 } 1113 1114 while (try commit_iter.next()) |repo_event_oid| { 1115 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 1116 defer commit_object.deinit(); 1117 1118 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1119 1120 // create a moment for this object id 1121 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 1122 1123 // if there was a previous object id, set this haxy moment's initial value to it. 1124 // this efficiently "clones" the map so we make further modifications based on it. 1125 if (parent_oids.len > 0) { 1126 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1127 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 1128 1129 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 1130 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 1131 } 1132 1133 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 1134 1135 // graph generation gives every event a causal order independent of 1136 // commit timestamps. concurrent events tie-break by id in their index. 1137 var event_order: u64 = 1; 1138 for (parent_oids) |*parent_oid| { 1139 var parent_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1140 _ = try std.fmt.hexToBytes(&parent_id, parent_oid); 1141 const parent_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &parent_id)) orelse return error.CursorNotFound; 1142 const parent = try DB.HashMap(.read_only).init(parent_cursor); 1143 const parent_order_cursor = try parent.getCursor(hash.hashInt(repo_opts.hash, event_order_key)) orelse return error.CursorNotFound; 1144 const parent_order = try parent_order_cursor.readUint(); 1145 event_order = @max(event_order, parent_order +| 1); 1146 } 1147 try haxy_moment.put(hash.hashInt(repo_opts.hash, event_order_key), .{ .uint = event_order }); 1148 1149 // merge changes from every parent after the first parent. the common 1150 // ancestor is the baseline, so a later parent only contributes records 1151 // it changed relative to the merge base. only the record maps are 1152 // merged; every other view is derived from them, and each kind's 1153 // `consume` re-derives its own as the winning records are written. 1154 if (parent_oids.len > 1) { 1155 for (parent_oids[1..]) |*parent_oid| { 1156 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1157 _ = try std.fmt.hexToBytes(&oid, parent_oid); 1158 1159 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 1160 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 1161 1162 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 1163 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1164 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 1165 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 1166 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 1167 1168 inline for (@typeInfo(Event).@"union".field_types) |field_type| { 1169 const T = @typeInfo(field_type).optional.child; 1170 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 1171 } 1172 } 1173 } 1174 1175 // associate this moment with the index it will first appear at in the 1176 // haxy history list. this will be important later so we can truncate 1177 // that list if the user ever rebases starting at this object id. 1178 const moment_index = try haxy_history.count() - 1; 1179 try haxy_moment.put(hash.hashInt(repo_opts.hash, moment_index_key), .{ .uint = moment_index }); 1180 1181 // consume the event unless it's a merge commit 1182 if (parent_oids.len <= 1) { 1183 var arena = std.heap.ArenaAllocator.init(allocator); 1184 defer arena.deinit(); 1185 1186 // read the message from the commit 1187 var message: std.ArrayList(u8) = .empty; 1188 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 1189 1190 const event_with_id = try EventWithId.fromString(&arena, message.items); 1191 if (!role.allows(std.meta.activeTag(event_with_id.event))) return error.EventKindNotAllowed; 1192 1193 const current_event_id = try parseEventId(&event_with_id.id); 1194 1195 // associate the transaction with the events it writes. this is 1196 // used by the undo tab to link the events that were affected 1197 // by a given transaction. 1198 { 1199 const sets = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, moment_index_to_event_id_set_key))); 1200 const ids = try DB.SortedSet(.read_write).init(try sets.putCursor(momentIndexKey(repo_opts.hash, moment_index))); 1201 try ids.put(&orderKeyDesc(event_order, &current_event_id)); 1202 } 1203 1204 // wrap the payload into the record `consume` stores, with its 1205 // commit-derived fields; on update, `consume` preserves the 1206 // existing record's 1207 switch (event_with_id.event) { 1208 .user => |event_maybe| { 1209 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1210 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1211 }, 1212 .repo => |event_maybe| { 1213 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1214 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1215 }, 1216 .fork => |event_maybe| { 1217 const record_maybe: ?Fork.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1218 try Fork.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1219 }, 1220 .grant => |event_maybe| { 1221 const record_maybe: ?Grant.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1222 try Grant.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1223 }, 1224 .discuss => |event_maybe| { 1225 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 1226 .event = event, 1227 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1228 .created_order = event_order, 1229 .updated_order = event_order, 1230 } else null; 1231 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1232 }, 1233 .issue => |event_maybe| { 1234 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 1235 .event = event, 1236 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1237 .created_order = event_order, 1238 .updated_order = event_order, 1239 } else null; 1240 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1241 }, 1242 .comment => |event_maybe| { 1243 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 1244 .event = event, 1245 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1246 .created_order = event_order, 1247 .updated_order = event_order, 1248 } else null; 1249 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1250 }, 1251 .attach => |event_maybe| { 1252 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 1253 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 1254 break :blk .{ 1255 .event = event, 1256 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1257 .created_order = event_order, 1258 .updated_order = event_order, 1259 .name = entry.name, 1260 .blob_oid = entry.oid, 1261 }; 1262 } else null; 1263 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1264 }, 1265 .assign => |event_maybe| { 1266 const record_maybe: ?Assignment.Record = if (event_maybe) |event| .{ 1267 .event = event, 1268 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1269 .created_order = event_order, 1270 .updated_order = event_order, 1271 } else null; 1272 try Assignment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1273 }, 1274 .patchrev => |event_maybe| { 1275 const record_maybe: ?PatchRev.Record = if (event_maybe) |event| blk: { 1276 const trees = try PatchRev.readTrees(repo_kind, repo_opts, read_state, io, allocator, &commit_object.content.commit.tree); 1277 const existing_maybe = try PatchRev.readById(DB, repo_opts.hash, haxy_moment.readOnly(), &arena, &current_event_id); 1278 const event_oid = std.fmt.bytesToHex(repo_event_oid, .lower); 1279 1280 var patch_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1281 if (existing_maybe) |existing| { 1282 if (existing.patch_oid.len != patch_oid.len) return error.InvalidPatch; 1283 @memcpy(&patch_oid, existing.patch_oid); 1284 } else { 1285 const author = try commitIdentity(commit_object.content.commit.metadata.author orelse return error.AuthorNotFound); 1286 const committer = try commitIdentity(commit_object.content.commit.metadata.committer orelse author); 1287 patch_oid = try PatchRev.writeSquashCommit( 1288 repo_kind, 1289 repo_opts, 1290 state, 1291 io, 1292 allocator, 1293 event, 1294 &trees.head, 1295 author, 1296 committer, 1297 commit_object.content.commit.metadata.timestamp, 1298 ); 1299 } 1300 1301 break :blk .{ 1302 .event = event, 1303 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1304 .created_order = event_order, 1305 .updated_order = event_order, 1306 .event_oid = &event_oid, 1307 .base_tree_oid = &trees.base, 1308 .head_tree_oid = &trees.head, 1309 .patch_oid = &patch_oid, 1310 .commit_count = PatchRev.commitCount(repo_kind, repo_opts, read_state, io, allocator, event.base_oid, event.source_oid) catch null, 1311 }; 1312 } else null; 1313 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1314 }, 1315 .patch => |event_maybe| { 1316 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 1317 .event = event, 1318 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1319 .created_order = event_order, 1320 .updated_order = event_order, 1321 } else null; 1322 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1323 }, 1324 } 1325 } 1326 1327 // the current object id is now the last one 1328 last_object_id_maybe = repo_event_oid; 1329 1330 // prevent any of the data created above from being mutated by future iterations of this loop 1331 try db.freeze(); 1332 } 1333 1334 if (last_object_id_maybe) |*last_object_id| { 1335 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1336 } 1337 1338 return true; 1339 } 1340 1341 // the conflicted records of one kind, keyed by the same order key its id set 1342 // uses, so this doubles as the index the conflicts view lists and counts. every 1343 // value under an entry is a slot reference to a structure that already exists: 1344 // 1345 // <order key> -> conflict entry 1346 // conflicted-fields the conflicting field names, space separated 1347 // base-record the merge base's whole record 1348 // their-record the merged-in side's whole record 1349 // their-field->oid that side's field name to commit map 1350 // 1351 // our own value is the live record and our commit is in the kind's oid map, so 1352 // neither is repeated here. 1353 pub const conflicted_fields_key = "conflicted-fields"; 1354 pub const base_record_key = "base-record"; 1355 pub const their_record_key = "their-record"; 1356 pub const their_field_to_oid_key = "their-field->oid"; 1357 1358 // record the commit against every field this event changes. a merge passes no 1359 // oid, since each field's winner may come from a different side. 1360 pub fn writeOid( 1361 comptime T: type, 1362 comptime DB: type, 1363 comptime hash_kind: hash.HashKind, 1364 id_to_field_to_oid: DB.HashMap(.read_write), 1365 record_key: hash.HashInt(hash_kind), 1366 existing_maybe: ?T, 1367 event: T, 1368 event_oid: ?[]const u8, 1369 ) !void { 1370 const oid = event_oid orelse return; 1371 1372 // created only once a field actually changes 1373 var field_oids: ?DB.SortedMap(.read_write) = null; 1374 1375 const info = @typeInfo(T).@"struct"; 1376 inline for (info.field_names, info.field_types) |field_name, field_type| { 1377 const changed = if (existing_maybe) |existing| 1378 !fieldEqual(field_type, @field(existing, field_name), @field(event, field_name)) 1379 else 1380 true; 1381 if (changed) { 1382 if (field_oids == null) { 1383 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1384 } 1385 if (field_oids) |map| try map.put(field_name, .{ .bytes = oid }); 1386 } 1387 } 1388 } 1389 1390 // the whole field list, space separated, is the longest it can get 1391 fn conflictedFieldsMaxLen(comptime T: type) usize { 1392 var len: usize = 0; 1393 for (@typeInfo(T).@"struct".field_names) |name| len += name.len + 1; 1394 return len; 1395 } 1396 1397 pub const MergePolicy = enum { 1398 field_conflicts, 1399 target_wins, 1400 }; 1401 1402 // what a three-way merge did with a field 1403 pub const FieldMerge = enum { 1404 // the target's value stands, because neither side changed it, both made the 1405 // same change, or only the target changed it 1406 kept, 1407 parent, 1408 conflicted, 1409 }; 1410 1411 // three-way merge each field. one only the parent changed takes the parent's 1412 // value; one both sides changed differently keeps the target's. a missing 1413 // baseline makes every differing field a conflict. 1414 fn mergeFields( 1415 comptime T: type, 1416 baseline_maybe: ?T, 1417 target: T, 1418 parent: T, 1419 outcome: *[@typeInfo(T).@"struct".field_names.len]FieldMerge, 1420 ) T { 1421 var merged = target; 1422 1423 const info = @typeInfo(T).@"struct"; 1424 inline for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { 1425 const target_value = @field(target, field_name); 1426 const parent_value = @field(parent, field_name); 1427 1428 if (!fieldEqual(field_type, target_value, parent_value)) { 1429 outcome[i] = if (baseline_maybe) |baseline| blk: { 1430 const baseline_value = @field(baseline, field_name); 1431 if (fieldEqual(field_type, target_value, baseline_value)) { 1432 @field(merged, field_name) = parent_value; 1433 break :blk .parent; 1434 } 1435 // only the target changed it 1436 if (fieldEqual(field_type, parent_value, baseline_value)) break :blk .kept; 1437 break :blk .conflicted; 1438 } else .conflicted; 1439 } 1440 } 1441 1442 return merged; 1443 } 1444 1445 // three-way merge of one kind's records from a merge parent. kinds that expose 1446 // conflicts merge field by field; the others take one whole record. the result 1447 // goes through the kind's `consume`, which re-derives the indexes from it. a 1448 // removal carries over unless the other side changed the record, so a merge 1449 // never fails. 1450 pub fn merge( 1451 comptime T: type, 1452 comptime DB: type, 1453 comptime hash_kind: hash.HashKind, 1454 allocator: std.mem.Allocator, 1455 haxy_moment: DB.HashMap(.read_write), 1456 parent_moment: DB.HashMap(.read_only), 1457 baseline_moment: DB.HashMap(.read_only), 1458 ) !void { 1459 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1460 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1461 1462 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1463 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1464 1465 var baseline_records: ?DB.HashMap(.read_only) = null; 1466 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1467 baseline_records = try DB.HashMap(.read_only).init(cursor); 1468 } 1469 1470 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1471 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1472 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1473 switch (comptime T.merge_policy) { 1474 .field_conflicts => { 1475 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1476 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1477 } 1478 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1479 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1480 } 1481 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1482 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1483 } 1484 }, 1485 .target_wins => {}, 1486 } 1487 1488 var arena = std.heap.ArenaAllocator.init(allocator); 1489 defer arena.deinit(); 1490 1491 var iter = try parent_set.iteratorFromIndex(0); 1492 while (try iter.next()) |kv_pair_cursor| { 1493 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1494 const record_key = hash.hashInt(hash_kind, &event_id); 1495 1496 _ = arena.reset(.retain_capacity); 1497 1498 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1499 const parent_slot = parent_record_cursor.slot(); 1500 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1501 1502 // the parent left this record alone 1503 if (baseline_slot) |slot| { 1504 if (slot.eql(parent_slot)) continue; 1505 } 1506 1507 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1508 1509 // re-derived every iteration, since `consume` writes through its own 1510 // handles 1511 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1512 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1513 1514 // a record the target doesn't have arrives wholesale from the parent 1515 var outcome: [@typeInfo(T).@"struct".field_names.len]FieldMerge = @splat(.parent); 1516 var merged = parent_record; 1517 1518 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1519 // both sides share the change 1520 if (target_record_cursor.slot().eql(parent_slot)) continue; 1521 1522 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1523 1524 var baseline_record: ?T.Record = null; 1525 if (baseline_records) |map| { 1526 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1527 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1528 } 1529 } 1530 1531 switch (comptime T.merge_policy) { 1532 .field_conflicts => { 1533 outcome = @splat(.kept); 1534 merged = target_record; 1535 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1536 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1537 if (comptime @hasDecl(T, "resolveMerge")) { 1538 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1539 } 1540 1541 // merge the removed state separately from serialized fields. removal 1542 // carries over an unchanged record, while an edit or restoration 1543 // keeps it active. 1544 merged.removed = if (target_record.removed == parent_record.removed) 1545 target_record.removed 1546 else if (baseline_record) |baseline| blk: { 1547 const active = if (!target_record.removed) target_record else parent_record; 1548 if (active.removed != baseline.removed) break :blk false; 1549 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1550 break :blk true; 1551 } else false; 1552 }, 1553 .target_wins => { 1554 // an uncontested parent change carries over. if both sides 1555 // changed the record, the target wins as a whole, except that 1556 // an edit or restoration wins over a removal. 1557 const target_changed = if (baseline_slot) |slot| 1558 !target_record_cursor.slot().eql(slot) 1559 else 1560 true; 1561 merged = if (!target_changed) 1562 parent_record 1563 else if (target_record.removed != parent_record.removed) 1564 if (target_record.removed) parent_record else target_record 1565 else 1566 target_record; 1567 }, 1568 } 1569 } 1570 1571 // the index is unique, so a key the target gave to a different record 1572 // leaves this one out rather than stranding that one behind a name it 1573 // no longer owns 1574 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1575 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1576 const name_index = try DB.SortedMap(.read_write).init(name_index_cursor); 1577 if (try name_index.getCursor(merged.event.name)) |owner_cursor| { 1578 var owner_id: [event_id_size]u8 = undefined; 1579 _ = try owner_cursor.readBytes(&owner_id); 1580 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1581 } 1582 } 1583 1584 // `consume` sets no oids, since each field's winner may come from 1585 // a different side 1586 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1587 1588 switch (comptime T.merge_policy) { 1589 .field_conflicts => {}, 1590 .target_wins => continue, 1591 } 1592 1593 // removed records do not carry field conflicts 1594 if (merged.removed) continue; 1595 1596 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1597 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1598 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1599 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1600 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1601 1602 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1603 if (parent_id_to_field_to_oid) |map| { 1604 if (try map.getCursor(record_key)) |field_oids_cursor| { 1605 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1606 } 1607 } 1608 // created only once a field actually comes from the parent 1609 var field_oids: ?DB.SortedMap(.read_write) = null; 1610 1611 // the fields both sides changed differently, space separated 1612 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1613 var conflicted_len: usize = 0; 1614 1615 inline for (@typeInfo(T).@"struct".field_names, 0..) |field_name, i| { 1616 switch (outcome[i]) { 1617 // the target's value stands, so its oid does too 1618 .kept => {}, 1619 // the parent set this value, so its commit takes the field. a 1620 // parent with no oid took its own value from a merge, leaving 1621 // the field unattributed rather than crediting the target's 1622 // commit for a value it no longer holds. 1623 .parent => { 1624 if (field_oids == null) { 1625 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1626 } 1627 const map = field_oids orelse unreachable; 1628 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field_name) else null; 1629 if (parent_oid) |oid_cursor| { 1630 try map.put(field_name, .{ .slot = oid_cursor.slot() }); 1631 } else { 1632 _ = try map.remove(field_name); 1633 } 1634 }, 1635 .conflicted => { 1636 if (conflicted_len > 0) { 1637 conflicted_fields[conflicted_len] = ' '; 1638 conflicted_len += 1; 1639 } 1640 @memcpy(conflicted_fields[conflicted_len..][0..field_name.len], field_name); 1641 conflicted_len += field_name.len; 1642 }, 1643 } 1644 } 1645 1646 if (conflicted_len > 0) { 1647 // each side's whole record is stored by reference, so the view can 1648 // show any of them or take theirs wholesale 1649 _ = try conflicts.remove(&merged_key); 1650 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1651 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1652 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1653 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1654 if (parent_field_oids) |map| { 1655 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1656 } 1657 continue; 1658 } 1659 1660 // created_order never changes, so the parent keys this record's conflict 1661 // identically, and it carries over when the target has none, unless the 1662 // parent's entry is unchanged from the baseline, meaning the target 1663 // inherited it too and resolving it removed it here. 1664 if (parent_conflicts) |map| { 1665 if (null == try conflicts.getCursor(&merged_key)) { 1666 if (try map.getSlot(&merged_key)) |conflict_slot| { 1667 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1668 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1669 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1670 } 1671 } 1672 } 1673 } 1674 } 1675 1676 // a comment, attachment or assignment a write names under a thread 1677 pub const ThreadChild = union(enum) { 1678 comment: *const [event_id_size]u8, 1679 attach: *const [event_id_size]u8, 1680 assign: *const [event_id_size]u8, 1681 }; 1682 1683 // whether `thread_id` names a thread of `thread_kind` in the repo's events, and 1684 // `child`, when given, belongs to it. a caller's url can claim any kind for any 1685 // id, so every write under a thread checks its claim here first. 1686 pub fn threadHolds( 1687 comptime repo_kind: rp.RepoKind, 1688 comptime repo_opts: rp.RepoOpts(repo_kind), 1689 io: std.Io, 1690 allocator: std.mem.Allocator, 1691 repo: *rp.Repo(repo_kind, repo_opts), 1692 thread_kind: EventKind, 1693 thread_id: *const [event_id_size]u8, 1694 child_maybe: ?ThreadChild, 1695 ) !bool { 1696 const DB = EventDB(repo_opts.hash); 1697 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; 1698 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1699 const moment = (if (event_db_maybe) |*event_db| 1700 currentMomentFromDb(repo_opts.hash, event_db.db) 1701 else if (repo_kind == .git) 1702 return false 1703 else 1704 currentMoment(repo_opts, repo)) catch return false; 1705 1706 // only these kinds are threads 1707 switch (thread_kind) { 1708 .discuss, .issue, .patch => {}, 1709 else => return false, 1710 } 1711 const kinds_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return false; 1712 const kinds = try DB.HashMap(.read_only).init(kinds_cursor); 1713 if ((try readEventKind(repo_opts.hash, kinds, thread_id)) != thread_kind) return false; 1714 1715 const child = child_maybe orelse return true; 1716 var arena = std.heap.ArenaAllocator.init(allocator); 1717 defer arena.deinit(); 1718 const thread_id_hex = std.fmt.bytesToHex(thread_id.*, .lower); 1719 switch (child) { 1720 .comment => |id| { 1721 const comment = (try readRecordSubset(Comment, struct { event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1722 return std.mem.eql(u8, &comment.event.thread_id, &thread_id_hex); 1723 }, 1724 .attach => |id| { 1725 const attachment = (try readRecordSubset(Attachment, struct { event: struct { parent_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1726 return std.mem.eql(u8, &attachment.event.parent_id, &thread_id_hex); 1727 }, 1728 // only an active assignment can be removed 1729 .assign => |id| { 1730 const assignment = (try readRecordSubset(Assignment, struct { removed: bool, event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1731 return !assignment.removed and std.mem.eql(u8, &assignment.event.thread_id, &thread_id_hex); 1732 }, 1733 } 1734 } 1735 1736 // remove an event a thread's page names: the thread itself, or a comment, 1737 // attachment or assignment, which must belong to it 1738 pub fn removeInThread( 1739 host: Host, 1740 comptime repo_kind: rp.RepoKind, 1741 comptime repo_opts: rp.RepoOpts(repo_kind), 1742 io: std.Io, 1743 allocator: std.mem.Allocator, 1744 repo: *rp.Repo(repo_kind, repo_opts), 1745 thread_kind: EventKind, 1746 thread_id: *const [event_id_size]u8, 1747 kind: EventKind, 1748 id: *const [event_id_size]u8, 1749 author: CommitAuthor, 1750 ) !void { 1751 const child_maybe: ?ThreadChild = switch (kind) { 1752 .comment => .{ .comment = id }, 1753 .attach => .{ .attach = id }, 1754 .assign => .{ .assign = id }, 1755 else => null, 1756 }; 1757 if (child_maybe) |child| { 1758 if (!try threadHolds(repo_kind, repo_opts, io, allocator, repo, thread_kind, thread_id, child)) return error.EventNotFound; 1759 } 1760 try remove(host, .repo, repo_kind, repo_opts, io, allocator, repo, id, kind, author); 1761 } 1762 1763 pub fn readFromRepo( 1764 comptime T: type, 1765 comptime repo_kind: rp.RepoKind, 1766 comptime repo_opts: rp.RepoOpts(repo_kind), 1767 io: std.Io, 1768 allocator: std.mem.Allocator, 1769 arena: *std.heap.ArenaAllocator, 1770 repo: *rp.Repo(repo_kind, repo_opts), 1771 id: *const [event_id_size]u8, 1772 ) !?T.Record { 1773 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; 1774 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1775 const moment = (if (event_db_maybe) |*event_db| 1776 currentMomentFromDb(repo_opts.hash, event_db.db) 1777 else if (repo_kind == .git) 1778 return null 1779 else 1780 currentMoment(repo_opts, repo)) catch return null; 1781 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1782 } 1783 1784 pub fn currentMoment( 1785 comptime repo_opts: rp.RepoOpts(.xit), 1786 repo: *rp.Repo(.xit, repo_opts), 1787 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1788 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1789 } 1790 1791 pub fn currentMomentFromDb( 1792 comptime hash_kind: hash.HashKind, 1793 db: *EventDB(hash_kind), 1794 ) !EventDB(hash_kind).HashMap(.read_only) { 1795 const DB = EventDB(hash_kind); 1796 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1797 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1798 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1799 return try currentMomentFromRepoMoment(hash_kind, moment); 1800 } 1801 1802 pub fn currentMomentFromRepoMoment( 1803 comptime hash_kind: hash.HashKind, 1804 moment: EventDB(hash_kind).HashMap(.read_only), 1805 ) !EventDB(hash_kind).HashMap(.read_only) { 1806 const DB = EventDB(hash_kind); 1807 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1808 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1809 _ = try last_object_id_cursor.readBytes(&last_object_id); 1810 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1811 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1812 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1813 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1814 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1815 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1816 } 1817 1818 // build a sorted-set key from an order and event id. big-endian order makes 1819 // byte order match numeric order; the event id breaks ties. 1820 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1821 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1822 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1823 @memcpy(key[@sizeOf(u64)..], event_id); 1824 return key; 1825 } 1826 1827 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1828 return orderKey(std.math.maxInt(u64) - order, event_id); 1829 } 1830 1831 pub fn removedRecord( 1832 comptime T: type, 1833 comptime DB: type, 1834 comptime hash_kind: hash.HashKind, 1835 haxy_moment: DB.HashMap(.read_only), 1836 existing_maybe: ?T, 1837 ) !T { 1838 var record = existing_maybe orelse return error.EventNotFound; 1839 record.removed = true; 1840 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1841 record.updated_order = try order_cursor.readUint(); 1842 return record; 1843 } 1844 1845 // add or refresh one entry in the global logical-event index 1846 pub fn indexEvent( 1847 comptime DB: type, 1848 comptime hash_kind: hash.HashKind, 1849 haxy_moment: DB.HashMap(.read_write), 1850 event_id: *const [event_id_size]u8, 1851 kind: EventKind, 1852 existing_maybe: anytype, 1853 record: anytype, 1854 ) !void { 1855 const event_key = hash.hashInt(hash_kind, event_id); 1856 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1857 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1858 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1859 1860 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1861 const active = try DB.SortedSet(.read_write).init(active_cursor); 1862 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1863 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1864 1865 if (existing_maybe) |existing| { 1866 const old_key = orderKeyDesc(existing.updated_order, event_id); 1867 _ = try active.remove(&old_key); 1868 _ = try removed_set.remove(&old_key); 1869 } 1870 1871 const order_key = orderKeyDesc(record.updated_order, event_id); 1872 if (record.removed) { 1873 try removed_set.put(&order_key); 1874 } else { 1875 try active.put(&order_key); 1876 } 1877 } 1878 1879 pub fn touchThread( 1880 comptime DB: type, 1881 comptime hash_kind: hash.HashKind, 1882 haxy_moment: DB.HashMap(.read_write), 1883 thread_id: *const [event_id_size]u8, 1884 order: u64, 1885 arena: *std.heap.ArenaAllocator, 1886 ) !void { 1887 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1888 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1889 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1890 switch (kind) { 1891 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1892 else => {}, 1893 } 1894 } 1895 1896 pub fn readEventKind( 1897 comptime hash_kind: hash.HashKind, 1898 kind_map: anytype, 1899 id: *const [event_id_size]u8, 1900 ) !?EventKind { 1901 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1902 var buffer: [64]u8 = undefined; 1903 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1904 } 1905 1906 // the email of the event's author, or null when the id names no authored event 1907 // of this kind 1908 pub fn readAuthorEmail( 1909 comptime repo_kind: rp.RepoKind, 1910 comptime repo_opts: rp.RepoOpts(repo_kind), 1911 io: std.Io, 1912 allocator: std.mem.Allocator, 1913 arena: *std.heap.ArenaAllocator, 1914 repo: *rp.Repo(repo_kind, repo_opts), 1915 kind: EventKind, 1916 id: *const [event_id_size]u8, 1917 ) !?[]const u8 { 1918 const record_map_key = switch (kind) { 1919 .discuss => Discussion.record_map_key, 1920 .issue => Issue.record_map_key, 1921 .comment => Comment.record_map_key, 1922 .attach => Attachment.record_map_key, 1923 .assign => Assignment.record_map_key, 1924 .patchrev => PatchRev.record_map_key, 1925 .patch => Patch.record_map_key, 1926 .user, .repo, .fork, .grant => return null, 1927 }; 1928 1929 const DB = EventDB(repo_opts.hash); 1930 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; 1931 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1932 const moment = (if (event_db_maybe) |*event_db| 1933 currentMomentFromDb(repo_opts.hash, event_db.db) 1934 else if (repo_kind == .git) 1935 return null 1936 else 1937 currentMoment(repo_opts, repo)) catch return null; 1938 1939 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 1940 const records = try DB.HashMap(.read_only).init(records_cursor); 1941 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 1942 const record = try DB.HashMap(.read_only).init(record_cursor); 1943 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 1944 } 1945 1946 // the event id embedded in a set entry's order key 1947 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1948 var cursor = kv_pair_cursor; 1949 const kv_pair = try cursor.readKeyValuePair(); 1950 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1951 _ = try kv_pair.key_cursor.readBytes(&order_key); 1952 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1953 } 1954 1955 // split a pushed "<owner>:<repo>" path into its two components, or null if it 1956 // isn't exactly two non-empty parts with no "/". 1957 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1958 if (std.mem.indexOfScalar(u8, path, '/') != null) return null; 1959 var it = std.mem.splitScalar(u8, path, ':'); 1960 const owner = it.next() orelse return null; 1961 const name = it.next() orelse return null; 1962 if (it.next() != null) return null; 1963 if (owner.len == 0 or name.len == 0) return null; 1964 1965 return .{ .owner = owner, .name = name }; 1966 } 1967 1968 pub const CreateRepoOptions = struct { 1969 read_access: Repo.Access = .private, 1970 }; 1971 1972 // the ids that locate a repo's on-disk directory 1973 pub const RepoLocation = struct { 1974 owner_id: [event_id_size]u8, 1975 repo_id: [event_id_size]u8, 1976 }; 1977 1978 // resolve a pushed `<owner>:<repo>` to the ids that locate its on-disk directory 1979 pub fn resolveOrCreateRepo( 1980 io: std.Io, 1981 allocator: std.mem.Allocator, 1982 users_dir: []const u8, 1983 admin_repo_path: []const u8, 1984 owner_name: []const u8, 1985 repo_name: []const u8, 1986 create_options_maybe: ?CreateRepoOptions, 1987 ) !?RepoLocation { 1988 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1989 error.RepoNotFound => return null, 1990 else => |e| return e, 1991 }; 1992 defer admin_repo.deinit(io, allocator); 1993 1994 var arena = std.heap.ArenaAllocator.init(allocator); 1995 defer arena.deinit(); 1996 1997 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 1998 1999 // an unknown owner can't own a repo, so the push is rejected 2000 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 2001 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 2002 defer user_repo.deinit(io, allocator); 2003 2004 // an already-registered repo reuses its event id, so a re-push (or a clone) 2005 // lands in the same repo 2006 if (try userMoment(&user_repo)) |moment| { 2007 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 2008 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 2009 } 2010 } 2011 2012 const create_options = create_options_maybe orelse return null; 2013 2014 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 2015 2016 var id_bytes: [event_id_size]u8 = undefined; 2017 io.random(&id_bytes); 2018 try writeRepoEvent(io, allocator, users_dir, &user_repo, &owner_user_id, .{ .name = owner.event.name, .email = owner.event.email }, &id_bytes, repo_name, "", create_options.read_access); 2019 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 2020 } 2021 2022 // create a bare repo with `hash_kind` and register it in its owner's user repo 2023 pub fn createRepo( 2024 io: std.Io, 2025 allocator: std.mem.Allocator, 2026 users_dir: []const u8, 2027 owner_id: *const [event_id_size]u8, 2028 owner: CommitAuthor, 2029 name: []const u8, 2030 description: []const u8, 2031 read_access: Repo.Access, 2032 hash_kind: hash.HashKind, 2033 ) !RepoLocation { 2034 try Repo.validateName(name); 2035 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2036 defer user_repo.deinit(io, allocator); 2037 if (try userMoment(&user_repo)) |moment| { 2038 var arena = std.heap.ArenaAllocator.init(allocator); 2039 defer arena.deinit(); 2040 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2041 } 2042 2043 var id_bytes: [event_id_size]u8 = undefined; 2044 io.random(&id_bytes); 2045 2046 // the directory comes first so a listed repo always has one 2047 { 2048 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2049 defer allocator.free(path); 2050 switch (hash_kind) { 2051 inline else => |kind| { 2052 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2053 defer repo.deinit(io, allocator); 2054 }, 2055 } 2056 } 2057 2058 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2059 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2060 } 2061 2062 // change the name, description, read access, and tab roles of the repo 2063 // named `old_name` in its owner's user repo 2064 pub fn updateRepo( 2065 io: std.Io, 2066 allocator: std.mem.Allocator, 2067 users_dir: []const u8, 2068 owner_id: *const [event_id_size]u8, 2069 author: CommitAuthor, 2070 old_name: []const u8, 2071 name: []const u8, 2072 description: []const u8, 2073 read_access: Repo.Access, 2074 discuss_role: ?Repo.Role, 2075 issue_role: ?Repo.Role, 2076 patch_role: ?Repo.Role, 2077 ) !void { 2078 try Repo.validateName(name); 2079 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2080 defer user_repo.deinit(io, allocator); 2081 var arena = std.heap.ArenaAllocator.init(allocator); 2082 defer arena.deinit(); 2083 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2084 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2085 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2086 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2087 } 2088 2089 var event = found.repo.event; 2090 event.name = name; 2091 event.description = description; 2092 event.read_access = read_access; 2093 event.discuss_role = discuss_role; 2094 event.issue_role = issue_role; 2095 event.patch_role = patch_role; 2096 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2097 .id = std.fmt.bytesToHex(found.event_id, .lower), 2098 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2099 .author = author, 2100 .event = .{ .repo = event }, 2101 }}); 2102 } 2103 2104 // grant `user_id` `role` on the repo `repo_id` in its owner's user repo, 2105 // replacing any role they held 2106 pub fn grantRole( 2107 io: std.Io, 2108 allocator: std.mem.Allocator, 2109 users_dir: []const u8, 2110 owner_id: *const [event_id_size]u8, 2111 repo_id: *const [event_id_size]u8, 2112 user_id: *const [event_id_size]u8, 2113 role: Repo.Role, 2114 author: CommitAuthor, 2115 ) !void { 2116 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2117 defer user_repo.deinit(io, allocator); 2118 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2119 .id = std.fmt.bytesToHex(Grant.idOf(repo_id, user_id), .lower), 2120 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2121 .author = author, 2122 .event = .{ .grant = .{ .target_id = repo_id, .user_id = user_id, .role = role } }, 2123 }}); 2124 } 2125 2126 // revoke `user_id`'s grant on the repo `repo_id` in its owner's user repo 2127 pub fn revokeRole( 2128 io: std.Io, 2129 allocator: std.mem.Allocator, 2130 users_dir: []const u8, 2131 owner_id: *const [event_id_size]u8, 2132 repo_id: *const [event_id_size]u8, 2133 user_id: *const [event_id_size]u8, 2134 author: CommitAuthor, 2135 ) !void { 2136 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2137 defer user_repo.deinit(io, allocator); 2138 // a revoked grant stays in the kind index, which is all `remove` checks 2139 { 2140 var arena = std.heap.ArenaAllocator.init(allocator); 2141 defer arena.deinit(); 2142 const moment = (try userMoment(&user_repo)) orelse return error.EventNotFound; 2143 if (try Grant.readRole(UserDB, user_repo_opts.hash, moment, &arena, repo_id, user_id) == null) return error.EventNotFound; 2144 } 2145 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, &Grant.idOf(repo_id, user_id), .grant, author); 2146 } 2147 2148 // create a user and their user repo, returning the new user's id 2149 pub fn createUser( 2150 io: std.Io, 2151 allocator: std.mem.Allocator, 2152 users_dir: []const u8, 2153 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2154 name: []const u8, 2155 email: []const u8, 2156 password: []const u8, 2157 password_again: []const u8, 2158 ) ![event_id_size]u8 { 2159 try User.validateName(name); 2160 if (email.len == 0) return error.EmailEmpty; 2161 if (password.len == 0) return error.PasswordEmpty; 2162 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2163 // a fresh admin repo has no moment until its first event 2164 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2165 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2166 var arena = std.heap.ArenaAllocator.init(allocator); 2167 defer arena.deinit(); 2168 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2169 } else |err| switch (err) { 2170 error.NotFound => {}, 2171 else => |e| return e, 2172 } 2173 2174 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2175 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2176 2177 var id_bytes: [event_id_size]u8 = undefined; 2178 io.random(&id_bytes); 2179 2180 // the user repo comes first so a listed user can always create repos 2181 { 2182 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2183 defer allocator.free(path); 2184 var user_repo = try initUserRepo(io, allocator, path); 2185 defer user_repo.deinit(io, allocator); 2186 } 2187 2188 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2189 .id = std.fmt.bytesToHex(id_bytes, .lower), 2190 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2191 .author = .{ .name = name, .email = email }, 2192 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2193 }}); 2194 return id_bytes; 2195 } 2196 2197 // change a user's email, and their password when the password fields are 2198 // filled in 2199 pub fn updateUser( 2200 io: std.Io, 2201 allocator: std.mem.Allocator, 2202 users_dir: []const u8, 2203 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2204 user_id: *const [event_id_size]u8, 2205 email: []const u8, 2206 current_password: []const u8, 2207 new_password: []const u8, 2208 new_password_again: []const u8, 2209 ) !void { 2210 if (email.len == 0) return error.EmailEmpty; 2211 var arena = std.heap.ArenaAllocator.init(allocator); 2212 defer arena.deinit(); 2213 const moment = try currentMoment(admin_repo_opts, admin_repo); 2214 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2215 if (user.removed) return error.NotFound; 2216 if (!std.mem.eql(u8, email, user.event.email) and try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2217 2218 var event = user.event; 2219 event.email = email; 2220 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2221 if (current_password.len + new_password.len + new_password_again.len > 0) { 2222 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2223 if (new_password.len == 0) return error.PasswordEmpty; 2224 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2225 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2226 } 2227 2228 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2229 .id = std.fmt.bytesToHex(user_id.*, .lower), 2230 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2231 .author = .{ .name = event.name, .email = email }, 2232 .event = .{ .user = event }, 2233 }}); 2234 } 2235 2236 // consume a new repo's event into its owner's user repo and mark it active 2237 fn writeRepoEvent( 2238 io: std.Io, 2239 allocator: std.mem.Allocator, 2240 users_dir: []const u8, 2241 user_repo: *rp.Repo(.xit, user_repo_opts), 2242 owner_id: *const [event_id_size]u8, 2243 owner: CommitAuthor, 2244 id_bytes: *const [event_id_size]u8, 2245 name: []const u8, 2246 description: []const u8, 2247 read_access: Repo.Access, 2248 ) !void { 2249 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2250 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2251 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2252 .timestamp = timestamp, 2253 .author = owner, 2254 .event = .{ .repo = .{ 2255 .user_id = owner_id, 2256 .name = name, 2257 .description = description, 2258 .read_access = read_access, 2259 } }, 2260 }}); 2261 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2262 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2263 }; 2264 } 2265 2266 // 2267 // reading from xitdb 2268 // 2269 2270 // read just `Fields`, a subset of `T.Record`, from the record with event id 2271 // `id`, or null when there is none 2272 pub fn readRecordSubset( 2273 comptime T: type, 2274 comptime Fields: type, 2275 comptime DB: type, 2276 comptime hash_kind: hash.HashKind, 2277 haxy_moment: DB.HashMap(.read_only), 2278 arena: *std.heap.ArenaAllocator, 2279 id: []const u8, 2280 ) !?Fields { 2281 comptime assertFieldSubset(Fields, T.Record); 2282 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2283 const records = try DB.HashMap(.read_only).init(records_cursor); 2284 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2285 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2286 } 2287 2288 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2289 const info = @typeInfo(Sub).@"struct"; 2290 for (info.field_names, info.field_types) |field_name, field_type| { 2291 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2292 const FullField = @FieldType(Full, field_name); 2293 if (@typeInfo(field_type) == .@"struct") { 2294 assertFieldSubset(field_type, FullField); 2295 } else if (field_type != FullField) { 2296 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2297 } 2298 } 2299 } 2300 2301 pub fn read( 2302 comptime T: type, 2303 comptime DB: type, 2304 comptime hash_kind: hash.HashKind, 2305 arena: *std.heap.ArenaAllocator, 2306 map: DB.HashMap(.read_only), 2307 ) !T { 2308 var event: T = undefined; 2309 switch (@typeInfo(T)) { 2310 .@"struct" => |struct_info| { 2311 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2312 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2313 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2314 } 2315 }, 2316 else => @compileError("read expects a struct"), 2317 } 2318 return event; 2319 } 2320 2321 fn readField( 2322 comptime Field: type, 2323 comptime DB: type, 2324 comptime hash_kind: hash.HashKind, 2325 arena: *std.heap.ArenaAllocator, 2326 cursor_maybe: ?DB.Cursor(.read_only), 2327 ) !Field { 2328 if (@typeInfo(Field) == .optional) { 2329 // a missing key or a null union payload is null 2330 const cursor = cursor_maybe orelse return null; 2331 if (cursor.slot().tag == .none) return null; 2332 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2333 } 2334 const cursor = cursor_maybe orelse return error.NotFound; 2335 switch (@typeInfo(Field)) { 2336 .pointer => |pointer_info| { 2337 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2338 @compileError("unsupported read field type: " ++ @typeName(Field)); 2339 } 2340 return try cursor.readBytesAlloc(arena.allocator(), null); 2341 }, 2342 .array => |array_info| { 2343 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2344 var bytes: Field = undefined; 2345 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2346 return bytes; 2347 }, 2348 .bool => { 2349 var buffer: [5]u8 = undefined; 2350 const bytes = try cursor.readBytesObject(&buffer); 2351 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2352 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2353 if (std.mem.eql(u8, bytes.value, "true")) return true; 2354 if (std.mem.eql(u8, bytes.value, "false")) return false; 2355 return error.InvalidBool; 2356 }, 2357 .int => |int_info| return switch (int_info.signedness) { 2358 .unsigned => @intCast(try cursor.readUint()), 2359 .signed => @intCast(try cursor.readInt()), 2360 }, 2361 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2362 .@"union" => |union_info| { 2363 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2364 switch (cursor.slot().tag) { 2365 .bytes, .short_bytes => { 2366 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2367 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2368 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2369 return @unionInit(Field, variant_name, {}); 2370 } 2371 } 2372 return error.InvalidUnion; 2373 }, 2374 .hash_map => { 2375 const variants = try DB.HashMap(.read_only).init(cursor); 2376 var iter = try variants.iterator(); 2377 const entry = (try iter.next()) orelse return error.InvalidUnion; 2378 const pair = try entry.readKeyValuePair(); 2379 if (try iter.next() != null) return error.InvalidUnion; 2380 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2381 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2382 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2383 } 2384 } 2385 return error.InvalidUnion; 2386 }, 2387 else => return error.InvalidUnion, 2388 } 2389 }, 2390 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2391 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2392 } 2393 } 2394 2395 // whether two events carry the same data 2396 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2397 switch (@typeInfo(T)) { 2398 .@"struct" => |struct_info| { 2399 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2400 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2401 } 2402 }, 2403 else => @compileError("fieldsEqual expects a struct"), 2404 } 2405 2406 return true; 2407 } 2408 2409 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2410 switch (@typeInfo(Field)) { 2411 .pointer => |pointer_info| { 2412 if (pointer_info.size == .slice and pointer_info.child == u8) { 2413 return std.mem.eql(u8, a, b); 2414 } else { 2415 @compileError("unsupported field type: " ++ @typeName(Field)); 2416 } 2417 }, 2418 .array => |array_info| { 2419 if (array_info.child == u8) { 2420 return std.mem.eql(u8, &a, &b); 2421 } else { 2422 @compileError("unsupported field type: " ++ @typeName(Field)); 2423 } 2424 }, 2425 .void => return true, 2426 .bool, .int, .@"enum" => return a == b, 2427 .@"union" => { 2428 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2429 return switch (a) { 2430 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2431 }; 2432 }, 2433 .@"struct" => return fieldsEqual(Field, a, b), 2434 .optional => |optional_info| { 2435 if (a) |a_value| { 2436 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2437 return false; 2438 } 2439 return b == null; 2440 }, 2441 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2442 } 2443 } 2444 2445 // 2446 // writing to xitdb 2447 // 2448 2449 pub fn upsert( 2450 comptime T: type, 2451 comptime DB: type, 2452 comptime hash_kind: hash.HashKind, 2453 map: DB.HashMap(.read_write), 2454 event: T, 2455 ) !void { 2456 switch (@typeInfo(T)) { 2457 .@"struct" => |struct_info| { 2458 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2459 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2460 } 2461 }, 2462 else => @compileError("upsert expects a struct"), 2463 } 2464 } 2465 2466 fn upsertField( 2467 comptime DB: type, 2468 comptime hash_kind: hash.HashKind, 2469 map: DB.HashMap(.read_write), 2470 comptime field_name: []const u8, 2471 comptime Field: type, 2472 value: Field, 2473 ) !void { 2474 const key = hash.hashInt(hash_kind, field_name); 2475 2476 switch (@typeInfo(Field)) { 2477 .pointer => |pointer_info| { 2478 if (pointer_info.size == .slice and pointer_info.child == u8) { 2479 try upsertBytes(DB, hash_kind, map, key, value); 2480 } else { 2481 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2482 } 2483 }, 2484 .array => |array_info| { 2485 if (array_info.child == u8) { 2486 try upsertBytes(DB, hash_kind, map, key, &value); 2487 } else { 2488 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2489 } 2490 }, 2491 .int => |int_info| switch (int_info.signedness) { 2492 .unsigned => { 2493 if (try map.getCursor(key)) |value_cursor| { 2494 if (try value_cursor.readUint() == value) { 2495 return; 2496 } 2497 } 2498 2499 try map.put(key, .{ .uint = value }); 2500 }, 2501 .signed => { 2502 if (try map.getCursor(key)) |value_cursor| { 2503 if (try value_cursor.readInt() == value) { 2504 return; 2505 } 2506 } 2507 2508 try map.put(key, .{ .int = value }); 2509 }, 2510 }, 2511 .bool => { 2512 const bytes = if (value) "true" else "false"; 2513 if (try map.getCursor(key)) |value_cursor| { 2514 var buffer: [5]u8 = undefined; 2515 const existing = try value_cursor.readBytesObject(&buffer); 2516 if (existing.format_tag) |format_tag| { 2517 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2518 return; 2519 } 2520 } 2521 } 2522 2523 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2524 }, 2525 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2526 .@"union" => switch (value) { 2527 inline else => |payload, tag| { 2528 if (@TypeOf(payload) == void) { 2529 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2530 } else { 2531 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2532 if (try map.getCursor(key)) |cursor| { 2533 switch (cursor.slot().tag) { 2534 .hash_map => { 2535 const variants = try DB.HashMap(.read_only).init(cursor); 2536 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2537 }, 2538 else => try map.put(key, .{ .slot = null }), 2539 } 2540 } 2541 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2542 if (@typeInfo(@TypeOf(payload)) == .optional) { 2543 // keep the variant even when its payload is null 2544 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2545 } 2546 if (try variants.getCursor(tag_key)) |cursor| { 2547 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2548 } 2549 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2550 } 2551 }, 2552 }, 2553 .optional => |optional_info| { 2554 // a missing key is null 2555 if (value) |child| { 2556 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2557 } else { 2558 _ = try map.remove(key); 2559 } 2560 }, 2561 .@"struct" => try upsert( 2562 Field, 2563 DB, 2564 hash_kind, 2565 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2566 value, 2567 ), 2568 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2569 } 2570 } 2571 2572 fn upsertBytes( 2573 comptime DB: type, 2574 comptime hash_kind: hash.HashKind, 2575 map: DB.HashMap(.read_write), 2576 key: hash.HashInt(hash_kind), 2577 value: []const u8, 2578 ) !void { 2579 var existing_cursor_maybe = try map.getCursor(key); 2580 if (existing_cursor_maybe) |*existing_cursor| { 2581 if (try bytesEqual(DB, existing_cursor, value)) { 2582 return; 2583 } 2584 } 2585 2586 try map.put(key, .{ .bytes = value }); 2587 } 2588 2589 fn bytesEqual( 2590 comptime DB: type, 2591 cursor: *DB.Cursor(.read_only), 2592 value: []const u8, 2593 ) !bool { 2594 switch (cursor.slot().tag) { 2595 .bytes, .short_bytes => {}, 2596 else => return false, 2597 } 2598 var read_buffer: [1024]u8 = undefined; 2599 var reader = try cursor.reader(&read_buffer); 2600 if (reader.size != value.len) { 2601 return false; 2602 } 2603 2604 var chunk_buffer: [1024]u8 = undefined; 2605 var offset: usize = 0; 2606 while (offset < value.len) { 2607 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2608 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2609 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2610 return false; 2611 } 2612 offset += chunk_len; 2613 } 2614 2615 return true; 2616 } 2617 2618 // 2619 // CommitIterator 2620 // 2621 // differs from xit's ObjectIterator in a few ways: 2622 // 2623 // 1. iterates parents first, rather than children first 2624 // 2. `next` only returns the object id, not the full Object 2625 // 3. stores its temporary state in a file on disk to avoid OOMs 2626 // 2627 2628 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2629 return struct { 2630 const DB = EventDB(repo_opts.hash); 2631 // a plain file is used for the scratch db because each write outside 2632 // a transaction is synced anyway, so buffering would gain nothing 2633 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2634 const db_name = "haxy-repo-events.db"; 2635 2636 repo_dir: std.Io.Dir, 2637 db_file: std.Io.File, 2638 db: *TempDB, 2639 // map of each object id to its children 2640 parent_to_children: TempDB.HashMap(.read_write), 2641 // tracking pending parents is necessary because a child can only 2642 // be returned after all of its unconsumed parents have been returned 2643 child_to_pending_parents: TempDB.HashMap(.read_write), 2644 // queue of object ids that are ready to be returned from `next` 2645 ready_queue: TempDB.ArrayList(.read_write), 2646 ready_queue_index: u64, 2647 // the object id at the tip of this branch 2648 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2649 // the object id furthest back in the history that hasn't been consumed 2650 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2651 2652 pub fn init( 2653 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2654 io: std.Io, 2655 allocator: std.mem.Allocator, 2656 consumed_object_ids: DB.HashMap(.read_only), 2657 ref: rf.Ref, 2658 ) !CommitIterator(repo_kind, repo_opts) { 2659 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2660 errdefer { 2661 db_file.close(io); 2662 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2663 } 2664 2665 // cursors point at the db, so it needs a stable address 2666 const db_ptr = try allocator.create(TempDB); 2667 errdefer allocator.destroy(db_ptr); 2668 // the db is scratch state that gets deleted after iteration, so 2669 // there is nothing worth fsyncing 2670 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2671 2672 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2673 2674 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2675 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2676 2677 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2678 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2679 2680 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2681 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2682 2683 var self = CommitIterator(repo_kind, repo_opts){ 2684 .repo_dir = state.core.repo_dir, 2685 .db_file = db_file, 2686 .db = db_ptr, 2687 .parent_to_children = parent_to_children, 2688 .child_to_pending_parents = child_to_pending_parents, 2689 .ready_queue = ready_queue, 2690 .ready_queue_index = 0, 2691 .newest_object_id = null, 2692 .oldest_object_id = null, 2693 }; 2694 errdefer self.deinit(io, allocator); 2695 2696 try self.collect(state, io, allocator, consumed_object_ids, ref); 2697 2698 return self; 2699 } 2700 2701 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2702 self.db_file.close(io); 2703 self.repo_dir.deleteFile(io, db_name) catch {}; 2704 allocator.destroy(self.db); 2705 } 2706 2707 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2708 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2709 2710 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2711 self.ready_queue_index += 1; 2712 2713 try self.enqueueChildren(&oid); 2714 return oid; 2715 } 2716 2717 fn collect( 2718 self: *CommitIterator(repo_kind, repo_opts), 2719 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2720 io: std.Io, 2721 allocator: std.mem.Allocator, 2722 consumed_object_ids: DB.HashMap(.read_only), 2723 ref: rf.Ref, 2724 ) !void { 2725 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2726 2727 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2728 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2729 var walk_queue_index: u64 = 0; 2730 2731 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2732 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2733 2734 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2735 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2736 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2737 try walk_queue.append(.{ .bytes = &head_oid }); 2738 2739 while (walk_queue_index < try walk_queue.count()) { 2740 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2741 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2742 2743 walk_queue_index += 1; 2744 2745 // if we've seen this object id, skip it 2746 if (null != try seen_object_ids.getCursor(oid_int)) { 2747 continue; 2748 } 2749 2750 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2751 2752 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2753 defer commit_object.deinit(); 2754 2755 // if this object id has already been consumed, skip it 2756 if (null != try consumed_object_ids.getCursor(oid_int)) { 2757 continue; 2758 } 2759 2760 if (self.newest_object_id == null) self.newest_object_id = oid; 2761 self.oldest_object_id = oid; 2762 2763 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2764 var pending_parent_count: u64 = 0; 2765 for (parent_oids) |*parent_oid| { 2766 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2767 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2768 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2769 2770 // if this object id has already been consumed, skip it 2771 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2772 continue; 2773 } 2774 2775 // if this object id hasn't already been seen, add it to the walk queue 2776 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2777 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2778 } 2779 2780 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2781 const children = try TempDB.HashSet(.read_write).init(children_cursor); 2782 try children.put(oid_int, .{ .bytes = &oid }); 2783 pending_parent_count += 1; 2784 } 2785 2786 if (pending_parent_count == 0) { 2787 try self.ready_queue.append(.{ .bytes = &oid }); 2788 } else { 2789 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2790 } 2791 } 2792 } 2793 2794 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2795 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2796 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2797 const children = try TempDB.HashSet(.read_only).init(children_cursor); 2798 var children_iter = try children.iterator(); 2799 2800 while (try children_iter.next()) |*child_cursor| { 2801 const kv_pair = try child_cursor.readKeyValuePair(); 2802 const child_oid_int = kv_pair.hash; 2803 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2804 const pending_parent_count = try pending_parent_cursor.readUint(); 2805 2806 if (pending_parent_count <= 1) { 2807 _ = try self.child_to_pending_parents.remove(child_oid_int); 2808 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2809 try self.ready_queue.append(.{ .bytes = &child_oid }); 2810 } else { 2811 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2812 } 2813 } 2814 } 2815 2816 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2817 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2818 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2819 _ = try oid_cursor.readBytes(&oid); 2820 return oid; 2821 } 2822 }; 2823 } 2824