fix(web): do not merge theme values into the shared theme defaults

MergeKV handed the nested maps of its first input to mergo, which reused them in the result and wrote the later values into them. The theme endpoint passes the package-level theme defaults first, so every request wrote the base and branding theme into those defaults, and concurrent requests crashed the process with "concurrent map writes". MergeKV now merges deep copies of its inputs.
This commit is contained in:
Dominik Schmidt committed 2026-11-09 15:59:57 +01:00
1 parent 14b9622edd
commit 8d3869b87d
2 files changed
+69 -2

No files matched your search

+29 -2
View File
@@ -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 {
+40
View File
@@ -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{