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