Debian Codegraph @

sdk/metric/cache.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package metric // import "go.opentelemetry.io/otel/sdk/metric"
5
6 import (
7 "sync"
8 )
9
10 // cache is a locking storage used to quickly return already computed values.
11 //
12 // The zero value of a cache is empty and ready to use.
13 //
14 // A cache must not be copied after first use.
15 //
16 // All methods of a cache are safe to call concurrently.
17 type cache[K comparable, V any] struct {
18 sync.Mutex
19 data map[K]V
20 }
21
22 // Lookup returns the value stored in the cache with the associated key if it
23 // exists. Otherwise, f is called and its returned value is set in the cache
24 // for key and returned.
25 //
26 // Lookup is safe to call concurrently. It will hold the cache lock, so f
27 // should not block excessively.
28 func (c *cache[K, V]) Lookup(key K, f func() V) V {
29 c.Lock()
30 defer c.Unlock()
31
32 if c.data == nil {
33 val := f()
34 c.data = map[K]V{key: val}
35 return val
36 }
37 if v, ok := c.data[key]; ok {
38 return v
39 }
40 val := f()
41 c.data[key] = val
42 return val
43 }
44
45 // HasKey returns true if Lookup has previously been called with that key
46 //
47 // HasKey is safe to call concurrently.
48 func (c *cache[K, V]) HasKey(key K) bool {
49 c.Lock()
50 defer c.Unlock()
51 _, ok := c.data[key]
52 return ok
53 }
54
55 // cacheWithErr is a locking storage used to quickly return already computed values and an error.
56 //
57 // The zero value of a cacheWithErr is empty and ready to use.
58 //
59 // A cacheWithErr must not be copied after first use.
60 //
61 // All methods of a cacheWithErr are safe to call concurrently.
62 type cacheWithErr[K comparable, V any] struct {
63 cache[K, valAndErr[V]]
64 }
65
66 type valAndErr[V any] struct {
67 val V
68 err error
69 }
70
71 // Lookup returns the value stored in the cacheWithErr with the associated key
72 // if it exists. Otherwise, f is called and its returned value is set in the
73 // cacheWithErr for key and returned.
74 //
75 // Lookup is safe to call concurrently. It will hold the cacheWithErr lock, so f
76 // should not block excessively.
77 func (c *cacheWithErr[K, V]) Lookup(key K, f func() (V, error)) (V, error) {
78 combined := c.cache.Lookup(key, func() valAndErr[V] {
79 val, err := f()
80 return valAndErr[V]{val: val, err: err}
81 })
82 return combined.val, combined.err
83 }