-
Notifications
You must be signed in to change notification settings - Fork 2.5k
feat(media): integrate TTL cleanup into FileMediaStore #728
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
alexhoshina
merged 7 commits into
sipeed:refactor/channel-system
from
ex-takashima:feat/media-cleanup-ttl
Feb 26, 2026
+491
−17
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e4d3650
feat(media): integrate TTL cleanup into FileMediaStore
ex-takashima 9a16f3b
fix(media): address review comments on TTL cleanup
ex-takashima 8e20644
fix(media): guard Interval<=0 panic, two-phase ReleaseAll
ex-takashima ad736d7
feat(line): add StartTyping and PlaceholderRecorder integration
ex-takashima af97540
Revert "feat(line): add StartTyping and PlaceholderRecorder integration"
ex-takashima 13a8ae4
fix(media): use project logger and harden map cleanup
ex-takashima 8979683
fix(media): separate import groups for gci linter
ex-takashima File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,8 +4,11 @@ import ( | |
| "fmt" | ||
| "os" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/google/uuid" | ||
|
|
||
| "github.com/sipeed/picoclaw/pkg/logger" | ||
| ) | ||
|
|
||
| // MediaMeta holds metadata about a stored media file. | ||
|
|
@@ -35,8 +38,16 @@ type MediaStore interface { | |
|
|
||
| // mediaEntry holds the path and metadata for a stored media file. | ||
| type mediaEntry struct { | ||
| path string | ||
| meta MediaMeta | ||
| path string | ||
| meta MediaMeta | ||
| storedAt time.Time | ||
| } | ||
|
|
||
| // MediaCleanerConfig configures the background TTL cleanup. | ||
| type MediaCleanerConfig struct { | ||
| Enabled bool | ||
| MaxAge time.Duration | ||
| Interval time.Duration | ||
| } | ||
|
|
||
| // FileMediaStore is a pure in-memory implementation of MediaStore. | ||
|
|
@@ -45,13 +56,34 @@ type FileMediaStore struct { | |
| mu sync.RWMutex | ||
| refs map[string]mediaEntry | ||
| scopeToRefs map[string]map[string]struct{} | ||
| refToScope map[string]string | ||
|
|
||
| cleanerCfg MediaCleanerConfig | ||
| stop chan struct{} | ||
| startOnce sync.Once | ||
| stopOnce sync.Once | ||
| nowFunc func() time.Time // for testing | ||
| } | ||
|
|
||
| // NewFileMediaStore creates a new FileMediaStore. | ||
| // NewFileMediaStore creates a new FileMediaStore without background cleanup. | ||
| func NewFileMediaStore() *FileMediaStore { | ||
| return &FileMediaStore{ | ||
| refs: make(map[string]mediaEntry), | ||
| scopeToRefs: make(map[string]map[string]struct{}), | ||
| refToScope: make(map[string]string), | ||
| 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), | ||
| cleanerCfg: cfg, | ||
| stop: make(chan struct{}), | ||
| nowFunc: time.Now, | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -66,11 +98,12 @@ func (s *FileMediaStore) Store(localPath string, meta MediaMeta, scope string) ( | |
| s.mu.Lock() | ||
| defer s.mu.Unlock() | ||
|
|
||
| s.refs[ref] = mediaEntry{path: localPath, meta: meta} | ||
| s.refs[ref] = mediaEntry{path: localPath, meta: meta, storedAt: s.nowFunc()} | ||
| if s.scopeToRefs[scope] == nil { | ||
| s.scopeToRefs[scope] = make(map[string]struct{}) | ||
| } | ||
| s.scopeToRefs[scope][ref] = struct{}{} | ||
| s.refToScope[ref] = scope | ||
|
|
||
| return ref, nil | ||
| } | ||
|
|
@@ -100,24 +133,139 @@ func (s *FileMediaStore) ResolveWithMeta(ref string) (string, MediaMeta, error) | |
| } | ||
|
|
||
| // ReleaseAll removes all files under the given scope and cleans up mappings. | ||
| // Phase 1 (under lock): remove entries from maps. | ||
| // Phase 2 (no lock): delete files from disk. | ||
| func (s *FileMediaStore) ReleaseAll(scope string) error { | ||
| s.mu.Lock() | ||
| defer s.mu.Unlock() | ||
| // Phase 1: collect paths and remove from maps under lock | ||
| var paths []string | ||
|
|
||
| s.mu.Lock() | ||
| refs, ok := s.scopeToRefs[scope] | ||
| if !ok { | ||
| s.mu.Unlock() | ||
| return nil | ||
| } | ||
|
|
||
| for ref := range refs { | ||
| if entry, exists := s.refs[ref]; exists { | ||
| if err := os.Remove(entry.path); err != nil && !os.IsNotExist(err) { | ||
| // Log but continue — best effort cleanup | ||
| paths = append(paths, entry.path) | ||
| } | ||
| delete(s.refs, ref) | ||
| delete(s.refToScope, ref) | ||
| } | ||
| delete(s.scopeToRefs, scope) | ||
| 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) { | ||
| logger.WarnCF("media", "release: failed to remove file", map[string]any{ | ||
| "path": p, | ||
| "error": err.Error(), | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // CleanExpired removes all entries older than MaxAge. | ||
| // Phase 1 (under lock): identify expired entries and remove from maps. | ||
| // Phase 2 (no lock): delete files from disk to minimize lock contention. | ||
| func (s *FileMediaStore) CleanExpired() int { | ||
| if s.cleanerCfg.MaxAge <= 0 { | ||
| return 0 | ||
| } | ||
|
|
||
| // Phase 1: collect expired entries under lock | ||
| type expiredEntry struct { | ||
| ref string | ||
| path string | ||
| } | ||
|
|
||
| s.mu.Lock() | ||
| cutoff := s.nowFunc().Add(-s.cleanerCfg.MaxAge) | ||
| var expired []expiredEntry | ||
|
|
||
| for ref, entry := range s.refs { | ||
| if entry.storedAt.Before(cutoff) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. and should cutoff >= 0 ? |
||
| expired = append(expired, expiredEntry{ref: ref, path: entry.path}) | ||
|
|
||
| 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) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| delete(s.refs, ref) | ||
| delete(s.refToScope, ref) | ||
| } | ||
| } | ||
| s.mu.Unlock() | ||
|
|
||
| delete(s.scopeToRefs, scope) | ||
| return nil | ||
| // Phase 2: delete files without holding the lock | ||
| for _, e := range expired { | ||
| if err := os.Remove(e.path); err != nil && !os.IsNotExist(err) { | ||
| logger.WarnCF("media", "cleanup: failed to remove file", map[string]any{ | ||
| "path": e.path, | ||
| "error": err.Error(), | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| return len(expired) | ||
| } | ||
|
|
||
| // Start begins the background cleanup goroutine if cleanup is enabled. | ||
| // Safe to call multiple times; only the first call starts the goroutine. | ||
| func (s *FileMediaStore) Start() { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Start function need match the Stop function also using |
||
| if !s.cleanerCfg.Enabled || s.stop == nil { | ||
| return | ||
| } | ||
| if s.cleanerCfg.Interval <= 0 || s.cleanerCfg.MaxAge <= 0 { | ||
| logger.WarnCF("media", "cleanup: skipped due to invalid config", map[string]any{ | ||
| "interval": s.cleanerCfg.Interval.String(), | ||
| "max_age": s.cleanerCfg.MaxAge.String(), | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| s.startOnce.Do(func() { | ||
| logger.InfoCF("media", "cleanup enabled", map[string]any{ | ||
| "interval": s.cleanerCfg.Interval.String(), | ||
| "max_age": s.cleanerCfg.MaxAge.String(), | ||
| }) | ||
|
|
||
| go func() { | ||
| ticker := time.NewTicker(s.cleanerCfg.Interval) | ||
| defer ticker.Stop() | ||
|
|
||
| for { | ||
| select { | ||
| case <-ticker.C: | ||
| if n := s.CleanExpired(); n > 0 { | ||
| logger.InfoCF("media", "cleanup: removed expired entries", map[string]any{ | ||
| "count": n, | ||
| }) | ||
| } | ||
| case <-s.stop: | ||
| return | ||
| } | ||
| } | ||
| }() | ||
| }) | ||
| } | ||
|
|
||
| // Stop terminates the background cleanup goroutine. | ||
| // Safe to call multiple times; only the first call closes the channel. | ||
| func (s *FileMediaStore) Stop() { | ||
| if s.stop == nil { | ||
| return | ||
| } | ||
| s.stopOnce.Do(func() { | ||
| close(s.stop) | ||
| }) | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
there err path not close the goroutine?