Skip to content

Commit 2ecaa71

Browse files
authored
Add Caching (#5)
Add in a simple templated cache used for memoization. For something that requires key/value, then use hashicorp/lru.
1 parent 07c3e46 commit 2ecaa71

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

charts/core/Chart.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ description: A Helm chart for deploying Unikorn Core
44

55
type: application
66

7-
version: v0.1.4
8-
appVersion: v0.1.4
7+
version: v0.1.5
8+
appVersion: v0.1.5
99

1010
icon: https://assets.unikorn-cloud.org/images/logos/dark-on-light/icon.svg

pkg/util/cache/timeout_cache.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Copyright 2024 the Unikorn Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package cache
18+
19+
import (
20+
"time"
21+
)
22+
23+
// TimeoutCache provides a cache with timeout.
24+
type TimeoutCache[V any] struct {
25+
value V
26+
refresh time.Duration
27+
invalid time.Time
28+
}
29+
30+
// New gets a new cache.
31+
func New[V any](refresh time.Duration) *TimeoutCache[V] {
32+
return &TimeoutCache[V]{
33+
refresh: refresh,
34+
}
35+
}
36+
37+
// Get returns the cached value if set and it hasn't timed out
38+
// and returns true. If it has timed out, it will return V's
39+
// zero value and false, and will need to be set again.
40+
//
41+
//nolint:nonamedreturns
42+
func (m *TimeoutCache[V]) Get() (value V, ok bool) {
43+
if time.Now().After(m.invalid) {
44+
return
45+
}
46+
47+
return m.value, true
48+
}
49+
50+
// Set remembers the value and resets the invalid time based
51+
// on when the cache was set.
52+
func (m *TimeoutCache[V]) Set(value V) {
53+
m.invalid = time.Now().Add(m.refresh)
54+
m.value = value
55+
}

0 commit comments

Comments
 (0)