package kunstzeal import ( "errors" "io" "os" "path/filepath" ) var ErrDiagramCacheLimit = errors.New("diagram cache exceeds limit") // ReadDiagramCache reads only a bounded derived artifact. filename must be // constructed by the application after validating kind/hash and authorizing // source provenance. A cache hit is not an access grant or a sanitized SVG. func ReadDiagramCache(filename string) ([]byte, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() b, err := io.ReadAll(io.LimitReader(f, DiagramOutputLimit+1)) if len(b) > DiagramOutputLimit { return nil, ErrDiagramCacheLimit } return b, err } // WriteDiagramCache publishes a complete artifact with same-directory rename. // Concurrent readers observe the old or new file, never a truncated write. // This is disposable cache storage, not a durable canonical Document commit. func WriteDiagramCache(filename string, data []byte) error { if len(data) > DiagramOutputLimit { return ErrDiagramCacheLimit } dir := filepath.Dir(filename) if err := os.MkdirAll(dir, 0755); err != nil { return err } f, err := os.CreateTemp(dir, ".diagram-*.tmp") if err != nil { return err } defer os.Remove(f.Name()) defer f.Close() if _, err = f.Write(data); err != nil { return err } if err = f.Chmod(0644); err != nil { return err } if err = f.Close(); err != nil { return err } return os.Rename(f.Name(), filename) }