Skip to content

Commit

Permalink
refactor: change Singleton to Map (#1305)
Browse files Browse the repository at this point in the history
And change its purpose slightly such that it is used to map FTL resource
handles to another type.

Rationale: the main goal of introducing the Singleton type was to allow
custom transformation of FTL resources, and this more closely reflects
that goal. I didn't thin of doing it in this way until later.
  • Loading branch information
alecthomas authored Apr 18, 2024
1 parent b1a9aeb commit d8da724
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 60 deletions.
29 changes: 29 additions & 0 deletions go-runtime/ftl/map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package ftl

import (
"context"
"sync"
)

type MapHandle[T, U any] struct {
fn func(context.Context, T) (U, error)
getter Handle[T]
out U
once *sync.Once
}

func (sh *MapHandle[T, U]) Get(ctx context.Context) U {
sh.once.Do(func() {
t, err := sh.fn(ctx, sh.getter.Get(ctx))
if err != nil {
panic(err)
}
sh.out = t
})
return sh.out
}

// Map an FTL resource type to a new type.
func Map[T, U any](getter Handle[T], fn func(context.Context, T) (U, error)) MapHandle[T, U] {
return MapHandle[T, U]{fn: fn, getter: getter, once: &sync.Once{}}
}
39 changes: 39 additions & 0 deletions go-runtime/ftl/map_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package ftl

import (
"context"
"fmt"
"testing"

"github.com/alecthomas/assert/v2"
)

type intHandle int

func (s intHandle) Get(ctx context.Context) int { return int(s) }

func TestMapBaseCase(t *testing.T) {
incrementer := 0

h := intHandle(123)
ctx := context.Background()
once := Map(h, func(ctx context.Context, n int) (string, error) {
incrementer++
return fmt.Sprintf("handle: %d", n), nil
})

assert.Equal(t, once.Get(ctx), "handle: 123")
assert.Equal(t, once.Get(ctx), "handle: 123")
assert.Equal(t, incrementer, 1)
}

func TestMapPanic(t *testing.T) {
ctx := context.Background()
n := intHandle(1)
once := Map(n, func(ctx context.Context, n int) (string, error) {
return "", fmt.Errorf("test error %d", n)
})
assert.Panics(t, func() {
once.Get(ctx)
})
}
27 changes: 0 additions & 27 deletions go-runtime/ftl/singleton.go

This file was deleted.

33 changes: 0 additions & 33 deletions go-runtime/ftl/singleton_test.go

This file was deleted.

5 changes: 5 additions & 0 deletions go-runtime/ftl/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import (
schemapb "github.com/TBD54566975/ftl/backend/protos/xyz/block/ftl/v1/schema"
)

// Handle represents a resource that can be retrieved such as a database connection, secret, etc.
type Handle[T any] interface {
Get(ctx context.Context) T
}

// Unit is a type that has no value.
//
// It can be used as a parameter or return value to indicate that a function
Expand Down

0 comments on commit d8da724

Please sign in to comment.