Skip to content

Commit

Permalink
renames, lint fixes, and an error d'oh
Browse files Browse the repository at this point in the history
  • Loading branch information
deniseli committed Apr 18, 2024
1 parent 77a6e23 commit 19c943d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
24 changes: 11 additions & 13 deletions go-runtime/ftl/singleton.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,23 @@ import (
"sync"
)

type InputLambda[T any] func(context.Context) (T, error)

type SingletonConstructor[T any] struct {
Fn InputLambda[T]
Out T
Once sync.Once
type SingletonHandle[T any] struct {
fn func(context.Context) (T, error)
out T
once *sync.Once
}

func (sf *SingletonConstructor[T]) Get(ctx context.Context) T {
sf.Once.Do(func() {
t, err := sf.Fn(ctx)
func (sh *SingletonHandle[T]) Get(ctx context.Context) T {
sh.once.Do(func() {
t, err := sh.fn(ctx)
if err != nil {
panic(err)
}
sf.Out = t
sh.out = t
})
return sf.Out
return sh.out
}

func Singleton[T any](fn InputLambda[T]) SingletonConstructor[T] {
return SingletonConstructor[T]{Fn: fn}
func Singleton[T any](fn func(context.Context) (T, error)) SingletonHandle[T] {
return SingletonHandle[T]{fn: fn, once: &sync.Once{}}
}
6 changes: 3 additions & 3 deletions go-runtime/ftl/singleton_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ftl

import (
"context"
"fmt"
"testing"

"github.com/alecthomas/assert/v2"
Expand All @@ -12,7 +13,7 @@ func TestSingletonBaseCase(t *testing.T) {

ctx := context.Background()
once := Singleton[string](func(ctx context.Context) (string, error) {
incrementer += 1
incrementer++
return "only once", nil
})

Expand All @@ -24,8 +25,7 @@ func TestSingletonBaseCase(t *testing.T) {
func TestSingletonPanic(t *testing.T) {
ctx := context.Background()
once := Singleton[string](func(ctx context.Context) (string, error) {
panic("test panic")
return "only once", nil
return "", fmt.Errorf("test error")
})
assert.Panics(t, func() {
once.Get(ctx)
Expand Down

0 comments on commit 19c943d

Please sign in to comment.