File size: 3,421 Bytes
1e69593 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | 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")
}
|