diff --git a/services/web/pkg/theme/kv.go b/services/web/pkg/theme/kv.go index 928c7edb7a..2b7c52a399 100644 --- a/services/web/pkg/theme/kv.go +++ b/services/web/pkg/theme/kv.go @@ -12,12 +12,14 @@ import ( // KV is a generic key-value map. type KV map[string]any -// MergeKV merges the given key-value maps. +// MergeKV merges the given key-value maps into a new map. The inputs are +// left untouched: mergo would otherwise reuse their nested maps in the result +// and write the later values into them. func MergeKV(values ...KV) (KV, error) { var kv KV for _, v := range values { - err := mergo.Merge(&kv, v, mergo.WithOverride) + err := mergo.Merge(&kv, deepCopy(v).(KV), mergo.WithOverride) if err != nil { return nil, err } @@ -26,6 +28,31 @@ func MergeKV(values ...KV) (KV, error) { return kv, nil } +func deepCopy(v any) any { + switch t := v.(type) { + case KV: + out := make(KV, len(t)) + for k, val := range t { + out[k] = deepCopy(val) + } + return out + case map[string]any: + out := make(map[string]any, len(t)) + for k, val := range t { + out[k] = deepCopy(val) + } + return out + case []any: + out := make([]any, len(t)) + for i, val := range t { + out[i] = deepCopy(val) + } + return out + default: + return v + } +} + // PatchKV injects the given values into to v. func PatchKV(v map[string]any, values KV) KV { if v == nil { diff --git a/services/web/pkg/theme/kv_test.go b/services/web/pkg/theme/kv_test.go index 855da86ec7..c15ebd5e4c 100644 --- a/services/web/pkg/theme/kv_test.go +++ b/services/web/pkg/theme/kv_test.go @@ -2,6 +2,7 @@ package theme_test import ( "encoding/json" + "sync" "testing" "github.com/spf13/afero" @@ -30,6 +31,45 @@ func TestMergeKV(t *testing.T) { }) } +func TestMergeKVLeavesNestedInputsUntouched(t *testing.T) { + defaults := theme.KV{ + "common": theme.KV{ + "name": "default", + }, + } + branding := theme.KV{ + "common": theme.KV{ + "name": "branded", + }, + } + + result, err := theme.MergeKV(defaults, branding) + assert.Nil(t, err) + assert.Equal(t, theme.KV{"common": theme.KV{"name": "branded"}}, result) + assert.Equal(t, theme.KV{"common": theme.KV{"name": "default"}}, defaults) +} + +func TestMergeKVConcurrently(t *testing.T) { + defaults := theme.KV{ + "common": theme.KV{ + "name": "default", + }, + } + + var wg sync.WaitGroup + for i := range 16 { + wg.Go(func() { + for range 100 { + _, err := theme.MergeKV(defaults, theme.KV{"common": theme.KV{"name": i}}) + assert.Nil(t, err) + } + }) + } + wg.Wait() + + assert.Equal(t, theme.KV{"common": theme.KV{"name": "default"}}, defaults) +} + func TestPatchKV(t *testing.T) { in := theme.KV{ "a": map[string]any{