mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
chore: add cacheCloser to cleanup all opened files (#18473)
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user