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