╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
67 return try std.Io.Dir.path.join(allocator, &.{ users_dir, &std.fmt.bytesToHex(user_id.*, .lower), "user" }); 68 } 69 70 // a repo's path, inside its owner's dir 71 pub fn repoPath(allocator: std.mem.Allocator, users_dir: []const u8, owner_id: *const [event_id_size]u8, repo_id: *const [event_id_size]u8) ![]u8 { 72 return try std.Io.Dir.path.join(allocator, &.{ users_dir, &std.fmt.bytesToHex(owner_id.*, .lower), "repos", &std.fmt.bytesToHex(repo_id.*, .lower) }); 73 } 74 75 // the ids a repo path names, or null for a path `repoPath` didn't build 76 pub fn parseRepoPath(users_dir: []const u8, path: []const u8) ?RepoLocation { 77 const repos_dir = std.Io.Dir.path.dirname(path) orelse return null; 78 if (!std.mem.eql(u8, std.Io.Dir.path.basename(repos_dir), "repos")) return null; 79 const owner_dir = std.Io.Dir.path.dirname(repos_dir) orelse return null; 80 if (!std.mem.eql(u8, std.Io.Dir.path.dirname(owner_dir) orelse return null, users_dir)) return null; 81 return .{ 82 .owner_id = parseEventId(std.Io.Dir.path.basename(owner_dir)) catch return null, 83 .repo_id = parseEventId(std.Io.Dir.path.basename(path)) catch return null, 84 }; 85 } 86 87 // the owner's repos newest activity first, as order keys 88 pub const recent_repo_id_set_key = "haxy/recent-repo-id-set"; 89 // each repo's activity time in that set 90 const repo_activity_time_key = "haxy/repo-id->activity-time"; 91 92 // a repo's activity time is rewritten at most once per window 93 pub const repo_activity_window_secs = 5 * 60; 94 95 // move a repo to `timestamp` in its owner's activity index, unless it moved within the window 96 pub fn bumpRepoActivity( 97 io: std.Io, 98 allocator: std.mem.Allocator, 99 users_dir: []const u8, 100 owner_id: *const [event_id_size]u8, 101 repo_id: *const [event_id_size]u8, 102 timestamp: u64, 103 ) !void { 104 const hash_kind = user_repo_opts.hash; 105 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return; 106 defer user_repo.deinit(io, allocator); 107 108 // a recent bump skips the transaction 109 if (try readActivityTime(try user_repo.core.latestMoment(), repo_id)) |time| { 110 if (timestamp -| time < repo_activity_window_secs) return; 111 } 112 113 const Ctx = struct { 114 repo_id: *const [event_id_size]u8, 115 timestamp: u64, 116 117 pub fn run(ctx: @This(), cursor: *UserDB.Cursor(.read_write)) !void { 118 const moment = try UserDB.HashMap(.read_write).init(cursor.*); 119 // reread so a concurrent bump can't leave its key behind 120 const old_time = try readActivityTime(moment.readOnly(), ctx.repo_id); 121 if (old_time) |time| { 122 if (ctx.timestamp -| time < repo_activity_window_secs) return error.CancelTransaction; 123 } 124 const recent = try UserDB.SortedSet(.read_write).init(try moment.putCursor(hash.hashInt(hash_kind, recent_repo_id_set_key))); 125 if (old_time) |time| _ = try recent.remove(&orderKeyDesc(time, ctx.repo_id)); 126 try recent.put(&orderKeyDesc(ctx.timestamp, ctx.repo_id)); 127 const times = try UserDB.HashMap(.read_write).init(try moment.putCursor(hash.hashInt(hash_kind, repo_activity_time_key))); 128 try times.put(hash.hashInt(hash_kind, ctx.repo_id), .{ .uint = ctx.timestamp }); 129 } 130 }; 131 132 try user_repo.core.db_file.lock(io, .exclusive); 133 defer user_repo.core.db_file.unlock(io); 134 135 const history = try UserDB.ArrayList(.read_write).init(user_repo.core.db.rootCursor()); 136 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ .repo_id = repo_id, .timestamp = timestamp }) catch |err| switch (err) { 137 error.CancelTransaction => {}, 138 else => |e| return e, 139 }; 140 } 141 142 // bump the repo at `repo_path` to now, logging rather than returning a failure 143 pub fn bumpRepoActivityAt(io: std.Io, allocator: std.mem.Allocator, server: Host.Server, repo_path: []const u8) void { 144 const location = parseRepoPath(server.users_dir, repo_path) orelse return; 145 const now: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 146 bumpRepoActivity(io, allocator, server.users_dir, &location.owner_id, &location.repo_id, now) catch |err| { 147 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 148 }; 149 } 150 151 fn readActivityTime(moment: UserDB.HashMap(.read_only), repo_id: *const [event_id_size]u8) !?u64 { 152 const times_cursor = try moment.getCursor(hash.hashInt(user_repo_opts.hash, repo_activity_time_key)) orelse return null; 153 const times = try UserDB.HashMap(.read_only).init(times_cursor); 154 const time_cursor = try times.getCursor(hash.hashInt(user_repo_opts.hash, repo_id)) orelse return null; 155 return try time_cursor.readUint(); 156 } 157 158 // the account each ssh key last logged into with a password, which the key 159 // logs into from then on. this instance's own state, so it lives outside the 160 // events, in the admin repo. 161 const login_key_to_user_id_key = "haxy/login-key->user-id"; 162 163 pub const LoginKeyChange = enum { trust, forget }; 164 165 // let the key with `fingerprint` log `user_id` in, or stop it doing so 166 pub fn setLoginKey( 167 io: std.Io, 168 admin_repo: *rp.Repo(.xit, admin_repo_opts), 169 fingerprint: *const [User.fingerprint_len]u8, 170 user_id: *const [event_id_size]u8, 171 change: LoginKeyChange, 172 ) !void { 173 const hash_kind = admin_repo_opts.hash; 174 const Ctx = struct { 175 fingerprint: *const [User.fingerprint_len]u8, 176 user_id: *const [event_id_size]u8, 177 change: LoginKeyChange, 178 179 pub fn run(ctx: @This(), cursor: *AdminDB.Cursor(.read_write)) !void { 180 const moment = try AdminDB.HashMap(.read_write).init(cursor.*); 181 const keys = try AdminDB.HashMap(.read_write).init(try moment.putCursor(hash.hashInt(hash_kind, login_key_to_user_id_key))); 182 const key = hash.hashInt(hash_kind, ctx.fingerprint); 183 switch (ctx.change) { 184 .trust => try keys.put(key, .{ .bytes = ctx.user_id }), 185 // a later login to another account keeps its trust 186 .forget => { 187 const trusted_cursor = try keys.getCursor(key) orelse return error.CancelTransaction; 188 var trusted_id: [event_id_size]u8 = undefined; 189 _ = try trusted_cursor.readBytes(&trusted_id); 190 if (!std.mem.eql(u8, &trusted_id, ctx.user_id)) return error.CancelTransaction; 191 _ = try keys.remove(key); 192 }, 193 } 194 } 195 }; 196 197 try admin_repo.core.db_file.lock(io, .exclusive); 198 defer admin_repo.core.db_file.unlock(io); 199 200 const history = try AdminDB.ArrayList(.read_write).init(admin_repo.core.db.rootCursor()); 201 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ .fingerprint = fingerprint, .user_id = user_id, .change = change }) catch |err| switch (err) { 202 error.CancelTransaction => {}, 203 else => |e| return e, 204 }; 205 } 206 207 // the account the key with `fingerprint` logs into, from the admin repo's moment 208 pub fn readLoginKeyUser(moment: AdminDB.HashMap(.read_only), fingerprint: *const [User.fingerprint_len]u8) !?[event_id_size]u8 { 209 const keys_cursor = try moment.getCursor(hash.hashInt(admin_repo_opts.hash, login_key_to_user_id_key)) orelse return null; 210 const keys = try AdminDB.HashMap(.read_only).init(keys_cursor); 211 const user_id_cursor = try keys.getCursor(hash.hashInt(admin_repo_opts.hash, fingerprint)) orelse return null; 212 var user_id: [event_id_size]u8 = undefined; 213 _ = try user_id_cursor.readBytes(&user_id); 214 return user_id; 215 } 216 217 // open a user's repo, or null when it's missing 218 pub fn openUserRepo(io: std.Io, allocator: std.mem.Allocator, users_dir: []const u8, user_id: *const [event_id_size]u8) !?rp.Repo(.xit, user_repo_opts) { 219 const path = try userRepoPath(allocator, users_dir, user_id); 220 defer allocator.free(path); 221 return rp.Repo(.xit, user_repo_opts).open(io, allocator, .{ .path = path, .require_repo_root = true }) catch |err| switch (err) { 222 error.RepoNotFound, error.FileNotFound => null, 223 else => |e| e, 224 }; 225 } 226 227 // a user repo's moment, or null before its first event 228 pub fn userMoment(repo: *rp.Repo(.xit, user_repo_opts)) !?UserDB.HashMap(.read_only) { 229 return currentMoment(user_repo_opts, repo) catch |err| switch (err) { 230 error.NotFound => null, 231 else => |e| e, 232 }; 233 } 234 235 // read a repo by its owner's name and its name, from the owner's user repo, 236 // with the role `viewer_id` holds in it. a null viewer is logged out. 237 pub fn readRepoByOwnerAndName( 238 io: std.Io, 239 allocator: std.mem.Allocator, 240 arena: *std.heap.ArenaAllocator, 241 admin_moment: AdminDB.HashMap(.read_only), 242 users_dir: []const u8, 243 owner_name: []const u8, 244 repo_name: []const u8, 245 viewer_id: ?[event_id_size]u8, 246 ) !?Repo.RepoWithRole { 247 const owner_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 248 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_id)) orelse return null; 249 defer user_repo.deinit(io, allocator); 250 const moment = (try userMoment(&user_repo)) orelse return null; 251 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, arena, repo_name)) orelse return null; 252 return .{ 253 .repo = found.repo, 254 .event_id = found.event_id, 255 .role = try Repo.roleOf(UserDB, user_repo_opts.hash, moment, arena, found.repo, &found.event_id, viewer_id), 256 }; 257 } 258 259 // read a repo by its owner's id and its id, from the owner's user repo, with 260 // the role `viewer_id` holds in it. a null viewer is logged out. 261 pub fn readRepoById( 262 io: std.Io, 263 allocator: std.mem.Allocator, 264 arena: *std.heap.ArenaAllocator, 265 users_dir: []const u8, 266 owner_id: *const [event_id_size]u8, 267 repo_id: *const [event_id_size]u8, 268 viewer_id: ?[event_id_size]u8, 269 ) !?Repo.RepoWithRole { 270 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return null; 271 defer user_repo.deinit(io, allocator); 272 const moment = (try userMoment(&user_repo)) orelse return null; 273 const repo = (try Repo.readById(UserDB, user_repo_opts.hash, moment, arena, repo_id)) orelse return null; 274 return .{ 275 .repo = repo, 276 .event_id = repo_id.*, 277 .role = try Repo.roleOf(UserDB, user_repo_opts.hash, moment, arena, repo, repo_id, viewer_id), 278 }; 279 } 280 281 // a repo's active grants, from its owner's user repo 282 pub fn readRepoGrants( 283 io: std.Io, 284 allocator: std.mem.Allocator, 285 arena: *std.heap.ArenaAllocator, 286 users_dir: []const u8, 287 owner_id: *const [event_id_size]u8, 288 repo_id: *const [event_id_size]u8, 289 ) ![]const Grant { 290 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return &.{}; 291 defer user_repo.deinit(io, allocator); 292 const moment = (try userMoment(&user_repo)) orelse return &.{}; 293 return try Grant.readByTarget(UserDB, user_repo_opts.hash, moment, arena, repo_id); 294 } 295 296 // read a fork by its forker's id and its id, from the forker's user repo 297 pub fn readForkById( 298 io: std.Io, 299 allocator: std.mem.Allocator, 300 arena: *std.heap.ArenaAllocator, 301 users_dir: []const u8, 302 forker_id: *const [event_id_size]u8, 303 fork_id: *const [event_id_size]u8, 304 ) !?Fork.Record { 305 var user_repo = (try openUserRepo(io, allocator, users_dir, forker_id)) orelse return null; 306 defer user_repo.deinit(io, allocator); 307 const moment = (try userMoment(&user_repo)) orelse return null; 308 return try Fork.readById(UserDB, user_repo_opts.hash, moment, arena, fork_id); 309 } 310 311 // the xitdb type events are stored in. it only depends on the hash kind, so 312 // this matches the db of any xit repo using that hash kind. 313 pub fn EventDB(comptime hash_kind: hash.HashKind) type { 314 return rp.Repo(.xit, .{ .hash = hash_kind }).DB; 315 } 316 317 // the email between a commit author line's angle brackets, or null 318 pub fn authorEmail(author_line: []const u8) ?[]const u8 { 319 const open_bracket = std.mem.indexOfScalar(u8, author_line, '<') orelse return null; 320 const close_bracket = std.mem.indexOfScalarPos(u8, author_line, open_bracket + 1, '>') orelse return null; 321 return author_line[open_bracket + 1 .. close_bracket]; 322 } 323 324 // build a `T` by copying its fields, by name, out of `source` 325 pub fn project(comptime T: type, source: anytype) T { 326 var result: T = undefined; 327 inline for (@typeInfo(T).@"struct".field_names) |name| { 328 @field(result, name) = @field(source, name); 329 } 330 return result; 331 } 332 333 pub const EventKind = enum { 334 user, 335 repo, 336 fork, 337 grant, 338 notify, 339 discuss, 340 issue, 341 comment, 342 attach, 343 assign, 344 patchrev, 345 patch, 346 }; 347 348 pub const RepoRole = enum { 349 admin, 350 user, 351 repo, 352 fork, 353 354 fn allows(self: RepoRole, kind: EventKind) bool { 355 return switch (self) { 356 .admin => kind == .user, 357 .user => switch (kind) { 358 .repo, .fork, .grant, .notify => true, 359 else => false, 360 }, 361 .repo => switch (kind) { 362 .discuss, .issue, .comment, .attach, .assign, .patchrev, .patch => true, 363 else => false, 364 }, 365 .fork => switch (kind) { 366 .patchrev, .patch => true, 367 else => false, 368 }, 369 }; 370 } 371 }; 372 373 // every logical event's kind and update-ordered active/removed id sets 374 pub const event_index_key = "event-id->kind"; 375 pub const active_event_id_set_key = "active-event-id-set"; 376 pub const removed_event_id_set_key = "removed-event-id-set"; 377 const event_order_key = "event-order"; 378 379 pub fn titleValid(title: []const u8) bool { 380 return std.mem.trim(u8, title, " \t\r\n").len != 0; 381 } 382 383 // a null payload removes the record 384 pub const Event = union(EventKind) { 385 user: ?User, 386 repo: ?Repo, 387 fork: ?Fork, 388 grant: ?Grant, 389 notify: ?Notify, 390 discuss: ?Discussion, 391 issue: ?Issue, 392 comment: ?Comment, 393 attach: ?Attachment, 394 assign: ?Assignment, 395 patchrev: ?PatchRev, 396 patch: ?Patch, 397 }; 398 399 // a file committed alongside its event 400 pub const Blob = struct { 401 name: []const u8, 402 size: u64, 403 reader: *std.Io.Reader, 404 }; 405 406 // an entry in the fresh tree carried by one event commit 407 pub const EventTreeEntry = union(enum) { 408 blob: Blob, 409 tree: struct { 410 name: []const u8, 411 oid: []const u8, 412 }, 413 }; 414 415 pub const HostKind = enum { 416 local, 417 server, 418 }; 419 420 // where events are written, with the context only a server has 421 pub const Host = union(HostKind) { 422 local, 423 server: Server, 424 425 pub const Server = struct { 426 users_dir: []const u8, 427 // where repo writes resolve their participants and recipients, null where they notify nobody 428 admin_repo_path: ?[]const u8 = null, 429 }; 430 }; 431 432 // who a commit is attributed to 433 pub const CommitAuthor = struct { 434 name: []const u8, 435 email: []const u8, 436 }; 437 438 pub const event_id_size: usize = 16; 439 440 pub fn parseEventId(id: []const u8) ![event_id_size]u8 { 441 var bytes: [event_id_size]u8 = undefined; 442 _ = try std.fmt.hexToBytes(&bytes, id); 443 if (!std.mem.eql(u8, id, &std.fmt.bytesToHex(bytes, .lower))) return error.InvalidEventId; 444 return bytes; 445 } 446 447 pub const EventWithId = struct { 448 id: [event_id_size * 2]u8, 449 event: Event, 450 timestamp: u64 = 0, // not serialized, because it comes from the commit timestamp 451 author: CommitAuthor, // not serialized, because it goes in the commit author line 452 tree_entries: []const EventTreeEntry = &.{}, // not serialized, because they go in the commit tree 453 454 pub fn jsonStringify(self: EventWithId, jw: anytype) !void { 455 try jw.beginObject(); 456 try jw.objectField("id"); 457 try jw.write(self.id); 458 try jw.objectField("kind"); 459 try jw.write(@tagName(self.event)); 460 try jw.objectField("data"); 461 switch (self.event) { 462 inline else => |event_maybe| try jw.write(event_maybe), 463 } 464 try jw.endObject(); 465 } 466 467 fn fromString(arena: *std.heap.ArenaAllocator, message: []const u8) !EventWithId { 468 const JsonEvent = struct { 469 id: [event_id_size * 2]u8, 470 kind: EventKind, 471 data: ?std.json.Value = null, 472 }; 473 const json_event = try std.json.parseFromSliceLeaky(JsonEvent, arena.allocator(), message, .{ .ignore_unknown_fields = true }); 474 return .{ 475 .id = json_event.id, 476 // unused when reading; the author lives in the commit 477 .author = .{ .name = "", .email = "" }, 478 .event = switch (json_event.kind) { 479 .user => .{ 480 .user = if (json_event.data) |value| 481 try std.json.parseFromValueLeaky(User, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 482 else 483 null, 484 }, 485 .repo => .{ 486 .repo = if (json_event.data) |value| 487 try std.json.parseFromValueLeaky(Repo, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 488 else 489 null, 490 }, 491 .fork => .{ 492 .fork = if (json_event.data) |value| 493 try std.json.parseFromValueLeaky(Fork, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 494 else 495 null, 496 }, 497 .grant => .{ 498 .grant = if (json_event.data) |value| 499 try std.json.parseFromValueLeaky(Grant, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 500 else 501 null, 502 }, 503 .notify => .{ 504 .notify = if (json_event.data) |value| 505 try std.json.parseFromValueLeaky(Notify, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 506 else 507 null, 508 }, 509 .discuss => .{ 510 .discuss = if (json_event.data) |value| 511 try std.json.parseFromValueLeaky(Discussion, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 512 else 513 null, 514 }, 515 .issue => .{ 516 .issue = if (json_event.data) |value| 517 try std.json.parseFromValueLeaky(Issue, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 518 else 519 null, 520 }, 521 .comment => .{ 522 .comment = if (json_event.data) |value| 523 try std.json.parseFromValueLeaky(Comment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 524 else 525 null, 526 }, 527 .attach => .{ 528 .attach = if (json_event.data) |value| 529 try std.json.parseFromValueLeaky(Attachment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 530 else 531 null, 532 }, 533 .assign => .{ 534 .assign = if (json_event.data) |value| 535 try std.json.parseFromValueLeaky(Assignment, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 536 else 537 null, 538 }, 539 .patch => .{ 540 .patch = if (json_event.data) |value| 541 try std.json.parseFromValueLeaky(Patch, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 542 else 543 null, 544 }, 545 .patchrev => .{ 546 .patchrev = if (json_event.data) |value| 547 try std.json.parseFromValueLeaky(PatchRev, arena.allocator(), value, .{ .ignore_unknown_fields = true }) 548 else 549 null, 550 }, 551 }, 552 }; 553 } 554 555 pub fn randomId(random: std.Random) [event_id_size]u8 { 556 var id_bytes: [event_id_size]u8 = undefined; 557 random.bytes(&id_bytes); 558 return id_bytes; 559 } 560 }; 561 562 // remove an event by emitting a null payload 563 pub fn remove( 564 host: Host, 565 comptime role: RepoRole, 566 comptime repo_kind: rp.RepoKind, 567 comptime repo_opts: rp.RepoOpts(repo_kind), 568 io: std.Io, 569 allocator: std.mem.Allocator, 570 repo: *rp.Repo(repo_kind, repo_opts), 571 id: *const [event_id_size]u8, 572 kind: EventKind, 573 author: CommitAuthor, 574 ) !void { 575 const DB = EventDB(repo_opts.hash); 576 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; 577 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 578 const moment = (if (event_db_maybe) |*event_db| 579 currentMomentFromDb(repo_opts.hash, event_db.db) 580 else if (repo_kind == .git) 581 return error.EventNotFound 582 else 583 currentMoment(repo_opts, repo)) catch return error.EventNotFound; 584 const kind_map_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return error.EventNotFound; 585 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 586 const stored_kind = (try readEventKind(repo_opts.hash, kind_map, id)) orelse return error.EventNotFound; 587 if (stored_kind != kind) return error.EventNotFound; 588 if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 589 event_db_maybe = null; 590 591 const event: Event = switch (kind) { 592 .user => .{ .user = null }, 593 .repo => .{ .repo = null }, 594 .fork => .{ .fork = null }, 595 .grant => .{ .grant = null }, 596 .notify => .{ .notify = null }, 597 .discuss => .{ .discuss = null }, 598 .issue => .{ .issue = null }, 599 .comment => .{ .comment = null }, 600 .attach => .{ .attach = null }, 601 .assign => .{ .assign = null }, 602 .patchrev => .{ .patchrev = null }, 603 .patch => .{ .patch = null }, 604 }; 605 try consume(host, role, repo_kind, repo_opts, io, allocator, repo, events_ref, &.{.{ 606 .id = std.fmt.bytesToHex(id.*, .lower), 607 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 608 .author = author, 609 .event = event, 610 }}); 611 } 612 613 pub const undo_action = "haxy/events"; 614 pub const merge_undo_action = "haxy/merge-events"; 615 616 // index that tracks the events consumed in a given haxy moment 617 pub const moment_index_to_event_id_set_key = "moment-index->event-id-set"; 618 619 // a haxy moment's own position in the haxy history 620 pub const moment_index_key = "moment-index"; 621 622 // a moment's key in the set map 623 fn momentIndexKey(comptime hash_kind: hash.HashKind, moment_index: u64) hash.HashInt(hash_kind) { 624 var buffer: [@sizeOf(u64)]u8 = undefined; 625 std.mem.writeInt(u64, &buffer, moment_index, .big); 626 return hash.hashInt(hash_kind, &buffer); 627 } 628 629 // the ids of the events a moment wrote, newest first, or null when it wrote none 630 pub fn momentEventIds( 631 comptime DB: type, 632 comptime hash_kind: hash.HashKind, 633 haxy_moment: DB.HashMap(.read_only), 634 moment_index: u64, 635 ) !?DB.SortedSet(.read_only) { 636 const sets_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, moment_index_to_event_id_set_key)) orelse return null; 637 const sets = try DB.HashMap(.read_only).init(sets_cursor); 638 const ids_cursor = try sets.getCursor(momentIndexKey(hash_kind, moment_index)) orelse return null; 639 return try DB.SortedSet(.read_only).init(ids_cursor); 640 } 641 642 // commit `events` (if any) as JSON commit messages on `ref`, then consume the 643 // events on `ref` into the db the repo's views read: the repo's own db for a 644 // xit repo, or the standalone event db next to a git repo. for a xit repo the 645 // commits and the consume run in one transaction, which also saves the 646 // mergeability of the patches the events touched. 647 pub fn consume( 648 host: Host, 649 comptime role: RepoRole, 650 comptime repo_kind: rp.RepoKind, 651 comptime repo_opts: rp.RepoOpts(repo_kind), 652 io: std.Io, 653 allocator: std.mem.Allocator, 654 repo: *rp.Repo(repo_kind, repo_opts), 655 ref: rf.Ref, 656 events: []const EventWithId, 657 ) !void { 658 for (events) |event| { 659 if (!role.allows(std.meta.activeTag(event.event))) return error.EventKindNotAllowed; 660 } 661 662 var resolved_remote_name: ?[]u8 = null; 663 defer if (resolved_remote_name) |name| allocator.free(name); 664 665 // the moment index a xit repo's transaction consumed into 666 var moment_index: ?u64 = null; 667 668 // a branch that only exists on a remote is consumed from its remote-tracking 669 // ref, while commits go on the local branch, continuing from the remote tip 670 // so a cloned repo's local branch stays connected to the server history 671 const resolved_ref: rf.Ref, const first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8 = blk: { 672 if (null != try repo.readRef(io, ref)) break :blk .{ ref, null }; 673 var remotes = try repo.listRemotes(io, allocator); 674 defer remotes.deinit(); 675 for (remotes.sections.keys()) |remote_name| { 676 const remote_ref: rf.Ref = .{ .kind = .{ .remote = remote_name }, .name = ref.name }; 677 if (try repo.readRef(io, remote_ref)) |oid| { 678 if (events.len > 0) break :blk .{ ref, .{oid} }; 679 const name = try allocator.dupe(u8, remote_name); 680 resolved_remote_name = name; 681 break :blk .{ rf.Ref{ .kind = .{ .remote = name }, .name = ref.name }, null }; 682 } 683 } 684 if (events.len > 0) break :blk .{ ref, null }; 685 // the branch is gone (or never existed): drop any db from a previous 686 // sync rather than serving its issues indefinitely 687 if (repo_kind == .git) try LocalEventDB(repo_opts.hash).delete(io, repo.core.repo_dir); 688 return; 689 }; 690 691 switch (repo_kind) { 692 .git => { 693 try commitEvents(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, ref, events, first_parent_oids); 694 695 var event_db = try LocalEventDB(repo_opts.hash).open(io, allocator, repo.core.repo_dir); 696 defer event_db.deinit(io, allocator); 697 698 try event_db.consume(repo_kind, repo_opts, io, allocator, repo, resolved_ref); 699 }, 700 .xit => { 701 const DB = rp.Repo(.xit, repo_opts).DB; 702 const State = rp.Repo(.xit, repo_opts).State; 703 var checks: pch.MergeCheckInputs(repo_opts) = .{}; 704 defer checks.deinit(io, allocator); 705 if (role == .repo and host == .server) { 706 checks.prepare(io, allocator, repo, host.server.users_dir, events) catch |err| { 707 std.log.warn("failed to prepare mergeability: {s}", .{@errorName(err)}); 708 }; 709 } 710 711 const Ctx = struct { 712 core: *rp.Repo(.xit, repo_opts).Core, 713 io: std.Io, 714 allocator: std.mem.Allocator, 715 ref: rf.Ref, 716 events: []const EventWithId, 717 checks: *pch.MergeCheckInputs(repo_opts), 718 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 719 moment_index: *?u64, 720 721 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 722 var moment = try DB.HashMap(.read_write).init(cursor.*); 723 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 724 725 try commitEvents(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.ref, ctx.events, ctx.first_parent_oids); 726 ctx.moment_index.* = try consumeInTransaction(role, .xit, repo_opts, state, &ctx.core.db, &moment, ctx.io, ctx.allocator, ctx.ref); 727 _ = try ctx.checks.update(state, ctx.io, ctx.allocator); 728 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = undo_action } }); 729 } 730 }; 731 732 try repo.core.db_file.lock(io, .exclusive); 733 defer repo.core.db_file.unlock(io); 734 735 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 736 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 737 .core = &repo.core, 738 .io = io, 739 .allocator = allocator, 740 .ref = resolved_ref, 741 .events = events, 742 .checks = &checks, 743 .first_parent_oids = first_parent_oids, 744 .moment_index = &moment_index, 745 }) catch |err| switch (err) { 746 error.CancelTransaction => return, 747 else => |e| return e, 748 }; 749 }, 750 } 751 752 // consuming an existing ref does not provide the set of changed patches 753 // explicit patch writes already saved their checks in the event transaction 754 if (role == .repo and repo_kind == .xit and host == .server and events.len == 0) { 755 pch.refreshOpenMergeability(repo_opts, io, allocator, repo, host.server.users_dir, null, null); 756 } 757 758 if (role == .repo and host == .server and events.len > 0) { 759 // before delivering, so a new assignee hears of their assignment 760 notify.subscribeParticipants(io, allocator, host.server, repo.core.work_path, events); 761 if (repo_kind == .xit) notify.deliverTransaction(io, allocator, host.server, repo_opts, repo, moment_index orelse unreachable, null, null); 762 bumpRepoActivityAt(io, allocator, host.server, repo.core.work_path); 763 } 764 } 765 766 // merge the remote events ref into the local events ref without touching head, 767 // the index, or the worktree 768 pub fn mergeEvents( 769 comptime repo_kind: rp.RepoKind, 770 comptime repo_opts: rp.RepoOpts(repo_kind), 771 io: std.Io, 772 allocator: std.mem.Allocator, 773 repo: *rp.Repo(repo_kind, repo_opts), 774 remote_ref: rf.Ref, 775 ) !void { 776 switch (repo_kind) { 777 .git => _ = try mergeEventsInTransaction(.git, repo_opts, .{ .core = &repo.core, .extra = .{} }, io, allocator, remote_ref), 778 .xit => { 779 const DB = rp.Repo(.xit, repo_opts).DB; 780 const State = rp.Repo(.xit, repo_opts).State; 781 782 const Ctx = struct { 783 core: *rp.Repo(.xit, repo_opts).Core, 784 io: std.Io, 785 allocator: std.mem.Allocator, 786 remote_ref: rf.Ref, 787 788 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 789 var moment = try DB.HashMap(.read_write).init(cursor.*); 790 const state = State(.read_write){ .core = ctx.core, .extra = .{ .moment = &moment } }; 791 if (!try mergeEventsInTransaction(.xit, repo_opts, state, ctx.io, ctx.allocator, ctx.remote_ref)) return error.CancelTransaction; 792 try xit.undo.write(repo_opts, state, std.Io.Timestamp.now(ctx.io, .real).toSeconds(), .{ .custom = .{ .action_kind = merge_undo_action } }); 793 } 794 }; 795 796 try repo.core.db_file.lock(io, .exclusive); 797 defer repo.core.db_file.unlock(io); 798 799 const history = try DB.ArrayList(.read_write).init(repo.core.db.rootCursor()); 800 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 801 .core = &repo.core, 802 .io = io, 803 .allocator = allocator, 804 .remote_ref = remote_ref, 805 }) catch |err| switch (err) { 806 error.CancelTransaction => {}, 807 else => |e| return e, 808 }; 809 }, 810 } 811 } 812 813 fn mergeEventsInTransaction( 814 comptime repo_kind: rp.RepoKind, 815 comptime repo_opts: rp.RepoOpts(repo_kind), 816 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 817 io: std.Io, 818 allocator: std.mem.Allocator, 819 remote_ref: rf.Ref, 820 ) !bool { 821 const remote_oid = (try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = remote_ref })) orelse return false; 822 const local_oid_maybe = try rf.readRecur(repo_kind, repo_opts, state.readOnly(), io, .{ .ref = events_ref }); 823 824 var ref_path_buffer: [rf.MAX_REF_CONTENT_SIZE]u8 = undefined; 825 const ref_path = try events_ref.toPath(&ref_path_buffer); 826 const local_oid = local_oid_maybe orelse { 827 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 828 return true; 829 }; 830 if (std.mem.eql(u8, &local_oid, &remote_oid)) return false; 831 832 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) { 833 error.NoCommonAncestor => null, 834 else => return err, 835 }; 836 if (ancestor_maybe) |ancestor| { 837 if (std.mem.eql(u8, &ancestor, &remote_oid)) return false; 838 if (std.mem.eql(u8, &ancestor, &local_oid)) { 839 try rf.write(repo_kind, repo_opts, state, io, ref_path, .{ .oid = &remote_oid }); 840 return true; 841 } 842 } 843 844 const parent_oids = [_][hash.hexLen(repo_opts.hash)]u8{ local_oid, remote_oid }; 845 var tree = try obj.Tree.init(allocator); 846 defer tree.deinit(); 847 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 848 .message = "merge events", 849 .parent_oids = &parent_oids, 850 }, &tree, events_ref); 851 return true; 852 } 853 854 // the file an attach event carries: the one entry in its commit's tree. the 855 // name and oid are allocated in `arena`. 856 fn attachedFile( 857 comptime repo_kind: rp.RepoKind, 858 comptime repo_opts: rp.RepoOpts(repo_kind), 859 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 860 io: std.Io, 861 allocator: std.mem.Allocator, 862 arena: *std.heap.ArenaAllocator, 863 tree_oid: *const [hash.hexLen(repo_opts.hash)]u8, 864 ) !struct { name: []const u8, oid: []const u8 } { 865 var tree_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, tree_oid); 866 defer tree_object.deinit(); 867 868 const entries = switch (tree_object.content) { 869 .tree => |tree| tree.entries, 870 else => return error.InvalidAttachment, 871 }; 872 if (entries.count() != 1) return error.InvalidAttachment; 873 const entry = entries.values()[0]; 874 if (entry.isTree()) return error.InvalidAttachment; 875 const name = entries.keys()[0]; 876 if (!Attachment.nameValid(name)) return error.InvalidAttachment; 877 878 const oid = std.fmt.bytesToHex(entry.oid, .lower); 879 var object_reader = try obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, &oid); 880 defer object_reader.deinit(); 881 if (object_reader.header().kind != .blob) return error.InvalidAttachment; 882 883 return .{ 884 .name = try arena.allocator().dupe(u8, name), 885 .oid = try arena.allocator().dupe(u8, &oid), 886 }; 887 } 888 889 fn commitIdentity(line: []const u8) ![]const u8 { 890 const close = std.mem.indexOfScalar(u8, line, '>') orelse return error.AuthorNotFound; 891 return line[0 .. close + 1]; 892 } 893 894 // commit each event as a JSON commit message on `ref` through `state`, so a 895 // xit repo can write them inside an already-open transaction 896 pub fn commitEvents( 897 comptime repo_kind: rp.RepoKind, 898 comptime repo_opts: rp.RepoOpts(repo_kind), 899 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 900 io: std.Io, 901 allocator: std.mem.Allocator, 902 ref: rf.Ref, 903 events: []const EventWithId, 904 first_parent_oids: ?[1][hash.hexLen(repo_opts.hash)]u8, 905 ) !void { 906 var parent_oids: ?[]const [hash.hexLen(repo_opts.hash)]u8 = if (first_parent_oids) |*oids| oids else null; 907 908 var json: std.Io.Writer.Allocating = .init(allocator); 909 defer json.deinit(); 910 911 for (events) |event| { 912 json.clearRetainingCapacity(); 913 try std.json.Stringify.value(event, .{}, &json.writer); 914 if (json.written().len > max_event_size) return error.EventTooLarge; 915 const author = try allocator.print("{s} <{s}>", .{ event.author.name, event.author.email }); 916 defer allocator.free(author); 917 918 // every event gets a fresh tree 919 var tree = try obj.Tree.init(allocator); 920 defer tree.deinit(); 921 for (event.tree_entries) |entry| { 922 switch (entry) { 923 .blob => |blob| { 924 var oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = @splat(0); 925 try obj.writeObject(repo_kind, repo_opts, state, io, allocator, blob.reader, .{ .kind = .blob, .size = blob.size }, &oid_bytes); 926 try tree.addBlobEntry(.{ .content = .{ .unix_permission = 0o644, .object_type = .regular_file } }, blob.name, &oid_bytes); 927 }, 928 .tree => |nested| { 929 var oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 930 _ = try std.fmt.hexToBytes(&oid_bytes, nested.oid); 931 if (!std.mem.eql(u8, nested.oid, &std.fmt.bytesToHex(oid_bytes, .lower))) return error.InvalidTreeObject; 932 try tree.addTreeEntry(nested.name, &oid_bytes); 933 }, 934 } 935 } 936 937 _ = try obj.writeCommit(repo_kind, repo_opts, state, io, allocator, .{ 938 .author = author, 939 .message = json.written(), 940 .timestamp = event.timestamp, 941 .parent_oids = parent_oids, 942 .allow_empty = true, 943 }, &tree, ref); 944 // later events parent on the ref's new tip 945 parent_oids = null; 946 } 947 } 948 949 // a standalone event db holding events consumed from a local repo's events 950 // branch. it lives inside the repo dir but is not part of the repo's own data, 951 // so viewing a repo never mutates it. 952 pub fn LocalEventDB(comptime hash_kind: hash.HashKind) type { 953 return struct { 954 file: std.Io.File, 955 buffer: *std.Io.Writer.Allocating, 956 db: *EventDB(hash_kind), 957 958 const db_name = "haxy"; 959 const Self = @This(); 960 961 // open the db in `repo_dir` for writing, creating it if it doesn't exist 962 pub fn open(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !Self { 963 const file = try repo_dir.createFile(io, db_name, .{ .truncate = false, .read = true, .lock = .exclusive }); 964 return fromFile(io, allocator, file); 965 } 966 967 // open the db in `repo_dir` for reading, or null if it doesn't exist 968 pub fn openReadOnly(io: std.Io, allocator: std.mem.Allocator, repo_dir: std.Io.Dir) !?Self { 969 const file = repo_dir.openFile(io, db_name, .{ .mode = .read_write, .lock = .shared }) catch |err| switch (err) { 970 error.FileNotFound => return null, 971 else => |e| return e, 972 }; 973 return try fromFile(io, allocator, file); 974 } 975 976 // remove the db from `repo_dir`, so a repo whose events branch 977 // disappeared doesn't keep showing stale issues 978 pub fn delete(io: std.Io, repo_dir: std.Io.Dir) !void { 979 repo_dir.deleteFile(io, db_name) catch |err| switch (err) { 980 error.FileNotFound => {}, 981 else => |e| return e, 982 }; 983 } 984 985 fn fromFile(io: std.Io, allocator: std.mem.Allocator, file: std.Io.File) !Self { 986 errdefer file.close(io); 987 988 const buffer = try allocator.create(std.Io.Writer.Allocating); 989 errdefer allocator.destroy(buffer); 990 buffer.* = std.Io.Writer.Allocating.init(allocator); 991 errdefer buffer.deinit(); 992 993 const db = try allocator.create(EventDB(hash_kind)); 994 errdefer allocator.destroy(db); 995 db.* = try EventDB(hash_kind).init(.{ .io = io, .file = file, .buffer = buffer }); 996 997 return .{ .file = file, .buffer = buffer, .db = db }; 998 } 999 1000 pub fn deinit(self: *Self, io: std.Io, allocator: std.mem.Allocator) void { 1001 self.file.close(io); 1002 self.buffer.deinit(); 1003 allocator.destroy(self.buffer); 1004 allocator.destroy(self.db); 1005 } 1006 1007 // consume the events on `repo`'s `ref` into this db. the db must come 1008 // from `open`, whose handle holds the exclusive lock guarding the 1009 // transaction. 1010 pub fn consume( 1011 self: *Self, 1012 comptime repo_kind: rp.RepoKind, 1013 comptime repo_opts: rp.RepoOpts(repo_kind), 1014 io: std.Io, 1015 allocator: std.mem.Allocator, 1016 repo: *rp.Repo(repo_kind, repo_opts), 1017 ref: rf.Ref, 1018 ) !void { 1019 comptime if (repo_opts.hash != hash_kind) @compileError("the repo must use the db's hash kind"); 1020 const DB = EventDB(hash_kind); 1021 1022 const Ctx = struct { 1023 repo: *rp.Repo(repo_kind, repo_opts), 1024 db: *DB, 1025 io: std.Io, 1026 allocator: std.mem.Allocator, 1027 ref: rf.Ref, 1028 1029 pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void { 1030 var moment = try DB.HashMap(.read_write).init(cursor.*); 1031 const state = rp.Repo(repo_kind, repo_opts).State(.read_write){ .core = &ctx.repo.core, .extra = .{} }; 1032 _ = try consumeInTransaction(.repo, repo_kind, repo_opts, state, ctx.db, &moment, ctx.io, ctx.allocator, ctx.ref); 1033 } 1034 }; 1035 1036 const history = try DB.ArrayList(.read_write).init(self.db.rootCursor()); 1037 history.appendContext(.{ .slot = try history.getSlot(-1) }, Ctx{ 1038 .repo = repo, 1039 .db = self.db, 1040 .io = io, 1041 .allocator = allocator, 1042 .ref = ref, 1043 }) catch |err| switch (err) { 1044 error.CancelTransaction => {}, 1045 else => |e| return e, 1046 }; 1047 } 1048 }; 1049 } 1050 1051 // consume the events on `ref` into the db `moment` writes to, returning the 1052 // moment index they landed in, or null when it only rewound to a tip consumed 1053 // before. a tip already consumed cancels the transaction. events are read 1054 // from `state`'s repo, which needn't be the repo backing the db — that's how 1055 // a local (possibly git-backed) repo's events land in a standalone db. 1056 pub fn consumeInTransaction( 1057 comptime role: RepoRole, 1058 comptime repo_kind: rp.RepoKind, 1059 comptime repo_opts: rp.RepoOpts(repo_kind), 1060 state: rp.Repo(repo_kind, repo_opts).State(.read_write), 1061 db: *EventDB(repo_opts.hash), 1062 moment: *EventDB(repo_opts.hash).HashMap(.read_write), 1063 io: std.Io, 1064 allocator: std.mem.Allocator, 1065 ref: rf.Ref, 1066 ) !?u64 { 1067 const DB = EventDB(repo_opts.hash); 1068 const read_state = state.readOnly(); 1069 1070 // the last_object_id represents the object id that was last consumed 1071 var last_object_id_maybe: ?[hash.byteLen(repo_opts.hash)]u8 = null; 1072 if (try moment.getCursor(hash.hashInt(repo_opts.hash, last_object_id_key))) |last_object_id_cursor| { 1073 var last_object_id_buffer: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1074 _ = try last_object_id_cursor.readBytes(&last_object_id_buffer); 1075 last_object_id_maybe = last_object_id_buffer; 1076 } 1077 1078 // the tip was already consumed, so there is nothing to do 1079 if (last_object_id_maybe) |*last_object_id| { 1080 const tip_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1081 var tip: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1082 _ = try std.fmt.hexToBytes(&tip, &tip_hex); 1083 if (std.mem.eql(u8, last_object_id, &tip)) return error.CancelTransaction; 1084 } 1085 1086 // the list with all of haxy's state, including materialized views. 1087 // the reason it is a list is so we can keep every previous haxy 1088 // state, making it easy to revert to an older state if the user 1089 // rebases some of the past commits. 1090 const haxy_history_cursor = try moment.putCursor(hash.hashInt(repo_opts.hash, history_key)); 1091 const haxy_history = try DB.ArrayList(.read_write).init(haxy_history_cursor); 1092 1093 // add a new item to the haxy history list created above. 1094 // we call the item haxy_moments. it is a map of object id to haxy moment. 1095 // in other words, it maps each object id to a hash map containing the 1096 // state that the database was in when that object id was consumed. 1097 var haxy_moments_cursor = try haxy_history.appendCursor(); 1098 // use the previous haxy_moments as the basis for this one if it exists 1099 if (try haxy_history.getCursor(-2)) |last_haxy_moments_cursor| { 1100 try haxy_moments_cursor.write(.{ .slot = last_haxy_moments_cursor.slot() }); 1101 } 1102 var haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 1103 1104 var commit_iter = try CommitIterator(repo_kind, repo_opts).init(read_state, io, allocator, haxy_moments.readOnly(), ref); 1105 defer commit_iter.deinit(io, allocator); 1106 1107 // if there are no events to process, look at the oid at HEAD and update 1108 // the last_object_id to point to it. this is important in situations 1109 // where we do a merge and then force-push to remove the merge. see the 1110 // merge test for an example. 1111 if (commit_iter.newest_object_id == null) { 1112 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, read_state, io, .{ .ref = ref })) orelse return error.OidNotFound; 1113 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1114 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 1115 1116 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &head_oid)) orelse return error.CursorNotFound; 1117 const haxy_moment = try DB.HashMap(.read_only).init(haxy_moment_cursor); 1118 1119 const moment_index_cursor = try haxy_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 1120 const moment_index = try moment_index_cursor.readUint(); 1121 1122 try haxy_history.slice(moment_index + 1); 1123 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = &head_oid }); 1124 return null; 1125 } 1126 1127 // if this branch was rebased and force pushed, we need to detect that and 1128 // properly revert the haxy state to the last valid state. we detect this 1129 // by simply asking if the last event is a descendent of the last event 1130 // we consumed. if it isn't, then we know the haxy state needs to be reverted. 1131 if (last_object_id_maybe) |*last_object_id| { 1132 var is_rebased = false; 1133 const newest_object_id = commit_iter.newest_object_id orelse return error.OidNotFound; 1134 1135 _ = mrg.getDescendent( 1136 repo_kind, 1137 repo_opts, 1138 read_state, 1139 io, 1140 allocator, 1141 &std.fmt.bytesToHex(last_object_id, .lower), 1142 &std.fmt.bytesToHex(&newest_object_id, .lower), 1143 ) catch |err| switch (err) { 1144 error.DescendentNotFound => is_rebased = true, 1145 else => |e| return e, 1146 }; 1147 1148 if (is_rebased) { 1149 const oldest_object_id = commit_iter.oldest_object_id orelse return error.OidNotFound; 1150 var oldest_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(oldest_object_id, .lower)); 1151 defer oldest_object.deinit(); 1152 1153 const parent_oids = oldest_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1154 switch (parent_oids.len) { 1155 0 => { 1156 // the branch was rebased all the way to the very beginning. 1157 // we have a repo event with no parent, which means it is now 1158 // the very first event. all we need to do is set the haxy 1159 // history list to be empty and make a new haxy_moments map 1160 // to work with. 1161 1162 try haxy_history.slice(0); 1163 haxy_moments_cursor = try haxy_history.appendCursor(); 1164 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 1165 1166 last_object_id_maybe = null; 1167 }, 1168 1 => { 1169 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1170 _ = try std.fmt.hexToBytes(&oid, &parent_oids[0]); 1171 1172 const old_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 1173 const old_moment = try DB.HashMap(.read_only).init(old_moment_cursor); 1174 1175 const old_moment_index_cursor = try old_moment.getCursor(hash.hashInt(repo_opts.hash, moment_index_key)) orelse return error.CursorNotFound; 1176 const old_moment_index = try old_moment_index_cursor.readUint(); 1177 1178 // resize the haxy history list so we truncate all the 1179 // moments that were created after the parent_oid was consumed 1180 try haxy_history.slice(old_moment_index + 1); 1181 1182 // make a new haxy moment and set its initial value to the last haxy moment 1183 haxy_moments_cursor = try haxy_history.appendCursor(); 1184 const old_haxy_moments_cursor = try haxy_history.getCursor(old_moment_index) orelse return error.CursorNotFound; 1185 try haxy_moments_cursor.write(.{ .slot = old_haxy_moments_cursor.slot() }); 1186 haxy_moments = try DB.HashMap(.read_write).init(haxy_moments_cursor); 1187 1188 last_object_id_maybe = oid; 1189 }, 1190 else => return error.UnexpectedParentCount, 1191 } 1192 } 1193 } 1194 1195 while (try commit_iter.next()) |repo_event_oid| { 1196 var commit_object = try obj.Object(repo_kind, repo_opts).init(read_state, io, allocator, &std.fmt.bytesToHex(repo_event_oid, .lower)); 1197 defer commit_object.deinit(); 1198 1199 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 1200 1201 // create a moment for this object id 1202 var haxy_moment_cursor = try haxy_moments.putCursor(hash.bytesToInt(repo_opts.hash, &repo_event_oid)); 1203 1204 // if there was a previous object id, set this haxy moment's initial value to it. 1205 // this efficiently "clones" the map so we make further modifications based on it. 1206 if (parent_oids.len > 0) { 1207 var first_parent_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1208 _ = try std.fmt.hexToBytes(&first_parent_oid, &parent_oids[0]); 1209 1210 const first_parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &first_parent_oid)) orelse return error.CursorNotFound; 1211 try haxy_moment_cursor.write(.{ .slot = first_parent_haxy_moment_cursor.slot() }); 1212 } 1213 1214 const haxy_moment = try DB.HashMap(.read_write).init(haxy_moment_cursor); 1215 1216 // graph generation gives every event a causal order independent of 1217 // commit timestamps. concurrent events tie-break by id in their index. 1218 var event_order: u64 = 1; 1219 for (parent_oids) |*parent_oid| { 1220 var parent_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1221 _ = try std.fmt.hexToBytes(&parent_id, parent_oid); 1222 const parent_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &parent_id)) orelse return error.CursorNotFound; 1223 const parent = try DB.HashMap(.read_only).init(parent_cursor); 1224 const parent_order_cursor = try parent.getCursor(hash.hashInt(repo_opts.hash, event_order_key)) orelse return error.CursorNotFound; 1225 const parent_order = try parent_order_cursor.readUint(); 1226 event_order = @max(event_order, parent_order +| 1); 1227 } 1228 try haxy_moment.put(hash.hashInt(repo_opts.hash, event_order_key), .{ .uint = event_order }); 1229 1230 // merge changes from every parent after the first parent. the common 1231 // ancestor is the baseline, so a later parent only contributes records 1232 // it changed relative to the merge base. only the record maps are 1233 // merged; every other view is derived from them, and each kind's 1234 // `consume` re-derives its own as the winning records are written. 1235 if (parent_oids.len > 1) { 1236 for (parent_oids[1..]) |*parent_oid| { 1237 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1238 _ = try std.fmt.hexToBytes(&oid, parent_oid); 1239 1240 const parent_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &oid)) orelse return error.CursorNotFound; 1241 const parent_haxy_moment = try DB.HashMap(.read_only).init(parent_haxy_moment_cursor); 1242 1243 const baseline_oid_hex = try mrg.commonAncestor(repo_kind, repo_opts, read_state, io, allocator, &parent_oids[0], parent_oid); 1244 var baseline_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 1245 _ = try std.fmt.hexToBytes(&baseline_oid, &baseline_oid_hex); 1246 const baseline_haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &baseline_oid)) orelse return error.CursorNotFound; 1247 const baseline_haxy_moment = try DB.HashMap(.read_only).init(baseline_haxy_moment_cursor); 1248 1249 inline for (@typeInfo(Event).@"union".field_types) |field_type| { 1250 const T = @typeInfo(field_type).optional.child; 1251 try merge(T, DB, repo_opts.hash, allocator, haxy_moment, parent_haxy_moment, baseline_haxy_moment); 1252 } 1253 } 1254 } 1255 1256 // associate this moment with the index it will first appear at in the 1257 // haxy history list. this will be important later so we can truncate 1258 // that list if the user ever rebases starting at this object id. 1259 const moment_index = try haxy_history.count() - 1; 1260 try haxy_moment.put(hash.hashInt(repo_opts.hash, moment_index_key), .{ .uint = moment_index }); 1261 1262 // consume the event unless it's a merge commit 1263 if (parent_oids.len <= 1) { 1264 var arena = std.heap.ArenaAllocator.init(allocator); 1265 defer arena.deinit(); 1266 1267 // read the message from the commit 1268 var message: std.ArrayList(u8) = .empty; 1269 try commit_object.readMessage(arena.allocator(), &message, .limited(max_event_size)); 1270 1271 const event_with_id = try EventWithId.fromString(&arena, message.items); 1272 if (!role.allows(std.meta.activeTag(event_with_id.event))) return error.EventKindNotAllowed; 1273 1274 const current_event_id = try parseEventId(&event_with_id.id); 1275 1276 // associate the transaction with the events it writes. this is 1277 // used by the undo tab to link the events that were affected 1278 // by a given transaction. 1279 { 1280 const sets = try DB.HashMap(.read_write).init(try haxy_moment.putCursor(hash.hashInt(repo_opts.hash, moment_index_to_event_id_set_key))); 1281 const ids = try DB.SortedSet(.read_write).init(try sets.putCursor(momentIndexKey(repo_opts.hash, moment_index))); 1282 try ids.put(&orderKeyDesc(event_order, &current_event_id)); 1283 } 1284 1285 // wrap the payload into the record `consume` stores, with its 1286 // commit-derived fields; on update, `consume` preserves the 1287 // existing record's 1288 switch (event_with_id.event) { 1289 .user => |event_maybe| { 1290 const record_maybe: ?User.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1291 try User.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1292 }, 1293 .repo => |event_maybe| { 1294 const record_maybe: ?Repo.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1295 try Repo.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1296 }, 1297 .fork => |event_maybe| { 1298 const record_maybe: ?Fork.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1299 try Fork.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1300 }, 1301 .grant => |event_maybe| { 1302 const record_maybe: ?Grant.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1303 try Grant.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1304 }, 1305 .notify => |event_maybe| { 1306 const record_maybe: ?Notify.Record = if (event_maybe) |event| .{ .event = event, .created_order = event_order, .updated_order = event_order } else null; 1307 try Notify.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1308 }, 1309 .discuss => |event_maybe| { 1310 const record_maybe: ?Discussion.Record = if (event_maybe) |event| .{ 1311 .event = event, 1312 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1313 .created_timestamp = commit_object.content.commit.metadata.timestamp, 1314 .created_order = event_order, 1315 .updated_order = event_order, 1316 } else null; 1317 try Discussion.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1318 }, 1319 .issue => |event_maybe| { 1320 const record_maybe: ?Issue.Record = if (event_maybe) |event| .{ 1321 .event = event, 1322 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1323 .created_timestamp = commit_object.content.commit.metadata.timestamp, 1324 .created_order = event_order, 1325 .updated_order = event_order, 1326 } else null; 1327 try Issue.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1328 }, 1329 .comment => |event_maybe| { 1330 const record_maybe: ?Comment.Record = if (event_maybe) |event| .{ 1331 .event = event, 1332 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1333 .created_timestamp = commit_object.content.commit.metadata.timestamp, 1334 .created_order = event_order, 1335 .updated_order = event_order, 1336 } else null; 1337 try Comment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1338 }, 1339 .attach => |event_maybe| { 1340 const record_maybe: ?Attachment.Record = if (event_maybe) |event| blk: { 1341 const entry = try attachedFile(repo_kind, repo_opts, read_state, io, allocator, &arena, &commit_object.content.commit.tree); 1342 break :blk .{ 1343 .event = event, 1344 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1345 .created_order = event_order, 1346 .updated_order = event_order, 1347 .name = entry.name, 1348 .blob_oid = entry.oid, 1349 }; 1350 } else null; 1351 try Attachment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1352 }, 1353 .assign => |event_maybe| { 1354 const record_maybe: ?Assignment.Record = if (event_maybe) |event| .{ 1355 .event = event, 1356 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1357 .created_order = event_order, 1358 .updated_order = event_order, 1359 } else null; 1360 try Assignment.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1361 }, 1362 .patchrev => |event_maybe| { 1363 const record_maybe: ?PatchRev.Record = if (event_maybe) |event| blk: { 1364 const trees = try PatchRev.readTrees(repo_kind, repo_opts, read_state, io, allocator, &commit_object.content.commit.tree); 1365 const existing_maybe = try PatchRev.readById(DB, repo_opts.hash, haxy_moment.readOnly(), &arena, &current_event_id); 1366 const event_oid = std.fmt.bytesToHex(repo_event_oid, .lower); 1367 1368 var patch_oid: [hash.hexLen(repo_opts.hash)]u8 = undefined; 1369 if (existing_maybe) |existing| { 1370 if (existing.patch_oid.len != patch_oid.len) return error.InvalidPatch; 1371 @memcpy(&patch_oid, existing.patch_oid); 1372 } else { 1373 const author = try commitIdentity(commit_object.content.commit.metadata.author orelse return error.AuthorNotFound); 1374 const committer = try commitIdentity(commit_object.content.commit.metadata.committer orelse author); 1375 patch_oid = try PatchRev.writeSquashCommit( 1376 repo_kind, 1377 repo_opts, 1378 state, 1379 io, 1380 allocator, 1381 event, 1382 &trees.head, 1383 author, 1384 committer, 1385 commit_object.content.commit.metadata.timestamp, 1386 ); 1387 } 1388 1389 break :blk .{ 1390 .event = event, 1391 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1392 .created_order = event_order, 1393 .updated_order = event_order, 1394 .event_oid = &event_oid, 1395 .base_tree_oid = &trees.base, 1396 .head_tree_oid = &trees.head, 1397 .patch_oid = &patch_oid, 1398 .commit_count = PatchRev.commitCount(repo_kind, repo_opts, read_state, io, allocator, event.base_oid, event.source_oid) catch null, 1399 }; 1400 } else null; 1401 try PatchRev.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1402 }, 1403 .patch => |event_maybe| { 1404 const record_maybe: ?Patch.Record = if (event_maybe) |event| .{ 1405 .event = event, 1406 .author_email = authorEmail(commit_object.content.commit.metadata.author orelse ""), 1407 .created_timestamp = commit_object.content.commit.metadata.timestamp, 1408 .created_order = event_order, 1409 .updated_order = event_order, 1410 } else null; 1411 try Patch.consume(DB, repo_opts.hash, haxy_moment, &current_event_id, record_maybe, &arena, &repo_event_oid); 1412 }, 1413 } 1414 } 1415 1416 // the current object id is now the last one 1417 last_object_id_maybe = repo_event_oid; 1418 1419 // prevent any of the data created above from being mutated by future iterations of this loop 1420 try db.freeze(); 1421 } 1422 1423 if (last_object_id_maybe) |*last_object_id| { 1424 try moment.put(hash.hashInt(repo_opts.hash, last_object_id_key), .{ .bytes = last_object_id }); 1425 } 1426 1427 return try haxy_history.count() - 1; 1428 } 1429 1430 // the conflicted records of one kind, keyed by the same order key its id set 1431 // uses, so this doubles as the index the conflicts view lists and counts. every 1432 // value under an entry is a slot reference to a structure that already exists: 1433 // 1434 // <order key> -> conflict entry 1435 // conflicted-fields the conflicting field names, space separated 1436 // base-record the merge base's whole record 1437 // their-record the merged-in side's whole record 1438 // their-field->oid that side's field name to commit map 1439 // 1440 // our own value is the live record and our commit is in the kind's oid map, so 1441 // neither is repeated here. 1442 pub const conflicted_fields_key = "conflicted-fields"; 1443 pub const base_record_key = "base-record"; 1444 pub const their_record_key = "their-record"; 1445 pub const their_field_to_oid_key = "their-field->oid"; 1446 1447 // record the commit against every field this event changes. a merge passes no 1448 // oid, since each field's winner may come from a different side. 1449 pub fn writeOid( 1450 comptime T: type, 1451 comptime DB: type, 1452 comptime hash_kind: hash.HashKind, 1453 id_to_field_to_oid: DB.HashMap(.read_write), 1454 record_key: hash.HashInt(hash_kind), 1455 existing_maybe: ?T, 1456 event: T, 1457 event_oid: ?[]const u8, 1458 ) !void { 1459 const oid = event_oid orelse return; 1460 1461 // created only once a field actually changes 1462 var field_oids: ?DB.SortedMap(.read_write) = null; 1463 1464 const info = @typeInfo(T).@"struct"; 1465 inline for (info.field_names, info.field_types) |field_name, field_type| { 1466 const changed = if (existing_maybe) |existing| 1467 !fieldEqual(field_type, @field(existing, field_name), @field(event, field_name)) 1468 else 1469 true; 1470 if (changed) { 1471 if (field_oids == null) { 1472 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1473 } 1474 if (field_oids) |map| try map.put(field_name, .{ .bytes = oid }); 1475 } 1476 } 1477 } 1478 1479 // the whole field list, space separated, is the longest it can get 1480 fn conflictedFieldsMaxLen(comptime T: type) usize { 1481 var len: usize = 0; 1482 for (@typeInfo(T).@"struct".field_names) |name| len += name.len + 1; 1483 return len; 1484 } 1485 1486 pub const MergePolicy = enum { 1487 field_conflicts, 1488 target_wins, 1489 }; 1490 1491 // what a three-way merge did with a field 1492 pub const FieldMerge = enum { 1493 // the target's value stands, because neither side changed it, both made the 1494 // same change, or only the target changed it 1495 kept, 1496 parent, 1497 conflicted, 1498 }; 1499 1500 // three-way merge each field. one only the parent changed takes the parent's 1501 // value; one both sides changed differently keeps the target's. a missing 1502 // baseline makes every differing field a conflict. 1503 fn mergeFields( 1504 comptime T: type, 1505 baseline_maybe: ?T, 1506 target: T, 1507 parent: T, 1508 outcome: *[@typeInfo(T).@"struct".field_names.len]FieldMerge, 1509 ) T { 1510 var merged = target; 1511 1512 const info = @typeInfo(T).@"struct"; 1513 inline for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { 1514 const target_value = @field(target, field_name); 1515 const parent_value = @field(parent, field_name); 1516 1517 if (!fieldEqual(field_type, target_value, parent_value)) { 1518 outcome[i] = if (baseline_maybe) |baseline| blk: { 1519 const baseline_value = @field(baseline, field_name); 1520 if (fieldEqual(field_type, target_value, baseline_value)) { 1521 @field(merged, field_name) = parent_value; 1522 break :blk .parent; 1523 } 1524 // only the target changed it 1525 if (fieldEqual(field_type, parent_value, baseline_value)) break :blk .kept; 1526 break :blk .conflicted; 1527 } else .conflicted; 1528 } 1529 } 1530 1531 return merged; 1532 } 1533 1534 // three-way merge of one kind's records from a merge parent. kinds that expose 1535 // conflicts merge field by field; the others take one whole record. the result 1536 // goes through the kind's `consume`, which re-derives the indexes from it. a 1537 // removal carries over unless the other side changed the record, so a merge 1538 // never fails. 1539 pub fn merge( 1540 comptime T: type, 1541 comptime DB: type, 1542 comptime hash_kind: hash.HashKind, 1543 allocator: std.mem.Allocator, 1544 haxy_moment: DB.HashMap(.read_write), 1545 parent_moment: DB.HashMap(.read_only), 1546 baseline_moment: DB.HashMap(.read_only), 1547 ) !void { 1548 const parent_set_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.all_id_set_key)) orelse return; 1549 const parent_set = try DB.SortedSet(.read_only).init(parent_set_cursor); 1550 1551 const parent_records_cursor = try parent_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return; 1552 const parent_records = try DB.HashMap(.read_only).init(parent_records_cursor); 1553 1554 var baseline_records: ?DB.HashMap(.read_only) = null; 1555 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key))) |cursor| { 1556 baseline_records = try DB.HashMap(.read_only).init(cursor); 1557 } 1558 1559 var parent_conflicts: ?DB.SortedMap(.read_only) = null; 1560 var baseline_conflicts: ?DB.SortedMap(.read_only) = null; 1561 var parent_id_to_field_to_oid: ?DB.HashMap(.read_only) = null; 1562 switch (comptime T.merge_policy) { 1563 .field_conflicts => { 1564 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1565 parent_conflicts = try DB.SortedMap(.read_only).init(cursor); 1566 } 1567 if (try baseline_moment.getCursor(hash.hashInt(hash_kind, T.conflicts_key))) |cursor| { 1568 baseline_conflicts = try DB.SortedMap(.read_only).init(cursor); 1569 } 1570 if (try parent_moment.getCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key))) |cursor| { 1571 parent_id_to_field_to_oid = try DB.HashMap(.read_only).init(cursor); 1572 } 1573 }, 1574 .target_wins => {}, 1575 } 1576 1577 var arena = std.heap.ArenaAllocator.init(allocator); 1578 defer arena.deinit(); 1579 1580 var iter = try parent_set.iteratorFromIndex(0); 1581 while (try iter.next()) |kv_pair_cursor| { 1582 const event_id = try readOrderKeyId(DB, kv_pair_cursor); 1583 const record_key = hash.hashInt(hash_kind, &event_id); 1584 1585 _ = arena.reset(.retain_capacity); 1586 1587 const parent_record_cursor = try parent_records.getCursor(record_key) orelse continue; 1588 const parent_slot = parent_record_cursor.slot(); 1589 const baseline_slot = if (baseline_records) |map| try map.getSlot(record_key) else null; 1590 1591 // the parent left this record alone 1592 if (baseline_slot) |slot| { 1593 if (slot.eql(parent_slot)) continue; 1594 } 1595 1596 const parent_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(parent_record_cursor)); 1597 1598 // re-derived every iteration, since `consume` writes through its own 1599 // handles 1600 const target_records_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.record_map_key)); 1601 const target_records = try DB.HashMap(.read_write).init(target_records_cursor); 1602 1603 // a record the target doesn't have arrives wholesale from the parent 1604 var outcome: [@typeInfo(T).@"struct".field_names.len]FieldMerge = @splat(.parent); 1605 var merged = parent_record; 1606 1607 if (try target_records.getCursor(record_key)) |target_record_cursor| { 1608 // both sides share the change 1609 if (target_record_cursor.slot().eql(parent_slot)) continue; 1610 1611 const target_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(target_record_cursor)); 1612 1613 var baseline_record: ?T.Record = null; 1614 if (baseline_records) |map| { 1615 if (try map.getCursor(record_key)) |baseline_record_cursor| { 1616 baseline_record = try read(T.Record, DB, hash_kind, &arena, try DB.HashMap(.read_only).init(baseline_record_cursor)); 1617 } 1618 } 1619 1620 switch (comptime T.merge_policy) { 1621 .field_conflicts => { 1622 outcome = @splat(.kept); 1623 merged = target_record; 1624 merged.event = mergeFields(T, if (baseline_record) |baseline| baseline.event else null, target_record.event, parent_record.event, &outcome); 1625 merged.updated_order = @max(target_record.updated_order, parent_record.updated_order); 1626 if (comptime @hasDecl(T, "resolveMerge")) { 1627 T.resolveMerge(target_record.event, parent_record.event, &merged.event, &outcome); 1628 } 1629 1630 // merge the removed state separately from serialized fields. removal 1631 // carries over an unchanged record, while an edit or restoration 1632 // keeps it active. 1633 merged.removed = if (target_record.removed == parent_record.removed) 1634 target_record.removed 1635 else if (baseline_record) |baseline| blk: { 1636 const active = if (!target_record.removed) target_record else parent_record; 1637 if (active.removed != baseline.removed) break :blk false; 1638 if (!fieldsEqual(T, active.event, baseline.event)) break :blk false; 1639 break :blk true; 1640 } else false; 1641 }, 1642 .target_wins => { 1643 // an uncontested parent change carries over. if both sides 1644 // changed the record, the target wins as a whole, except that 1645 // an edit or restoration wins over a removal. 1646 const target_changed = if (baseline_slot) |slot| 1647 !target_record_cursor.slot().eql(slot) 1648 else 1649 true; 1650 merged = if (!target_changed) 1651 parent_record 1652 else if (target_record.removed != parent_record.removed) 1653 if (target_record.removed) parent_record else target_record 1654 else 1655 target_record; 1656 }, 1657 } 1658 } 1659 1660 // the index is unique, so a key the target gave to a different record 1661 // leaves this one out rather than stranding that one behind a name it 1662 // no longer owns 1663 if (!merged.removed and @hasDecl(T, "name_index_key")) { 1664 const name_index_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.name_index_key)); 1665 const name_index = try DB.SortedMap(.read_write).init(name_index_cursor); 1666 if (try name_index.getCursor(merged.event.name)) |owner_cursor| { 1667 var owner_id: [event_id_size]u8 = undefined; 1668 _ = try owner_cursor.readBytes(&owner_id); 1669 if (!std.mem.eql(u8, &owner_id, &event_id)) continue; 1670 } 1671 } 1672 1673 // `consume` sets no oids, since each field's winner may come from 1674 // a different side 1675 try T.consume(DB, hash_kind, haxy_moment, &event_id, merged, &arena, null); 1676 1677 switch (comptime T.merge_policy) { 1678 .field_conflicts => {}, 1679 .target_wins => continue, 1680 } 1681 1682 // removed records do not carry field conflicts 1683 if (merged.removed) continue; 1684 1685 const conflicts_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.conflicts_key)); 1686 const conflicts = try DB.SortedMap(.read_write).init(conflicts_cursor); 1687 const id_to_field_to_oid_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, T.id_to_field_to_oid_key)); 1688 const id_to_field_to_oid = try DB.HashMap(.read_write).init(id_to_field_to_oid_cursor); 1689 const merged_key = orderKeyDesc(merged.created_order, &event_id); 1690 1691 var parent_field_oids: ?DB.SortedMap(.read_only) = null; 1692 if (parent_id_to_field_to_oid) |map| { 1693 if (try map.getCursor(record_key)) |field_oids_cursor| { 1694 parent_field_oids = try DB.SortedMap(.read_only).init(field_oids_cursor); 1695 } 1696 } 1697 // created only once a field actually comes from the parent 1698 var field_oids: ?DB.SortedMap(.read_write) = null; 1699 1700 // the fields both sides changed differently, space separated 1701 var conflicted_fields: [conflictedFieldsMaxLen(T)]u8 = undefined; 1702 var conflicted_len: usize = 0; 1703 1704 inline for (@typeInfo(T).@"struct".field_names, 0..) |field_name, i| { 1705 switch (outcome[i]) { 1706 // the target's value stands, so its oid does too 1707 .kept => {}, 1708 // the parent set this value, so its commit takes the field. a 1709 // parent with no oid took its own value from a merge, leaving 1710 // the field unattributed rather than crediting the target's 1711 // commit for a value it no longer holds. 1712 .parent => { 1713 if (field_oids == null) { 1714 field_oids = try DB.SortedMap(.read_write).init(try id_to_field_to_oid.putCursor(record_key)); 1715 } 1716 const map = field_oids orelse unreachable; 1717 const parent_oid = if (parent_field_oids) |parent_map| try parent_map.getCursor(field_name) else null; 1718 if (parent_oid) |oid_cursor| { 1719 try map.put(field_name, .{ .slot = oid_cursor.slot() }); 1720 } else { 1721 _ = try map.remove(field_name); 1722 } 1723 }, 1724 .conflicted => { 1725 if (conflicted_len > 0) { 1726 conflicted_fields[conflicted_len] = ' '; 1727 conflicted_len += 1; 1728 } 1729 @memcpy(conflicted_fields[conflicted_len..][0..field_name.len], field_name); 1730 conflicted_len += field_name.len; 1731 }, 1732 } 1733 } 1734 1735 if (conflicted_len > 0) { 1736 // each side's whole record is stored by reference, so the view can 1737 // show any of them or take theirs wholesale 1738 _ = try conflicts.remove(&merged_key); 1739 const conflict = try DB.HashMap(.read_write).init(try conflicts.putCursor(&merged_key)); 1740 try conflict.put(hash.hashInt(hash_kind, conflicted_fields_key), .{ .bytes = conflicted_fields[0..conflicted_len] }); 1741 try conflict.put(hash.hashInt(hash_kind, base_record_key), .{ .slot = baseline_slot }); 1742 try conflict.put(hash.hashInt(hash_kind, their_record_key), .{ .slot = parent_slot }); 1743 if (parent_field_oids) |map| { 1744 try conflict.put(hash.hashInt(hash_kind, their_field_to_oid_key), .{ .slot = map.slot() }); 1745 } 1746 continue; 1747 } 1748 1749 // created_order never changes, so the parent keys this record's conflict 1750 // identically, and it carries over when the target has none, unless the 1751 // parent's entry is unchanged from the baseline, meaning the target 1752 // inherited it too and resolving it removed it here. 1753 if (parent_conflicts) |map| { 1754 if (null == try conflicts.getCursor(&merged_key)) { 1755 if (try map.getSlot(&merged_key)) |conflict_slot| { 1756 const baseline_conflict_slot = if (baseline_conflicts) |baseline_map| try baseline_map.getSlot(&merged_key) else null; 1757 const resolved = if (baseline_conflict_slot) |slot| slot.eql(conflict_slot) else false; 1758 if (!resolved) try conflicts.put(&merged_key, .{ .slot = conflict_slot }); 1759 } 1760 } 1761 } 1762 } 1763 } 1764 1765 // a comment, attachment or assignment a write names under a thread 1766 pub const ThreadChild = union(enum) { 1767 comment: *const [event_id_size]u8, 1768 attach: *const [event_id_size]u8, 1769 assign: *const [event_id_size]u8, 1770 }; 1771 1772 // whether `thread_id` names a thread of `thread_kind` in the repo's events, and 1773 // `child`, when given, belongs to it. a caller's url can claim any kind for any 1774 // id, so every write under a thread checks its claim here first. 1775 pub fn threadHolds( 1776 comptime repo_kind: rp.RepoKind, 1777 comptime repo_opts: rp.RepoOpts(repo_kind), 1778 io: std.Io, 1779 allocator: std.mem.Allocator, 1780 repo: *rp.Repo(repo_kind, repo_opts), 1781 thread_kind: EventKind, 1782 thread_id: *const [event_id_size]u8, 1783 child_maybe: ?ThreadChild, 1784 ) !bool { 1785 const DB = EventDB(repo_opts.hash); 1786 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; 1787 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1788 const moment = (if (event_db_maybe) |*event_db| 1789 currentMomentFromDb(repo_opts.hash, event_db.db) 1790 else if (repo_kind == .git) 1791 return false 1792 else 1793 currentMoment(repo_opts, repo)) catch return false; 1794 1795 // only these kinds are threads 1796 switch (thread_kind) { 1797 .discuss, .issue, .patch => {}, 1798 else => return false, 1799 } 1800 const kinds_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, event_index_key)) orelse return false; 1801 const kinds = try DB.HashMap(.read_only).init(kinds_cursor); 1802 if ((try readEventKind(repo_opts.hash, kinds, thread_id)) != thread_kind) return false; 1803 1804 const child = child_maybe orelse return true; 1805 var arena = std.heap.ArenaAllocator.init(allocator); 1806 defer arena.deinit(); 1807 const thread_id_hex = std.fmt.bytesToHex(thread_id.*, .lower); 1808 switch (child) { 1809 .comment => |id| { 1810 const comment = (try readRecordSubset(Comment, struct { event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1811 return std.mem.eql(u8, &comment.event.thread_id, &thread_id_hex); 1812 }, 1813 .attach => |id| { 1814 const attachment = (try readRecordSubset(Attachment, struct { event: struct { target_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1815 return std.mem.eql(u8, &attachment.event.target_id, &thread_id_hex); 1816 }, 1817 // only an active assignment can be removed 1818 .assign => |id| { 1819 const assignment = (try readRecordSubset(Assignment, struct { removed: bool, event: struct { thread_id: [event_id_size * 2]u8 } }, DB, repo_opts.hash, moment, &arena, id)) orelse return false; 1820 return !assignment.removed and std.mem.eql(u8, &assignment.event.thread_id, &thread_id_hex); 1821 }, 1822 } 1823 } 1824 1825 // remove an event a thread's page names: the thread itself, or a comment, 1826 // attachment or assignment, which must belong to it 1827 pub fn removeInThread( 1828 host: Host, 1829 comptime repo_kind: rp.RepoKind, 1830 comptime repo_opts: rp.RepoOpts(repo_kind), 1831 io: std.Io, 1832 allocator: std.mem.Allocator, 1833 repo: *rp.Repo(repo_kind, repo_opts), 1834 thread_kind: EventKind, 1835 thread_id: *const [event_id_size]u8, 1836 kind: EventKind, 1837 id: *const [event_id_size]u8, 1838 author: CommitAuthor, 1839 ) !void { 1840 const child_maybe: ?ThreadChild = switch (kind) { 1841 .comment => .{ .comment = id }, 1842 .attach => .{ .attach = id }, 1843 .assign => .{ .assign = id }, 1844 else => null, 1845 }; 1846 if (child_maybe) |child| { 1847 if (!try threadHolds(repo_kind, repo_opts, io, allocator, repo, thread_kind, thread_id, child)) return error.EventNotFound; 1848 } 1849 try remove(host, .repo, repo_kind, repo_opts, io, allocator, repo, id, kind, author); 1850 } 1851 1852 pub fn readFromRepo( 1853 comptime T: type, 1854 comptime repo_kind: rp.RepoKind, 1855 comptime repo_opts: rp.RepoOpts(repo_kind), 1856 io: std.Io, 1857 allocator: std.mem.Allocator, 1858 arena: *std.heap.ArenaAllocator, 1859 repo: *rp.Repo(repo_kind, repo_opts), 1860 id: *const [event_id_size]u8, 1861 ) !?T.Record { 1862 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; 1863 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1864 const moment = (if (event_db_maybe) |*event_db| 1865 currentMomentFromDb(repo_opts.hash, event_db.db) 1866 else if (repo_kind == .git) 1867 return null 1868 else 1869 currentMoment(repo_opts, repo)) catch return null; 1870 return T.readById(EventDB(repo_opts.hash), repo_opts.hash, moment, arena, id); 1871 } 1872 1873 pub fn currentMoment( 1874 comptime repo_opts: rp.RepoOpts(.xit), 1875 repo: *rp.Repo(.xit, repo_opts), 1876 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 1877 return currentMomentFromDb(repo_opts.hash, &repo.core.db); 1878 } 1879 1880 pub fn currentMomentFromDb( 1881 comptime hash_kind: hash.HashKind, 1882 db: *EventDB(hash_kind), 1883 ) !EventDB(hash_kind).HashMap(.read_only) { 1884 const DB = EventDB(hash_kind); 1885 const history = try DB.ArrayList(.read_only).init(db.rootCursor().readOnly()); 1886 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 1887 const moment = try DB.HashMap(.read_only).init(moment_cursor); 1888 return try currentMomentFromRepoMoment(hash_kind, moment); 1889 } 1890 1891 pub fn currentMomentFromRepoMoment( 1892 comptime hash_kind: hash.HashKind, 1893 moment: EventDB(hash_kind).HashMap(.read_only), 1894 ) !EventDB(hash_kind).HashMap(.read_only) { 1895 const DB = EventDB(hash_kind); 1896 const last_object_id_cursor = try moment.getCursor(hash.hashInt(hash_kind, last_object_id_key)) orelse return error.NotFound; 1897 var last_object_id: [hash.byteLen(hash_kind)]u8 = undefined; 1898 _ = try last_object_id_cursor.readBytes(&last_object_id); 1899 const haxy_history_cursor = try moment.getCursor(hash.hashInt(hash_kind, history_key)) orelse return error.NotFound; 1900 const haxy_history = try DB.ArrayList(.read_only).init(haxy_history_cursor); 1901 const haxy_moments_cursor = try haxy_history.getCursor(-1) orelse return error.NotFound; 1902 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 1903 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(hash_kind, &last_object_id)) orelse return error.NotFound; 1904 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 1905 } 1906 1907 // build a sorted-set key from an order and event id. big-endian order makes 1908 // byte order match numeric order; the event id breaks ties. 1909 pub fn orderKey(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1910 var key: [@sizeOf(u64) + event_id_size]u8 = undefined; 1911 std.mem.writeInt(u64, key[0..@sizeOf(u64)], order, .big); 1912 @memcpy(key[@sizeOf(u64)..], event_id); 1913 return key; 1914 } 1915 1916 pub fn orderKeyDesc(order: u64, event_id: *const [event_id_size]u8) [@sizeOf(u64) + event_id_size]u8 { 1917 return orderKey(std.math.maxInt(u64) - order, event_id); 1918 } 1919 1920 pub fn removedRecord( 1921 comptime T: type, 1922 comptime DB: type, 1923 comptime hash_kind: hash.HashKind, 1924 haxy_moment: DB.HashMap(.read_only), 1925 existing_maybe: ?T, 1926 ) !T { 1927 var record = existing_maybe orelse return error.EventNotFound; 1928 record.removed = true; 1929 const order_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_order_key)) orelse return error.CursorNotFound; 1930 record.updated_order = try order_cursor.readUint(); 1931 return record; 1932 } 1933 1934 // add or refresh one entry in the global logical-event index 1935 pub fn indexEvent( 1936 comptime DB: type, 1937 comptime hash_kind: hash.HashKind, 1938 haxy_moment: DB.HashMap(.read_write), 1939 event_id: *const [event_id_size]u8, 1940 kind: EventKind, 1941 existing_maybe: anytype, 1942 record: anytype, 1943 ) !void { 1944 const event_key = hash.hashInt(hash_kind, event_id); 1945 const kind_map_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, event_index_key)); 1946 const kind_map = try DB.HashMap(.read_write).init(kind_map_cursor); 1947 try kind_map.put(event_key, .{ .bytes = @tagName(kind) }); 1948 1949 const active_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, active_event_id_set_key)); 1950 const active = try DB.SortedSet(.read_write).init(active_cursor); 1951 const removed_cursor = try haxy_moment.putCursor(hash.hashInt(hash_kind, removed_event_id_set_key)); 1952 const removed_set = try DB.SortedSet(.read_write).init(removed_cursor); 1953 1954 if (existing_maybe) |existing| { 1955 const old_key = orderKeyDesc(existing.updated_order, event_id); 1956 _ = try active.remove(&old_key); 1957 _ = try removed_set.remove(&old_key); 1958 } 1959 1960 const order_key = orderKeyDesc(record.updated_order, event_id); 1961 if (record.removed) { 1962 try removed_set.put(&order_key); 1963 } else { 1964 try active.put(&order_key); 1965 } 1966 } 1967 1968 pub fn touchThread( 1969 comptime DB: type, 1970 comptime hash_kind: hash.HashKind, 1971 haxy_moment: DB.HashMap(.read_write), 1972 thread_id: *const [event_id_size]u8, 1973 order: u64, 1974 arena: *std.heap.ArenaAllocator, 1975 ) !void { 1976 const kind_map_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, event_index_key)) orelse return; 1977 const kind_map = try DB.HashMap(.read_only).init(kind_map_cursor); 1978 const kind = (try readEventKind(hash_kind, kind_map, thread_id)) orelse return; 1979 switch (kind) { 1980 .discuss => try Discussion.touch(DB, hash_kind, haxy_moment, thread_id, order, arena), 1981 else => {}, 1982 } 1983 } 1984 1985 pub fn readEventKind( 1986 comptime hash_kind: hash.HashKind, 1987 kind_map: anytype, 1988 id: *const [event_id_size]u8, 1989 ) !?EventKind { 1990 const cursor = try kind_map.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 1991 var buffer: [64]u8 = undefined; 1992 return std.meta.stringToEnum(EventKind, try cursor.readBytes(&buffer)) orelse error.InvalidEventKind; 1993 } 1994 1995 // the email of the event's author, or null when the id names no authored event 1996 // of this kind 1997 pub fn readAuthorEmail( 1998 comptime repo_kind: rp.RepoKind, 1999 comptime repo_opts: rp.RepoOpts(repo_kind), 2000 io: std.Io, 2001 allocator: std.mem.Allocator, 2002 arena: *std.heap.ArenaAllocator, 2003 repo: *rp.Repo(repo_kind, repo_opts), 2004 kind: EventKind, 2005 id: *const [event_id_size]u8, 2006 ) !?[]const u8 { 2007 const record_map_key = switch (kind) { 2008 .discuss => Discussion.record_map_key, 2009 .issue => Issue.record_map_key, 2010 .comment => Comment.record_map_key, 2011 .attach => Attachment.record_map_key, 2012 .assign => Assignment.record_map_key, 2013 .patchrev => PatchRev.record_map_key, 2014 .patch => Patch.record_map_key, 2015 .user, .repo, .fork, .grant, .notify => return null, 2016 }; 2017 2018 const DB = EventDB(repo_opts.hash); 2019 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; 2020 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 2021 const moment = (if (event_db_maybe) |*event_db| 2022 currentMomentFromDb(repo_opts.hash, event_db.db) 2023 else if (repo_kind == .git) 2024 return null 2025 else 2026 currentMoment(repo_opts, repo)) catch return null; 2027 2028 const records_cursor = (try moment.getCursor(hash.hashInt(repo_opts.hash, record_map_key))) orelse return null; 2029 const records = try DB.HashMap(.read_only).init(records_cursor); 2030 const record_cursor = (try records.getCursor(hash.hashInt(repo_opts.hash, id))) orelse return null; 2031 const record = try DB.HashMap(.read_only).init(record_cursor); 2032 return try readField(?[]const u8, DB, repo_opts.hash, arena, try record.getCursor(hash.hashInt(repo_opts.hash, "author_email"))); 2033 } 2034 2035 // the event id embedded in a set entry's order key 2036 pub fn readOrderKeyId(comptime DB: type, kv_pair_cursor: DB.Cursor(.read_only)) ![event_id_size]u8 { 2037 var cursor = kv_pair_cursor; 2038 const kv_pair = try cursor.readKeyValuePair(); 2039 var order_key: [@sizeOf(u64) + event_id_size]u8 = undefined; 2040 _ = try kv_pair.key_cursor.readBytes(&order_key); 2041 return order_key[@sizeOf(u64)..][0..event_id_size].*; 2042 } 2043 2044 // split a pushed "<owner>:<repo>" path into its two components, or null if it 2045 // isn't exactly two non-empty parts with no "/". 2046 pub fn parseOwnerRepoPath(path: []const u8) ?struct { owner: []const u8, name: []const u8 } { 2047 if (std.mem.indexOfScalar(u8, path, '/') != null) return null; 2048 var it = std.mem.splitScalar(u8, path, ':'); 2049 const owner = it.next() orelse return null; 2050 const name = it.next() orelse return null; 2051 if (it.next() != null) return null; 2052 if (owner.len == 0 or name.len == 0) return null; 2053 2054 return .{ .owner = owner, .name = name }; 2055 } 2056 2057 pub const CreateRepoOptions = struct { 2058 read_access: Repo.Access = .private, 2059 }; 2060 2061 // the ids that locate a repo's on-disk directory 2062 pub const RepoLocation = struct { 2063 owner_id: [event_id_size]u8, 2064 repo_id: [event_id_size]u8, 2065 }; 2066 2067 // resolve a pushed `<owner>:<repo>` to the ids that locate its on-disk directory 2068 pub fn resolveOrCreateRepo( 2069 io: std.Io, 2070 allocator: std.mem.Allocator, 2071 users_dir: []const u8, 2072 admin_repo_path: []const u8, 2073 owner_name: []const u8, 2074 repo_name: []const u8, 2075 create_options_maybe: ?CreateRepoOptions, 2076 ) !?RepoLocation { 2077 var admin_repo = rp.Repo(.xit, admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }) catch |err| switch (err) { 2078 error.RepoNotFound => return null, 2079 else => |e| return e, 2080 }; 2081 defer admin_repo.deinit(io, allocator); 2082 2083 var arena = std.heap.ArenaAllocator.init(allocator); 2084 defer arena.deinit(); 2085 2086 const admin_moment = try currentMoment(admin_repo_opts, &admin_repo); 2087 2088 // an unknown owner can't own a repo, so the push is rejected 2089 const owner_user_id = (try User.readIdByName(AdminDB, admin_repo_opts.hash, admin_moment, owner_name)) orelse return null; 2090 var user_repo = (try openUserRepo(io, allocator, users_dir, &owner_user_id)) orelse return null; 2091 defer user_repo.deinit(io, allocator); 2092 2093 // an already-registered repo reuses its event id, so a re-push (or a clone) 2094 // lands in the same repo 2095 if (try userMoment(&user_repo)) |moment| { 2096 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, repo_name)) |found| { 2097 return .{ .owner_id = owner_user_id, .repo_id = found.event_id }; 2098 } 2099 } 2100 2101 const create_options = create_options_maybe orelse return null; 2102 2103 const owner = (try User.readById(AdminDB, admin_repo_opts.hash, admin_moment, &arena, &owner_user_id)) orelse unreachable; 2104 2105 var id_bytes: [event_id_size]u8 = undefined; 2106 io.random(&id_bytes); 2107 try writeRepoEvent(io, allocator, users_dir, &user_repo, &owner_user_id, .{ .name = owner.event.name, .email = owner.event.email }, &id_bytes, repo_name, "", create_options.read_access); 2108 return .{ .owner_id = owner_user_id, .repo_id = id_bytes }; 2109 } 2110 2111 // create a bare repo with `hash_kind` and register it in its owner's user repo 2112 pub fn createRepo( 2113 io: std.Io, 2114 allocator: std.mem.Allocator, 2115 users_dir: []const u8, 2116 owner_id: *const [event_id_size]u8, 2117 owner: CommitAuthor, 2118 name: []const u8, 2119 description: []const u8, 2120 read_access: Repo.Access, 2121 hash_kind: hash.HashKind, 2122 ) !RepoLocation { 2123 try Repo.validateName(name); 2124 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2125 defer user_repo.deinit(io, allocator); 2126 if (try userMoment(&user_repo)) |moment| { 2127 var arena = std.heap.ArenaAllocator.init(allocator); 2128 defer arena.deinit(); 2129 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name) != null) return error.NameTaken; 2130 } 2131 2132 var id_bytes: [event_id_size]u8 = undefined; 2133 io.random(&id_bytes); 2134 2135 // the directory comes first so a listed repo always has one 2136 { 2137 const path = try repoPath(allocator, users_dir, owner_id, &id_bytes); 2138 defer allocator.free(path); 2139 switch (hash_kind) { 2140 inline else => |kind| { 2141 var repo = try rp.Repo(.xit, .{ .hash = kind }).init(io, allocator, .{ .path = path, .bare = true }); 2142 defer repo.deinit(io, allocator); 2143 }, 2144 } 2145 } 2146 2147 try writeRepoEvent(io, allocator, users_dir, &user_repo, owner_id, owner, &id_bytes, name, description, read_access); 2148 return .{ .owner_id = owner_id.*, .repo_id = id_bytes }; 2149 } 2150 2151 // change the name, description, read access, and tab roles of the repo 2152 // named `old_name` in its owner's user repo 2153 pub fn updateRepo( 2154 io: std.Io, 2155 allocator: std.mem.Allocator, 2156 users_dir: []const u8, 2157 owner_id: *const [event_id_size]u8, 2158 author: CommitAuthor, 2159 old_name: []const u8, 2160 name: []const u8, 2161 description: []const u8, 2162 read_access: Repo.Access, 2163 discuss_role: ?Repo.Role, 2164 issue_role: ?Repo.Role, 2165 patch_role: ?Repo.Role, 2166 ) !void { 2167 try Repo.validateName(name); 2168 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2169 defer user_repo.deinit(io, allocator); 2170 var arena = std.heap.ArenaAllocator.init(allocator); 2171 defer arena.deinit(); 2172 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2173 const found = (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, old_name)) orelse return error.NotFound; 2174 if (try Repo.readByName(UserDB, user_repo_opts.hash, moment, &arena, name)) |taken| { 2175 if (!std.mem.eql(u8, &taken.event_id, &found.event_id)) return error.NameTaken; 2176 } 2177 2178 var event = found.repo.event; 2179 event.name = name; 2180 event.description = description; 2181 event.read_access = read_access; 2182 event.discuss_role = discuss_role; 2183 event.issue_role = issue_role; 2184 event.patch_role = patch_role; 2185 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2186 .id = std.fmt.bytesToHex(found.event_id, .lower), 2187 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2188 .author = author, 2189 .event = .{ .repo = event }, 2190 }}); 2191 } 2192 2193 // grant `user_id` `role` on the repo `repo_id` in its owner's user repo, 2194 // replacing any role they held 2195 pub fn grantRole( 2196 io: std.Io, 2197 allocator: std.mem.Allocator, 2198 users_dir: []const u8, 2199 owner_id: *const [event_id_size]u8, 2200 repo_id: *const [event_id_size]u8, 2201 user_id: *const [event_id_size]u8, 2202 role: Repo.Role, 2203 author: CommitAuthor, 2204 ) !void { 2205 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2206 defer user_repo.deinit(io, allocator); 2207 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2208 .id = std.fmt.bytesToHex(Grant.idOf(repo_id, user_id), .lower), 2209 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2210 .author = author, 2211 .event = .{ .grant = .{ .target_id = std.fmt.bytesToHex(repo_id.*, .lower), .user_id = std.fmt.bytesToHex(user_id.*, .lower), .role = role } }, 2212 }}); 2213 } 2214 2215 // revoke `user_id`'s grant on the repo `repo_id` in its owner's user repo 2216 pub fn revokeRole( 2217 io: std.Io, 2218 allocator: std.mem.Allocator, 2219 users_dir: []const u8, 2220 owner_id: *const [event_id_size]u8, 2221 repo_id: *const [event_id_size]u8, 2222 user_id: *const [event_id_size]u8, 2223 author: CommitAuthor, 2224 ) !void { 2225 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2226 defer user_repo.deinit(io, allocator); 2227 // a revoked grant stays in the kind index, which is all `remove` checks 2228 { 2229 var arena = std.heap.ArenaAllocator.init(allocator); 2230 defer arena.deinit(); 2231 const moment = (try userMoment(&user_repo)) orelse return error.EventNotFound; 2232 if (try Grant.readRole(UserDB, user_repo_opts.hash, moment, &arena, repo_id, user_id) == null) return error.EventNotFound; 2233 } 2234 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, &Grant.idOf(repo_id, user_id), .grant, author); 2235 } 2236 2237 // add `branch` to the protected branches of the repo `repo_id` in its owner's 2238 // user repo, or take it out when `protect` is false. taking out a branch that 2239 // isn't protected writes nothing. 2240 pub fn protectBranch( 2241 io: std.Io, 2242 allocator: std.mem.Allocator, 2243 users_dir: []const u8, 2244 owner_id: *const [event_id_size]u8, 2245 repo_id: *const [event_id_size]u8, 2246 branch: []const u8, 2247 protect: bool, 2248 author: CommitAuthor, 2249 ) !void { 2250 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2251 defer user_repo.deinit(io, allocator); 2252 var arena = std.heap.ArenaAllocator.init(allocator); 2253 defer arena.deinit(); 2254 const aa = arena.allocator(); 2255 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2256 const repo = (try Repo.readById(UserDB, user_repo_opts.hash, moment, &arena, repo_id)) orelse return error.NotFound; 2257 if (repo.removed) return error.NotFound; 2258 2259 var branches: std.ArrayList(u8) = .empty; 2260 var count: usize = 0; 2261 var held = false; 2262 for (try repo.event.protectedBranchNames(aa)) |name| { 2263 if (std.mem.eql(u8, name, branch)) { 2264 held = true; 2265 if (!protect) continue; 2266 } 2267 if (branches.items.len > 0) try branches.append(aa, '\n'); 2268 try branches.appendSlice(aa, name); 2269 count += 1; 2270 } 2271 if (protect) { 2272 if (held) return error.BranchProtected; 2273 if (count >= Repo.protected_branch_max_count) return error.TooManyProtectedBranches; 2274 if (branches.items.len > 0) try branches.append(aa, '\n'); 2275 try branches.appendSlice(aa, branch); 2276 } else if (!held) return; 2277 2278 var event = repo.event; 2279 event.protected_branches = branches.items; 2280 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2281 .id = std.fmt.bytesToHex(repo_id.*, .lower), 2282 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2283 .author = author, 2284 .event = .{ .repo = event }, 2285 }}); 2286 } 2287 2288 // create a user and their user repo, returning the new user's id 2289 pub fn createUser( 2290 io: std.Io, 2291 allocator: std.mem.Allocator, 2292 users_dir: []const u8, 2293 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2294 name: []const u8, 2295 email: []const u8, 2296 password: []const u8, 2297 password_again: []const u8, 2298 ) ![event_id_size]u8 { 2299 try User.validateName(name); 2300 if (email.len == 0) return error.EmailEmpty; 2301 if (password.len == 0) return error.PasswordEmpty; 2302 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2303 // a fresh admin repo has no moment until its first event 2304 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2305 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2306 var arena = std.heap.ArenaAllocator.init(allocator); 2307 defer arena.deinit(); 2308 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2309 } else |err| switch (err) { 2310 error.NotFound => {}, 2311 else => |e| return e, 2312 } 2313 2314 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2315 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2316 2317 var id_bytes: [event_id_size]u8 = undefined; 2318 io.random(&id_bytes); 2319 2320 // the user repo comes first so a listed user can always create repos 2321 { 2322 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2323 defer allocator.free(path); 2324 var user_repo = try initUserRepo(io, allocator, path); 2325 defer user_repo.deinit(io, allocator); 2326 } 2327 2328 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2329 .id = std.fmt.bytesToHex(id_bytes, .lower), 2330 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2331 .author = .{ .name = name, .email = email }, 2332 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2333 }}); 2334 return id_bytes; 2335 } 2336 2337 // change a user's email, and their password when the password fields are 2338 // filled in 2339 pub fn updateUser( 2340 io: std.Io, 2341 allocator: std.mem.Allocator, 2342 users_dir: []const u8, 2343 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2344 user_id: *const [event_id_size]u8, 2345 email: []const u8, 2346 current_password: []const u8, 2347 new_password: []const u8, 2348 new_password_again: []const u8, 2349 ) !void { 2350 if (email.len == 0) return error.EmailEmpty; 2351 var arena = std.heap.ArenaAllocator.init(allocator); 2352 defer arena.deinit(); 2353 const moment = try currentMoment(admin_repo_opts, admin_repo); 2354 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2355 if (user.removed) return error.NotFound; 2356 if (!std.mem.eql(u8, email, user.event.email) and try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2357 2358 var event = user.event; 2359 event.email = email; 2360 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2361 if (current_password.len + new_password.len + new_password_again.len > 0) { 2362 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2363 if (new_password.len == 0) return error.PasswordEmpty; 2364 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2365 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2366 } 2367 2368 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2369 .id = std.fmt.bytesToHex(user_id.*, .lower), 2370 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2371 .author = .{ .name = event.name, .email = email }, 2372 .event = .{ .user = event }, 2373 }}); 2374 } 2375 2376 // add an authorized_keys line to the user's ssh keys 2377 pub fn addUserKey( 2378 io: std.Io, 2379 allocator: std.mem.Allocator, 2380 users_dir: []const u8, 2381 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2382 user_id: *const [event_id_size]u8, 2383 key_text: []const u8, 2384 ) !void { 2385 const key = std.mem.trim(u8, key_text, " \t\r"); 2386 // the keys are stored one per line 2387 if (std.mem.indexOfScalar(u8, key, '\n') != null) return error.InvalidKey; 2388 const fingerprint = User.fingerprintOfKey(key) orelse return error.InvalidKey; 2389 // the key types the ssh server verifies 2390 const key_type = std.mem.sliceTo(key, ' '); 2391 if (!std.mem.eql(u8, key_type, "ssh-ed25519") and !std.mem.eql(u8, key_type, "ssh-rsa")) return error.UnsupportedKey; 2392 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, &fingerprint, key); 2393 } 2394 2395 // remove the user's ssh key with this fingerprint. removing a key they don't 2396 // hold writes nothing. 2397 pub fn removeUserKey( 2398 io: std.Io, 2399 allocator: std.mem.Allocator, 2400 users_dir: []const u8, 2401 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2402 user_id: *const [event_id_size]u8, 2403 fingerprint: *const [User.fingerprint_len]u8, 2404 ) !void { 2405 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, fingerprint, null); 2406 } 2407 2408 // rewrite the user's ssh keys with `added` appended, or without the key with 2409 // `fingerprint` when nothing is added 2410 fn writeUserKeys( 2411 io: std.Io, 2412 allocator: std.mem.Allocator, 2413 users_dir: []const u8, 2414 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2415 user_id: *const [event_id_size]u8, 2416 fingerprint: *const [User.fingerprint_len]u8, 2417 added: ?[]const u8, 2418 ) !void { 2419 var arena = std.heap.ArenaAllocator.init(allocator); 2420 defer arena.deinit(); 2421 const moment = try currentMoment(admin_repo_opts, admin_repo); 2422 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2423 if (user.removed) return error.NotFound; 2424 2425 var keys: std.ArrayList(u8) = .empty; 2426 var count: usize = 0; 2427 var held = false; 2428 var lines = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 2429 while (lines.next()) |line| { 2430 const line_fingerprint = User.fingerprintOfKey(line) orelse continue; 2431 if (std.mem.eql(u8, &line_fingerprint, fingerprint)) { 2432 held = true; 2433 if (added == null) continue; 2434 } 2435 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2436 try keys.appendSlice(arena.allocator(), line); 2437 count += 1; 2438 } 2439 if (added) |key| { 2440 if (held) return error.KeyAdded; 2441 if (count >= User.ssh_key_max_count) return error.TooManyKeys; 2442 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2443 try keys.appendSlice(arena.allocator(), key); 2444 } else if (!held) return; 2445 2446 var event = user.event; 2447 event.ssh_keys = keys.items; 2448 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2449 .id = std.fmt.bytesToHex(user_id.*, .lower), 2450 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2451 .author = .{ .name = event.name, .email = event.email }, 2452 .event = .{ .user = event }, 2453 }}); 2454 } 2455 2456 // consume a new repo's event into its owner's user repo and mark it active 2457 fn writeRepoEvent( 2458 io: std.Io, 2459 allocator: std.mem.Allocator, 2460 users_dir: []const u8, 2461 user_repo: *rp.Repo(.xit, user_repo_opts), 2462 owner_id: *const [event_id_size]u8, 2463 owner: CommitAuthor, 2464 id_bytes: *const [event_id_size]u8, 2465 name: []const u8, 2466 description: []const u8, 2467 read_access: Repo.Access, 2468 ) !void { 2469 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2470 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2471 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2472 .timestamp = timestamp, 2473 .author = owner, 2474 .event = .{ .repo = .{ 2475 .user_id = std.fmt.bytesToHex(owner_id.*, .lower), 2476 .name = name, 2477 .description = description, 2478 .read_access = read_access, 2479 } }, 2480 }}); 2481 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2482 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2483 }; 2484 } 2485 2486 // 2487 // reading from xitdb 2488 // 2489 2490 // read just `Fields`, a subset of `T.Record`, from the record with event id 2491 // `id`, or null when there is none 2492 pub fn readRecordSubset( 2493 comptime T: type, 2494 comptime Fields: type, 2495 comptime DB: type, 2496 comptime hash_kind: hash.HashKind, 2497 haxy_moment: DB.HashMap(.read_only), 2498 arena: *std.heap.ArenaAllocator, 2499 id: []const u8, 2500 ) !?Fields { 2501 comptime assertFieldSubset(Fields, T.Record); 2502 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2503 const records = try DB.HashMap(.read_only).init(records_cursor); 2504 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2505 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2506 } 2507 2508 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2509 const info = @typeInfo(Sub).@"struct"; 2510 for (info.field_names, info.field_types) |field_name, field_type| { 2511 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2512 const FullField = @FieldType(Full, field_name); 2513 if (@typeInfo(field_type) == .@"struct") { 2514 assertFieldSubset(field_type, FullField); 2515 } else if (field_type != FullField) { 2516 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2517 } 2518 } 2519 } 2520 2521 pub fn read( 2522 comptime T: type, 2523 comptime DB: type, 2524 comptime hash_kind: hash.HashKind, 2525 arena: *std.heap.ArenaAllocator, 2526 map: DB.HashMap(.read_only), 2527 ) !T { 2528 var event: T = undefined; 2529 switch (@typeInfo(T)) { 2530 .@"struct" => |struct_info| { 2531 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2532 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2533 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2534 } 2535 }, 2536 else => @compileError("read expects a struct"), 2537 } 2538 return event; 2539 } 2540 2541 fn readField( 2542 comptime Field: type, 2543 comptime DB: type, 2544 comptime hash_kind: hash.HashKind, 2545 arena: *std.heap.ArenaAllocator, 2546 cursor_maybe: ?DB.Cursor(.read_only), 2547 ) !Field { 2548 if (@typeInfo(Field) == .optional) { 2549 // a missing key or a null union payload is null 2550 const cursor = cursor_maybe orelse return null; 2551 if (cursor.slot().tag == .none) return null; 2552 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2553 } 2554 const cursor = cursor_maybe orelse return error.NotFound; 2555 switch (@typeInfo(Field)) { 2556 .pointer => |pointer_info| { 2557 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2558 @compileError("unsupported read field type: " ++ @typeName(Field)); 2559 } 2560 return try cursor.readBytesAlloc(arena.allocator(), null); 2561 }, 2562 .array => |array_info| { 2563 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2564 var bytes: Field = undefined; 2565 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2566 return bytes; 2567 }, 2568 .bool => { 2569 var buffer: [5]u8 = undefined; 2570 const bytes = try cursor.readBytesObject(&buffer); 2571 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2572 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2573 if (std.mem.eql(u8, bytes.value, "true")) return true; 2574 if (std.mem.eql(u8, bytes.value, "false")) return false; 2575 return error.InvalidBool; 2576 }, 2577 .int => |int_info| return switch (int_info.signedness) { 2578 .unsigned => @intCast(try cursor.readUint()), 2579 .signed => @intCast(try cursor.readInt()), 2580 }, 2581 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2582 .@"union" => |union_info| { 2583 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2584 switch (cursor.slot().tag) { 2585 .bytes, .short_bytes => { 2586 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2587 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2588 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2589 return @unionInit(Field, variant_name, {}); 2590 } 2591 } 2592 return error.InvalidUnion; 2593 }, 2594 .hash_map => { 2595 const variants = try DB.HashMap(.read_only).init(cursor); 2596 var iter = try variants.iterator(); 2597 const entry = (try iter.next()) orelse return error.InvalidUnion; 2598 const pair = try entry.readKeyValuePair(); 2599 if (try iter.next() != null) return error.InvalidUnion; 2600 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2601 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2602 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2603 } 2604 } 2605 return error.InvalidUnion; 2606 }, 2607 else => return error.InvalidUnion, 2608 } 2609 }, 2610 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2611 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2612 } 2613 } 2614 2615 // whether two events carry the same data 2616 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2617 switch (@typeInfo(T)) { 2618 .@"struct" => |struct_info| { 2619 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2620 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2621 } 2622 }, 2623 else => @compileError("fieldsEqual expects a struct"), 2624 } 2625 2626 return true; 2627 } 2628 2629 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2630 switch (@typeInfo(Field)) { 2631 .pointer => |pointer_info| { 2632 if (pointer_info.size == .slice and pointer_info.child == u8) { 2633 return std.mem.eql(u8, a, b); 2634 } else { 2635 @compileError("unsupported field type: " ++ @typeName(Field)); 2636 } 2637 }, 2638 .array => |array_info| { 2639 if (array_info.child == u8) { 2640 return std.mem.eql(u8, &a, &b); 2641 } else { 2642 @compileError("unsupported field type: " ++ @typeName(Field)); 2643 } 2644 }, 2645 .void => return true, 2646 .bool, .int, .@"enum" => return a == b, 2647 .@"union" => { 2648 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2649 return switch (a) { 2650 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2651 }; 2652 }, 2653 .@"struct" => return fieldsEqual(Field, a, b), 2654 .optional => |optional_info| { 2655 if (a) |a_value| { 2656 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2657 return false; 2658 } 2659 return b == null; 2660 }, 2661 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2662 } 2663 } 2664 2665 // 2666 // writing to xitdb 2667 // 2668 2669 pub fn upsert( 2670 comptime T: type, 2671 comptime DB: type, 2672 comptime hash_kind: hash.HashKind, 2673 map: DB.HashMap(.read_write), 2674 event: T, 2675 ) !void { 2676 switch (@typeInfo(T)) { 2677 .@"struct" => |struct_info| { 2678 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2679 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2680 } 2681 }, 2682 else => @compileError("upsert expects a struct"), 2683 } 2684 } 2685 2686 fn upsertField( 2687 comptime DB: type, 2688 comptime hash_kind: hash.HashKind, 2689 map: DB.HashMap(.read_write), 2690 comptime field_name: []const u8, 2691 comptime Field: type, 2692 value: Field, 2693 ) !void { 2694 const key = hash.hashInt(hash_kind, field_name); 2695 2696 switch (@typeInfo(Field)) { 2697 .pointer => |pointer_info| { 2698 if (pointer_info.size == .slice and pointer_info.child == u8) { 2699 try upsertBytes(DB, hash_kind, map, key, value); 2700 } else { 2701 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2702 } 2703 }, 2704 .array => |array_info| { 2705 if (array_info.child == u8) { 2706 try upsertBytes(DB, hash_kind, map, key, &value); 2707 } else { 2708 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2709 } 2710 }, 2711 .int => |int_info| switch (int_info.signedness) { 2712 .unsigned => { 2713 if (try map.getCursor(key)) |value_cursor| { 2714 if (try value_cursor.readUint() == value) { 2715 return; 2716 } 2717 } 2718 2719 try map.put(key, .{ .uint = value }); 2720 }, 2721 .signed => { 2722 if (try map.getCursor(key)) |value_cursor| { 2723 if (try value_cursor.readInt() == value) { 2724 return; 2725 } 2726 } 2727 2728 try map.put(key, .{ .int = value }); 2729 }, 2730 }, 2731 .bool => { 2732 const bytes = if (value) "true" else "false"; 2733 if (try map.getCursor(key)) |value_cursor| { 2734 var buffer: [5]u8 = undefined; 2735 const existing = try value_cursor.readBytesObject(&buffer); 2736 if (existing.format_tag) |format_tag| { 2737 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2738 return; 2739 } 2740 } 2741 } 2742 2743 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2744 }, 2745 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2746 .@"union" => switch (value) { 2747 inline else => |payload, tag| { 2748 if (@TypeOf(payload) == void) { 2749 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2750 } else { 2751 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2752 if (try map.getCursor(key)) |cursor| { 2753 switch (cursor.slot().tag) { 2754 .hash_map => { 2755 const variants = try DB.HashMap(.read_only).init(cursor); 2756 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2757 }, 2758 else => try map.put(key, .{ .slot = null }), 2759 } 2760 } 2761 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2762 if (@typeInfo(@TypeOf(payload)) == .optional) { 2763 // keep the variant even when its payload is null 2764 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2765 } 2766 if (try variants.getCursor(tag_key)) |cursor| { 2767 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2768 } 2769 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2770 } 2771 }, 2772 }, 2773 .optional => |optional_info| { 2774 // a missing key is null 2775 if (value) |child| { 2776 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2777 } else { 2778 _ = try map.remove(key); 2779 } 2780 }, 2781 .@"struct" => try upsert( 2782 Field, 2783 DB, 2784 hash_kind, 2785 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2786 value, 2787 ), 2788 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2789 } 2790 } 2791 2792 fn upsertBytes( 2793 comptime DB: type, 2794 comptime hash_kind: hash.HashKind, 2795 map: DB.HashMap(.read_write), 2796 key: hash.HashInt(hash_kind), 2797 value: []const u8, 2798 ) !void { 2799 var existing_cursor_maybe = try map.getCursor(key); 2800 if (existing_cursor_maybe) |*existing_cursor| { 2801 if (try bytesEqual(DB, existing_cursor, value)) { 2802 return; 2803 } 2804 } 2805 2806 try map.put(key, .{ .bytes = value }); 2807 } 2808 2809 fn bytesEqual( 2810 comptime DB: type, 2811 cursor: *DB.Cursor(.read_only), 2812 value: []const u8, 2813 ) !bool { 2814 switch (cursor.slot().tag) { 2815 .bytes, .short_bytes => {}, 2816 else => return false, 2817 } 2818 var read_buffer: [1024]u8 = undefined; 2819 var reader = try cursor.reader(&read_buffer); 2820 if (reader.size != value.len) { 2821 return false; 2822 } 2823 2824 var chunk_buffer: [1024]u8 = undefined; 2825 var offset: usize = 0; 2826 while (offset < value.len) { 2827 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2828 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2829 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2830 return false; 2831 } 2832 offset += chunk_len; 2833 } 2834 2835 return true; 2836 } 2837 2838 // 2839 // CommitIterator 2840 // 2841 // differs from xit's ObjectIterator in a few ways: 2842 // 2843 // 1. iterates parents first, rather than children first 2844 // 2. `next` only returns the object id, not the full Object 2845 // 3. stores its temporary state in a file on disk to avoid OOMs 2846 // 2847 2848 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2849 return struct { 2850 const DB = EventDB(repo_opts.hash); 2851 // a plain file is used for the scratch db because each write outside 2852 // a transaction is synced anyway, so buffering would gain nothing 2853 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2854 const db_name = "haxy-repo-events.db"; 2855 2856 repo_dir: std.Io.Dir, 2857 db_file: std.Io.File, 2858 db: *TempDB, 2859 // map of each object id to its children 2860 parent_to_children: TempDB.HashMap(.read_write), 2861 // tracking pending parents is necessary because a child can only 2862 // be returned after all of its unconsumed parents have been returned 2863 child_to_pending_parents: TempDB.HashMap(.read_write), 2864 // queue of object ids that are ready to be returned from `next` 2865 ready_queue: TempDB.ArrayList(.read_write), 2866 ready_queue_index: u64, 2867 // the object id at the tip of this branch 2868 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2869 // the object id furthest back in the history that hasn't been consumed 2870 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2871 2872 pub fn init( 2873 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2874 io: std.Io, 2875 allocator: std.mem.Allocator, 2876 consumed_object_ids: DB.HashMap(.read_only), 2877 ref: rf.Ref, 2878 ) !CommitIterator(repo_kind, repo_opts) { 2879 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2880 errdefer { 2881 db_file.close(io); 2882 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2883 } 2884 2885 // cursors point at the db, so it needs a stable address 2886 const db_ptr = try allocator.create(TempDB); 2887 errdefer allocator.destroy(db_ptr); 2888 // the db is scratch state that gets deleted after iteration, so 2889 // there is nothing worth fsyncing 2890 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2891 2892 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2893 2894 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2895 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2896 2897 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2898 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2899 2900 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2901 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2902 2903 var self = CommitIterator(repo_kind, repo_opts){ 2904 .repo_dir = state.core.repo_dir, 2905 .db_file = db_file, 2906 .db = db_ptr, 2907 .parent_to_children = parent_to_children, 2908 .child_to_pending_parents = child_to_pending_parents, 2909 .ready_queue = ready_queue, 2910 .ready_queue_index = 0, 2911 .newest_object_id = null, 2912 .oldest_object_id = null, 2913 }; 2914 errdefer self.deinit(io, allocator); 2915 2916 try self.collect(state, io, allocator, consumed_object_ids, ref); 2917 2918 return self; 2919 } 2920 2921 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2922 self.db_file.close(io); 2923 self.repo_dir.deleteFile(io, db_name) catch {}; 2924 allocator.destroy(self.db); 2925 } 2926 2927 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2928 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2929 2930 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2931 self.ready_queue_index += 1; 2932 2933 try self.enqueueChildren(&oid); 2934 return oid; 2935 } 2936 2937 fn collect( 2938 self: *CommitIterator(repo_kind, repo_opts), 2939 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2940 io: std.Io, 2941 allocator: std.mem.Allocator, 2942 consumed_object_ids: DB.HashMap(.read_only), 2943 ref: rf.Ref, 2944 ) !void { 2945 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2946 2947 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2948 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2949 var walk_queue_index: u64 = 0; 2950 2951 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2952 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2953 2954 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2955 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2956 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2957 try walk_queue.append(.{ .bytes = &head_oid }); 2958 2959 while (walk_queue_index < try walk_queue.count()) { 2960 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2961 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2962 2963 walk_queue_index += 1; 2964 2965 // if we've seen this object id, skip it 2966 if (null != try seen_object_ids.getCursor(oid_int)) { 2967 continue; 2968 } 2969 2970 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 2971 2972 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 2973 defer commit_object.deinit(); 2974 2975 // if this object id has already been consumed, skip it 2976 if (null != try consumed_object_ids.getCursor(oid_int)) { 2977 continue; 2978 } 2979 2980 if (self.newest_object_id == null) self.newest_object_id = oid; 2981 self.oldest_object_id = oid; 2982 2983 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 2984 var pending_parent_count: u64 = 0; 2985 for (parent_oids) |*parent_oid| { 2986 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2987 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 2988 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 2989 2990 // if this object id has already been consumed, skip it 2991 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 2992 continue; 2993 } 2994 2995 // if this object id hasn't already been seen, add it to the walk queue 2996 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 2997 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 2998 } 2999 3000 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 3001 const children = try TempDB.HashSet(.read_write).init(children_cursor); 3002 try children.put(oid_int, .{ .bytes = &oid }); 3003 pending_parent_count += 1; 3004 } 3005 3006 if (pending_parent_count == 0) { 3007 try self.ready_queue.append(.{ .bytes = &oid }); 3008 } else { 3009 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 3010 } 3011 } 3012 } 3013 3014 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 3015 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 3016 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 3017 const children = try TempDB.HashSet(.read_only).init(children_cursor); 3018 var children_iter = try children.iterator(); 3019 3020 while (try children_iter.next()) |*child_cursor| { 3021 const kv_pair = try child_cursor.readKeyValuePair(); 3022 const child_oid_int = kv_pair.hash; 3023 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 3024 const pending_parent_count = try pending_parent_cursor.readUint(); 3025 3026 if (pending_parent_count <= 1) { 3027 _ = try self.child_to_pending_parents.remove(child_oid_int); 3028 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 3029 try self.ready_queue.append(.{ .bytes = &child_oid }); 3030 } else { 3031 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 3032 } 3033 } 3034 } 3035 3036 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 3037 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 3038 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 3039 _ = try oid_cursor.readBytes(&oid); 3040 return oid; 3041 } 3042 }; 3043 } 3044