╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ event.zig ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
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 // remove the repo `repo_id` from its owner's user repo, then its dir. tombstone 2194 // first so a missing repo never remains visible 2195 pub fn deleteRepo( 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 author: CommitAuthor, 2202 ) !void { 2203 { 2204 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2205 defer user_repo.deinit(io, allocator); 2206 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, repo_id, .repo, author); 2207 } 2208 const path = try repoPath(allocator, users_dir, owner_id, repo_id); 2209 defer allocator.free(path); 2210 try std.Io.Dir.cwd().deleteTree(io, path); 2211 } 2212 2213 // grant `user_id` `role` on the repo `repo_id` in its owner's user repo, 2214 // replacing any role they held 2215 pub fn grantRole( 2216 io: std.Io, 2217 allocator: std.mem.Allocator, 2218 users_dir: []const u8, 2219 owner_id: *const [event_id_size]u8, 2220 repo_id: *const [event_id_size]u8, 2221 user_id: *const [event_id_size]u8, 2222 role: Repo.Role, 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 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2228 .id = std.fmt.bytesToHex(Grant.idOf(repo_id, user_id), .lower), 2229 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2230 .author = author, 2231 .event = .{ .grant = .{ .target_id = std.fmt.bytesToHex(repo_id.*, .lower), .user_id = std.fmt.bytesToHex(user_id.*, .lower), .role = role } }, 2232 }}); 2233 } 2234 2235 // revoke `user_id`'s grant on the repo `repo_id` in its owner's user repo 2236 pub fn revokeRole( 2237 io: std.Io, 2238 allocator: std.mem.Allocator, 2239 users_dir: []const u8, 2240 owner_id: *const [event_id_size]u8, 2241 repo_id: *const [event_id_size]u8, 2242 user_id: *const [event_id_size]u8, 2243 author: CommitAuthor, 2244 ) !void { 2245 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2246 defer user_repo.deinit(io, allocator); 2247 // a revoked grant stays in the kind index, which is all `remove` checks 2248 { 2249 var arena = std.heap.ArenaAllocator.init(allocator); 2250 defer arena.deinit(); 2251 const moment = (try userMoment(&user_repo)) orelse return error.EventNotFound; 2252 if (try Grant.readRole(UserDB, user_repo_opts.hash, moment, &arena, repo_id, user_id) == null) return error.EventNotFound; 2253 } 2254 try remove(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, &Grant.idOf(repo_id, user_id), .grant, author); 2255 } 2256 2257 // add `branch` to the protected branches of the repo `repo_id` in its owner's 2258 // user repo, or take it out when `protect` is false. taking out a branch that 2259 // isn't protected writes nothing. 2260 pub fn protectBranch( 2261 io: std.Io, 2262 allocator: std.mem.Allocator, 2263 users_dir: []const u8, 2264 owner_id: *const [event_id_size]u8, 2265 repo_id: *const [event_id_size]u8, 2266 branch: []const u8, 2267 protect: bool, 2268 author: CommitAuthor, 2269 ) !void { 2270 var user_repo = (try openUserRepo(io, allocator, users_dir, owner_id)) orelse return error.NotFound; 2271 defer user_repo.deinit(io, allocator); 2272 var arena = std.heap.ArenaAllocator.init(allocator); 2273 defer arena.deinit(); 2274 const aa = arena.allocator(); 2275 const moment = (try userMoment(&user_repo)) orelse return error.NotFound; 2276 const repo = (try Repo.readById(UserDB, user_repo_opts.hash, moment, &arena, repo_id)) orelse return error.NotFound; 2277 if (repo.removed) return error.NotFound; 2278 2279 var branches: std.ArrayList(u8) = .empty; 2280 var count: usize = 0; 2281 var held = false; 2282 for (try repo.event.protectedBranchNames(aa)) |name| { 2283 if (std.mem.eql(u8, name, branch)) { 2284 held = true; 2285 if (!protect) continue; 2286 } 2287 if (branches.items.len > 0) try branches.append(aa, '\n'); 2288 try branches.appendSlice(aa, name); 2289 count += 1; 2290 } 2291 if (protect) { 2292 if (held) return error.BranchProtected; 2293 if (count >= Repo.protected_branch_max_count) return error.TooManyProtectedBranches; 2294 if (branches.items.len > 0) try branches.append(aa, '\n'); 2295 try branches.appendSlice(aa, branch); 2296 } else if (!held) return; 2297 2298 var event = repo.event; 2299 event.protected_branches = branches.items; 2300 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, &user_repo, events_ref, &[_]EventWithId{.{ 2301 .id = std.fmt.bytesToHex(repo_id.*, .lower), 2302 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2303 .author = author, 2304 .event = .{ .repo = event }, 2305 }}); 2306 } 2307 2308 // create a user and their user repo, returning the new user's id 2309 pub fn createUser( 2310 io: std.Io, 2311 allocator: std.mem.Allocator, 2312 users_dir: []const u8, 2313 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2314 name: []const u8, 2315 email: []const u8, 2316 password: []const u8, 2317 password_again: []const u8, 2318 ) ![event_id_size]u8 { 2319 try User.validateName(name); 2320 if (email.len == 0) return error.EmailEmpty; 2321 if (password.len == 0) return error.PasswordEmpty; 2322 if (!std.mem.eql(u8, password, password_again)) return error.PasswordMismatch; 2323 // a fresh admin repo has no moment until its first event 2324 if (currentMoment(admin_repo_opts, admin_repo)) |moment| { 2325 if (try User.readIdByName(AdminDB, admin_repo_opts.hash, moment, name) != null) return error.NameTaken; 2326 var arena = std.heap.ArenaAllocator.init(allocator); 2327 defer arena.deinit(); 2328 if (try User.readByEmail(AdminDB, admin_repo_opts.hash, moment, &arena, email) != null) return error.EmailTaken; 2329 } else |err| switch (err) { 2330 error.NotFound => {}, 2331 else => |e| return e, 2332 } 2333 2334 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2335 const password_hash = try User.hashPassword(password, &password_hash_buf, io); 2336 2337 var id_bytes: [event_id_size]u8 = undefined; 2338 io.random(&id_bytes); 2339 2340 // the user repo comes first so a listed user can always create repos 2341 { 2342 const path = try userRepoPath(allocator, users_dir, &id_bytes); 2343 defer allocator.free(path); 2344 var user_repo = try initUserRepo(io, allocator, path); 2345 defer user_repo.deinit(io, allocator); 2346 } 2347 2348 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2349 .id = std.fmt.bytesToHex(id_bytes, .lower), 2350 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2351 .author = .{ .name = name, .email = email }, 2352 .event = .{ .user = .{ .name = name, .email = email, .password_hash = password_hash } }, 2353 }}); 2354 return id_bytes; 2355 } 2356 2357 // change a user's email, and their password when the password fields are 2358 // filled in 2359 pub fn updateUser( 2360 io: std.Io, 2361 allocator: std.mem.Allocator, 2362 users_dir: []const u8, 2363 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2364 user_id: *const [event_id_size]u8, 2365 email: []const u8, 2366 current_password: []const u8, 2367 new_password: []const u8, 2368 new_password_again: []const u8, 2369 ) !void { 2370 if (email.len == 0) return error.EmailEmpty; 2371 var arena = std.heap.ArenaAllocator.init(allocator); 2372 defer arena.deinit(); 2373 const moment = try currentMoment(admin_repo_opts, admin_repo); 2374 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2375 if (user.removed) return error.NotFound; 2376 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; 2377 2378 var event = user.event; 2379 event.email = email; 2380 var password_hash_buf: [User.password_hash_max_len]u8 = undefined; 2381 if (current_password.len + new_password.len + new_password_again.len > 0) { 2382 if (!User.verifyPassword(user.event.password_hash, current_password)) return error.WrongPassword; 2383 if (new_password.len == 0) return error.PasswordEmpty; 2384 if (!std.mem.eql(u8, new_password, new_password_again)) return error.PasswordMismatch; 2385 event.password_hash = try User.hashPassword(new_password, &password_hash_buf, io); 2386 } 2387 2388 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2389 .id = std.fmt.bytesToHex(user_id.*, .lower), 2390 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2391 .author = .{ .name = event.name, .email = email }, 2392 .event = .{ .user = event }, 2393 }}); 2394 } 2395 2396 // remove a user from the admin repo, then their dir with every repo and fork 2397 // in it. tombstone first so a missing user never remains visible 2398 pub fn deleteUser( 2399 io: std.Io, 2400 allocator: std.mem.Allocator, 2401 users_dir: []const u8, 2402 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2403 user_id: *const [event_id_size]u8, 2404 author: CommitAuthor, 2405 ) !void { 2406 try remove(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, user_id, .user, author); 2407 const path = try std.Io.Dir.path.join(allocator, &.{ users_dir, &std.fmt.bytesToHex(user_id.*, .lower) }); 2408 defer allocator.free(path); 2409 try std.Io.Dir.cwd().deleteTree(io, path); 2410 } 2411 2412 // add an authorized_keys line to the user's ssh keys 2413 pub fn addUserKey( 2414 io: std.Io, 2415 allocator: std.mem.Allocator, 2416 users_dir: []const u8, 2417 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2418 user_id: *const [event_id_size]u8, 2419 key_text: []const u8, 2420 ) !void { 2421 const key = std.mem.trim(u8, key_text, " \t\r"); 2422 // the keys are stored one per line 2423 if (std.mem.indexOfScalar(u8, key, '\n') != null) return error.InvalidKey; 2424 const fingerprint = User.fingerprintOfKey(key) orelse return error.InvalidKey; 2425 // the key types the ssh server verifies 2426 const key_type = std.mem.sliceTo(key, ' '); 2427 if (!std.mem.eql(u8, key_type, "ssh-ed25519") and !std.mem.eql(u8, key_type, "ssh-rsa")) return error.UnsupportedKey; 2428 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, &fingerprint, key); 2429 } 2430 2431 // remove the user's ssh key with this fingerprint. removing a key they don't 2432 // hold writes nothing. 2433 pub fn removeUserKey( 2434 io: std.Io, 2435 allocator: std.mem.Allocator, 2436 users_dir: []const u8, 2437 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2438 user_id: *const [event_id_size]u8, 2439 fingerprint: *const [User.fingerprint_len]u8, 2440 ) !void { 2441 try writeUserKeys(io, allocator, users_dir, admin_repo, user_id, fingerprint, null); 2442 } 2443 2444 // rewrite the user's ssh keys with `added` appended, or without the key with 2445 // `fingerprint` when nothing is added 2446 fn writeUserKeys( 2447 io: std.Io, 2448 allocator: std.mem.Allocator, 2449 users_dir: []const u8, 2450 admin_repo: *rp.Repo(.xit, admin_repo_opts), 2451 user_id: *const [event_id_size]u8, 2452 fingerprint: *const [User.fingerprint_len]u8, 2453 added: ?[]const u8, 2454 ) !void { 2455 var arena = std.heap.ArenaAllocator.init(allocator); 2456 defer arena.deinit(); 2457 const moment = try currentMoment(admin_repo_opts, admin_repo); 2458 const user = (try User.readById(AdminDB, admin_repo_opts.hash, moment, &arena, user_id)) orelse return error.NotFound; 2459 if (user.removed) return error.NotFound; 2460 2461 var keys: std.ArrayList(u8) = .empty; 2462 var count: usize = 0; 2463 var held = false; 2464 var lines = std.mem.splitScalar(u8, user.event.ssh_keys, '\n'); 2465 while (lines.next()) |line| { 2466 const line_fingerprint = User.fingerprintOfKey(line) orelse continue; 2467 if (std.mem.eql(u8, &line_fingerprint, fingerprint)) { 2468 held = true; 2469 if (added == null) continue; 2470 } 2471 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2472 try keys.appendSlice(arena.allocator(), line); 2473 count += 1; 2474 } 2475 if (added) |key| { 2476 if (held) return error.KeyAdded; 2477 if (count >= User.ssh_key_max_count) return error.TooManyKeys; 2478 if (keys.items.len > 0) try keys.append(arena.allocator(), '\n'); 2479 try keys.appendSlice(arena.allocator(), key); 2480 } else if (!held) return; 2481 2482 var event = user.event; 2483 event.ssh_keys = keys.items; 2484 try consume(.{ .server = .{ .users_dir = users_dir } }, .admin, .xit, admin_repo_opts, io, allocator, admin_repo, events_ref, &[_]EventWithId{.{ 2485 .id = std.fmt.bytesToHex(user_id.*, .lower), 2486 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2487 .author = .{ .name = event.name, .email = event.email }, 2488 .event = .{ .user = event }, 2489 }}); 2490 } 2491 2492 // consume a new repo's event into its owner's user repo and mark it active 2493 fn writeRepoEvent( 2494 io: std.Io, 2495 allocator: std.mem.Allocator, 2496 users_dir: []const u8, 2497 user_repo: *rp.Repo(.xit, user_repo_opts), 2498 owner_id: *const [event_id_size]u8, 2499 owner: CommitAuthor, 2500 id_bytes: *const [event_id_size]u8, 2501 name: []const u8, 2502 description: []const u8, 2503 read_access: Repo.Access, 2504 ) !void { 2505 const timestamp: u64 = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()); 2506 try consume(.{ .server = .{ .users_dir = users_dir } }, .user, .xit, user_repo_opts, io, allocator, user_repo, events_ref, &[_]EventWithId{.{ 2507 .id = std.fmt.bytesToHex(id_bytes.*, .lower), 2508 .timestamp = timestamp, 2509 .author = owner, 2510 .event = .{ .repo = .{ 2511 .user_id = std.fmt.bytesToHex(owner_id.*, .lower), 2512 .name = name, 2513 .description = description, 2514 .read_access = read_access, 2515 } }, 2516 }}); 2517 bumpRepoActivity(io, allocator, users_dir, owner_id, id_bytes, timestamp) catch |err| { 2518 std.log.warn("failed to record repo activity: {s}", .{@errorName(err)}); 2519 }; 2520 } 2521 2522 // 2523 // reading from xitdb 2524 // 2525 2526 // read just `Fields`, a subset of `T.Record`, from the record with event id 2527 // `id`, or null when there is none 2528 pub fn readRecordSubset( 2529 comptime T: type, 2530 comptime Fields: type, 2531 comptime DB: type, 2532 comptime hash_kind: hash.HashKind, 2533 haxy_moment: DB.HashMap(.read_only), 2534 arena: *std.heap.ArenaAllocator, 2535 id: []const u8, 2536 ) !?Fields { 2537 comptime assertFieldSubset(Fields, T.Record); 2538 const records_cursor = try haxy_moment.getCursor(hash.hashInt(hash_kind, T.record_map_key)) orelse return null; 2539 const records = try DB.HashMap(.read_only).init(records_cursor); 2540 const record_cursor = try records.getCursor(hash.hashInt(hash_kind, id)) orelse return null; 2541 return try read(Fields, DB, hash_kind, arena, try DB.HashMap(.read_only).init(record_cursor)); 2542 } 2543 2544 fn assertFieldSubset(comptime Sub: type, comptime Full: type) void { 2545 const info = @typeInfo(Sub).@"struct"; 2546 for (info.field_names, info.field_types) |field_name, field_type| { 2547 if (!@hasField(Full, field_name)) @compileError(@typeName(Full) ++ " has no field " ++ field_name); 2548 const FullField = @FieldType(Full, field_name); 2549 if (@typeInfo(field_type) == .@"struct") { 2550 assertFieldSubset(field_type, FullField); 2551 } else if (field_type != FullField) { 2552 @compileError(@typeName(Full) ++ "." ++ field_name ++ " is a " ++ @typeName(FullField)); 2553 } 2554 } 2555 } 2556 2557 pub fn read( 2558 comptime T: type, 2559 comptime DB: type, 2560 comptime hash_kind: hash.HashKind, 2561 arena: *std.heap.ArenaAllocator, 2562 map: DB.HashMap(.read_only), 2563 ) !T { 2564 var event: T = undefined; 2565 switch (@typeInfo(T)) { 2566 .@"struct" => |struct_info| { 2567 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2568 const cursor = try map.getCursor(hash.hashInt(hash_kind, field_name)); 2569 @field(event, field_name) = try readField(field_type, DB, hash_kind, arena, cursor); 2570 } 2571 }, 2572 else => @compileError("read expects a struct"), 2573 } 2574 return event; 2575 } 2576 2577 fn readField( 2578 comptime Field: type, 2579 comptime DB: type, 2580 comptime hash_kind: hash.HashKind, 2581 arena: *std.heap.ArenaAllocator, 2582 cursor_maybe: ?DB.Cursor(.read_only), 2583 ) !Field { 2584 if (@typeInfo(Field) == .optional) { 2585 // a missing key or a null union payload is null 2586 const cursor = cursor_maybe orelse return null; 2587 if (cursor.slot().tag == .none) return null; 2588 return try readField(@typeInfo(Field).optional.child, DB, hash_kind, arena, cursor); 2589 } 2590 const cursor = cursor_maybe orelse return error.NotFound; 2591 switch (@typeInfo(Field)) { 2592 .pointer => |pointer_info| { 2593 if (pointer_info.size != .slice or pointer_info.child != u8 or !pointer_info.attrs.@"const") { 2594 @compileError("unsupported read field type: " ++ @typeName(Field)); 2595 } 2596 return try cursor.readBytesAlloc(arena.allocator(), null); 2597 }, 2598 .array => |array_info| { 2599 if (array_info.child != u8) @compileError("unsupported read field type: " ++ @typeName(Field)); 2600 var bytes: Field = undefined; 2601 if ((try cursor.readBytes(&bytes)).len != bytes.len) return error.InvalidByteArrayLength; 2602 return bytes; 2603 }, 2604 .bool => { 2605 var buffer: [5]u8 = undefined; 2606 const bytes = try cursor.readBytesObject(&buffer); 2607 const format_tag = bytes.format_tag orelse return error.InvalidFormatTag; 2608 if (!std.mem.eql(u8, &format_tag, "bl")) return error.InvalidFormatTag; 2609 if (std.mem.eql(u8, bytes.value, "true")) return true; 2610 if (std.mem.eql(u8, bytes.value, "false")) return false; 2611 return error.InvalidBool; 2612 }, 2613 .int => |int_info| return switch (int_info.signedness) { 2614 .unsigned => @intCast(try cursor.readUint()), 2615 .signed => @intCast(try cursor.readInt()), 2616 }, 2617 .@"enum" => return std.meta.stringToEnum(Field, try cursor.readBytesAlloc(arena.allocator(), null)) orelse error.InvalidEnumTag, 2618 .@"union" => |union_info| { 2619 if (union_info.tag_type == null) @compileError("unsupported read field type: " ++ @typeName(Field)); 2620 switch (cursor.slot().tag) { 2621 .bytes, .short_bytes => { 2622 const name = try cursor.readBytesAlloc(arena.allocator(), null); 2623 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2624 if (variant_type == void and std.mem.eql(u8, name, variant_name)) { 2625 return @unionInit(Field, variant_name, {}); 2626 } 2627 } 2628 return error.InvalidUnion; 2629 }, 2630 .hash_map => { 2631 const variants = try DB.HashMap(.read_only).init(cursor); 2632 var iter = try variants.iterator(); 2633 const entry = (try iter.next()) orelse return error.InvalidUnion; 2634 const pair = try entry.readKeyValuePair(); 2635 if (try iter.next() != null) return error.InvalidUnion; 2636 inline for (union_info.field_names, union_info.field_types) |variant_name, variant_type| { 2637 if (variant_type != void and pair.hash == hash.hashInt(hash_kind, variant_name)) { 2638 return @unionInit(Field, variant_name, try readField(variant_type, DB, hash_kind, arena, pair.value_cursor)); 2639 } 2640 } 2641 return error.InvalidUnion; 2642 }, 2643 else => return error.InvalidUnion, 2644 } 2645 }, 2646 .@"struct" => return try read(Field, DB, hash_kind, arena, try DB.HashMap(.read_only).init(cursor)), 2647 else => @compileError("unsupported read field type: " ++ @typeName(Field)), 2648 } 2649 } 2650 2651 // whether two events carry the same data 2652 fn fieldsEqual(comptime T: type, a: T, b: T) bool { 2653 switch (@typeInfo(T)) { 2654 .@"struct" => |struct_info| { 2655 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2656 if (!fieldEqual(field_type, @field(a, field_name), @field(b, field_name))) return false; 2657 } 2658 }, 2659 else => @compileError("fieldsEqual expects a struct"), 2660 } 2661 2662 return true; 2663 } 2664 2665 pub fn fieldEqual(comptime Field: type, a: Field, b: Field) bool { 2666 switch (@typeInfo(Field)) { 2667 .pointer => |pointer_info| { 2668 if (pointer_info.size == .slice and pointer_info.child == u8) { 2669 return std.mem.eql(u8, a, b); 2670 } else { 2671 @compileError("unsupported field type: " ++ @typeName(Field)); 2672 } 2673 }, 2674 .array => |array_info| { 2675 if (array_info.child == u8) { 2676 return std.mem.eql(u8, &a, &b); 2677 } else { 2678 @compileError("unsupported field type: " ++ @typeName(Field)); 2679 } 2680 }, 2681 .void => return true, 2682 .bool, .int, .@"enum" => return a == b, 2683 .@"union" => { 2684 if (std.meta.activeTag(a) != std.meta.activeTag(b)) return false; 2685 return switch (a) { 2686 inline else => |value, tag| fieldEqual(@TypeOf(value), value, @field(b, @tagName(tag))), 2687 }; 2688 }, 2689 .@"struct" => return fieldsEqual(Field, a, b), 2690 .optional => |optional_info| { 2691 if (a) |a_value| { 2692 if (b) |b_value| return fieldEqual(optional_info.child, a_value, b_value); 2693 return false; 2694 } 2695 return b == null; 2696 }, 2697 else => @compileError("unsupported field type: " ++ @typeName(Field)), 2698 } 2699 } 2700 2701 // 2702 // writing to xitdb 2703 // 2704 2705 pub fn upsert( 2706 comptime T: type, 2707 comptime DB: type, 2708 comptime hash_kind: hash.HashKind, 2709 map: DB.HashMap(.read_write), 2710 event: T, 2711 ) !void { 2712 switch (@typeInfo(T)) { 2713 .@"struct" => |struct_info| { 2714 inline for (struct_info.field_names, struct_info.field_types) |field_name, field_type| { 2715 try upsertField(DB, hash_kind, map, field_name, field_type, @field(event, field_name)); 2716 } 2717 }, 2718 else => @compileError("upsert expects a struct"), 2719 } 2720 } 2721 2722 fn upsertField( 2723 comptime DB: type, 2724 comptime hash_kind: hash.HashKind, 2725 map: DB.HashMap(.read_write), 2726 comptime field_name: []const u8, 2727 comptime Field: type, 2728 value: Field, 2729 ) !void { 2730 const key = hash.hashInt(hash_kind, field_name); 2731 2732 switch (@typeInfo(Field)) { 2733 .pointer => |pointer_info| { 2734 if (pointer_info.size == .slice and pointer_info.child == u8) { 2735 try upsertBytes(DB, hash_kind, map, key, value); 2736 } else { 2737 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2738 } 2739 }, 2740 .array => |array_info| { 2741 if (array_info.child == u8) { 2742 try upsertBytes(DB, hash_kind, map, key, &value); 2743 } else { 2744 @compileError("unsupported upsert field type: " ++ @typeName(Field)); 2745 } 2746 }, 2747 .int => |int_info| switch (int_info.signedness) { 2748 .unsigned => { 2749 if (try map.getCursor(key)) |value_cursor| { 2750 if (try value_cursor.readUint() == value) { 2751 return; 2752 } 2753 } 2754 2755 try map.put(key, .{ .uint = value }); 2756 }, 2757 .signed => { 2758 if (try map.getCursor(key)) |value_cursor| { 2759 if (try value_cursor.readInt() == value) { 2760 return; 2761 } 2762 } 2763 2764 try map.put(key, .{ .int = value }); 2765 }, 2766 }, 2767 .bool => { 2768 const bytes = if (value) "true" else "false"; 2769 if (try map.getCursor(key)) |value_cursor| { 2770 var buffer: [5]u8 = undefined; 2771 const existing = try value_cursor.readBytesObject(&buffer); 2772 if (existing.format_tag) |format_tag| { 2773 if (std.mem.eql(u8, &format_tag, "bl") and std.mem.eql(u8, existing.value, bytes)) { 2774 return; 2775 } 2776 } 2777 } 2778 2779 try map.put(key, .{ .bytes_object = .{ .value = bytes, .format_tag = "bl".* } }); 2780 }, 2781 .@"enum" => try upsertBytes(DB, hash_kind, map, key, @tagName(value)), 2782 .@"union" => switch (value) { 2783 inline else => |payload, tag| { 2784 if (@TypeOf(payload) == void) { 2785 try upsertBytes(DB, hash_kind, map, key, @tagName(tag)); 2786 } else { 2787 const tag_key = hash.hashInt(hash_kind, @tagName(tag)); 2788 if (try map.getCursor(key)) |cursor| { 2789 switch (cursor.slot().tag) { 2790 .hash_map => { 2791 const variants = try DB.HashMap(.read_only).init(cursor); 2792 if (try variants.getCursor(tag_key) == null) try map.put(key, .{ .slot = null }); 2793 }, 2794 else => try map.put(key, .{ .slot = null }), 2795 } 2796 } 2797 const variants = try DB.HashMap(.read_write).init(try map.putCursor(key)); 2798 if (@typeInfo(@TypeOf(payload)) == .optional) { 2799 // keep the variant even when its payload is null 2800 if (payload == null) return try variants.put(tag_key, .{ .slot = null }); 2801 } 2802 if (try variants.getCursor(tag_key)) |cursor| { 2803 if (cursor.slot().tag == .none) _ = try variants.remove(tag_key); 2804 } 2805 try upsertField(DB, hash_kind, variants, @tagName(tag), @TypeOf(payload), payload); 2806 } 2807 }, 2808 }, 2809 .optional => |optional_info| { 2810 // a missing key is null 2811 if (value) |child| { 2812 try upsertField(DB, hash_kind, map, field_name, optional_info.child, child); 2813 } else { 2814 _ = try map.remove(key); 2815 } 2816 }, 2817 .@"struct" => try upsert( 2818 Field, 2819 DB, 2820 hash_kind, 2821 try DB.HashMap(.read_write).init(try map.putCursor(key)), 2822 value, 2823 ), 2824 else => @compileError("unsupported upsert field type: " ++ @typeName(Field)), 2825 } 2826 } 2827 2828 fn upsertBytes( 2829 comptime DB: type, 2830 comptime hash_kind: hash.HashKind, 2831 map: DB.HashMap(.read_write), 2832 key: hash.HashInt(hash_kind), 2833 value: []const u8, 2834 ) !void { 2835 var existing_cursor_maybe = try map.getCursor(key); 2836 if (existing_cursor_maybe) |*existing_cursor| { 2837 if (try bytesEqual(DB, existing_cursor, value)) { 2838 return; 2839 } 2840 } 2841 2842 try map.put(key, .{ .bytes = value }); 2843 } 2844 2845 fn bytesEqual( 2846 comptime DB: type, 2847 cursor: *DB.Cursor(.read_only), 2848 value: []const u8, 2849 ) !bool { 2850 switch (cursor.slot().tag) { 2851 .bytes, .short_bytes => {}, 2852 else => return false, 2853 } 2854 var read_buffer: [1024]u8 = undefined; 2855 var reader = try cursor.reader(&read_buffer); 2856 if (reader.size != value.len) { 2857 return false; 2858 } 2859 2860 var chunk_buffer: [1024]u8 = undefined; 2861 var offset: usize = 0; 2862 while (offset < value.len) { 2863 const chunk_len = @min(chunk_buffer.len, value.len - offset); 2864 try reader.interface.readSliceAll(chunk_buffer[0..chunk_len]); 2865 if (!std.mem.eql(u8, chunk_buffer[0..chunk_len], value[offset .. offset + chunk_len])) { 2866 return false; 2867 } 2868 offset += chunk_len; 2869 } 2870 2871 return true; 2872 } 2873 2874 // 2875 // CommitIterator 2876 // 2877 // differs from xit's ObjectIterator in a few ways: 2878 // 2879 // 1. iterates parents first, rather than children first 2880 // 2. `next` only returns the object id, not the full Object 2881 // 3. stores its temporary state in a file on disk to avoid OOMs 2882 // 2883 2884 pub fn CommitIterator(comptime repo_kind: rp.RepoKind, comptime repo_opts: rp.RepoOpts(repo_kind)) type { 2885 return struct { 2886 const DB = EventDB(repo_opts.hash); 2887 // a plain file is used for the scratch db because each write outside 2888 // a transaction is synced anyway, so buffering would gain nothing 2889 const TempDB = xit.xitdb.Database(.file, hash.HashInt(repo_opts.hash)); 2890 const db_name = "haxy-repo-events.db"; 2891 2892 repo_dir: std.Io.Dir, 2893 db_file: std.Io.File, 2894 db: *TempDB, 2895 // map of each object id to its children 2896 parent_to_children: TempDB.HashMap(.read_write), 2897 // tracking pending parents is necessary because a child can only 2898 // be returned after all of its unconsumed parents have been returned 2899 child_to_pending_parents: TempDB.HashMap(.read_write), 2900 // queue of object ids that are ready to be returned from `next` 2901 ready_queue: TempDB.ArrayList(.read_write), 2902 ready_queue_index: u64, 2903 // the object id at the tip of this branch 2904 newest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2905 // the object id furthest back in the history that hasn't been consumed 2906 oldest_object_id: ?[hash.byteLen(repo_opts.hash)]u8, 2907 2908 pub fn init( 2909 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2910 io: std.Io, 2911 allocator: std.mem.Allocator, 2912 consumed_object_ids: DB.HashMap(.read_only), 2913 ref: rf.Ref, 2914 ) !CommitIterator(repo_kind, repo_opts) { 2915 const db_file = try state.core.repo_dir.createFile(io, db_name, .{ .truncate = true, .lock = .exclusive, .read = true }); 2916 errdefer { 2917 db_file.close(io); 2918 state.core.repo_dir.deleteFile(io, db_name) catch {}; 2919 } 2920 2921 // cursors point at the db, so it needs a stable address 2922 const db_ptr = try allocator.create(TempDB); 2923 errdefer allocator.destroy(db_ptr); 2924 // the db is scratch state that gets deleted after iteration, so 2925 // there is nothing worth fsyncing 2926 db_ptr.* = try TempDB.init(.{ .io = io, .file = db_file, .fsync = false }); 2927 2928 const map = try TempDB.HashMap(.read_write).init(db_ptr.rootCursor()); 2929 2930 const parent_to_children_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "parent->children")); 2931 const parent_to_children = try TempDB.HashMap(.read_write).init(parent_to_children_cursor); 2932 2933 const child_to_pending_parents_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "child->pending-parents")); 2934 const child_to_pending_parents = try TempDB.HashMap(.read_write).init(child_to_pending_parents_cursor); 2935 2936 const ready_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "ready-queue")); 2937 const ready_queue = try TempDB.ArrayList(.read_write).init(ready_queue_cursor); 2938 2939 var self = CommitIterator(repo_kind, repo_opts){ 2940 .repo_dir = state.core.repo_dir, 2941 .db_file = db_file, 2942 .db = db_ptr, 2943 .parent_to_children = parent_to_children, 2944 .child_to_pending_parents = child_to_pending_parents, 2945 .ready_queue = ready_queue, 2946 .ready_queue_index = 0, 2947 .newest_object_id = null, 2948 .oldest_object_id = null, 2949 }; 2950 errdefer self.deinit(io, allocator); 2951 2952 try self.collect(state, io, allocator, consumed_object_ids, ref); 2953 2954 return self; 2955 } 2956 2957 pub fn deinit(self: *CommitIterator(repo_kind, repo_opts), io: std.Io, allocator: std.mem.Allocator) void { 2958 self.db_file.close(io); 2959 self.repo_dir.deleteFile(io, db_name) catch {}; 2960 allocator.destroy(self.db); 2961 } 2962 2963 pub fn next(self: *CommitIterator(repo_kind, repo_opts)) !?[hash.byteLen(repo_opts.hash)]u8 { 2964 if (self.ready_queue_index >= try self.ready_queue.count()) return null; 2965 2966 const oid = try readOidFromList(self.ready_queue.readOnly(), self.ready_queue_index); 2967 self.ready_queue_index += 1; 2968 2969 try self.enqueueChildren(&oid); 2970 return oid; 2971 } 2972 2973 fn collect( 2974 self: *CommitIterator(repo_kind, repo_opts), 2975 state: rp.Repo(repo_kind, repo_opts).State(.read_only), 2976 io: std.Io, 2977 allocator: std.mem.Allocator, 2978 consumed_object_ids: DB.HashMap(.read_only), 2979 ref: rf.Ref, 2980 ) !void { 2981 const map = try TempDB.HashMap(.read_write).init(self.db.rootCursor()); 2982 2983 const walk_queue_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "walk-queue")); 2984 const walk_queue = try TempDB.ArrayList(.read_write).init(walk_queue_cursor); 2985 var walk_queue_index: u64 = 0; 2986 2987 const seen_object_ids_cursor = try map.putCursor(hash.hashInt(repo_opts.hash, "seen-object-ids")); 2988 const seen_object_ids = try TempDB.HashSet(.read_write).init(seen_object_ids_cursor); 2989 2990 const head_oid_hex = (try rf.readRecur(repo_kind, repo_opts, state, io, .{ .ref = ref })) orelse return error.OidNotFound; 2991 var head_oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 2992 _ = try std.fmt.hexToBytes(&head_oid, &head_oid_hex); 2993 try walk_queue.append(.{ .bytes = &head_oid }); 2994 2995 while (walk_queue_index < try walk_queue.count()) { 2996 const oid = try readOidFromList(walk_queue.readOnly(), walk_queue_index); 2997 const oid_int = hash.bytesToInt(repo_opts.hash, &oid); 2998 2999 walk_queue_index += 1; 3000 3001 // if we've seen this object id, skip it 3002 if (null != try seen_object_ids.getCursor(oid_int)) { 3003 continue; 3004 } 3005 3006 try seen_object_ids.put(oid_int, .{ .bytes = &oid }); 3007 3008 var commit_object = try obj.Object(repo_kind, repo_opts).init(state, io, allocator, &std.fmt.bytesToHex(oid, .lower)); 3009 defer commit_object.deinit(); 3010 3011 // if this object id has already been consumed, skip it 3012 if (null != try consumed_object_ids.getCursor(oid_int)) { 3013 continue; 3014 } 3015 3016 if (self.newest_object_id == null) self.newest_object_id = oid; 3017 self.oldest_object_id = oid; 3018 3019 const parent_oids = commit_object.content.commit.metadata.parent_oids orelse return error.ParentOidsNotFound; 3020 var pending_parent_count: u64 = 0; 3021 for (parent_oids) |*parent_oid| { 3022 var parent_oid_bytes: [hash.byteLen(repo_opts.hash)]u8 = undefined; 3023 _ = try std.fmt.hexToBytes(&parent_oid_bytes, parent_oid); 3024 const parent_oid_int = hash.bytesToInt(repo_opts.hash, &parent_oid_bytes); 3025 3026 // if this object id has already been consumed, skip it 3027 if (null != try consumed_object_ids.getCursor(parent_oid_int)) { 3028 continue; 3029 } 3030 3031 // if this object id hasn't already been seen, add it to the walk queue 3032 if (null == try seen_object_ids.getCursor(parent_oid_int)) { 3033 try walk_queue.append(.{ .bytes = &parent_oid_bytes }); 3034 } 3035 3036 const children_cursor = try self.parent_to_children.putCursor(parent_oid_int); 3037 const children = try TempDB.HashSet(.read_write).init(children_cursor); 3038 try children.put(oid_int, .{ .bytes = &oid }); 3039 pending_parent_count += 1; 3040 } 3041 3042 if (pending_parent_count == 0) { 3043 try self.ready_queue.append(.{ .bytes = &oid }); 3044 } else { 3045 try self.child_to_pending_parents.put(oid_int, .{ .uint = pending_parent_count }); 3046 } 3047 } 3048 } 3049 3050 fn enqueueChildren(self: *CommitIterator(repo_kind, repo_opts), oid: *const [hash.byteLen(repo_opts.hash)]u8) !void { 3051 const oid_int = hash.bytesToInt(repo_opts.hash, oid); 3052 const children_cursor = try self.parent_to_children.getCursor(oid_int) orelse return; 3053 const children = try TempDB.HashSet(.read_only).init(children_cursor); 3054 var children_iter = try children.iterator(); 3055 3056 while (try children_iter.next()) |*child_cursor| { 3057 const kv_pair = try child_cursor.readKeyValuePair(); 3058 const child_oid_int = kv_pair.hash; 3059 const pending_parent_cursor = try self.child_to_pending_parents.getCursor(child_oid_int) orelse return error.CursorNotFound; 3060 const pending_parent_count = try pending_parent_cursor.readUint(); 3061 3062 if (pending_parent_count <= 1) { 3063 _ = try self.child_to_pending_parents.remove(child_oid_int); 3064 const child_oid = hash.intToBytes(hash.HashInt(repo_opts.hash), child_oid_int); 3065 try self.ready_queue.append(.{ .bytes = &child_oid }); 3066 } else { 3067 try self.child_to_pending_parents.put(child_oid_int, .{ .uint = pending_parent_count - 1 }); 3068 } 3069 } 3070 } 3071 3072 fn readOidFromList(list: TempDB.ArrayList(.read_only), index: u64) ![hash.byteLen(repo_opts.hash)]u8 { 3073 const oid_cursor = try list.getCursor(index) orelse return error.CursorNotFound; 3074 var oid: [hash.byteLen(repo_opts.hash)]u8 = undefined; 3075 _ = try oid_cursor.readBytes(&oid); 3076 return oid; 3077 } 3078 }; 3079 } 3080