package staterpc import ( "context" "sync" "time" "github.com/samcharles93/archie-core/internal/domain/usage" ) // A usage record is written on the model-call path, so a State Store outage // must not lose it: chat, title, sampling and curator usage cannot be rebuilt // from events the way task usage can. The Client therefore carries a local // outbox: a write that fails is queued and retried until the store accepts it. const ( // usageQueueBound caps the outbox. A record that does not fit is refused // so the caller can report the drop; the bound keeps a long outage from // growing memory without limit. usageQueueBound = 1024 // usageAttemptTimeout bounds one retry's RPC. usageAttemptTimeout = 10 * time.Second // usageRetryMinBackoff is the first wait between retries. It doubles up // to usageRetryMaxBackoff, so a dead store is not polled in a spin. usageRetryMinBackoff = time.Second usageRetryMaxBackoff = time.Minute ) // usageOutbox is a bounded FIFO of usage records waiting for the store. Its // worker starts on the first enqueue and runs for the Client's life, parked // while the queue is empty. type usageOutbox struct { write func(ctx context.Context, r usage.Record) error minBackoff time.Duration maxBackoff time.Duration mu sync.Mutex pending []usage.Record notify chan struct{} done chan struct{} start sync.Once stopped sync.Once } func newUsageOutbox(write func(ctx context.Context, r usage.Record) error) *usageOutbox { return &usageOutbox{ write: write, minBackoff: usageRetryMinBackoff, maxBackoff: usageRetryMaxBackoff, notify: make(chan struct{}, 1), done: make(chan struct{}), } } // enqueue appends r for retry and wakes the worker. It reports false when the // queue is full: the record is not queued and the caller must report the loss. func (o *usageOutbox) enqueue(r usage.Record) bool { o.mu.Lock() if len(o.pending) >= usageQueueBound { o.mu.Unlock() return false } o.pending = append(o.pending, r) o.mu.Unlock() o.start.Do(func() { go o.run() }) select { case o.notify <- struct{}{}: default: } return true } // stop halts the worker; records still queued are dropped. func (o *usageOutbox) stop() { o.stopped.Do(func() { close(o.done) }) } // run delivers the queue's head until the store accepts it, backing off // between failed attempts, then moves to the next record. Retries are // detached from any caller's cancellation: the record outlives the call that // produced it. func (o *usageOutbox) run() { backoff := o.minBackoff for { o.mu.Lock() if len(o.pending) == 0 { o.mu.Unlock() select { case <-o.notify: continue case <-o.done: return } } record := o.pending[0] o.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), usageAttemptTimeout) err := o.write(ctx, record) cancel() if err == nil { o.mu.Lock() o.pending = o.pending[1:] o.mu.Unlock() backoff = o.minBackoff continue } timer := time.NewTimer(backoff) select { case <-timer.C: case <-o.done: timer.Stop() return } backoff = min(backoff*2, o.maxBackoff) } }