Skip to content

Commit

Permalink
Restores ModuleConfig.WithName to support cloned Wasm (#282)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
codefromthecrypt authored Feb 23, 2022
1 parent fc26fdd commit 782dad3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
10 changes: 10 additions & 0 deletions wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 13 additions & 2 deletions wasm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,32 @@ 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) {
config := &ModuleConfig{Source: wat}
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)
})
}

Expand Down

0 comments on commit 782dad3

Please sign in to comment.