| 1 | package proc |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "io/fs" |
| 7 | "os" |
| 8 | "slices" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | ) |
| 13 | |
| 14 | // Store keeps one JSON record durably at Path (written beside, synced, |
| 15 | // renamed over), or in memory when Path is "" (one process: tests). |
| 16 | type Store struct { |
| 17 | Path string |
| 18 | mu sync.Mutex |
| 19 | mem []byte |
| 20 | } |
| 21 | |
| 22 | // Save keeps v. |
| 23 | func (s *Store) Save(v any) error { |
| 24 | raw, err := json.Marshal(v) |
| 25 | if err != nil { |
| 26 | return err |
| 27 | } |
| 28 | if s.Path != "" { |
| 29 | return WriteDurably(s.Path, raw) |
| 30 | } |
| 31 | s.mu.Lock() |
| 32 | s.mem = raw |
| 33 | s.mu.Unlock() |
| 34 | return nil |
| 35 | } |
| 36 | |
| 37 | // Load reads the record into v; ok is false when there is none. One |
| 38 | // that cannot be read or decoded is an error. |
| 39 | func (s *Store) Load(v any) (bool, error) { |
| 40 | var raw []byte |
| 41 | if s.Path == "" { |
| 42 | s.mu.Lock() |
| 43 | raw = slices.Clone(s.mem) |
| 44 | s.mu.Unlock() |
| 45 | } else { |
| 46 | var err error |
| 47 | if raw, err = os.ReadFile(s.Path); errors.Is(err, fs.ErrNotExist) { |
| 48 | return false, nil |
| 49 | } else if err != nil { |
| 50 | return false, err |
| 51 | } |
| 52 | } |
| 53 | if raw == nil { |
| 54 | return false, nil |
| 55 | } |
| 56 | return true, json.Unmarshal(raw, v) |
| 57 | } |
| 58 | |
| 59 | // Drop removes the record (none is not an error). |
| 60 | func (s *Store) Drop() error { |
| 61 | if s.Path == "" { |
| 62 | s.mu.Lock() |
| 63 | s.mem = nil |
| 64 | s.mu.Unlock() |
| 65 | return nil |
| 66 | } |
| 67 | if err := os.Remove(s.Path); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| 68 | return err |
| 69 | } |
| 70 | return nil |
| 71 | } |
| 72 | |
| 73 | var self struct { |
| 74 | once sync.Once |
| 75 | id ID |
| 76 | } |
| 77 | |
| 78 | // Self is this process's identity (read once). |
| 79 | func Self() ID { |
| 80 | self.once.Do(func() { |
| 81 | if q, ok := Platform.Lookup(os.Getpid()); ok { |
| 82 | self.id = q.ID |
| 83 | } else { |
| 84 | self.id = ID{PID: os.Getpid()} |
| 85 | } |
| 86 | }) |
| 87 | return self.id |
| 88 | } |
| 89 | |
| 90 | // ParseRecord reads a process record, "pg:<pgid>:<marker>" (pgid 0: the |
| 91 | // marker alone; never 1, never negative, never without a marker). |
| 92 | func ParseRecord(id string) (int, string, bool) { |
| 93 | rest, ok := strings.CutPrefix(id, "pg:") |
| 94 | if !ok { |
| 95 | return 0, "", false |
| 96 | } |
| 97 | num, attempt, _ := strings.Cut(rest, ":") |
| 98 | pgid, err := strconv.Atoi(num) |
| 99 | if err != nil || pgid < 0 || pgid == 1 || attempt == "" { |
| 100 | return 0, "", false |
| 101 | } |
| 102 | return pgid, attempt, true |
| 103 | } |
| 104 | |