mirror of
https://github.com/coder/coder.git
synced 2026-06-02 20:48:20 +00:00
chore: add files cache for reading template tar archives from db (#17141)
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package lazy
|
||||
|
||||
type ValueWithError[T any] struct {
|
||||
inner Value[result[T]]
|
||||
}
|
||||
|
||||
type result[T any] struct {
|
||||
value T
|
||||
err error
|
||||
}
|
||||
|
||||
// NewWithError allows you to provide a lazy initializer that can fail.
|
||||
func NewWithError[T any](fn func() (T, error)) *ValueWithError[T] {
|
||||
return &ValueWithError[T]{
|
||||
inner: Value[result[T]]{fn: func() result[T] {
|
||||
value, err := fn()
|
||||
return result[T]{value: value, err: err}
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
func (v *ValueWithError[T]) Load() (T, error) {
|
||||
result := v.inner.Load()
|
||||
return result.value, result.err
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package lazy_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/util/lazy"
|
||||
)
|
||||
|
||||
func TestLazyWithErrorOK(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
l := lazy.NewWithError(func() (int, error) {
|
||||
return 1, nil
|
||||
})
|
||||
|
||||
i, err := l.Load()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, i)
|
||||
}
|
||||
|
||||
func TestLazyWithErrorErr(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
l := lazy.NewWithError(func() (int, error) {
|
||||
return 0, xerrors.New("oh no! everything that could went horribly wrong!")
|
||||
})
|
||||
|
||||
i, err := l.Load()
|
||||
require.Error(t, err)
|
||||
require.Equal(t, 0, i)
|
||||
}
|
||||
|
||||
func TestLazyWithErrorPointers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
a := 1
|
||||
l := lazy.NewWithError(func() (*int, error) {
|
||||
return &a, nil
|
||||
})
|
||||
|
||||
b, err := l.Load()
|
||||
require.NoError(t, err)
|
||||
c, err := l.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
*b++
|
||||
*c++
|
||||
require.Equal(t, 3, a)
|
||||
}
|
||||
Reference in New Issue
Block a user