46 lines
848 B
Go
46 lines
848 B
Go
package agent
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
)
|
|
|
|
const (
|
|
fifoMaxItems = 256
|
|
fifoMaxBytes = 4 * 1024 * 1024
|
|
)
|
|
|
|
// Fifo is a thread-safe queue for buffered prompts.
|
|
type Fifo struct {
|
|
mu sync.Mutex
|
|
items []string
|
|
bytes int
|
|
}
|
|
|
|
// Push appends a prompt to the queue.
|
|
func (f *Fifo) Push(s string) error {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
if len(s) > fifoMaxBytes || len(f.items) >= fifoMaxItems || f.bytes+len(s) > fifoMaxBytes {
|
|
return fmt.Errorf("prompt queue limit reached")
|
|
}
|
|
f.items = append(f.items, s)
|
|
f.bytes += len(s)
|
|
return nil
|
|
}
|
|
|
|
// Pop removes and returns the next prompt.
|
|
// Returns ("", false) if the queue is empty.
|
|
func (f *Fifo) Pop() (string, bool) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
if len(f.items) == 0 {
|
|
return "", false
|
|
}
|
|
s := f.items[0]
|
|
f.items[0] = ""
|
|
f.items = f.items[1:]
|
|
f.bytes -= len(s)
|
|
return s, true
|
|
}
|