Restores ModuleConfig.WithName to support cloned Wasm (#282)
PR #281 allowed repetitive use of the same module config to avoid re-decoding the same wasm. However, it is possible that configuration is renamed in separate goroutines. This makes caching safer by restoring the `WithName` function deleted earlier. By using this, a configuration and its cache state are cloned, and doing that is thread safe. Signed-off-by: Adrian Cole <adrian@tetrate.io>
This commit is contained in:
10
wasm.go
10
wasm.go
@@ -78,6 +78,16 @@ func (m *ModuleConfig) Validate() (err error) {
|
||||
return err
|
||||
}
|
||||
|
||||
// WithName returns a new instance which overrides the Name, but keeps any internal cache made by Validate.
|
||||
func (m *ModuleConfig) WithName(moduleName string) *ModuleConfig {
|
||||
return &ModuleConfig{
|
||||
Name: moduleName,
|
||||
Source: m.Source,
|
||||
validatedSource: m.validatedSource,
|
||||
decodedModule: m.decodedModule,
|
||||
}
|
||||
}
|
||||
|
||||
// InstantiateModule instantiates the module namespace or errs if the configuration was invalid.
|
||||
//
|
||||
// Ex.
|
||||
|
||||
15
wasm_test.go
15
wasm_test.go
@@ -55,8 +55,12 @@ func TestDecodeModule(t *testing.T) {
|
||||
|
||||
again, _, err := decodeModule(config)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Same(t, m, again)
|
||||
|
||||
// Ensure config that only changes the name doesn't have to re-decode the source.
|
||||
cloned, _, err := decodeModule(config.WithName("wazero"))
|
||||
require.NoError(t, err)
|
||||
require.Same(t, m, cloned)
|
||||
})
|
||||
|
||||
t.Run("changing source invalidates decode cache", func(t *testing.T) {
|
||||
@@ -64,12 +68,19 @@ func TestDecodeModule(t *testing.T) {
|
||||
m, _, err := decodeModule(config)
|
||||
require.NoError(t, err)
|
||||
|
||||
clonedConfig := config.WithName("wazero")
|
||||
|
||||
// When the source is changed, the module needs to be decoded again
|
||||
config.Source = wasm
|
||||
again, _, err := decodeModule(config)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, m, again)
|
||||
require.NotSame(t, m, again)
|
||||
|
||||
// Any copies of the config shouldn't be invalidated
|
||||
cloned, _, err := decodeModule(clonedConfig)
|
||||
require.NoError(t, err)
|
||||
require.Same(t, m, cloned)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user