X-Git-Url: https://git.giacomolli.uk/onechat/blobdiff_plain/ddd0a50f7b801112376d7fb27bfd05d2fc26c2fd..6004a6d0f7af1ecf3d0ac976f50bb4f93c619887:/subagent.go?ds=sidebyside diff --git a/subagent.go b/subagent.go index 596c038..07bfa45 100644 --- a/subagent.go +++ b/subagent.go @@ -124,14 +124,40 @@ func (s *Subagents) Get(ctx context.Context, name string) (*Subagent, error) { return subagent, nil } +// Snapshot flushes and locks the open logs while snapshot reads the subagent +// files. snapshot must not call Subagents or an open Subagent. +func (s *Subagents) Snapshot(ctx context.Context, snapshot func() error) error { + s.mutex.Lock() + defer s.mutex.Unlock() + + for _, subagent := range s.open { + subagent.mutex.Lock() + defer subagent.mutex.Unlock() + + err := subagent.Flush(ctx) + if err != nil { + return fmt.Errorf("flush subagent snapshot: %w", err) + } + } + + err := snapshot() + if err != nil { + return fmt.Errorf("copy subagent snapshot: %w", err) + } + + return nil +} + // Close makes the writes of each open log durable and closes it. func (s *Subagents) Close() error { s.mutex.Lock() defer s.mutex.Unlock() var err error + for name, subagent := range s.open { err = errors.Join(err, subagent.close()) + delete(s.open, name) } @@ -169,6 +195,14 @@ func (a *Subagent) Flush(ctx context.Context) error { return a.syncer.Flush(ctx) } +// First returns the first message of the log. +func (a *Subagent) First() (Message, error) { + a.mutex.Lock() + defer a.mutex.Unlock() + + return a.log.Message(0) +} + // Show returns the whole log, each message as "i|kind: text", with a blank line // between messages. func (a *Subagent) Show() (string, error) {