-
Notifications
You must be signed in to change notification settings - Fork 646
Add proper V8 sys module versioning #3527
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
09735ba
Add proper syscall versioning
coolreader18 827afd9
Apply suggestions from code review
coolreader18 d311665
Address comments
coolreader18 9d71548
Error if no describe_module
coolreader18 aca5d8e
[noa/v8-sys-versioning]: Merge remote-tracking branch 'origin/master'…
bfops File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| use std::cell::OnceCell; | ||
| use std::rc::Rc; | ||
|
|
||
| use enum_map::EnumMap; | ||
| use v8::{Context, Function, Local, Object, PinScope}; | ||
|
|
||
| use super::AbiVersion; | ||
| use crate::host::v8::de::property; | ||
| use crate::host::v8::error::ExcResult; | ||
| use crate::host::v8::error::Throwable; | ||
| use crate::host::v8::error::TypeError; | ||
| use crate::host::v8::from_value::cast; | ||
| use crate::host::v8::string::StringConst; | ||
|
|
||
| /// Returns the hook function `name` on `hooks_obj`. | ||
| pub(super) fn get_hook_function<'scope>( | ||
| scope: &mut PinScope<'scope, '_>, | ||
| hooks_obj: Local<'_, Object>, | ||
| name: &'static StringConst, | ||
| ) -> ExcResult<Local<'scope, Function>> { | ||
| let key = name.string(scope); | ||
| let object = property(scope, hooks_obj, key)?; | ||
| cast!(scope, object, Function, "module function hook `{}`", name.as_str()).map_err(|e| e.throw(scope)) | ||
| } | ||
|
|
||
| /// Registers all the module function `hooks` | ||
| /// and sets the given `AbiVersion` to `abi`. | ||
| pub(super) fn set_hook_slots( | ||
coolreader18 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| scope: &mut PinScope<'_, '_>, | ||
| abi: AbiVersion, | ||
| hooks: &[(ModuleHookKey, Local<'_, Function>)], | ||
| ) -> ExcResult<()> { | ||
| // Make sure to call `set_slot` first, as it creates the annex | ||
| // and `set_embedder_data` is currently buggy. | ||
| let ctx = scope.get_current_context(); | ||
| let hooks_info = HooksInfo::get_or_create(&ctx, abi) | ||
| .map_err(|_| TypeError("cannot call `register_hooks` from different versions").throw(scope))?; | ||
| for &(hook, func) in hooks { | ||
| hooks_info | ||
| .register(hook) | ||
| .map_err(|_| TypeError("cannot call `register_hooks` multiple times").throw(scope))?; | ||
| ctx.set_embedder_data(hook.to_slot_index(), func.into()); | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| #[derive(enum_map::Enum, Copy, Clone)] | ||
| pub(in super::super) enum ModuleHookKey { | ||
| DescribeModule, | ||
| CallReducer, | ||
| } | ||
|
|
||
| impl ModuleHookKey { | ||
| /// Returns the index for the slot that holds the module function hook. | ||
| /// The index is passed to `v8::Context::{get,set}_embedder_data`. | ||
| fn to_slot_index(self) -> i32 { | ||
| match self { | ||
| // high numbers to avoid overlapping with rusty_v8 - can be | ||
| // reverted to just 0, 1... once denoland/rusty_v8#1868 merges | ||
| ModuleHookKey::DescribeModule => 20, | ||
| ModuleHookKey::CallReducer => 21, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Holds the `AbiVersion` used by the module | ||
| /// and the module hooks registered by the module | ||
| /// for that version. | ||
| struct HooksInfo { | ||
| abi: AbiVersion, | ||
| registered: EnumMap<ModuleHookKey, OnceCell<()>>, | ||
| } | ||
|
|
||
| impl HooksInfo { | ||
| /// Returns, and possibly creates, the [`HooksInfo`] stored in `ctx`. | ||
| /// | ||
| /// Returns an error if `abi` doesn't match the abi version in the | ||
| /// already existing `HooksInfo`. | ||
| fn get_or_create(ctx: &Context, abi: AbiVersion) -> Result<Rc<Self>, ()> { | ||
| match ctx.get_slot::<Self>() { | ||
| Some(this) if this.abi == abi => Ok(this), | ||
| Some(_) => Err(()), | ||
| None => { | ||
| let this = Rc::new(Self { | ||
| abi, | ||
| registered: EnumMap::default(), | ||
| }); | ||
| ctx.set_slot(this.clone()); | ||
| Ok(this) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Mark down the given `hook` as registered, returning an error if it already was. | ||
| fn register(&self, hook: ModuleHookKey) -> Result<(), ()> { | ||
| self.registered[hook].set(()) | ||
| } | ||
|
|
||
| /// Returns the `AbiVersion` for the given `hook`, if any. | ||
| fn get(&self, hook: ModuleHookKey) -> Option<AbiVersion> { | ||
| self.registered[hook].get().map(|_| self.abi) | ||
| } | ||
| } | ||
|
|
||
| #[derive(Copy, Clone)] | ||
| /// The actual callable module hook function and its abi version. | ||
| pub(in super::super) struct HookFunction<'scope>(pub AbiVersion, pub Local<'scope, Function>); | ||
|
|
||
| /// Returns the hook function previously registered in [`register_hooks`]. | ||
| pub(in super::super) fn get_hook<'scope>( | ||
| scope: &mut PinScope<'scope, '_>, | ||
| hook: ModuleHookKey, | ||
| ) -> Option<HookFunction<'scope>> { | ||
| let ctx = scope.get_current_context(); | ||
| let hooks = ctx.get_slot::<HooksInfo>()?; | ||
|
|
||
| let abi_version = hooks.get(hook)?; | ||
|
|
||
| let hooks = ctx | ||
| .get_embedder_data(scope, hook.to_slot_index()) | ||
| .expect("if `AbiVersion` is set the hook must be set"); | ||
| Some(HookFunction(abi_version, hooks.cast())) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| use spacetimedb_lib::{RawModuleDef, VersionTuple}; | ||
| use v8::{callback_scope, Context, FixedArray, Local, Module, PinScope}; | ||
|
|
||
| use crate::host::v8::de::scratch_buf; | ||
| use crate::host::v8::error::{ErrorOrException, ExcResult, ExceptionThrown, Throwable, TypeError}; | ||
| use crate::host::wasm_common::abi::parse_abi_version; | ||
| use crate::host::wasm_common::module_host_actor::{ReducerOp, ReducerResult}; | ||
|
|
||
| mod hooks; | ||
| mod v1; | ||
|
|
||
| pub(super) use self::hooks::{get_hook, HookFunction, ModuleHookKey}; | ||
|
|
||
| /// The return type of a module -> host syscall. | ||
| pub(super) type FnRet<'scope> = ExcResult<Local<'scope, v8::Value>>; | ||
|
|
||
| /// The version of the ABI that is exposed to V8. | ||
| #[derive(Copy, Clone, PartialEq, Eq)] | ||
| pub enum AbiVersion { | ||
| V1, | ||
| } | ||
|
|
||
| /// A dependency resolver for the user's module | ||
| /// that will resolve `spacetimedb_sys` to a module that exposes the ABI. | ||
| pub(super) fn resolve_sys_module<'scope>( | ||
| context: Local<'scope, Context>, | ||
| spec: Local<'scope, v8::String>, | ||
| _attrs: Local<'scope, FixedArray>, | ||
| _referrer: Local<'scope, Module>, | ||
| ) -> Option<Local<'scope, Module>> { | ||
| callback_scope!(unsafe scope, context); | ||
| resolve_sys_module_inner(scope, spec).ok() | ||
| } | ||
|
|
||
| fn resolve_sys_module_inner<'scope>( | ||
| scope: &mut PinScope<'scope, '_>, | ||
| spec: Local<'scope, v8::String>, | ||
| ) -> ExcResult<Local<'scope, Module>> { | ||
| let scratch = &mut scratch_buf::<32>(); | ||
| let spec = spec.to_rust_cow_lossy(scope, scratch); | ||
|
|
||
| let generic_error = || TypeError(format!("Could not find module {spec:?}")); | ||
|
|
||
| let (module, ver) = spec | ||
| .strip_prefix("spacetime:") | ||
| .and_then(|spec| spec.split_once('@')) | ||
| .ok_or_else(|| generic_error().throw(scope))?; | ||
|
|
||
| let VersionTuple { major, minor } = parse_abi_version(ver) | ||
| .ok_or_else(|| TypeError(format!("Invalid version in module spec {spec:?}")).throw(scope))?; | ||
|
|
||
| match module { | ||
| "sys" => match (major, minor) { | ||
| (1, 0) => Ok(v1::sys_v1_0(scope)), | ||
| _ => Err(TypeError(format!( | ||
| "Could not import {spec:?}, likely because this module was built for a newer version of SpacetimeDB.\n\ | ||
| It requires sys module v{major}.{minor}, but that version is not supported by the database." | ||
| )) | ||
| .throw(scope)), | ||
| }, | ||
| _ => Err(generic_error().throw(scope)), | ||
| } | ||
| } | ||
|
|
||
| /// Calls the registered `__call_reducer__` function hook. | ||
| /// | ||
| /// This handles any (future) ABI version differences. | ||
| pub(super) fn call_call_reducer( | ||
coolreader18 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| scope: &mut PinScope<'_, '_>, | ||
| fun: HookFunction<'_>, | ||
| op: ReducerOp<'_>, | ||
| ) -> ExcResult<ReducerResult> { | ||
| let HookFunction(ver, fun) = fun; | ||
| match ver { | ||
| AbiVersion::V1 => v1::call_call_reducer(scope, fun, op), | ||
| } | ||
| } | ||
|
|
||
| /// Calls the registered `__describe_module__` function hook. | ||
coolreader18 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| /// | ||
| /// This handles any (future) ABI version differences. | ||
| pub(super) fn call_describe_module<'scope>( | ||
| scope: &mut PinScope<'scope, '_>, | ||
| fun: HookFunction<'_>, | ||
| ) -> Result<RawModuleDef, ErrorOrException<ExceptionThrown>> { | ||
| let HookFunction(ver, fun) = fun; | ||
| match ver { | ||
| AbiVersion::V1 => v1::call_describe_module(scope, fun), | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.