6
1
mirror of https://git.mills.io/saltyim/saltyim.git synced 2024-06-20 22:08:21 +00:00
prologic-saltyim/state.go
James Mills e8110e2a86 Use the new and improved with write-ahead-log (wal) support (#136)
Improves how inbox indices are peristed, hopefully much better now as the topic sequences are now a proper monotonic increasing integer, messages survive crashes/resrarts and so forth.

- [] Remove the `go.mod` replace directive after https://git.mills.io/prologic/msgbus/pulls/33 is merged

cc @xuu

Co-authored-by: James Mills <prologic@shortcircuit.net.au>
Reviewed-on: https://git.mills.io/saltyim/saltyim/pulls/136
Reviewed-by: xuu <xuu@noreply@mills.io>
2022-04-03 16:45:59 +00:00

82 lines
1.3 KiB
Go

package saltyim
import (
"encoding/json"
"fmt"
"io"
"os"
sync "github.com/sasha-s/go-deadlock"
)
// DefaultState returns a default state file
func DefaultState() string {
return os.ExpandEnv("$HOME/.config/salty/state.json")
}
type State struct {
sync.RWMutex
Indicies map[string]int64
}
func NewState() *State {
return &State{
Indicies: make(map[string]int64),
}
}
func (s *State) GetIndex(name string) int64 {
s.RLock()
defer s.RUnlock()
return s.Indicies[name]
}
func (s *State) SetIndex(name string, index int64) {
s.Lock()
defer s.Unlock()
s.Indicies[name] = index
}
func (s *State) Bytes() ([]byte, error) {
s.Lock()
defer s.Unlock()
data, err := json.Marshal(s)
if err != nil {
return nil, fmt.Errorf("error encoding state: %w", err)
}
return data, nil
}
func (s *State) Save(fn string) error {
data, err := s.Bytes()
if err != nil {
return err
}
if err := os.WriteFile(fn, data, 0644); err != nil {
return fmt.Errorf("error writing state file %s: %w", fn, err)
}
return nil
}
func LoadState(r io.Reader) (*State, error) {
var state *State
data, err := io.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("error reading state: %w", err)
}
if err := json.Unmarshal(data, &state); err != nil {
return nil, fmt.Errorf("error reading state: %w", err)
}
return state, nil
}