package signedoci import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io/fs" "os" "path/filepath" "sync" "time" "github.com/samcharles93/archie-core/internal/fsutil" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" ) // FileFreshness is the durable freshness mark of accepted issue times, kept as one small JSON file // written atomically so a crash never leaves a half-written mark. A missing // file is no mark yet; a file that exists but does not parse is an error, so // a corrupt mark fails closed instead of opening a replay window. type FileFreshness struct { Path string mu sync.Mutex } func (f *FileFreshness) Newest(context.Context) (time.Time, error) { f.mu.Lock() defer f.mu.Unlock() return f.read() } func (f *FileFreshness) Accept(_ context.Context, issuedAt time.Time) error { f.mu.Lock() defer f.mu.Unlock() current, err := f.read() if err != nil { return err } if !issuedAt.After(current) { return nil } encoded, err := json.Marshal(struct { IssuedAt time.Time `json:"issued_at"` }{IssuedAt: issuedAt.UTC()}) if err != nil { return err } return fsutil.WriteFileAtomic(f.Path, encoded, 0o600) } // read returns the mark, or the zero time when nothing has been // accepted yet. func (f *FileFreshness) read() (time.Time, error) { raw, err := os.ReadFile(f.Path) if errors.Is(err, fs.ErrNotExist) { return time.Time{}, nil } if err != nil { return time.Time{}, err } var mark struct { IssuedAt time.Time `json:"issued_at"` } if err := json.Unmarshal(raw, &mark); err != nil { return time.Time{}, fmt.Errorf("freshness mark %s: %w", f.Path, err) } return mark.IssuedAt, nil } // MarkPath is where the freshness mark for one kind of artifact from one // source lives: $XDG_STATE_HOME///.json, the state home // the update journal uses too. The key names the reference, so two sources // never share a mark. func MarkPath(kind, reference string) string { dir := os.Getenv("XDG_STATE_HOME") if dir == "" { home, _ := os.UserHomeDir() dir = filepath.Join(home, ".local", "state") } sum := sha256.Sum256([]byte(reference)) return filepath.Join(dir, configuration.InstanceName(), kind, hex.EncodeToString(sum[:8])+".json") }