2026-02-22 15:27:55 +00:00
|
|
|
package media
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"os"
|
|
|
|
|
"sync"
|
2026-02-24 12:24:32 +00:00
|
|
|
"time"
|
2026-02-22 15:27:55 +00:00
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2026-02-26 13:45:59 +00:00
|
|
|
|
2026-02-26 13:39:58 +00:00
|
|
|
"github.com/sipeed/picoclaw/pkg/logger"
|
2026-02-22 15:27:55 +00:00
|
|
|
)
|
|
|
|
|
|
2026-03-23 04:13:59 +00:00
|
|
|
// CleanupPolicy controls how the MediaStore treats the underlying file when
|
|
|
|
|
// a ref is released or expires.
|
|
|
|
|
type CleanupPolicy string
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
// CleanupPolicyDeleteOnCleanup means the file is store-managed and may be
|
|
|
|
|
// deleted once the final ref for that path is gone.
|
|
|
|
|
CleanupPolicyDeleteOnCleanup CleanupPolicy = "delete_on_cleanup"
|
|
|
|
|
// CleanupPolicyForgetOnly means the store should only drop ref mappings and
|
|
|
|
|
// must never delete the underlying file.
|
|
|
|
|
CleanupPolicyForgetOnly CleanupPolicy = "forget_only"
|
|
|
|
|
)
|
|
|
|
|
|
2026-02-22 15:27:55 +00:00
|
|
|
// MediaMeta holds metadata about a stored media file.
|
|
|
|
|
type MediaMeta struct {
|
2026-03-23 04:13:59 +00:00
|
|
|
Filename string
|
|
|
|
|
ContentType string
|
|
|
|
|
Source string // "telegram", "discord", "tool:image-gen", etc.
|
|
|
|
|
CleanupPolicy CleanupPolicy // defaults to CleanupPolicyDeleteOnCleanup
|
2026-02-22 15:27:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MediaStore manages the lifecycle of media files associated with processing scopes.
|
|
|
|
|
type MediaStore interface {
|
|
|
|
|
// Store registers an existing local file under the given scope.
|
|
|
|
|
// Returns a ref identifier (e.g. "media://<id>").
|
|
|
|
|
// Store does not move or copy the file; it only records the mapping.
|
2026-03-23 04:13:59 +00:00
|
|
|
// If meta.CleanupPolicy is empty, CleanupPolicyDeleteOnCleanup is assumed.
|
2026-02-22 15:27:55 +00:00
|
|
|
Store(localPath string, meta MediaMeta, scope string) (ref string, err error)
|
|
|
|
|
|
|
|
|
|
// Resolve returns the local file path for a given ref.
|
|
|
|
|
Resolve(ref string) (localPath string, err error)
|
|
|
|
|
|
2026-02-22 22:03:23 +00:00
|
|
|
// ResolveWithMeta returns the local file path and metadata for a given ref.
|
|
|
|
|
ResolveWithMeta(ref string) (localPath string, meta MediaMeta, err error)
|
|
|
|
|
|
2026-02-22 15:27:55 +00:00
|
|
|
// ReleaseAll deletes all files registered under the given scope
|
|
|
|
|
// and removes the mapping entries. File-not-exist errors are ignored.
|
|
|
|
|
ReleaseAll(scope string) error
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-22 22:03:23 +00:00
|
|
|
// mediaEntry holds the path and metadata for a stored media file.
|
|
|
|
|
type mediaEntry struct {
|
2026-02-24 12:24:32 +00:00
|
|
|
path string
|
|
|
|
|
meta MediaMeta
|
|
|
|
|
storedAt time.Time
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-23 04:13:59 +00:00
|
|
|
type pathRefState struct {
|
|
|
|
|
refCount int
|
|
|
|
|
deleteEligible bool
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-24 12:24:32 +00:00
|
|
|
// MediaCleanerConfig configures the background TTL cleanup.
|
|
|
|
|
type MediaCleanerConfig struct {
|
|
|
|
|
Enabled bool
|
|
|
|
|
MaxAge time.Duration
|
|
|
|
|
Interval time.Duration
|
2026-02-22 22:03:23 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-22 15:27:55 +00:00
|
|
|
// FileMediaStore is a pure in-memory implementation of MediaStore.
|
|
|
|
|
// Files are expected to already exist on disk (e.g. in /tmp/picoclaw_media/).
|
|
|
|
|
type FileMediaStore struct {
|
|
|
|
|
mu sync.RWMutex
|
2026-02-22 22:03:23 +00:00
|
|
|
refs map[string]mediaEntry
|
2026-02-22 15:27:55 +00:00
|
|
|
scopeToRefs map[string]map[string]struct{}
|
2026-02-24 12:24:32 +00:00
|
|
|
refToScope map[string]string
|
2026-03-23 04:13:59 +00:00
|
|
|
refToPath map[string]string
|
|
|
|
|
pathStates map[string]pathRefState
|
2026-02-24 12:24:32 +00:00
|
|
|
|
|
|
|
|
cleanerCfg MediaCleanerConfig
|
|
|
|
|
stop chan struct{}
|
2026-02-26 07:22:49 +00:00
|
|
|
startOnce sync.Once
|
|
|
|
|
stopOnce sync.Once
|
2026-02-24 12:24:32 +00:00
|
|
|
nowFunc func() time.Time // for testing
|
2026-02-22 15:27:55 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-24 12:24:32 +00:00
|
|
|
// NewFileMediaStore creates a new FileMediaStore without background cleanup.
|
2026-02-22 15:27:55 +00:00
|
|
|
func NewFileMediaStore() *FileMediaStore {
|
|
|
|
|
return &FileMediaStore{
|
2026-02-22 22:03:23 +00:00
|
|
|
refs: make(map[string]mediaEntry),
|
2026-02-22 15:27:55 +00:00
|
|
|
scopeToRefs: make(map[string]map[string]struct{}),
|
2026-02-24 12:24:32 +00:00
|
|
|
refToScope: make(map[string]string),
|
2026-03-23 04:13:59 +00:00
|
|
|
refToPath: make(map[string]string),
|
|
|
|
|
pathStates: make(map[string]pathRefState),
|
2026-02-24 12:24:32 +00:00
|
|
|
nowFunc: time.Now,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NewFileMediaStoreWithCleanup creates a FileMediaStore with TTL-based background cleanup.
|
|
|
|
|
func NewFileMediaStoreWithCleanup(cfg MediaCleanerConfig) *FileMediaStore {
|
|
|
|
|
return &FileMediaStore{
|
|
|
|
|
refs: make(map[string]mediaEntry),
|
|
|
|
|
scopeToRefs: make(map[string]map[string]struct{}),
|
|
|
|
|
refToScope: make(map[string]string),
|
2026-03-23 04:13:59 +00:00
|
|
|
refToPath: make(map[string]string),
|
|
|
|
|
pathStates: make(map[string]pathRefState),
|
2026-02-24 12:24:32 +00:00
|
|
|
cleanerCfg: cfg,
|
|
|
|
|
stop: make(chan struct{}),
|
|
|
|
|
nowFunc: time.Now,
|
2026-02-22 15:27:55 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Store registers a local file under the given scope. The file must exist.
|
|
|
|
|
func (s *FileMediaStore) Store(localPath string, meta MediaMeta, scope string) (string, error) {
|
|
|
|
|
if _, err := os.Stat(localPath); err != nil {
|
2026-02-22 22:03:23 +00:00
|
|
|
return "", fmt.Errorf("media store: %s: %w", localPath, err)
|
2026-02-22 15:27:55 +00:00
|
|
|
}
|
|
|
|
|
|
2026-02-22 22:03:23 +00:00
|
|
|
ref := "media://" + uuid.New().String()
|
2026-03-23 04:13:59 +00:00
|
|
|
meta.CleanupPolicy = normalizeCleanupPolicy(meta.CleanupPolicy)
|
2026-02-22 15:27:55 +00:00
|
|
|
|
|
|
|
|
s.mu.Lock()
|
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
|
|
2026-02-24 12:24:32 +00:00
|
|
|
s.refs[ref] = mediaEntry{path: localPath, meta: meta, storedAt: s.nowFunc()}
|
2026-02-22 15:27:55 +00:00
|
|
|
if s.scopeToRefs[scope] == nil {
|
|
|
|
|
s.scopeToRefs[scope] = make(map[string]struct{})
|
|
|
|
|
}
|
|
|
|
|
s.scopeToRefs[scope][ref] = struct{}{}
|
2026-02-24 12:24:32 +00:00
|
|
|
s.refToScope[ref] = scope
|
2026-03-23 04:13:59 +00:00
|
|
|
s.refToPath[ref] = localPath
|
|
|
|
|
|
|
|
|
|
pathState := s.pathStates[localPath]
|
|
|
|
|
if pathState.refCount == 0 {
|
|
|
|
|
pathState.deleteEligible = meta.CleanupPolicy == CleanupPolicyDeleteOnCleanup
|
|
|
|
|
} else if meta.CleanupPolicy == CleanupPolicyForgetOnly {
|
|
|
|
|
// Be conservative: once a path is borrowed externally, never let this
|
|
|
|
|
// lifecycle auto-delete it even if store-managed refs also exist.
|
|
|
|
|
pathState.deleteEligible = false
|
|
|
|
|
}
|
|
|
|
|
pathState.refCount++
|
|
|
|
|
s.pathStates[localPath] = pathState
|
2026-02-22 15:27:55 +00:00
|
|
|
|
|
|
|
|
return ref, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Resolve returns the local path for the given ref.
|
|
|
|
|
func (s *FileMediaStore) Resolve(ref string) (string, error) {
|
|
|
|
|
s.mu.RLock()
|
|
|
|
|
defer s.mu.RUnlock()
|
|
|
|
|
|
2026-02-22 22:03:23 +00:00
|
|
|
entry, ok := s.refs[ref]
|
2026-02-22 15:27:55 +00:00
|
|
|
if !ok {
|
|
|
|
|
return "", fmt.Errorf("media store: unknown ref: %s", ref)
|
|
|
|
|
}
|
2026-02-22 22:03:23 +00:00
|
|
|
return entry.path, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ResolveWithMeta returns the local path and metadata for the given ref.
|
|
|
|
|
func (s *FileMediaStore) ResolveWithMeta(ref string) (string, MediaMeta, error) {
|
|
|
|
|
s.mu.RLock()
|
|
|
|
|
defer s.mu.RUnlock()
|
|
|
|
|
|
|
|
|
|
entry, ok := s.refs[ref]
|
|
|
|
|
if !ok {
|
|
|
|
|
return "", MediaMeta{}, fmt.Errorf("media store: unknown ref: %s", ref)
|
|
|
|
|
}
|
|
|
|
|
return entry.path, entry.meta, nil
|
2026-02-22 15:27:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ReleaseAll removes all files under the given scope and cleans up mappings.
|
2026-02-26 07:33:32 +00:00
|
|
|
// Phase 1 (under lock): remove entries from maps.
|
2026-03-23 04:13:59 +00:00
|
|
|
// Phase 2 (no lock): delete store-managed files from disk once their final
|
|
|
|
|
// path ref is gone.
|
2026-02-22 15:27:55 +00:00
|
|
|
func (s *FileMediaStore) ReleaseAll(scope string) error {
|
2026-02-26 07:33:32 +00:00
|
|
|
// Phase 1: collect paths and remove from maps under lock
|
|
|
|
|
var paths []string
|
2026-02-22 15:27:55 +00:00
|
|
|
|
2026-02-26 07:33:32 +00:00
|
|
|
s.mu.Lock()
|
2026-02-22 15:27:55 +00:00
|
|
|
refs, ok := s.scopeToRefs[scope]
|
|
|
|
|
if !ok {
|
2026-02-26 07:33:32 +00:00
|
|
|
s.mu.Unlock()
|
2026-02-22 15:27:55 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for ref := range refs {
|
2026-03-23 04:13:59 +00:00
|
|
|
fallbackPath := ""
|
2026-02-22 22:03:23 +00:00
|
|
|
if entry, exists := s.refs[ref]; exists {
|
2026-03-23 04:13:59 +00:00
|
|
|
fallbackPath = entry.path
|
|
|
|
|
}
|
|
|
|
|
if removablePath, shouldDelete := s.releaseRefLocked(ref, fallbackPath); shouldDelete {
|
|
|
|
|
paths = append(paths, removablePath)
|
2026-02-22 15:27:55 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
delete(s.scopeToRefs, scope)
|
2026-02-26 07:33:32 +00:00
|
|
|
s.mu.Unlock()
|
|
|
|
|
|
|
|
|
|
// Phase 2: delete files without holding the lock
|
|
|
|
|
for _, p := range paths {
|
|
|
|
|
if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
|
2026-02-26 13:39:58 +00:00
|
|
|
logger.WarnCF("media", "release: failed to remove file", map[string]any{
|
|
|
|
|
"path": p,
|
|
|
|
|
"error": err.Error(),
|
|
|
|
|
})
|
2026-02-26 07:33:32 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-22 15:27:55 +00:00
|
|
|
return nil
|
|
|
|
|
}
|
2026-02-24 12:24:32 +00:00
|
|
|
|
|
|
|
|
// CleanExpired removes all entries older than MaxAge.
|
2026-02-26 07:22:49 +00:00
|
|
|
// Phase 1 (under lock): identify expired entries and remove from maps.
|
2026-03-23 04:13:59 +00:00
|
|
|
// Phase 2 (no lock): delete store-managed files from disk to minimize lock contention.
|
2026-02-24 12:24:32 +00:00
|
|
|
func (s *FileMediaStore) CleanExpired() int {
|
2026-02-26 07:22:49 +00:00
|
|
|
if s.cleanerCfg.MaxAge <= 0 {
|
|
|
|
|
return 0
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Phase 1: collect expired entries under lock
|
|
|
|
|
type expiredEntry struct {
|
2026-03-23 04:13:59 +00:00
|
|
|
ref string
|
|
|
|
|
deletePath string
|
2026-02-26 07:22:49 +00:00
|
|
|
}
|
2026-02-24 12:24:32 +00:00
|
|
|
|
2026-02-26 07:22:49 +00:00
|
|
|
s.mu.Lock()
|
2026-02-24 12:24:32 +00:00
|
|
|
cutoff := s.nowFunc().Add(-s.cleanerCfg.MaxAge)
|
2026-02-26 07:22:49 +00:00
|
|
|
var expired []expiredEntry
|
2026-02-24 12:24:32 +00:00
|
|
|
|
|
|
|
|
for ref, entry := range s.refs {
|
|
|
|
|
if entry.storedAt.Before(cutoff) {
|
2026-02-26 13:39:58 +00:00
|
|
|
if scope, ok := s.refToScope[ref]; ok {
|
|
|
|
|
if scopeRefs, ok := s.scopeToRefs[scope]; ok {
|
|
|
|
|
delete(scopeRefs, ref)
|
|
|
|
|
if len(scopeRefs) == 0 {
|
|
|
|
|
delete(s.scopeToRefs, scope)
|
|
|
|
|
}
|
2026-02-24 12:24:32 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-23 04:13:59 +00:00
|
|
|
expiredItem := expiredEntry{ref: ref}
|
|
|
|
|
if deletePath, shouldDelete := s.releaseRefLocked(ref, entry.path); shouldDelete {
|
|
|
|
|
expiredItem.deletePath = deletePath
|
|
|
|
|
}
|
|
|
|
|
expired = append(expired, expiredItem)
|
2026-02-26 07:22:49 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
s.mu.Unlock()
|
|
|
|
|
|
|
|
|
|
// Phase 2: delete files without holding the lock
|
|
|
|
|
for _, e := range expired {
|
2026-03-23 04:13:59 +00:00
|
|
|
if e.deletePath == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if err := os.Remove(e.deletePath); err != nil && !os.IsNotExist(err) {
|
2026-02-26 13:39:58 +00:00
|
|
|
logger.WarnCF("media", "cleanup: failed to remove file", map[string]any{
|
2026-03-23 04:13:59 +00:00
|
|
|
"path": e.deletePath,
|
2026-02-26 13:39:58 +00:00
|
|
|
"error": err.Error(),
|
|
|
|
|
})
|
2026-02-24 12:24:32 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-26 07:22:49 +00:00
|
|
|
return len(expired)
|
2026-02-24 12:24:32 +00:00
|
|
|
}
|
|
|
|
|
|
2026-03-23 04:13:59 +00:00
|
|
|
func normalizeCleanupPolicy(policy CleanupPolicy) CleanupPolicy {
|
|
|
|
|
switch policy {
|
|
|
|
|
case "", CleanupPolicyDeleteOnCleanup:
|
|
|
|
|
return CleanupPolicyDeleteOnCleanup
|
|
|
|
|
case CleanupPolicyForgetOnly:
|
|
|
|
|
return CleanupPolicyForgetOnly
|
|
|
|
|
default:
|
|
|
|
|
return CleanupPolicyDeleteOnCleanup
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *FileMediaStore) releaseRefLocked(ref, fallbackPath string) (string, bool) {
|
|
|
|
|
path := fallbackPath
|
|
|
|
|
if storedPath, ok := s.refToPath[ref]; ok {
|
|
|
|
|
path = storedPath
|
|
|
|
|
delete(s.refToPath, ref)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
delete(s.refs, ref)
|
|
|
|
|
delete(s.refToScope, ref)
|
|
|
|
|
|
|
|
|
|
if path == "" {
|
|
|
|
|
return "", false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pathState, ok := s.pathStates[path]
|
|
|
|
|
if !ok {
|
|
|
|
|
return "", false
|
|
|
|
|
}
|
|
|
|
|
if pathState.refCount <= 1 {
|
|
|
|
|
delete(s.pathStates, path)
|
|
|
|
|
return path, pathState.deleteEligible
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pathState.refCount--
|
|
|
|
|
s.pathStates[path] = pathState
|
|
|
|
|
return "", false
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-24 12:24:32 +00:00
|
|
|
// Start begins the background cleanup goroutine if cleanup is enabled.
|
2026-02-26 07:22:49 +00:00
|
|
|
// Safe to call multiple times; only the first call starts the goroutine.
|
2026-02-24 12:24:32 +00:00
|
|
|
func (s *FileMediaStore) Start() {
|
|
|
|
|
if !s.cleanerCfg.Enabled || s.stop == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-02-26 07:33:32 +00:00
|
|
|
if s.cleanerCfg.Interval <= 0 || s.cleanerCfg.MaxAge <= 0 {
|
2026-02-26 13:39:58 +00:00
|
|
|
logger.WarnCF("media", "cleanup: skipped due to invalid config", map[string]any{
|
|
|
|
|
"interval": s.cleanerCfg.Interval.String(),
|
|
|
|
|
"max_age": s.cleanerCfg.MaxAge.String(),
|
|
|
|
|
})
|
2026-02-26 07:33:32 +00:00
|
|
|
return
|
|
|
|
|
}
|
2026-02-24 12:24:32 +00:00
|
|
|
|
2026-02-26 07:22:49 +00:00
|
|
|
s.startOnce.Do(func() {
|
2026-02-26 13:39:58 +00:00
|
|
|
logger.InfoCF("media", "cleanup enabled", map[string]any{
|
|
|
|
|
"interval": s.cleanerCfg.Interval.String(),
|
|
|
|
|
"max_age": s.cleanerCfg.MaxAge.String(),
|
|
|
|
|
})
|
2026-02-26 07:22:49 +00:00
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
|
ticker := time.NewTicker(s.cleanerCfg.Interval)
|
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ticker.C:
|
|
|
|
|
if n := s.CleanExpired(); n > 0 {
|
2026-02-26 13:39:58 +00:00
|
|
|
logger.InfoCF("media", "cleanup: removed expired entries", map[string]any{
|
|
|
|
|
"count": n,
|
|
|
|
|
})
|
2026-02-26 07:22:49 +00:00
|
|
|
}
|
|
|
|
|
case <-s.stop:
|
|
|
|
|
return
|
2026-02-24 12:24:32 +00:00
|
|
|
}
|
|
|
|
|
}
|
2026-02-26 07:22:49 +00:00
|
|
|
}()
|
|
|
|
|
})
|
2026-02-24 12:24:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Stop terminates the background cleanup goroutine.
|
2026-02-26 07:22:49 +00:00
|
|
|
// Safe to call multiple times; only the first call closes the channel.
|
2026-02-24 12:24:32 +00:00
|
|
|
func (s *FileMediaStore) Stop() {
|
|
|
|
|
if s.stop == nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-02-26 07:22:49 +00:00
|
|
|
s.stopOnce.Do(func() {
|
2026-02-24 12:24:32 +00:00
|
|
|
close(s.stop)
|
|
|
|
|
})
|
|
|
|
|
}
|