Skip to content
15 changes: 15 additions & 0 deletions src/rust/jsg-macros/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ produces a property whose value is `null`. An absent input property becomes `Non
or `Undefined`, respectively. If all public fields are optional, a `null` or
`undefined` input is accepted as an empty dictionary.

A field that holds a JavaScript value, as a C++ `jsg::JsRef<jsg::JsValue>` field does, is a
`jsg::v8::TracedGlobal<M>`. It converts as a `Local<'s, M>` does: `TracedGlobal<Value>` takes any
value, an absent property included, and `TracedGlobal<Object>` only an object. The struct then
holds GC references, and a resource that keeps it traces the value. Once GC has visited it there,
the handle is weak and relies on that trace, so a resource that sets or takes the struct after
construction keeps it in a `jsg::Cell` or `jsg::RefCell`, which make the handle strong again
before the struct can leave; a `std::cell::Cell` or `RefCell` of it doesn't compile. See "Cells"
in `src/rust/jsg/README.md`.

`ts_root` marks a TypeScript generation root; it can be combined with `name`.
RTTI describes the public fields using their types' `TypeInfo` implementations.

Expand All @@ -43,6 +52,12 @@ pub struct CaaRecord {
pub value: String,
}

#[jsg_struct]
pub struct ProduceResult {
pub value: jsg::v8::TracedGlobal<jsg::v8::Value>,
pub expiration: Option<f64>,
}

#[jsg_struct(name = "CustomName")]
pub struct MyRecord {
pub value: String,
Expand Down
5 changes: 4 additions & 1 deletion src/rust/jsg-macros/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ use utils::this_param;
/// impl, and a field whose conversion fails fails the struct's conversion with that error.
/// The generated `Traced` impl visits every field, so a field can be a `jsg::Rc<R>`.
/// Optional fields use `Option<T>` or `jsg::NullOrUndefined<T>`; prefer the latter to
/// `Option<jsg::Nullable<T>>` to distinguish `null` from `undefined`.
/// `Option<jsg::Nullable<T>>` to distinguish `null` from `undefined`. A field that holds a
/// JavaScript value, as a C++ `jsg::JsRef<T>` field does, is a `jsg::v8::TracedGlobal<M>`;
/// a resource that moves such a struct out of a field keeps it in a `jsg::Cell` or
/// `jsg::RefCell`, which make the handle strong before it leaves.
/// Use `#[jsg_struct(name = "MyName")]` to override `Type::class_name()`
/// metadata and the TypeScript declaration name; it does not define a JS class.
#[proc_macro_attribute]
Expand Down
98 changes: 98 additions & 0 deletions src/rust/jsg-test/tests/jsg_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use jsg::Error;
use jsg::ExceptionType;
use jsg::FromJS;
use jsg::ToJS;
use jsg::v8;
use jsg_macros::jsg_struct;
Expand Down Expand Up @@ -81,6 +82,13 @@ struct FailingNullishFieldStruct {
pub bad: jsg::NullOrUndefined<Unconvertible>,
}

/// A struct with fields that hold JavaScript values, as C++ `jsg::JsRef<T>` fields do.
#[jsg_struct]
struct JsValueStruct {
pub value: v8::TracedGlobal<v8::Value>,
pub object: Option<v8::TracedGlobal<v8::Object>>,
}

#[test]
fn objects_can_be_wrapped_and_unwrapped() {
let harness = crate::Harness::new();
Expand Down Expand Up @@ -431,6 +439,96 @@ fn nullish_struct_fields_use_consuming_fallible_conversion() {
}
}

/// A `TracedGlobal` field holds the value itself, which converts back to JavaScript unchanged,
/// with and without `fast_jsg_struct`.
#[test]
fn struct_js_value_fields_keep_identity() {
for fast in [false, true] {
let harness = crate::Harness::with_flags(|mut flags| flags.set_fast_jsg_struct(fast));
harness.run_in_context(|lock, ctx| {
let result = convert::<JsValueStruct>(
lock,
ctx,
"globalThis.v = { a: 1 }; ({ value: v, object: v })",
)?;
assert!(result.object.is_some());
let back = result.to_js(lock)?;
ctx.set_global(lock, "back", back);
assert!(
ctx.eval::<bool>(lock, "back.value === v && back.object === v")
.unwrap()
);
Ok(())
});
}
}

/// Like C++ JSG's `jsg::JsRef<jsg::JsValue>`, a `TracedGlobal<Value>` field takes any value, an
/// absent property as `undefined`; an optional field is absent then.
#[test]
fn struct_js_value_field_takes_any_value() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
let result = convert::<JsValueStruct>(lock, ctx, "({})")?;
assert!(result.value.as_local(lock).is_undefined());
assert!(result.object.is_none());

let result = convert::<JsValueStruct>(lock, ctx, "({ value: 42 })")?;
let value = result.value.as_local(lock);
assert_eq!(u32::from_js(lock, value)?, 42);

let Err(err) = convert::<JsValueStruct>(lock, ctx, "null") else {
panic!("null has no value");
};
assert_eq!(err.name, ExceptionType::TypeError);
assert_eq!(
err.message,
"Cannot initialize JsValueStruct with required members from an undefined or null value."
);
Ok(())
});
}

/// A `TracedGlobal<Object>` field takes only an object, as a `Local<Object>` does.
#[test]
fn struct_js_object_field_rejects_other_values() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
let Err(err) = convert::<JsValueStruct>(lock, ctx, "({ value: 1, object: 2 })") else {
panic!("2 is not an object");
};
assert_eq!(err.name, ExceptionType::TypeError);
assert_eq!(err.message, "Expected Object but got number");
Ok(())
});
}

/// A struct with `TracedGlobal` fields outlives the scope it was converted in, and keeps its
/// values through a GC: outside a resource, nothing has made its handles weak.
#[test]
fn struct_js_value_field_outlives_its_scope() {
let harness = crate::Harness::new();
let kept = std::cell::RefCell::new(None);
harness.run_in_context(|lock, ctx| {
*kept.borrow_mut() = Some(convert::<JsValueStruct>(
lock,
ctx,
"({ value: { a: 1 }, object: { b: 2 } })",
)?);
Ok(())
});
harness.run_in_context(|lock, ctx| {
Comment thread
bartlomieju marked this conversation as resolved.
Resolved
crate::Harness::request_gc(lock);
let back = kept.borrow_mut().take().unwrap().to_js(lock)?;
ctx.set_global(lock, "back", back);
assert!(
ctx.eval::<bool>(lock, "back.value.a === 1 && back.object.b === 2")
.unwrap()
);
Ok(())
});
}

/// A `Vec<u8>` field converts to an `Array` of numbers, like any other `Vec`, with and without
/// `fast_jsg_struct`.
#[test]
Expand Down
86 changes: 86 additions & 0 deletions src/rust/jsg-test/tests/traceable_gc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use std::sync::atomic::Ordering;

use jsg::ToJS;
use jsg::Traced;
use jsg_macros::jsg_method;
use jsg_macros::jsg_resource;
use jsg_macros::jsg_struct;

Expand Down Expand Up @@ -263,3 +264,88 @@ fn cycle_through_struct_field_is_collected() {
Ok(())
});
}

static HOLDER_DROPS: AtomicUsize = AtomicUsize::new(0);

/// A struct whose field holds a JavaScript value, as a C++ `jsg::JsRef<T>` field does.
#[jsg_struct]
struct ValueLink {
pub value: jsg::v8::TracedGlobal<jsg::v8::Value>,
}

#[jsg_resource]
struct Holder {
pub link: jsg::RefCell<Option<ValueLink>>,
}

impl Drop for Holder {
fn drop(&mut self) {
HOLDER_DROPS.fetch_add(1, Ordering::SeqCst);
}
}

#[jsg_resource]
impl Holder {
#[jsg_method]
fn set_link<'s>(&self, lock: &mut jsg::Lock<'s>, value: jsg::v8::Local<'s, jsg::v8::Value>) {
*self.link.borrow_mut(lock) = Some(ValueLink {
value: value.to_traced_global(lock),
});
}
}

/// A struct with a `TracedGlobal` field holds GC references, and a cycle through it is
/// collected: `Holder` keeps a `ValueLink` whose value is the `Holder`'s own wrapper.
#[test]
fn cycle_through_struct_js_value_field_is_collected() {
assert!(ValueLink::holds_gc_references());
HOLDER_DROPS.store(0, Ordering::SeqCst);

let harness = crate::Harness::new();
harness.run_in_context(|lock, _ctx| {
let holder = jsg::Rc::new(Holder {
link: jsg::RefCell::new(None),
});
let wrapper = holder.clone().to_js(lock)?;
*holder.link.borrow_mut(lock) = Some(ValueLink {
value: wrapper.to_traced_global(lock),
});
std::mem::drop(holder);
assert_eq!(HOLDER_DROPS.load(Ordering::SeqCst), 0);
Ok(())
});

harness.run_in_context(|lock, _ctx| {
crate::Harness::request_gc(lock);
assert_eq!(HOLDER_DROPS.load(Ordering::SeqCst), 1);
Ok(())
});
}

/// A struct taken out of a resource after a GC visit made its `TracedGlobal` weak is strong
/// again, so a GC leaves its value alone while nothing traces it: `jsg::RefCell::borrow_mut`
/// detaches the struct before it can leave the cell.
#[test]
fn struct_js_value_field_taken_from_a_resource_keeps_its_value() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
let holder = jsg::Rc::new(Holder {
link: jsg::RefCell::new(None),
});
let wrapper = holder.clone().to_js(lock)?;
ctx.set_global(lock, "holder", wrapper);
// Only the `Holder` keeps the value alive; the script ends in `undefined` so that no
// `Local` of it outlives the script.
ctx.eval_raw(lock, "holder.setLink({ kept: 1 }); undefined")
.expect("should evaluate");
// The holder's wrapper is reachable, so the visit puts the value's handle in traced mode.
crate::Harness::request_gc(lock);

let link = holder.link.borrow_mut(lock).take().expect("set above");
crate::Harness::request_gc(lock);
let back = link.to_js(lock)?;
ctx.set_global(lock, "back", back);
assert!(ctx.eval::<bool>(lock, "back.value.kept === 1").unwrap());
Ok(())
});
}
13 changes: 13 additions & 0 deletions src/rust/jsg/rtti-test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -402,3 +402,16 @@ fn bridge_contexts_take_canonical_flags() {
]
);
}

#[test]
fn handles_are_described_as_their_values() {
let mut cx = Context::default();
assert!(matches!(
v8::TracedGlobal::<v8::Object>::describe(&mut cx),
Type::Object
));
assert!(matches!(
v8::TracedGlobal::<v8::Value>::describe(&mut cx),
Type::Unknown
));
}
7 changes: 7 additions & 0 deletions src/rust/jsg/rtti.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,13 @@ impl<T: TypeInfo> TypeInfo for v8::Global<T> {
}
}

// As C++ describes a `jsg::JsRef<T>` field: as its value.
impl<T: TypeInfo> TypeInfo for v8::TracedGlobal<T> {
fn describe(cx: &mut Context) -> Type {
T::describe(cx)
}
}

#[cfg(test)]
#[path = "rtti-test.rs"]
mod tests;
58 changes: 58 additions & 0 deletions src/rust/jsg/wrappable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
//! | `Vec<T>` | `Array<T>` |
//! | `&[T]` | `Array<T>` (parameter only) |
//! | `Dict<V>` | `Record<string, V>`: an object other than an array |
//! | `v8::Local<'s, M>` | the value itself, of `M`'s type |
//! | `v8::TracedGlobal<M>` | as `v8::Local<'s, M>`, held past the scope (C++ JSG's `jsg::JsRef<T>`) |
//!
//! [`Option`], [`NullOrUndefined`], and [`Lenient`] method arguments may be omitted.
//! [`Nullable`] arguments remain required even though explicitly passing `undefined` converts to `Null`.
Expand Down Expand Up @@ -1778,6 +1780,62 @@ impl_handle_from_js! {
TypedArray: UnionMember::Fallible;
}

// =============================================================================
// Persistent handles
// =============================================================================

// A `TracedGlobal<M>` is C++ JSG's `jsg::JsRef<T>` / `jsg::V8Ref<T>`: it converts as a
// `Local<'s, M>` does, and outlives the scope, so it can be a field of a `#[jsg_struct]` that
// a resource keeps or a typed promise carries.

impl<M: Type> Type for v8::TracedGlobal<M> {
const UNION_TYPES: UnionTypes = M::UNION_TYPES;
const UNION_NAMES: &'static [&'static str] = M::UNION_NAMES;

fn class_name() -> &'static str {
M::class_name()
}

fn is_exact(value: v8::Local<'_, v8::Value>) -> bool {
M::is_exact(value)
}
}

impl<'s, M> ToJS<'s> for v8::TracedGlobal<M>
where
v8::Local<'s, M>: Into<v8::Local<'s, v8::Value>>,
{
fn to_js(self, lock: &mut Lock<'s>) -> Result<v8::Local<'s, v8::Value>, Error> {
Ok(self.as_local(lock).into())
}
}

impl<'s, M> FromJS<'s> for v8::TracedGlobal<M>
where
v8::Local<'s, M>: FromJS<'s, ResultType = v8::Local<'s, M>>,
{
type ResultType = Self;

const UNION_MEMBER: UnionMember = <v8::Local<'s, M> as FromJS<'s>>::UNION_MEMBER;

fn type_name() -> String {
<v8::Local<'s, M> as FromJS<'s>>::type_name()
}

fn from_js(lock: &mut Lock<'s>, value: v8::Local<'s, v8::Value>) -> Result<Self, Error> {
let local = <v8::Local<'s, M> as FromJS<'s>>::from_js(lock, value)?;
Ok(Self::new(lock, local))
}

fn try_from_js(
lock: &mut Lock<'s>,
value: v8::Local<'s, v8::Value>,
) -> Result<Option<Self>, Error> {
Ok(<v8::Local<'s, M> as FromJS<'s>>::try_from_js(lock, value)?
.map(|local| Self::new(lock, local)))
}
}

#[cfg(test)]
#[path = "wrappable-test.rs"]
mod tests;
Loading