Files
NwflowerandClaude Opus 5.5 90fbce8b47 refactor: write small files through one atomic writer
Fifteen call sites each had their own temp-file-and-rename code. Some
used a fixed temporary name, so two writers could mix their content, and
most did not flush before the rename. They now share atomicfile.Write.

An architecture test keeps new os.Rename calls out of other packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:59:56 -07:00

173 lines
5.8 KiB
Go

package plugin
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/Nwflower/reims-go/internal/atomicfile"
)
const (
StateFileName = "state.json"
StartupSentinel = ".startup-sentinel"
CurrentStateSchema = 1
)
// PluginRecord persists enablement, pinned version, approved permissions, and
// settings for one plugin in `<DataRoot>/plugins/state.json` (§6.1).
type PluginRecord struct {
ID string `json:"id"`
Version string `json:"version,omitempty"`
Source SourceKind `json:"source,omitempty"`
Trust TrustLevel `json:"trust,omitempty"`
Enabled bool `json:"enabled"`
Pinned bool `json:"pinned,omitempty"`
DevPath string `json:"dev_path,omitempty"`
ApprovedPermissions []string `json:"approved_permissions,omitempty"`
ApprovedEntryHash string `json:"approved_entry_hash,omitempty"`
BlockingGuardOK bool `json:"blocking_guard_ok,omitempty"`
AppSettings map[string]any `json:"app_settings,omitempty"`
VMSettings map[string]map[string]any `json:"vm_settings,omitempty"` // driver.VMRef.Key() -> key -> val
InstalledVersions []string `json:"installed_versions,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
// CustomThemeScheme stores a user-created or edited theme color scheme (§5.1).
type CustomThemeScheme struct {
ID string `json:"id"`
ThemeID string `json:"theme_id"`
Name string `json:"name"`
Appearance string `json:"appearance,omitempty"`
Seeds map[string]string `json:"seeds"`
}
// StateFile is the authoritative persisted plugin state at `<DataRoot>/plugins/state.json`.
type StateFile struct {
Schema int `json:"schema"`
DeveloperMode bool `json:"developer_mode,omitempty"`
ActiveThemeID string `json:"active_theme_id,omitempty"`
ActiveThemePluginID string `json:"active_theme_plugin_id,omitempty"`
ActiveSchemeID string `json:"active_scheme_id,omitempty"`
CustomSchemes []CustomThemeScheme `json:"custom_schemes,omitempty"`
Plugins map[string]*PluginRecord `json:"plugins"`
}
// StateStore safely reads and atomically writes state.json with .bak fallback.
// Per §6.1: read/parse errors are NEVER treated as an empty plugin list!
type StateStore struct {
mu sync.Mutex
dir string
data *StateFile
}
func NewStateStore(pluginsDir string) *StateStore {
return &StateStore{dir: pluginsDir}
}
func (s *StateStore) Path() string { return filepath.Join(s.dir, StateFileName) }
// Load reads state.json. Missing file initializes a fresh StateFile; any read
// or JSON parse error is returned immediately (never wiped to empty, §6.1).
func (s *StateStore) Load() (*StateFile, error) {
s.mu.Lock()
defer s.mu.Unlock()
p := s.Path()
raw, err := os.ReadFile(p)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
st := &StateFile{
Schema: CurrentStateSchema,
Plugins: make(map[string]*PluginRecord),
}
s.data = st
return st, nil
}
return nil, fmt.Errorf("read plugin state %s: %w", p, err)
}
var st StateFile
if err := json.Unmarshal(raw, &st); err != nil {
return nil, fmt.Errorf("corrupt plugin state %s (refusing to overwrite): %w", p, err)
}
if st.Plugins == nil {
st.Plugins = make(map[string]*PluginRecord)
}
if st.Schema == 0 {
st.Schema = CurrentStateSchema
}
s.data = &st
return &st, nil
}
// Save atomically persists state.json via temp file + .bak backup + rename (§6.1).
func (s *StateStore) Save(st *StateFile) error {
s.mu.Lock()
defer s.mu.Unlock()
if st == nil {
return errors.New("nil plugin state")
}
if st.Plugins == nil {
st.Plugins = make(map[string]*PluginRecord)
}
st.Schema = CurrentStateSchema
if err := os.MkdirAll(s.dir, 0o755); err != nil {
return err
}
target := s.Path()
// Preserve the previous valid file as .bak before the swap. A failed backup
// aborts the migration/save instead of silently destroying the only fallback.
if prev, err := os.ReadFile(target); err == nil {
if err := os.WriteFile(target+".bak", prev, 0o644); err != nil {
return fmt.Errorf("backup plugin state: %w", err)
}
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("read plugin state before backup: %w", err)
}
if err := atomicfile.WriteJSON(target, st, 0o644); err != nil {
return err
}
s.data = st
return nil
}
// --- Safe-mode startup sentinel (§9) ---
// SentinelPath returns `<DataRoot>/plugins/.startup-sentinel`.
func SentinelPath(pluginsDir string) string {
return filepath.Join(pluginsDir, StartupSentinel)
}
// DidLastStartupCrash reports whether a startup sentinel from an unfinished
// plugin initialization is still on disk.
func DidLastStartupCrash(pluginsDir string) bool {
if strings.TrimSpace(pluginsDir) == "" {
return false
}
_, err := os.Stat(SentinelPath(pluginsDir))
return err == nil
}
// BeginStartupInit writes the startup sentinel before loading third-party plugins.
func BeginStartupInit(pluginsDir string) error {
if strings.TrimSpace(pluginsDir) == "" {
return nil
}
if err := os.MkdirAll(pluginsDir, 0o755); err != nil {
return err
}
return os.WriteFile(SentinelPath(pluginsDir), []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), 0o644)
}
// EndStartupInit removes the startup sentinel once plugin init succeeds.
func EndStartupInit(pluginsDir string) {
if strings.TrimSpace(pluginsDir) == "" {
return
}
_ = os.Remove(SentinelPath(pluginsDir))
}