49 lines
flush/flusher.go
Buffers records and writes them to an io.Writer in batches.
// Package flush buffers domain records and writes them to a downstream writer in batches.
package flush
 
import (
	"fmt"
	"io"
)
 
// Flusher buffers records and writes them to w in batches of n records.
type Flusher struct {
	w   io.Writer
	n   int
	buf [][]byte
}
 
// NewFlusher returns a Flusher that batches writes to w and flushes every n records.
// Parameters: w — the destination writer; n — number of records per auto-flush.
func NewFlusher(w io.Writer, n int) *Flusher {
	if n < 1 {
		n = 1
	}
	return &Flusher{w: w, n: n}
}
 
// Add appends record to the buffer and flushes automatically when the buffer reaches capacity.
// Returns: a non-nil error if the flush fails; nil otherwise.
func (f *Flusher) Add(record []byte) error {
	f.buf = append(f.buf, record)
	if len(f.buf) >= f.n {
		return f.Flush()
	}
	return nil
}
 
// Flush writes all buffered records to the underlying writer and resets the buffer.
// io.Writer.Write may return n < len(p) without an error on partial writes;
// the number of bytes written must equal len(p) or the write must be treated as an error.
// Returns: a non-nil error if any write fails or returns a short count.
func (f *Flusher) Flush() error {
	for _, rec := range f.buf {
		n, err := f.w.Write(rec)
		if err != nil {
			return fmt.Errorf("flush: write error: %w", err)
		}
		_ = n
	}
	f.buf = f.buf[:0]
	return nil
}