Skip to content

Commit

Permalink
feat: pass cache to init callback
Browse files Browse the repository at this point in the history
  • Loading branch information
ydylla committed Jul 9, 2022
1 parent 5bf7a40 commit 124255e
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
11 changes: 8 additions & 3 deletions builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type builder struct {
evictionInterval time.Duration
fileMode fs.FileMode
backgroundInit bool
initCallback func(err error)
initCallback InitCallback
}

// WithEvictionInterval configures how much time has to pass between evictions.
Expand All @@ -43,10 +43,15 @@ func (b *builder) WithFileMode(perm fs.FileMode) *builder {
return b
}

// InitCallback is called after the cache finished restoring all entries from disk.
// cache is the Cache that was doing the init.
// err indicates if the init was successful or not.
type InitCallback func(cache Cache, err error)

// WithBackgroundInit restores the cache state in background instead of in Build.
// If initCallback is not nil it will be called once when all cache entries are restored or an error occurred.
// For the duration of init all cache operations will block.
func (b *builder) WithBackgroundInit(initCallback func(initError error)) *builder {
func (b *builder) WithBackgroundInit(initCallback InitCallback) *builder {
b.backgroundInit = true
b.initCallback = initCallback
return b
Expand Down Expand Up @@ -110,7 +115,7 @@ func (b *builder) Build() (Cache, error) {
if err != nil {
err = fmt.Errorf("failed to restore cache: %w", err)
}
b.initCallback(err)
b.initCallback(c, err)
}
}()
} else {
Expand Down
6 changes: 5 additions & 1 deletion builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,18 @@ func TestBuilder_WithBackgroundInit(t *testing.T) {
wg := sync.WaitGroup{}

wg.Add(1)
c2, err := Builder(dir, 50*MB).WithBackgroundInit(func(initError error) {
var cacheFromInit Cache
c2, err := Builder(dir, 50*MB).WithBackgroundInit(func(initCache Cache, initError error) {
defer wg.Done()
cacheFromInit = initCache
assertNoError(t, initError)
}).Build()
assertNoError(t, err)

wg.Wait()

assertStruct(t, c2, cacheFromInit)

assertStruct(t, Stats{
Items: 1,
Bytes: 11,
Expand Down

0 comments on commit 124255e

Please sign in to comment.