package hypr import ( "bufio" "encoding/json" "errors" "fmt" "os" "path/filepath" "sync" "ccp/internal/ingest" ) // Buffer holds events that haven't been uploaded yet, persisted as JSONL so // they survive restarts and server outages. type Buffer struct { mu sync.Mutex path string pending []ingest.Event } // OpenBuffer loads any events left over from a previous run. Corrupt lines // (e.g. from a crash mid-write) are skipped. func OpenBuffer(path string) (*Buffer, error) { if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return nil, err } b := &Buffer{path: path} f, err := os.Open(path) if errors.Is(err, os.ErrNotExist) { return b, nil } if err != nil { return nil, err } defer f.Close() sc := bufio.NewScanner(f) sc.Buffer(make([]byte, 64*1024), 1024*1024) for sc.Scan() { var e ingest.Event if json.Unmarshal(sc.Bytes(), &e) == nil && e.ID != "" { b.pending = append(b.pending, e) } } return b, sc.Err() } // Add appends an event to the buffer and its file. func (b *Buffer) Add(e ingest.Event) error { line, err := json.Marshal(e) if err != nil { return err } b.mu.Lock() defer b.mu.Unlock() f, err := os.OpenFile(b.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) if err != nil { return err } defer f.Close() if _, err := f.Write(append(line, '\n')); err != nil { return err } b.pending = append(b.pending, e) return nil } // Peek returns up to max of the oldest pending events. func (b *Buffer) Peek(max int) []ingest.Event { b.mu.Lock() defer b.mu.Unlock() n := min(max, len(b.pending)) return append([]ingest.Event(nil), b.pending[:n]...) } // Ack drops the n oldest events and rewrites the file. func (b *Buffer) Ack(n int) error { b.mu.Lock() defer b.mu.Unlock() if n > len(b.pending) { return fmt.Errorf("ack %d of %d pending events", n, len(b.pending)) } b.pending = b.pending[n:] return b.rewrite() } func (b *Buffer) Len() int { b.mu.Lock() defer b.mu.Unlock() return len(b.pending) } // rewrite atomically replaces the file with the pending events. func (b *Buffer) rewrite() error { tmp := b.path + ".tmp" f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) if err != nil { return err } w := bufio.NewWriter(f) enc := json.NewEncoder(w) for _, e := range b.pending { if err := enc.Encode(e); err != nil { f.Close() return err } } if err := w.Flush(); err != nil { f.Close() return err } if err := f.Close(); err != nil { return err } return os.Rename(tmp, b.path) }