; persist/log — the log facet: append-only event streams. seq is assigned from
; a monotonic per-stream high-water mark (1-based) held by the backend, so it
; keeps climbing even after the log prefix is compacted away. Reads return the
; events currently stored, oldest-first.
; Requires: lib/persist/event.sx, lib/persist/backend.sx.

; logical last seq assigned in a stream (0 if none) — survives compaction
(define
  persist/last-seq
  (fn (b stream) (persist/backend-last-seq b stream)))

; number of events physically stored in a stream (shrinks on compaction)
(define
  persist/count
  (fn (b stream) (len (persist/backend-read b stream))))

; append an event, auto-assigning the next seq. Returns the stored event.
(define
  persist/append
  (fn
    (b stream type at data)
    (let
      ((seq (+ 1 (persist/last-seq b stream))))
      (let
        ((ev (persist/event stream seq type at data)))
        (begin (persist/backend-append b stream ev) ev)))))

; read all events currently stored in a stream, oldest-first
(define persist/read (fn (b stream) (persist/backend-read b stream)))

; read events with seq >= from
(define
  persist/read-from
  (fn
    (b stream from)
    (filter
      (fn (e) (>= (persist/event-seq e) from))
      (persist/read b stream))))

; drop events with seq <= n (compaction); the seq counter is untouched
(define
  persist/truncate
  (fn (b stream n) (persist/backend-truncate b stream n)))
