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") }