Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions charts/core/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: A Helm chart for deploying Unikorn Core

type: application

version: v0.1.4
appVersion: v0.1.4
version: v0.1.5
appVersion: v0.1.5

icon: https://assets.unikorn-cloud.org/images/logos/dark-on-light/icon.svg
55 changes: 55 additions & 0 deletions pkg/util/cache/timeout_cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
Copyright 2024 the Unikorn Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cache

import (
"time"
)

// TimeoutCache provides a cache with timeout.
type TimeoutCache[V any] struct {
value V
refresh time.Duration
invalid time.Time
}

// New gets a new cache.
func New[V any](refresh time.Duration) *TimeoutCache[V] {
return &TimeoutCache[V]{
refresh: refresh,
}
}

// Get returns the cached value if set and it hasn't timed out
// and returns true. If it has timed out, it will return V's
// zero value and false, and will need to be set again.
//
//nolint:nonamedreturns
func (m *TimeoutCache[V]) Get() (value V, ok bool) {
if time.Now().After(m.invalid) {
return
}

return m.value, true
}

// Set remembers the value and resets the invalid time based
// on when the cache was set.
func (m *TimeoutCache[V]) Set(value V) {
m.invalid = time.Now().Add(m.refresh)
m.value = value
}