Mexa / internal /writequeue /queue.go
Mrkiti's picture
HF snapshot of main ac37255 (excludes fly.toml and binaries)
1e69593
Raw History Blame Contribute Delete
3.42 kB
package writequeue
import (
"context"
"database/sql"
"fmt"
"log"
"strings"
"sync"
"time"
)
// Entry β€” one append-only write destined for a DB table
type Entry struct {
Table string
Cols []string
Vals []interface{}
}
// Queue β€” buffered channel + drain goroutine
// Batches append-only INSERTs across escalation_log, voip_bridge_log, cbk_audit_log
// Buffer 5000 β€” batch 200 β€” drain tick 50ms
type Queue struct {
db *sql.DB
ch chan Entry
stop chan struct{}
wg sync.WaitGroup
}
const (
BufferSize = 5000
BatchSize = 200
DrainTick = 50 * time.Millisecond
)
// New β€” creates and starts the write queue
func New(db *sql.DB) *Queue {
q := &Queue{
db: db,
ch: make(chan Entry, BufferSize),
stop: make(chan struct{}),
}
q.wg.Add(1)
go q.drain()
log.Printf("writequeue: started β€” buffer %d batch %d tick %s", BufferSize, BatchSize, DrainTick)
return q
}
// Push β€” enqueues an entry β€” non-blocking
// Returns error if queue is full β€” caller logs and continues
func (q *Queue) Push(e Entry) error {
select {
case q.ch <- e:
return nil
default:
return fmt.Errorf("writequeue: buffer full β€” dropping entry for table %s", e.Table)
}
}
// drain β€” background goroutine β€” flushes on tick or batch size
func (q *Queue) drain() {
defer q.wg.Done()
ticker := time.NewTicker(DrainTick)
defer ticker.Stop()
batch := make([]Entry, 0, BatchSize)
for {
select {
case e := <-q.ch:
batch = append(batch, e)
if len(batch) >= BatchSize {
q.flush(batch)
batch = batch[:0]
}
case <-ticker.C:
if len(batch) > 0 {
q.flush(batch)
batch = batch[:0]
}
case <-q.stop:
// Drain remaining entries before exit
for {
select {
case e := <-q.ch:
batch = append(batch, e)
default:
goto done
}
}
done:
if len(batch) > 0 {
q.flush(batch)
}
return
}
}
}
// flush β€” writes a batch of entries β€” groups by table β€” single transaction per table
func (q *Queue) flush(batch []Entry) {
if len(batch) == 0 {
return
}
// Group by table
groups := make(map[string][]Entry)
for _, e := range batch {
groups[e.Table] = append(groups[e.Table], e)
}
for table, entries := range groups {
if err := q.insertBatch(table, entries); err != nil {
log.Printf("writequeue: flush error table=%s entries=%d err=%v", table, len(entries), err)
}
}
}
// insertBatch β€” builds and executes a single multi-row INSERT for a table
func (q *Queue) insertBatch(table string, entries []Entry) error {
if len(entries) == 0 {
return nil
}
cols := entries[0].Cols
colList := strings.Join(cols, ", ")
var placeholders []string
var args []interface{}
idx := 1
for _, e := range entries {
rowPlaceholders := make([]string, len(e.Vals))
for i := range e.Vals {
rowPlaceholders[i] = fmt.Sprintf("$%d", idx)
args = append(args, e.Vals[i])
idx++
}
placeholders = append(placeholders, "("+strings.Join(rowPlaceholders, ", ")+")")
}
query := fmt.Sprintf("INSERT INTO %s (%s) VALUES %s",
table, colList, strings.Join(placeholders, ", "))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := q.db.ExecContext(ctx, query, args...)
return err
}
// Shutdown β€” signals drain goroutine to flush and exit β€” waits for completion
func (q *Queue) Shutdown() {
close(q.stop)
q.wg.Wait()
log.Printf("writequeue: shutdown complete")
}