package hub import ( "context" "encoding/json" "errors" "os" "path/filepath" "sync" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire" ) // MaxQueue is the most commands kept per node; the oldest are dropped. const MaxQueue = 10000 // CmdQueue is the persisted command queue of one node (commands.json). type CmdQueue struct { mu sync.Mutex path string next uint64 dropped uint64 cmds []wire.Cmd dirty bool notify chan struct{} // closed and replaced on every enqueue stop chan struct{} done chan struct{} } type queueFile struct { Next uint64 `json:"next"` Dropped uint64 `json:"dropped"` Cmds []wire.Cmd `json:"cmds"` } // OpenQueue loads path (missing: empty) and starts the debounced writer; call // Close to flush. An empty path keeps the queue in memory only. func OpenQueue(path string) (*CmdQueue, error) { q := &CmdQueue{path: path, next: 1, notify: make(chan struct{}), stop: make(chan struct{}), done: make(chan struct{})} if path != "" { if b, err := os.ReadFile(path); err == nil { var f queueFile if err := json.Unmarshal(b, &f); err != nil { _ = os.Rename(path, path+".corrupt") } else { q.next, q.dropped, q.cmds = max(f.Next, 1), f.Dropped, f.Cmds for _, c := range q.cmds { q.next = max(q.next, c.Seq+1) } } } else if !errors.Is(err, os.ErrNotExist) { return nil, err } } go q.writer() return q, nil } func (q *CmdQueue) writer() { defer close(q.done) t := time.NewTicker(time.Second) defer t.Stop() for { select { case <-q.stop: q.flush() return case <-t.C: q.flush() } } } func (q *CmdQueue) flush() { if q.path == "" { return } q.mu.Lock() if !q.dirty { q.mu.Unlock() return } b, err := json.Marshal(queueFile{Next: q.next, Dropped: q.dropped, Cmds: q.cmds}) q.dirty = false q.mu.Unlock() if err != nil { return } _ = os.MkdirAll(filepath.Dir(q.path), 0o700) tmp := q.path + ".tmp" if os.WriteFile(tmp, b, 0o600) == nil { _ = os.Rename(tmp, q.path) } } // Close flushes the queue and stops the writer. func (q *CmdQueue) Close() { select { case <-q.stop: default: close(q.stop) } <-q.done } // Enqueue appends a command; it matches the signature of enforce.Config.Sink. func (q *CmdQueue) Enqueue(kind, line string) error { if !wire.ValidCmdLine(kind, line) { return errors.New("invalid command line") } q.mu.Lock() q.cmds = append(q.cmds, wire.Cmd{Seq: q.next, Kind: kind, Line: line}) q.next++ if len(q.cmds) > MaxQueue { n := len(q.cmds) - MaxQueue q.dropped += uint64(n) q.cmds = append([]wire.Cmd(nil), q.cmds[n:]...) } q.dirty = true old := q.notify q.notify = make(chan struct{}) q.mu.Unlock() close(old) return nil } // Last is the highest queued sequence (0 when nothing was ever queued). func (q *CmdQueue) Last() uint64 { q.mu.Lock() defer q.mu.Unlock() return q.next - 1 } // Pending counts the queued commands after seq. func (q *CmdQueue) Pending(after uint64) int { q.mu.Lock() defer q.mu.Unlock() n := 0 for _, c := range q.cmds { if c.Seq > after { n++ } } return n } // Dropped counts the commands discarded by the size cap. func (q *CmdQueue) Dropped() uint64 { q.mu.Lock() defer q.mu.Unlock() return q.dropped } func (q *CmdQueue) after(seq uint64) ([]wire.Cmd, chan struct{}, uint64) { q.mu.Lock() defer q.mu.Unlock() // the probe persisted everything up to seq: forget it i := 0 for i < len(q.cmds) && q.cmds[i].Seq <= seq { i++ } if i > 0 { q.cmds = append([]wire.Cmd(nil), q.cmds[i:]...) q.dirty = true } out := q.cmds if len(out) > 500 { out = out[:500] } return append([]wire.Cmd(nil), out...), q.notify, q.dropped } // Wait returns the commands after seq at once, or holds up to wait for one. func (q *CmdQueue) Wait(ctx context.Context, seq uint64, wait time.Duration) wire.CmdResp { cmds, ch, dropped := q.after(seq) if len(cmds) == 0 && wait > 0 { t := time.NewTimer(wait) defer t.Stop() select { case <-ch: cmds, _, dropped = q.after(seq) case <-t.C: case <-ctx.Done(): } } if cmds == nil { cmds = []wire.Cmd{} } return wire.CmdResp{Cmds: cmds, Dropped: dropped} }