chore: add cacheCloser to cleanup all opened files (#18473)

This commit is contained in:
Steven Masley
2025-06-20 13:25:33 -05:00
committed by GitHub
parent 9b5d49967c
commit 556b095d0f
3 changed files with 79 additions and 16 deletions
+4
View File
@@ -19,6 +19,10 @@ import (
"github.com/coder/coder/v2/coderd/util/lazy"
)
type FileAcquirer interface {
Acquire(ctx context.Context, fileID uuid.UUID) (*CloseFS, error)
}
// NewFromStore returns a file cache that will fetch files from the provided
// database.
func NewFromStore(store database.Store, registerer prometheus.Registerer, authz rbac.Authorizer) *Cache {
+57
View File
@@ -0,0 +1,57 @@
package files
import (
"context"
"sync"
"github.com/google/uuid"
"golang.org/x/xerrors"
)
// CacheCloser is a cache wrapper used to close all acquired files.
// This is a more simple interface to use if opening multiple files at once.
type CacheCloser struct {
cache FileAcquirer
closers []func()
mu sync.Mutex
}
func NewCacheCloser(cache FileAcquirer) *CacheCloser {
return &CacheCloser{
cache: cache,
closers: make([]func(), 0),
}
}
func (c *CacheCloser) Close() {
c.mu.Lock()
defer c.mu.Unlock()
for _, doClose := range c.closers {
doClose()
}
// Prevent further acquisitions
c.cache = nil
// Remove any references
c.closers = nil
}
func (c *CacheCloser) Acquire(ctx context.Context, fileID uuid.UUID) (*CloseFS, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.cache == nil {
return nil, xerrors.New("cache is closed, and cannot acquire new files")
}
f, err := c.cache.Acquire(ctx, fileID)
if err != nil {
return nil, err
}
c.closers = append(c.closers, f.close)
return f, nil
}