╭ 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 // a standalone event db holding events consumed from a local repo's events 566 // branch. it lives inside the repo dir but is not part of the repo's own data, 567 // so viewing a repo never mutates it. 568 pub fn LocalEventDB(comptime hash_kind: hash.HashKind) type { 569 return struct { 570 file: std.Io.File, 571 buffer: *std.Io.Writer.Allocating, 572 db: *EventDB(hash_kind), 573 574 const db_name = "haxy"; 575 const Self = @This(); 576 577 // open the db in `repo_dir` for writing, creating it if it doesn't exist 578 pub fn open(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !Self { 579 const file = try repo_dir.createFile(io, db_name, .{ .truncate = false, .read = true, .lock = .exclusive }); 580 return fromFile(io, allocator, file); 581 } 582 583 // open the db in `repo_dir` for reading, or null if it doesn't exist 584 pub fn openReadOnly(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !?Self { 585 const file = repo_dir.openFile(io, db_name, .{ .mode = .read_write, .lock = .shared }) catch |err| switch (err) { 586 error.FileNotFound => return null, 587 else => |e| return e, 588 }; 589 return try fromFile(io, allocator, file); 590 } 591 592 // remove the db from `repo_dir`, so a repo whose events branch 593 // disappeared doesn't keep showing stale issues 594 pub fn delete(io: std.Io, repo_dir: std.Io.Dir) !void { 595 repo_dir.deleteFile(io, db_name) catch |err| switch (err) { 596 error.FileNotFound => {}, 597 else => |e| return e, 598 }; 599 } 600 601 fn fromFile(io: std.Io, allocator: std.mem.Allocator, file: std.Io.File) !Self { 602 errdefer file.close(io); 603 604 const buffer = try allocator.create(std.Io.Writer.Allocating); 605 errdefer allocator.destroy(buffer); 606 buffer.* = std.Io.Writer.Allocating.init(allocator); 607 errdefer buffer.deinit(); 608 609 const db = try allocator.create(EventDB(hash_kind)); 610 errdefer allocator.destroy(db); 611 db.* = try EventDB(hash_kind).init(.{ .io = io, .file = file, .buffer = buffer }); 612 613 return .{ .file = file, .buffer = buffer, .db = db }; 614 } 615 616 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 617 self.file.close(io); 618 self.buffer.deinit(); 619 allocator.destroy(self.buffer); 620 allocator.destroy(self.db); 621 } 622 623 // consume the events on `repo`'s `ref` into this db. the db must come 624 // from `open`, whose handle holds the exclusive lock guarding the 625 // transaction. 626 pub fn consume( 627 self: *Self, 628 comptime repo_kind: rp.RepoKind, 629 comptime repo_opts: rp.RepoOpts(repo_kind), 630 io: std.Io, 631 allocator: std.mem.Allocator, 632 repo: *rp.Repo(repo_kind, repo_opts), 633 ref: rf.Ref, 634 ) !void { 635 comptime if (repo_opts.hash != hash_kind) @compileError("the repo must use the db's hash kind"); 636 const DB = EventDB(hash_kind); 637 638 const Ctx = struct { 639 repo: *rp.Repo(repo_kind, repo_opts), 640 db: *DB, 641 io: std.Io, 642 allocator: std.mem.Allocator, 643 ref: rf.Ref, 644 645 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 646 var moment = try DB.HashMap(.read_write).init(cursor.*); 647 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{} }; 648 if (!try consumeInTransaction(.repo, repo_kind, repo_opts, state, ctx.db, &moment, ctx.io, ctx.allocator, ctx.ref)) return error.CancelTransaction; 649 } 650 }; 651 652 const history = try DB.ArrayList(.read_write).init(self.db.rootCursor()); 653 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 654 .repo = repo, 655 .db = self.db, 656 .io = io, 657 .allocator = allocator, 658 .ref = ref, 659 }) catch |err| switch (err) { 660 error.CancelTransaction => {}, 661 else => |e| return e, 662 }; 663 } 664 }; 665 } 666 667 // consume the events on `ref` into the db `moment` writes to, returning false 668 // if there was nothing to do. events are read from `state`'s repo, which 669 // needn't be the repo backing the db — that's how a local (possibly 670 // git-backed) repo's events land in a standalone db. 671 pub fn consumeInTransaction( 672 comptime role: RepoRole, 673 comptime repo_kind: rp.RepoKind, 674 comptime repo_opts: rp.RepoOpts(repo_kind), 675 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 676 db: *EventDB(repo_opts.hash), 677 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 678 io: std.Io, 679 allocator: std.mem.Allocator, 680 ref: rf.Ref, 681 ) !bool { 682 const DB = EventDB(repo_opts.hash); 683 const read_state = state.readOnly(); 684 685 // the last_object_id represents the object id that was last consumed 686 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 687 if (try moment.getCursor(hash.hashInt(repo_opts.hash, last_object_id_key))) |last_object_id_cursor| { 688 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 689 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 690 last_object_id_maybe = last_object_id_buffer; 691 } 692 693 // the tip was already consumed, so there is nothing to do 694 if (last_object_id_maybe) |*last_object_id| { 695 const tip_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 696 var tip: [hash.byteLen(repo_opts.hash)]u8 = undefined; 697 _ = try std.fmt.hexToBytes(&tip, &tip_hex); 698 if (std.mem.eql(u8, last_object_id, &tip)) return false; 699 } 700 701 // the list with all of haxy's state, including materialized views. 702 // the reason it is a list is so we can keep every previous haxy 703 // state, making it easy to revert to an older state if the user 704 // rebases some of the past commits. 705 const haxy_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, materialized_key)); 706 const haxy = try DB.ArrayList(.read_write).init(haxy_cursor); 707 708 // add a new item to the haxy list created above. 709 // we call the item haxy_moments. it is a map of object id to haxy moment. 710 // in other words, it maps each object id to a hash map containing the 711 // state that the database was in when that object id was consumed. 712 var haxy_moments_cursor = try haxy.appendCursor(); 713 // use the previous haxy_moments as the basis for this one if it exists 714 if (try haxy.getCursor(-2)) |last_haxy_moments_cursor| { 715 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 716 } 717 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 718 719 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 720 defer commit_iter.deinit(io, allocator); 721 722 // if there are no events to process, look at the oid at HEAD and update 723 // the last_object_id to point to it. this is important in situations 724 // where we do a merge and then force-push to remove the merge. see the 725 // merge test for an example. 726 if (commit_iter.newest_object_id == null) { 727 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 728 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 729 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 730 731 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 732 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 733 734 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 735 const moment_index = try moment_index_cursor.readUint(); 736 737 try haxy.slice(moment_index + 1); 738 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = &head_oid }); 739 return true; 740 } 741 742 // if this branch was rebased and force pushed, we need to detect that and 743 // properly revert the haxy state to the last valid state. we detect this 744 // by simply asking if the last event is a descendent of the last event 745 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 746 if (last_object_id_maybe) |*last_object_id| { 747 var is_rebased = false; 748 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 749 750 _ = mrg.getDescendent( 751 repo_kind, 752 repo_opts, 753 read_state, 754 io, 755 allocator, 756 &std.fmt.bytesToHex(last_object_id, .lower), 757 &std.fmt.bytesToHex(&newest_object_id, .lower), 758 ) catch |err| switch (err) { 759 error.DescendentNotFound => is_rebased = true, 760 else => |e| return e, 761 }; 762 763 if (is_rebased) { 764 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 765 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 766 defer oldest_object.deinit(); 767 768 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 769 switch (parent_oids.len) { 770 0 => { 771 // the branch was rebased all the way to the very beginning. 772 // we have a repo event with no parent, which means it is now 773 // the very first event. all we need to do is set the haxy list 774 // to be empty and make a new haxy_moments map to work with. 775 776 try haxy.slice(0); 777 haxy_moments_cursor = try haxy.appendCursor(); 778 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 779 780 last_object_id_maybe = null; 781 }, 782 1 => { 783 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 784 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 785 786 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 787 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 788 789 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, "moment-index")) orelse return error.CursorNotFound; 790 const old_moment_index = try old_moment_index_cursor.readUint(); 791 792 // resize the haxy list so we truncate all the moments that were 793 // created after the parent_oid was consumed 794 try haxy.slice(old_moment_index + 1); 795 796 // make a new haxy moment and set its initial value to the last haxy moment 797 haxy_moments_cursor = try haxy.appendCursor(); 798 const old_haxy_moments_cursor = try haxy.getCursor(old_moment_index) orelse return error.CursorNotFound; 799 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 800 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 801 802 last_object_id_maybe = oid; 803 }, 804 else => return error.UnexpectedParentCount, 805 } 806 } 807 } 808 809 while (try commit_iter.next()) |repo_event_oid| { 810 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 811 defer commit_object.deinit(); 812 813 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 814 815 // create a moment for this object id 816 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 817 818 // if there was a previous object id, set this haxy moment's initial value to it. 819 // this efficiently "clones" the map so we make further modifications based on it. 820 if (parent_oids.len > 0) { 821 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 822 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 823 824 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 825 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 826 } 827 828 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 829 830 // graph generation gives every event a causal order independent of 831 // commit timestamps. concurrent events tie-break by id in their index. 832 var event_order: u64 = 1; 833 for (parent_oids) |*parent_oid| { 834 var parent_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 835 _ = try std.fmt.hexToBytes(&parent_id, parent_oid); 836 const parent_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &parent_id)) orelse return error.CursorNotFound; 837 const parent = try DB.HashMap(.read_only).init(parent_cursor); 838 const parent_order_cursor = try parent.getCursor(hash.hashInt(repo_opts.hash, event_order_key)) orelse return error.CursorNotFound; 839 const parent_order = try parent_order_cursor.readUint(); 840 event_order = @max(event_order, parent_order +| 1); 841 } 842 try haxy_moment.put(hash.hashInt(repo_opts.hash, event_order_key), .{ .uint = event_order }); 843 844 // merge changes from every parent after the first parent. the common 845 // ancestor is the baseline, so a later parent only contributes records 846 // it changed relative to the merge base. only the record maps are 847 // merged; every other view is derived from them, and each kind's 848 // `consume` re-derives its own as the winning records are written. 849 if (parent_oids.len > 1) { 850 for (parent_oids[1..]) |*parent_oid| { 851 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 852 _ = try std.fmt.hexToBytes(&oid, parent_oid); 853 854 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 855 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 856 857 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 858 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 859 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 860 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 861 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 862 863 inline for (std.meta.fields(Event)) |field| { 864 const T = @typeInfo(field.type).optional.child; 865 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 866 } 867 } 868 } 869 870 // associate this moment with the index it will first appear at in the haxy list. 871 // this will be important later so we can truncate that list if the user ever 872 // rebases starting at this object id. 873 try haxy_moment.put(hash.hashInt(repo_opts.hash, "moment-index"), .{ .uint = try haxy.count() - 1 }); 874 875 // consume the event unless it's a merge commit 876 if (parent_oids.len <= 1) { 877 var arena = std.heap.ArenaAllocator.init(allocator); 878 defer arena.deinit(); 879 880 // read the message from the commit 881 var message: std.ArrayList(u8) = .empty; 882 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 883 884 const event_with_id = try EventWithId.fromString(&arena, message.items); 885 if (!role.allows(std.meta.activeTag(event_with_id.event))) return error.EventKindNotAllowed; 886 887 const current_event_id = try parseEventId(&event_with_id.id); 888 889 // wrap the payload into the record `consume` stores, with its 890 // commit-derived fields; on update, `consume` preserves the 891 // existing record's 892 switch (event_with_id.event) { 893 .user => |event_maybe| { 894 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 895 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 896 }, 897 .repo => |event_maybe| { 898 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 899 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 900 }, 901 .fork => |event_maybe| { 902 const record_maybe: ?Fork.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 903 try Fork.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 904 }, 905 .issue => |event_maybe| { 906 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 907 .event = event, 908 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 909 .created_order = event_order, 910 .updated_order = event_order, 911 } else null; 912 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 913 }, 914 .discuss => |event_maybe| { 915 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 916 .event = event, 917 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 918 .created_order = event_order, 919 .updated_order = event_order, 920 } else null; 921 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 922 }, 923 .comment => |event_maybe| { 924 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 925 .event = event, 926 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 927 .created_order = event_order, 928 .updated_order = event_order, 929 } else null; 930 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 931 }, 932 .attach => |event_maybe| { 933 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 934 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 935 break :blk .{ 936 .event = event, 937 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 938 .created_order = event_order, 939 .updated_order = event_order, 940 .name = entry.name, 941 .blob_oid = entry.oid, 942 }; 943 } else null; 944 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 945 }, 946 .patchrev => |event_maybe| { 947 const record_maybe: ?PatchRev.Record = if (event_maybe) |event| blk: { 948 const trees = try PatchRev.readTrees(repo_kind, repo_opts, read_state, io, allocator, &commit_object.content.commit.tree); 949 const existing_maybe = try PatchRev.readById(DB, repo_opts.hash, haxy_moment.readOnly(), &arena, &current_event_id); 950 const event_oid = std.fmt.bytesToHex(repo_event_oid, .lower); 951 952 var patch_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 953 if (existing_maybe) |existing| { 954 if (existing.patch_oid.len != patch_oid.len) return error.InvalidPatch; 955 @memcpy(&patch_oid, existing.patch_oid); 956 } else { 957 const author = try commitIdentity(commit_object.content.commit.metadata.author orelse return error.AuthorNotFound); 958 const committer = try commitIdentity(commit_object.content.commit.metadata.committer orelse author); 959 patch_oid = try PatchRev.writeSquashCommit( 960 repo_kind, 961 repo_opts, 962 state, 963 io, 964 allocator, 965 event, 966 &trees.head, 967 author, 968 committer, 969 commit_object.content.commit.metadata.timestamp, 970 ); 971 } 972 973 break :blk .{ 974 .event = event, 975 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 976 .created_order = event_order, 977 .updated_order = event_order, 978 .event_oid = &event_oid, 979 .base_tree_oid = &trees.base, 980 .head_tree_oid = &trees.head, 981 .patch_oid = &patch_oid, 982 }; 983 } else null; 984 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 985 }, 986 .patch => |event_maybe| { 987 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 988 .event = event, 989 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 990 .created_order = event_order, 991 .updated_order = event_order, 992 } else null; 993 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 994 }, 995 } 996 } 997 998 // the current object id is now the last one 999 last_object_id_maybe = repo_event_oid; 1000 1001 // prevent any of the data created above from being mutated by future iterations of this loop 1002 try db.freeze(); 1003 } 1004 1005 if (last_object_id_maybe) |*last_object_id| { 1006 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1007 } 1008 1009 return true; 1010 } 1011 1012 // the conflicted records of one kind, keyed by the same order key its id set 1013 // uses, so this doubles as the index the conflicts view lists and counts. every 1014 // value under an entry is a slot reference to a structure that already exists: 1015 // 1016 // <order key> -> conflict entry 1017 // conflicted-fields the conflicting field names, space separated 1018 // base-record the merge base's whole record 1019 // their-record the merged-in side's whole record 1020 // their-field->oid that side's field name to commit map 1021 // 1022 // our own value is the live record and our commit is in the kind's oid map, so 1023 // neither is repeated here. 1024 pub const conflicted_fields_key = "conflicted-fields"; 1025 pub const base_record_key = "base-record"; 1026 pub const their_record_key = "their-record"; 1027 pub const their_field_to_oid_key = "their-field->oid"; 1028 1029 // record the commit against every field this event changes. a merge passes no 1030 // oid, since each field's winner may come from a different side. 1031 pub fn writeOid( 1032 comptime T: type, 1033 comptime DB: type, 1034 comptime hash_kind: hash.HashKind, 1035 id_to_field_to_oid: DB.HashMap(.read_write), 1036 record_key: hash.HashInt(hash_kind), 1037 existing_maybe: ?T, 1038 event: T, 1039 event_oid: ?[]const u8, 1040 ) !void { 1041 const oid = event_oid orelse return; 1042 1043 // created only once a field actually changes 1044 var field_oids: ?DB.SortedMap(.read_write) = null; 1045 1046 inline for (std.meta.fields(T)) |field| { 1047 const changed = if (existing_maybe) |existing| 1048 !fieldEqual(field.type, @field(existing, field.name), @field(event, field.name)) 1049 else 1050 true; 1051 if (changed) { 1052 if (field_oids == null) { 1053 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1054 } 1055 if (field_oids) |map| try map.put(field.name, .{ .bytes = oid }); 1056 } 1057 } 1058 } 1059 1060 // the whole field list, space separated, is the longest it can get 1061 fn conflictedFieldsMaxLen(comptime T: type) usize { 1062 var len: usize = 0; 1063 for (std.meta.fields(T)) |field| len += field.name.len + 1; 1064 return len; 1065 } 1066 1067 pub const MergePolicy = enum { 1068 field_conflicts, 1069 target_wins, 1070 }; 1071 1072 // what a three-way merge did with a field 1073 pub const FieldMerge = enum { 1074 // the target's value stands, because neither side changed it, both made the 1075 // same change, or only the target changed it 1076 kept, 1077 parent, 1078 conflicted, 1079 }; 1080 1081 // three-way merge each field. one only the parent changed takes the parent's 1082 // value; one both sides changed differently keeps the target's. a missing 1083 // baseline makes every differing field a conflict. 1084 fn mergeFields( 1085 comptime T: type, 1086 baseline_maybe: ?T, 1087 target: T, 1088 parent: T, 1089 outcome: *[std.meta.fields(T).len]FieldMerge, 1090 ) T { 1091 var merged = target; 1092 1093 inline for (std.meta.fields(T), 0..) |field, i| { 1094 const target_value = @field(target, field.name); 1095 const parent_value = @field(parent, field.name); 1096 1097 if (!fieldEqual(field.type, target_value, parent_value)) { 1098 outcome[i] = if (baseline_maybe) |baseline| blk: { 1099 const baseline_value = @field(baseline, field.name); 1100 if (fieldEqual(field.type, target_value, baseline_value)) { 1101 @field(merged, field.name) = parent_value; 1102 break :blk .parent; 1103 } 1104 // only the target changed it 1105 if (fieldEqual(field.type, parent_value, baseline_value)) break :blk .kept; 1106 break :blk .conflicted; 1107 } else .conflicted; 1108 } 1109 } 1110 1111 return merged; 1112 } 1113 1114 // three-way merge of one kind's records from a merge parent. kinds that expose 1115 // conflicts merge field by field; the others take one whole record. the result 1116 // goes through the kind's `consume`, which re-derives the indexes from it. a 1117 // removal carries over unless the other side changed the record, so a merge 1118 // never fails. 1119 pub fn merge( 1120 comptime T: type, 1121 comptime DB: type, 1122 comptime hash_kind: hash.HashKind, 1123 allocator: std.mem.Allocator, 1124 haxy_moment: DB.HashMap(.read_write), 1125 parent_moment: DB.HashMap(.read_only), 1126 baseline_moment: DB.HashMap(.read_only), 1127 ) !void { 1128 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1129 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1130 1131 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1132 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1133 1134 var baseline_records: ?DB.HashMap(.read_only) = null; 1135 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1136 baseline_records = try DB.HashMap(.read_only).init(cursor); 1137 } 1138 1139 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1140 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1141 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1142 switch (comptime T.merge_policy) { 1143 .field_conflicts => { 1144 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1145 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1146 } 1147 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1148 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1149 } 1150 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1151 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1152 } 1153 }, 1154 .target_wins => {}, 1155 } 1156 1157 var arena = std.heap.ArenaAllocator.init(allocator); 1158 defer arena.deinit(); 1159 1160 var iter = try parent_set.iteratorFromIndex(0); 1161 while (try iter.next()) |kv_pair_cursor| { 1162 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1163 const record_key = hash.hashInt(hash_kind, &event_id); 1164 1165 _ = arena.reset(.retain_capacity); 1166 1167 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1168 const parent_slot = parent_record_cursor.slot(); 1169 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1170 1171 // the parent left this record alone 1172 if (baseline_slot) |slot| { 1173 if (slot.eql(parent_slot)) continue; 1174 } 1175 1176 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1177 1178 // re-derived every iteration, since `consume` writes through its own 1179 // handles 1180 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1181 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1182 1183 // a record the target doesn't have arrives wholesale from the parent 1184 var outcome: [std.meta.fields(T).len]FieldMerge = @splat(.parent); 1185 var merged = parent_record; 1186 1187 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1188 // both sides share the change 1189 if (target_record_cursor.slot().eql(parent_slot)) continue; 1190 1191 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1192 1193 var baseline_record: ?T.Record = null; 1194 if (baseline_records) |map| { 1195 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1196 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1197 } 1198 } 1199 1200 switch (comptime T.merge_policy) { 1201 .field_conflicts => { 1202 outcome = @splat(.kept); 1203 merged = target_record; 1204 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1205 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1206 if (comptime @hasDecl(T, "resolveMerge")) { 1207 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1208 } 1209 1210 // merge the removed state separately from serialized fields. removal 1211 // carries over an unchanged record, while an edit or restoration 1212 // keeps it active. 1213 merged.removed = if (target_record.removed == parent_record.removed) 1214 target_record.removed 1215 else if (baseline_record) |baseline| blk: { 1216 const active = if (!target_record.removed) target_record else parent_record; 1217 if (active.removed != baseline.removed) break :blk false; 1218 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1219 break :blk true; 1220 } else false; 1221 }, 1222 .target_wins => { 1223 // an uncontested parent change carries over. if both sides 1224 // changed the record, the target wins as a whole, except that 1225 // an edit or restoration wins over a removal. 1226 const target_changed = if (baseline_slot) |slot| 1227 !target_record_cursor.slot().eql(slot) 1228 else 1229 true; 1230 merged = if (!target_changed) 1231 parent_record 1232 else if (target_record.removed != parent_record.removed) 1233 if (target_record.removed) parent_record else target_record 1234 else 1235 target_record; 1236 }, 1237 } 1238 } 1239 1240 // the index is unique, so a key the target gave to a different record 1241 // leaves this one out rather than stranding that one behind a name it 1242 // no longer owns 1243 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1244 const index_key = try merged.indexKey(arena.allocator()); 1245 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1246 const name_index = try DB.HashMap(.read_write).init(name_index_cursor); 1247 if (try name_index.getCursor(hash.hashInt(hash_kind, index_key))) |owner_cursor| { 1248 var owner_id: [event_id_size]u8 = undefined; 1249 _ = try owner_cursor.readBytes(&owner_id); 1250 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1251 } 1252 } 1253 1254 // `consume` sets no oids, since each field's winner may come from 1255 // a different side 1256 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1257 1258 switch (comptime T.merge_policy) { 1259 .field_conflicts => {}, 1260 .target_wins => continue, 1261 } 1262 1263 // removed records do not carry field conflicts 1264 if (merged.removed) continue; 1265 1266 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1267 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1268 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1269 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1270 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1271 1272 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1273 if (parent_id_to_field_to_oid) |map| { 1274 if (try map.getCursor(record_key)) |field_oids_cursor| { 1275 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1276 } 1277 } 1278 // created only once a field actually comes from the parent 1279 var field_oids: ?DB.SortedMap(.read_write) = null; 1280 1281 // the fields both sides changed differently, space separated 1282 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1283 var conflicted_len: usize = 0; 1284 1285 inline for (std.meta.fields(T), 0..) |field, i| { 1286 switch (outcome[i]) { 1287 // the target's value stands, so its oid does too 1288 .kept => {}, 1289 // the parent set this value, so its commit takes the field. a 1290 // parent with no oid took its own value from a merge, leaving 1291 // the field unattributed rather than crediting the target's 1292 // commit for a value it no longer holds. 1293 .parent => { 1294 if (field_oids == null) { 1295 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1296 } 1297 const map = field_oids orelse unreachable; 1298 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field.name) else null; 1299 if (parent_oid) |oid_cursor| { 1300 try map.put(field.name, .{ .slot = oid_cursor.slot() }); 1301 } else { 1302 _ = try map.remove(field.name); 1303 } 1304 }, 1305 .conflicted => { 1306 if (conflicted_len > 0) { 1307 conflicted_fields[conflicted_len] = ' '; 1308 conflicted_len += 1; 1309 } 1310 @memcpy(conflicted_fields[conflicted_len..][0..field.name.len], field.name); 1311 conflicted_len += field.name.len; 1312 }, 1313 } 1314 } 1315 1316 if (conflicted_len > 0) { 1317 // each side's whole record is stored by reference, so the view can 1318 // show any of them or take theirs wholesale 1319 _ = try conflicts.remove(&merged_key); 1320 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1321 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1322 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1323 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1324 if (parent_field_oids) |map| { 1325 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1326 } 1327 continue; 1328 } 1329 1330 // created_order never changes, so the parent keys this record's conflict 1331 // identically, and it carries over when the target has none, unless the 1332 // parent's entry is unchanged from the baseline, meaning the target 1333 // inherited it too and resolving it removed it here. 1334 if (parent_conflicts) |map| { 1335 if (null == try conflicts.getCursor(&merged_key)) { 1336 if (try map.getSlot(&merged_key)) |conflict_slot| { 1337 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1338 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1339 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1340 } 1341 } 1342 } 1343 } 1344 } 1345 1346 pub fn currentMoment( 1347 comptime repo_opts: rp.RepoOpts(.xit), 1348 repo: *rp.Repo(.xit, repo_opts), 1349 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1350 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1351 } 1352 1353 pub fn currentMomentFromDb( 1354 comptime hash_kind: hash.HashKind, 1355 db: *EventDB(hash_kind), 1356 ) !EventDB(hash_kind).HashMap(.read_only) { 1357 const DB = EventDB(hash_kind); 1358 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1359 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1360 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1361 return try currentMomentFromRepoMoment(hash_kind, moment); 1362 } 1363 1364 pub fn currentMomentFromRepoMoment( 1365 comptime hash_kind: hash.HashKind, 1366 moment: EventDB(hash_kind).HashMap(.read_only), 1367 ) !EventDB(hash_kind).HashMap(.read_only) { 1368 const DB = EventDB(hash_kind); 1369 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1370 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1371 _ = try last_object_id_cursor.readBytes(&last_object_id); 1372 const haxy_cursor = try moment.getCursor(hash.hashInt(hash_kind, materialized_key)) orelse return error.NotFound; 1373 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 1374 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 1375 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1376 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1377 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1378 } 1379 1380 // build a sorted-set key from an order and event id. big-endian order makes 1381 // byte order match numeric order; the event id breaks ties. 1382 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1383 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1384 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1385 @memcpy(key[@sizeOf(u64)..], event_id); 1386 return key; 1387 } 1388 1389 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1390 return orderKey(std.math.maxInt(u64) - order, event_id); 1391 } 1392 1393 pub fn removedRecord( 1394 comptime T: type, 1395 comptime DB: type, 1396 comptime hash_kind: hash.HashKind, 1397 haxy_moment: DB.HashMap(.read_only), 1398 existing_maybe: ?T, 1399 ) !T { 1400 var record = existing_maybe orelse return error.EventNotFound; 1401 record.removed = true; 1402 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1403 record.updated_order = try order_cursor.readUint(); 1404 return record; 1405 } 1406 1407 // add or refresh one entry in the global logical-event index 1408 pub fn indexEvent( 1409 comptime DB: type, 1410 comptime hash_kind: hash.HashKind, 1411 haxy_moment: DB.HashMap(.read_write), 1412 event_id: *const [event_id_size]u8, 1413 kind: EventKind, 1414 existing_maybe: anytype, 1415 record: anytype, 1416 ) !void { 1417 const event_key = hash.hashInt(hash_kind, event_id); 1418 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1419 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1420 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1421 1422 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1423 const active = try DB.SortedSet(.read_write).init(active_cursor); 1424 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1425 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1426 1427 if (existing_maybe) |existing| { 1428 const old_key = orderKeyDesc(existing.updated_order, event_id); 1429 _ = try active.remove(&old_key); 1430 _ = try removed_set.remove(&old_key); 1431 } 1432 1433 const order_key = orderKeyDesc(record.updated_order, event_id); 1434 if (record.removed) { 1435 try removed_set.put(&order_key); 1436 } else { 1437 try active.put(&order_key); 1438 } 1439 } 1440 1441 pub fn touchThread( 1442 comptime DB: type, 1443 comptime hash_kind: hash.HashKind, 1444 haxy_moment: DB.HashMap(.read_write), 1445 thread_id: *const [event_id_size]u8, 1446 order: u64, 1447 arena: *std.heap.ArenaAllocator, 1448 ) !void { 1449 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1450 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1451 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1452 switch (kind) { 1453 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1454 else => {}, 1455 } 1456 } 1457 1458 pub fn readEventKind( 1459 comptime hash_kind: hash.HashKind, 1460 kind_map: anytype, 1461 id: *const [event_id_size]u8, 1462 ) !?EventKind { 1463 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1464 var buffer: [64]u8 = undefined; 1465 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1466 } 1467 1468 // the event id embedded in a set entry's order key 1469 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 1470 var cursor = kv_pair_cursor; 1471 const kv_pair = try cursor.readKeyValuePair(); 1472 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1473 _ = try kv_pair.key_cursor.readBytes(&order_key); 1474 return order_key[@sizeOf(u64)..][0..event_id_size].*; 1475 } 1476 1477 // split a pushed "<owner>/<repo>" path into its two components, or null if it 1478 // isn't exactly two non-empty segments. 1479 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 1480 var it = std.mem.splitScalar(u8, path, '/'); 1481 const owner = it.next() orelse return null; 1482 const name = it.next() orelse return null; 1483 if (it.next() != null) return null; 1484 if (owner.len == 0 or name.len == 0) return null; 1485 1486 return .{ .owner = owner, .name = name }; 1487 } 1488 1489 pub const CreateRepoOptions = struct { 1490 read_access: Repo.Access = .private, 1491 }; 1492 1493 // resolve a pushed `<owner>/<repo>` to the hex event id that names its on-disk 1494 // directory under the repos dir 1495 pub fn resolveOrCreateRepo( 1496 io: std.Io, 1497 allocator: std.mem.Allocator, 1498 admin_repo_path: []const u8, 1499 owner_name: []const u8, 1500 repo_name: []const u8, 1501 create_options_maybe: ?CreateRepoOptions, 1502 ) !?[event_id_size * 2]u8 { 1503 var repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 1504 error.RepoNotFound => return null, 1505 else => |e| return e, 1506 }; 1507 defer repo.deinit(io, allocator); 1508 1509 var arena = std.heap.ArenaAllocator.init(allocator); 1510 defer arena.deinit(); 1511 1512 const moment = try currentMoment(admin_repo_opts, &repo); 1513 1514 // an already-registered repo reuses its event id, so a re-push (or a clone) 1515 // lands in the same repo 1516 if (try Repo.readByOwnerAndName(AdminDB, admin_repo_opts.hash, moment, &arena, owner_name, repo_name)) |found| { 1517 return std.fmt.bytesToHex(found.event_id, .lower); 1518 } 1519 1520 const create_options = create_options_maybe orelse return null; 1521 1522 // the new repo is owned by the named user, read from the name index; an 1523 // unknown owner can't own a repo, so the push is rejected 1524 const name_to_user_id_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, "name->user-id")) orelse return null; 1525 const name_to_user_id = try AdminDB.HashMap(.read_only).init(name_to_user_id_cursor); 1526 const owner_id_cursor = try name_to_user_id.getCursor(hash.hashInt(admin_repo_opts.hash, owner_name)) orelse return null; 1527 var owner_user_id: [event_id_size]u8 = undefined; 1528 _ = try owner_id_cursor.readBytes(&owner_user_id); 1529 1530 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, &owner_user_id)) orelse unreachable; 1531 1532 var id_bytes: [event_id_size]u8 = undefined; 1533 io.random(&id_bytes); 1534 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1535 1536 try consume(.admin, .xit, admin_repo_opts, io, allocator, &repo, events_ref, &[_]EventWithId{.{ 1537 .id = event_id_hex, 1538 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1539 .author = .{ .name = owner.event.name, .email = owner.event.email }, 1540 .event = .{ .repo = .{ 1541 .user_id = &owner_user_id, 1542 .name = repo_name, 1543 .description = "", 1544 .read_access = create_options.read_access, 1545 } }, 1546 }}); 1547 1548 return event_id_hex; 1549 } 1550 1551 // 1552 // reading from xitdb 1553 // 1554 1555 pub fn read( 1556 comptime T: type, 1557 comptime DB: type, 1558 comptime hash_kind: hash.HashKind, 1559 arena: *std.heap.ArenaAllocator, 1560 map: DB.HashMap(.read_only), 1561 ) !T { 1562 var event: T = undefined; 1563 1564 switch (@typeInfo(T)) { 1565 .@"struct" => |struct_info| { 1566 inline for (struct_info.fields) |field| { 1567 switch (@typeInfo(field.type)) { 1568 .pointer => |pointer_info| { 1569 if (pointer_info.size == .slice and pointer_info.child == u8 and pointer_info.is_const) { 1570 @field(event, field.name) = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1571 } else { 1572 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1573 } 1574 }, 1575 .array => |array_info| { 1576 if (array_info.child == u8) { 1577 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1578 if (bytes.len != array_info.len) return error.InvalidByteArrayLength; 1579 @memcpy(@field(event, field.name)[0..], bytes); 1580 } else { 1581 @compileError("unsupported read field type: " ++ @typeName(field.type)); 1582 } 1583 }, 1584 .bool => @field(event, field.name) = try readBool(DB, hash_kind, map, field.name), 1585 .int => |int_info| switch (int_info.signedness) { 1586 .unsigned => @field(event, field.name) = @intCast(try readUint(DB, hash_kind, map, field.name)), 1587 .signed => @field(event, field.name) = @intCast(try readInt(DB, hash_kind, map, field.name)), 1588 }, 1589 .@"enum" => { 1590 const bytes = try readBytes(DB, hash_kind, arena.allocator(), map, field.name); 1591 @field(event, field.name) = std.meta.stringToEnum(field.type, bytes) orelse return error.InvalidEnumTag; 1592 }, 1593 .@"union" => { 1594 if (!@hasDecl(field.type, "decode")) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1595 @field(event, field.name) = try field.type.decode(try readBytes(DB, hash_kind, arena.allocator(), map, field.name)); 1596 }, 1597 .optional => |optional_info| { 1598 // a missing key is null 1599 if (try map.getCursor(hash.hashInt(hash_kind, field.name))) |cursor| { 1600 if (optional_info.child == []const u8) { 1601 @field(event, field.name) = try cursor.readBytesAlloc(arena.allocator(), null); 1602 } else switch (@typeInfo(optional_info.child)) { 1603 .array => |array_info| { 1604 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(field.type)); 1605 var bytes: optional_info.child = undefined; 1606 const value = try cursor.readBytes(&bytes); 1607 if (value.len != bytes.len) return error.InvalidByteArrayLength; 1608 @field(event, field.name) = bytes; 1609 }, 1610 .@"struct" => @field(event, field.name) = try read( 1611 optional_info.child, 1612 DB, 1613 hash_kind, 1614 arena, 1615 try DB.HashMap(.read_only).init(cursor), 1616 ), 1617 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1618 } 1619 } else { 1620 @field(event, field.name) = null; 1621 } 1622 }, 1623 .@"struct" => { 1624 const cursor = try map.getCursor(hash.hashInt(hash_kind, field.name)) orelse return error.NotFound; 1625 @field(event, field.name) = try read( 1626 field.type, 1627 DB, 1628 hash_kind, 1629 arena, 1630 try DB.HashMap(.read_only).init(cursor), 1631 ); 1632 }, 1633 else => @compileError("unsupported read field type: " ++ @typeName(field.type)), 1634 } 1635 } 1636 }, 1637 else => @compileError("read expects a struct"), 1638 } 1639 1640 return event; 1641 } 1642 1643 // whether two events carry the same data 1644 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 1645 switch (@typeInfo(T)) { 1646 .@"struct" => |struct_info| { 1647 inline for (struct_info.fields) |field| { 1648 if (!fieldEqual(field.type, @field(a, field.name), @field(b, field.name))) return false; 1649 } 1650 }, 1651 else => @compileError("fieldsEqual expects a struct"), 1652 } 1653 1654 return true; 1655 } 1656 1657 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 1658 switch (@typeInfo(Field)) { 1659 .pointer => |pointer_info| { 1660 if (pointer_info.size == .slice and pointer_info.child == u8) { 1661 return std.mem.eql(u8, a, b); 1662 } else { 1663 @compileError("unsupported field type: " ++ @typeName(Field)); 1664 } 1665 }, 1666 .array => |array_info| { 1667 if (array_info.child == u8) { 1668 return std.mem.eql(u8, &a, &b); 1669 } else { 1670 @compileError("unsupported field type: " ++ @typeName(Field)); 1671 } 1672 }, 1673 .void => return true, 1674 .bool, .int, .@"enum" => return a == b, 1675 .@"union" => { 1676 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 1677 return switch (a) { 1678 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 1679 }; 1680 }, 1681 .@"struct" => return fieldsEqual(Field, a, b), 1682 .optional => |optional_info| { 1683 if (a) |a_value| { 1684 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 1685 return false; 1686 } 1687 return b == null; 1688 }, 1689 else => @compileError("unsupported field type: " ++ @typeName(Field)), 1690 } 1691 } 1692 1693 fn readBytes( 1694 comptime DB: type, 1695 comptime hash_kind: hash.HashKind, 1696 allocator: std.mem.Allocator, 1697 map: DB.HashMap(.read_only), 1698 field_name: []const u8, 1699 ) ![]const u8 { 1700 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1701 return try cursor.readBytesAlloc(allocator, null); 1702 } 1703 1704 fn readUint( 1705 comptime DB: type, 1706 comptime hash_kind: hash.HashKind, 1707 map: DB.HashMap(.read_only), 1708 field_name: []const u8, 1709 ) !u64 { 1710 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1711 return try cursor.readUint(); 1712 } 1713 1714 fn readInt( 1715 comptime DB: type, 1716 comptime hash_kind: hash.HashKind, 1717 map: DB.HashMap(.read_only), 1718 field_name: []const u8, 1719 ) !i64 { 1720 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1721 return try cursor.readInt(); 1722 } 1723 1724 fn readBool( 1725 comptime DB: type, 1726 comptime hash_kind: hash.HashKind, 1727 map: DB.HashMap(.read_only), 1728 field_name: []const u8, 1729 ) !bool { 1730 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)) orelse return error.NotFound; 1731 var buffer: [5]u8 = undefined; 1732 const bytes = try cursor.readBytesObject(&buffer); 1733 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 1734 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 1735 if (std.mem.eql(u8, bytes.value, "true")) return true; 1736 if (std.mem.eql(u8, bytes.value, "false")) return false; 1737 return error.InvalidBool; 1738 } 1739 1740 // 1741 // writing to xitdb 1742 // 1743 1744 pub fn upsert( 1745 comptime T: type, 1746 comptime DB: type, 1747 comptime hash_kind: hash.HashKind, 1748 map: DB.HashMap(.read_write), 1749 event: T, 1750 ) !void { 1751 switch (@typeInfo(T)) { 1752 .@"struct" => |struct_info| { 1753 inline for (struct_info.fields) |field| { 1754 try upsertField(DB, hash_kind, map, field.name, field.type, @field(event, field.name)); 1755 } 1756 }, 1757 else => @compileError("upsert expects a struct"), 1758 } 1759 } 1760 1761 fn upsertField( 1762 comptime DB: type, 1763 comptime hash_kind: hash.HashKind, 1764 map: DB.HashMap(.read_write), 1765 comptime field_name: []const u8, 1766 comptime Field: type, 1767 value: Field, 1768 ) !void { 1769 const key = hash.hashInt(hash_kind, field_name); 1770 1771 switch (@typeInfo(Field)) { 1772 .pointer => |pointer_info| { 1773 if (pointer_info.size == .slice and pointer_info.child == u8) { 1774 try upsertBytes(DB, hash_kind, map, key, value); 1775 } else { 1776 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1777 } 1778 }, 1779 .array => |array_info| { 1780 if (array_info.child == u8) { 1781 try upsertBytes(DB, hash_kind, map, key, &value); 1782 } else { 1783 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1784 } 1785 }, 1786 .int => |int_info| switch (int_info.signedness) { 1787 .unsigned => { 1788 if (try map.getCursor(key)) |value_cursor| { 1789 if (try value_cursor.readUint() == value) { 1790 return; 1791 } 1792 } 1793 1794 try map.put(key, .{ .uint = value }); 1795 }, 1796 .signed => { 1797 if (try map.getCursor(key)) |value_cursor| { 1798 if (try value_cursor.readInt() == value) { 1799 return; 1800 } 1801 } 1802 1803 try map.put(key, .{ .int = value }); 1804 }, 1805 }, 1806 .bool => { 1807 const bytes = if (value) "true" else "false"; 1808 if (try map.getCursor(key)) |value_cursor| { 1809 var buffer: [5]u8 = undefined; 1810 const existing = try value_cursor.readBytesObject(&buffer); 1811 if (existing.format_tag) |format_tag| { 1812 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 1813 return; 1814 } 1815 } 1816 } 1817 1818 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 1819 }, 1820 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 1821 .@"union" => { 1822 if (!@hasDecl(Field, "encode") or !@hasDecl(Field, "max_encoded_len")) { 1823 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1824 } 1825 var buffer: [Field.max_encoded_len]u8 = undefined; 1826 try upsertBytes(DB, hash_kind, map, key, try value.encode(&buffer)); 1827 }, 1828 .optional => |optional_info| { 1829 // a missing key is null 1830 if (value) |child| { 1831 if (optional_info.child == []const u8) { 1832 try upsertBytes(DB, hash_kind, map, key, child); 1833 } else switch (@typeInfo(optional_info.child)) { 1834 .array => |array_info| { 1835 if (array_info.child != u8) @compileError("unsupported upsert field type: " ++ @typeName(Field)); 1836 try upsertBytes(DB, hash_kind, map, key, &child); 1837 }, 1838 .@"struct" => try upsert( 1839 optional_info.child, 1840 DB, 1841 hash_kind, 1842 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1843 child, 1844 ), 1845 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1846 } 1847 } else { 1848 _ = try map.remove(key); 1849 } 1850 }, 1851 .@"struct" => try upsert( 1852 Field, 1853 DB, 1854 hash_kind, 1855 try DB.HashMap(.read_write).init(try map.putCursor(key)), 1856 value, 1857 ), 1858 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 1859 } 1860 } 1861 1862 fn upsertBytes( 1863 comptime DB: type, 1864 comptime hash_kind: hash.HashKind, 1865 map: DB.HashMap(.read_write), 1866 key: hash.HashInt(hash_kind), 1867 value: []const u8, 1868 ) !void { 1869 var existing_cursor_maybe = try map.getCursor(key); 1870 if (existing_cursor_maybe) |*existing_cursor| { 1871 if (try bytesEqual(DB, existing_cursor, value)) { 1872 return; 1873 } 1874 } 1875 1876 var value_cursor = try map.putCursor(key); 1877 var write_buffer: [1024]u8 = undefined; 1878 var writer = try value_cursor.writer(&write_buffer); 1879 try writer.interface.writeAll(value); 1880 try writer.finish(); 1881 } 1882 1883 fn bytesEqual( 1884 comptime DB: type, 1885 cursor: *DB.Cursor(.read_only), 1886 value: []const u8, 1887 ) !bool { 1888 var read_buffer: [1024]u8 = undefined; 1889 var reader = try cursor.reader(&read_buffer); 1890 if (reader.size != value.len) { 1891 return false; 1892 } 1893 1894 var chunk_buffer: [1024]u8 = undefined; 1895 var offset: usize = 0; 1896 while (offset < value.len) { 1897 const chunk_len = @min(chunk_buffer.len, value.len - offset); 1898 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 1899 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 1900 return false; 1901 } 1902 offset += chunk_len; 1903 } 1904 1905 return true; 1906 } 1907 1908 // 1909 // CommitIterator 1910 // 1911 // differs from xit's ObjectIterator in a few ways: 1912 // 1913 // 1. iterates parents first, rather than children first 1914 // 2. `next` only returns the object id, not the full Object 1915 // 3. stores its temporary state in a file on disk to avoid OOMs 1916 // 1917 1918 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 1919 return struct { 1920 const DB = EventDB(repo_opts.hash); 1921 const db_name = "haxy-repo-events.db"; 1922 1923 repo_dir: std.Io.Dir, 1924 db_file: std.Io.File, 1925 db: *DB, 1926 // map of each object id to its children 1927 parent_to_children: DB.HashMap(.read_write), 1928 // tracking pending parents is necessary because a child can only 1929 // be returned after all of its unconsumed parents have been returned 1930 child_to_pending_parents: DB.HashMap(.read_write), 1931 // queue of object ids that are ready to be returned from `next` 1932 ready_queue: DB.ArrayList(.read_write), 1933 ready_queue_index: u64, 1934 // the object id at the tip of this branch 1935 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1936 // the object id furthest back in the history that hasn't been consumed 1937 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 1938 1939 pub fn init( 1940 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 1941 io: std.Io, 1942 allocator: std.mem.Allocator, 1943 consumed_object_ids: DB.HashMap(.read_only), 1944 ref: rf.Ref, 1945 ) !CommitIterator(repo_kind, repo_opts) { 1946 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 1947 errdefer { 1948 db_file.close(io); 1949 state.core.repo_dir.deleteFile(io, db_name) catch {}; 1950 } 1951 1952 const buffer_ptr = try allocator.create(std.Io.Writer.Allocating); 1953 errdefer allocator.destroy(buffer_ptr); 1954 1955 buffer_ptr.* = std.Io.Writer.Allocating.init(allocator); 1956 errdefer buffer_ptr.deinit(); 1957 1958 const db_ptr = try allocator.create(DB); 1959 errdefer allocator.destroy(db_ptr); 1960 // the db is scratch state that gets deleted after iteration, so 1961 // there is nothing worth fsyncing 1962 db_ptr.* = try DB.init(.{ .io = io, .file = db_file, .buffer = buffer_ptr, .fsync = false }); 1963 1964 const map = try DB.HashMap(.read_write).init(db_ptr.rootCursor()); 1965 1966 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 1967 const parent_to_children = try DB.HashMap(.read_write).init(parent_to_children_cursor); 1968 1969 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 1970 const child_to_pending_parents = try DB.HashMap(.read_write).init(child_to_pending_parents_cursor); 1971 1972 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 1973 const ready_queue = try DB.ArrayList(.read_write).init(ready_queue_cursor); 1974 1975 var self = CommitIterator(repo_kind, repo_opts){ 1976 .repo_dir = state.core.repo_dir, 1977 .db_file = db_file, 1978 .db = db_ptr, 1979 .parent_to_children = parent_to_children, 1980 .child_to_pending_parents = child_to_pending_parents, 1981 .ready_queue = ready_queue, 1982 .ready_queue_index = 0, 1983 .newest_object_id = null, 1984 .oldest_object_id = null, 1985 }; 1986 errdefer self.deinit(io, allocator); 1987 1988 try self.collect(state, io, allocator, consumed_object_ids, ref); 1989 1990 return self; 1991 } 1992 1993 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 1994 self.db_file.close(io); 1995 self.db.core.memory.buffer.deinit(); 1996 allocator.destroy(self.db.core.memory.buffer); 1997 self.repo_dir.deleteFile(io, db_name) catch {}; 1998 allocator.destroy(self.db); 1999 } 2000 2001 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2002 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2003 2004 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2005 self.ready_queue_index += 1; 2006 2007 try self.enqueueChildren(&oid); 2008 return oid; 2009 } 2010 2011 fn collect( 2012 self: *CommitIterator(repo_kind, repo_opts), 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 ) !void { 2019 const map = try DB.HashMap(.read_write).init(self.db.rootCursor()); 2020 2021 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2022 const walk_queue = try DB.ArrayList(.read_write).init(walk_queue_cursor); 2023 var walk_queue_index: u64 = 0; 2024 2025 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2026 const seen_object_ids = try DB.HashSet(.read_write).init(seen_object_ids_cursor); 2027 2028 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2029 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2030 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2031 try walk_queue.append(.{ .bytes = &head_oid }); 2032 2033 while (walk_queue_index < try walk_queue.count()) { 2034 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2035 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2036 2037 walk_queue_index += 1; 2038 2039 // if we've seen this object id, skip it 2040 if (null != try seen_object_ids.getCursor(oid_int)) { 2041 continue; 2042 } 2043 2044 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2045 2046 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2047 defer commit_object.deinit(); 2048 2049 // if this object id has already been consumed, skip it 2050 if (null != try consumed_object_ids.getCursor(oid_int)) { 2051 continue; 2052 } 2053 2054 if (self.newest_object_id == null) self.newest_object_id = oid; 2055 self.oldest_object_id = oid; 2056 2057 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2058 var pending_parent_count: u64 = 0; 2059 for (parent_oids) |*parent_oid| { 2060 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2061 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2062 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2063 2064 // if this object id has already been consumed, skip it 2065 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2066 continue; 2067 } 2068 2069 // if this object id hasn't already been seen, add it to the walk queue 2070 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2071 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2072 } 2073 2074 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 2075 const children = try DB.HashSet(.read_write).init(children_cursor); 2076 try children.put(oid_int, .{ .bytes = &oid }); 2077 pending_parent_count += 1; 2078 } 2079 2080 if (pending_parent_count == 0) { 2081 try self.ready_queue.append(.{ .bytes = &oid }); 2082 } else { 2083 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 2084 } 2085 } 2086 } 2087 2088 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 2089 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 2090 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 2091 const children = try DB.HashSet(.read_only).init(children_cursor); 2092 var children_iter = try children.iterator(); 2093 2094 while (try children_iter.next()) |*child_cursor| { 2095 const kv_pair = try child_cursor.readKeyValuePair(); 2096 const child_oid_int = kv_pair.hash; 2097 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 2098 const pending_parent_count = try pending_parent_cursor.readUint(); 2099 2100 if (pending_parent_count <= 1) { 2101 _ = try self.child_to_pending_parents.remove(child_oid_int); 2102 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 2103 try self.ready_queue.append(.{ .bytes = &child_oid }); 2104 } else { 2105 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 2106 } 2107 } 2108 } 2109 2110 fn readOidFromList(list: DB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 2111 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 2112 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2113 _ = try oid_cursor.readBytes(&oid); 2114 return oid; 2115 } 2116 }; 2117 } 2118