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