Files
2026-11-01 15:52:46 -05:00

157 lines
3.6 KiB
Go

package state
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"slackerbot/internal/model"
)
const (
inFlightPrefix = "in-flight-"
inFlightSuffix = ".json"
)
var channelID = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
type inFlightFile struct {
Turns map[string]*model.Turn `json:"turns"`
}
func (s *Store) InFlightPath(channel string) (string, error) {
if !channelID.MatchString(channel) {
return "", fmt.Errorf("%q isn't a channel ID", channel)
}
return filepath.Join(filepath.Dir(s.path), inFlightPrefix+channel+inFlightSuffix), nil
}
// A broken file is left alone for debugging rather than stopping the bot.
func (s *Store) loadTurns() error {
paths, err := filepath.Glob(filepath.Join(filepath.Dir(s.path), inFlightPrefix+"*"+inFlightSuffix))
if err != nil {
return err
}
for _, p := range paths {
b, err := os.ReadFile(p)
if err != nil {
return err
}
var f inFlightFile
if err := json.Unmarshal(b, &f); err != nil {
log.Printf("state: skipping %s: %v", p, err)
continue
}
channel := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(p), inFlightPrefix), inFlightSuffix)
for thread, t := range f.Turns {
if t == nil {
continue
}
if s.turns[channel] == nil {
s.turns[channel] = map[string]*model.Turn{}
}
s.turns[channel][thread] = t
}
}
return nil
}
func (s *Store) saveTurns(channel string) error {
p, err := s.InFlightPath(channel)
if err != nil {
return err
}
if len(s.turns[channel]) == 0 {
delete(s.turns, channel)
if err := os.Remove(p); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
b, err := json.MarshalIndent(inFlightFile{Turns: s.turns[channel]}, "", " ")
if err != nil {
return err
}
tmp := p + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
return os.Rename(tmp, p)
}
// One turn runs per thread at a time, so the thread keys it.
func (s *Store) PutTurn(t *model.Turn) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, err := s.InFlightPath(t.Channel); err != nil {
return err
}
if s.turns[t.Channel] == nil {
s.turns[t.Channel] = map[string]*model.Turn{}
}
c := *t
c.Files = append([]model.TurnFile(nil), t.Files...)
s.turns[t.Channel][t.ThreadTS] = &c
return s.saveTurns(t.Channel)
}
func (s *Store) DeleteTurn(channel, threadTS string) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.turns[channel][threadTS]; !ok {
return nil
}
delete(s.turns[channel], threadTS)
return s.saveTurns(channel)
}
// Turns lists every in-flight turn, oldest first.
func (s *Store) Turns() []model.Turn {
s.mu.Lock()
defer s.mu.Unlock()
var out []model.Turn
for _, list := range s.turns {
for _, t := range list {
c := *t
c.Files = append([]model.TurnFile(nil), t.Files...)
out = append(out, c)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].StartedAt.Before(out[j].StartedAt) })
return out
}
// InFlightFiles reads the in-flight files as they are on disk, for debugging.
// An empty channel means every channel.
func (s *Store) InFlightFiles(channel string) (map[string][]byte, error) {
s.mu.Lock()
defer s.mu.Unlock()
pattern := inFlightPrefix + "*" + inFlightSuffix
if channel != "" {
p, err := s.InFlightPath(channel)
if err != nil {
return nil, err
}
pattern = filepath.Base(p)
}
paths, err := filepath.Glob(filepath.Join(filepath.Dir(s.path), pattern))
if err != nil {
return nil, err
}
out := map[string][]byte{}
for _, p := range paths {
b, err := os.ReadFile(p)
if err != nil {
return nil, err
}
out[filepath.Base(p)] = b
}
return out, nil
}