-
Notifications
You must be signed in to change notification settings - Fork 8
/
tcache.go
66 lines (53 loc) · 1.27 KB
/
tcache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package tcache
import (
"context"
"sync"
"namespacelabs.dev/foundation/std/tasks"
)
type Cache[V any] struct {
mu sync.Mutex
entries map[string]*result[V]
}
type result[V any] struct {
once sync.Once
value V
err error
}
type Deferred[V any] struct {
action *tasks.ActionEvent
produce func(context.Context) (V, error)
result result[V]
}
func NewCache[V any]() *Cache[V] {
return &Cache[V]{
entries: map[string]*result[V]{},
}
}
func (c *Cache[V]) Compute(key string, produce func() (V, error)) (V, error) {
c.mu.Lock()
v, ok := c.entries[key]
if !ok {
v = &result[V]{}
c.entries[key] = v
}
c.mu.Unlock()
v.once.Do(func() {
v.value, v.err = produce()
})
return v.value, v.err
}
func NewDeferred[V any](action *tasks.ActionEvent, produce func(context.Context) (V, error)) *Deferred[V] {
return &Deferred[V]{
action: action,
produce: produce,
}
}
func (d *Deferred[V]) Get(ctx context.Context) (V, error) {
d.result.once.Do(func() {
d.result.value, d.result.err = tasks.Return(ctx, d.action, d.produce)
})
return d.result.value, d.result.err
}