package proc import ( "encoding/json" "errors" "io/fs" "os" "slices" "strconv" "strings" "sync" ) // Store keeps one JSON record durably at Path (written beside, synced, // renamed over), or in memory when Path is "" (one process: tests). type Store struct { Path string mu sync.Mutex mem []byte } // Save keeps v. func (s *Store) Save(v any) error { raw, err := json.Marshal(v) if err != nil { return err } if s.Path != "" { return WriteDurably(s.Path, raw) } s.mu.Lock() s.mem = raw s.mu.Unlock() return nil } // Load reads the record into v; ok is false when there is none. One // that cannot be read or decoded is an error. func (s *Store) Load(v any) (bool, error) { var raw []byte if s.Path == "" { s.mu.Lock() raw = slices.Clone(s.mem) s.mu.Unlock() } else { var err error if raw, err = os.ReadFile(s.Path); errors.Is(err, fs.ErrNotExist) { return false, nil } else if err != nil { return false, err } } if raw == nil { return false, nil } return true, json.Unmarshal(raw, v) } // Drop removes the record (none is not an error). func (s *Store) Drop() error { if s.Path == "" { s.mu.Lock() s.mem = nil s.mu.Unlock() return nil } if err := os.Remove(s.Path); err != nil && !errors.Is(err, fs.ErrNotExist) { return err } return nil } var self struct { once sync.Once id ID } // Self is this process's identity (read once). func Self() ID { self.once.Do(func() { if q, ok := Platform.Lookup(os.Getpid()); ok { self.id = q.ID } else { self.id = ID{PID: os.Getpid()} } }) return self.id } // ParseRecord reads a process record, "pg::" (pgid 0: the // marker alone; never 1, never negative, never without a marker). func ParseRecord(id string) (int, string, bool) { rest, ok := strings.CutPrefix(id, "pg:") if !ok { return 0, "", false } num, attempt, _ := strings.Cut(rest, ":") pgid, err := strconv.Atoi(num) if err != nil || pgid < 0 || pgid == 1 || attempt == "" { return 0, "", false } return pgid, attempt, true }