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