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