From acdb53a32568932faebf8e61822867dbb3dac1d6 Mon Sep 17 00:00:00 2001 From: Matt Toohey Date: Wed, 8 May 2024 12:14:35 +1000 Subject: [PATCH] fix: remove once in ftl.Map to allow changing underlying values (#1435) fixes https://github.com/TBD54566975/ftl/issues/1390 `ftl.Map` was just using `once` as an optimisation. But this unit test case was not being handled properly: ``` ctx := ftltest.Context( ftltest.WithConfig(example, "hello"), ) //Call a verb that uses ftl.Map with example config resp, err := Verb(ctx, req) ctx = ftltest.Context( ftltest.WithConfig(example, "world"), ) //When this execution of the verb is done, it should execute again because the underlying value is different (hello -> world) resp, err = Verb(ctx, req) ``` To solve this, now the mapping func is called each time. For use cases where modules want to map a `*sql.DB` to a `DAL`, it will create a new DAL instance each time --- go-runtime/ftl/map.go | 20 +++++++------------- go-runtime/ftl/map_test.go | 15 --------------- 2 files changed, 7 insertions(+), 28 deletions(-) diff --git a/go-runtime/ftl/map.go b/go-runtime/ftl/map.go index 230c6b7ca2..18baf19ba3 100644 --- a/go-runtime/ftl/map.go +++ b/go-runtime/ftl/map.go @@ -2,28 +2,22 @@ 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 +func (mh *MapHandle[T, U]) Get(ctx context.Context) U { + t, err := mh.fn(ctx, mh.getter.Get(ctx)) + if err != nil { + panic(err) + } + return t } // 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{}} + return MapHandle[T, U]{fn: fn, getter: getter} } diff --git a/go-runtime/ftl/map_test.go b/go-runtime/ftl/map_test.go index 866ad06b79..436a661ec8 100644 --- a/go-runtime/ftl/map_test.go +++ b/go-runtime/ftl/map_test.go @@ -12,21 +12,6 @@ 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)