wazero icon indicating copy to clipboard operation
wazero copied to clipboard

Implement a shared stated on api.Module

Open jerbob92 opened this issue 2 years ago • 1 comments

Is your feature request related to a problem? Please describe. When implementing Embind C++ Exceptions support in Wazero I have the need to have a shared state (the cxaState var) that I can access from host functions. Currently this is a global var but that won't work for multiple instances of modules. I tried various way to share this state through the context, but it is not possible to do so from the host functions itself, since the context is only passed down, not up. The only viable way is to add something to the context at the highest level (when instantiating the module or calling a function on it) that adds a pointer to the state so that the host functions can access the shared state.

Describe the solution you'd like My suggestion would be to create a shared state on the module instance (api.Module), like context.Context that I can reach from host functions. Perhaps we can call Store or State?

I could then implement something like:

func getExceptionsState(mod api.Module) *exceptionsState {
	if !mod.Store().Has(exceptionsStateKey{}) {
		newState := &exceptionsState{}
		mod.Store().Set(exceptionsStateKey{}, newState)
		return newState
	}
	
	return mod.Store().Get(exceptionsStateKey{}).(*exceptionsStateKey)
}

That would get the state or create one when it doesn't exist yet.

When the module closes we can just drop the state and that should be it memory-wise.

I would be fine by just making this internal for now, but I think there is also a use-case for other people that are writing host functions to have a place to store state for that module instance.

Describe alternatives you've considered

  • Adding state to the context outside Wazero, while possible it would be very annoying to users because they have to do extra setup to make internals work.
  • Adding a global map where the key is the pointer to the api.Module and the value the state, would work but there won't really be a way to clean them up I guess

Additional context Slack disucssions: https://gophers.slack.com/archives/C04CG4A2NKX/p1692262036922369 https://gophers.slack.com/archives/C04CG4A2NKX/p1692523505662049

jerbob92 avatar Aug 23 '23 10:08 jerbob92

can i join you

Ashrafmohdiit avatar Sep 17 '23 09:09 Ashrafmohdiit