deno icon indicating copy to clipboard operation
deno copied to clipboard

[wip] feat(serde_v8): Garbage collectable resources

Open littledivy opened this issue 2 years ago • 2 comments

serde_v8::Resource<T> is an "object wrap" around Rust allocated objects whose lifetime is managed by the V8 GC. Rust-side shared reference is managed with an Rc<T>.

Rust can reclaim ownership with Resource::into_inner. This prevents the finalizer to drops the held reference, transferring ownership back to Rust.

use serde_v8::Resource;
use deno_core::op;

pub struct ExtResource {
  msg: String,
}

#[op]
fn create_resource() -> Result<Resource<ExtResource>> {
  Ok(Resource::new(ExtResource { msg: String::from("Hi, I'm a Rust allocated value _owned_ by V8") }))
}

#[op]
fn print_resource_thing(resource: Resource<ExtResource>) -> Result<()> {
  let rc = resource.borrow();
  println!("{}", rc.msg);
  Ok(())
}

I've also updated the fetch() API to use this implementation.

TODO:

  • [x] Drop all leaked v8::Weaks when the isolate disposes without calling the finalizer. This causes a crash!
  • [x] https://github.com/denoland/rusty_v8/pull/895 (does most V8 <-> Rust Weak handles heavylifting stuff, thanks @andreubotella)

littledivy avatar Apr 08 '22 12:04 littledivy

I really want to have this feature for FFI callbacks. I'm thinking that perhaps the registered callbacks themselves can be GC'able resources, at which point parsing FFI arguments could be as simple as:

enum Arg {
  Value(serde_v8::Value),
  Buffer(ZeroCopyBuf),
  Callback(FfiCallbackResource),
}

Now that would be grand.

aapoalas avatar May 17 '22 16:05 aapoalas

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed in 7 days if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Jul 30 '22 15:07 stale[bot]

This pull request has been automatically marked as stale because it has not had recent activity. It will be closed in 7 days if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Sep 30 '22 17:09 stale[bot]