Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/rust/jsg-cpp/jsg-cpp.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@

#include <kj/memory.h>

#include <type_traits>

namespace workerd::rust::jsg_cpp {

using Isolate = v8::Isolate;
Expand Down Expand Up @@ -189,6 +191,16 @@ MaybeLocal cppRefWrap(Isolate* isolate, const CppRef& ref) {
return ::workerd::rust::jsg::maybe_local_to_ffi(result);
}

// The base of RustRef<Tag>: forwards `Tag::JsgRttiDelegate` when the tag declares one, and is
// empty otherwise.
template <typename Tag, typename = void>
struct RustRefRtti {};

template <typename Tag>
struct RustRefRtti<Tag, std::void_t<typename Tag::JsgRttiDelegate>> {
using JsgRttiDelegate = Tag::JsgRttiDelegate;
};

// A reference from C++ to a Rust JSG resource, typed by `Tag`. `Tag` is a C++ struct that
// stands for the Rust resource type:
//
Expand All @@ -197,14 +209,17 @@ MaybeLocal cppRefWrap(Isolate* isolate, const CppRef& ref) {
// static constexpr const char* NAME = "MyResource";
// // An `extern "Rust"` function returning `jsg::resource::ffi_is::<MyResource>()`.
// static kj::Maybe<bool> isInstance(v8::Isolate* isolate, Local value);
// // Optional: describes `RustRef<MyResourceTag>` to RTTI, and so to TypeScript
// // generation, as an existing C++ API type.
// using JsgRttiDelegate = jsg::Ref<SomeApiType>;
// };
//
// It holds the resource's JavaScript wrapper, which owns the resource, so it keeps both alive,
// preserves the wrapper's identity, and is traced like any `jsg::V8Ref`: a cycle through it, for
// example back from the Rust resource through a `jsg_cpp::Ref`, is collected. C++ calls the
// resource's methods through `extern "Rust"` functions given `toFfi()`.
template <typename Tag>
class RustRef {
class RustRef: public RustRefRtti<Tag> {
public:
// `value` if it is the wrapper of a `Tag` resource, kj::none for any other value. Throws
// JsExceptionThrown if the check left an exception pending.
Expand Down
1 change: 1 addition & 0 deletions src/rust/jsg-test/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ mod resource_template;
mod resource_this;
mod rest_arguments;
mod serialization;
mod set_prototype;
mod signature_callback;
mod startup_snapshot;
mod string;
Expand Down
23 changes: 23 additions & 0 deletions src/rust/jsg-test/tests/resource_template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,29 @@ fn eval_string(harness: &Harness, code: &str) -> String {
out
}

#[test]
fn resource_prototype_can_link_to_a_parent_in_the_current_realm() {
Harness::new().run_in_context(|lock, ctx| {
let constructor = jsg::resource::function_template_of::<Sample>(lock)?;
let prototype = jsg::v8::Local::<jsg::v8::Object>::try_from(
jsg::v8::Local::<jsg::v8::Object>::from(constructor).get(lock, "prototype")?,
)
.unwrap();
let parent = lock.new_object();
prototype.set_prototype(lock, Some(parent))?;
ctx.set_global(lock, "Sample", constructor);
ctx.set_global(lock, "ParentProto", parent);
assert!(
ctx.eval::<bool>(
lock,
"ParentProto.isPrototypeOf(new Sample('x')) && new Sample('x') instanceof Sample"
)
.unwrap()
);
Ok(())
});
}

#[test]
fn to_string_tag_follows_set_to_string_tag() {
let code = "Object.prototype.toString.call(new Sample('x'))";
Expand Down
84 changes: 84 additions & 0 deletions src/rust/jsg-test/tests/set_prototype.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

//! `Local<Object>::set_prototype`, the counterpart of `v8::Object::SetPrototype`.

use jsg::ExceptionType;
use jsg::v8;

fn eval_object<'s>(
lock: &mut jsg::Lock<'s>,
ctx: &crate::EvalContext,
code: &str,
) -> v8::Local<'s, v8::Object> {
v8::Local::<v8::Object>::try_from(ctx.eval_raw(lock, code).unwrap()).unwrap()
}

#[test]
fn set_prototype_changes_the_prototype() {
crate::Harness::new().run_in_context(|lock, ctx| {
let object = lock.new_object();
let parent = lock.new_object();
object.set_prototype(lock, Some(parent))?;
ctx.set_global(lock, "object", object);
ctx.set_global(lock, "parent", parent);
assert!(
ctx.eval::<bool>(lock, "Object.getPrototypeOf(object) === parent")
.unwrap()
);

object.set_prototype(lock, None)?;
assert!(
ctx.eval::<bool>(lock, "Object.getPrototypeOf(object) === null")
.unwrap()
);
Ok(())
});
}

// V8 reports each refusal as `Nothing` without an exception; it must reach Rust as a
// `TypeError`, not as an error that claims an exception is pending.
fn assert_refused(result: jsg::Result<()>) {
let err = result.unwrap_err();
assert!(!err.is_pending(), "pending: {err}");
assert_eq!(err.name, ExceptionType::TypeError);
}

#[test]
fn set_prototype_refuses_a_cycle() {
crate::Harness::new().run_in_context(|lock, ctx| {
let a = lock.new_object();
let b = lock.new_object();
a.set_prototype(lock, Some(b))?;
assert_refused(b.set_prototype(lock, Some(a)));
// Nothing was left pending, so JavaScript still runs.
assert!(ctx.eval::<bool>(lock, "true").unwrap());
Ok(())
});
}

#[test]
fn set_prototype_refuses_a_non_extensible_object() {
crate::Harness::new().run_in_context(|lock, ctx| {
let object = eval_object(lock, ctx, "Object.preventExtensions({})");
let parent = lock.new_object();
assert_refused(object.set_prototype(lock, Some(parent)));
Ok(())
});
}

#[test]
fn set_prototype_refuses_when_a_proxy_trap_throws() {
crate::Harness::new().run_in_context(|lock, ctx| {
let proxy = eval_object(
lock,
ctx,
"new Proxy({}, { setPrototypeOf() { throw new Error('trap'); } })",
);
let parent = lock.new_object();
assert_refused(proxy.set_prototype(lock, Some(parent)));
assert!(ctx.eval::<bool>(lock, "true").unwrap());
Ok(())
});
}
13 changes: 13 additions & 0 deletions src/rust/jsg/ffi.c++
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,19 @@ bool local_object_set_property_by_global_name(
.IsJust();
}

kj::Maybe<bool> local_object_set_prototype(Isolate* isolate, const Local& object, Local prototype) {
if (exceptionPending(isolate)) return kj::none;
if (local_as_ref_from_ffi<v8::Object>(object)
->SetPrototype(isolate->GetCurrentContext(), local_from_ffi<v8::Value>(kj::mv(prototype)))
.IsJust()) {
return true;
}
// V8 reports a refused change as Nothing without an exception, and swallows a Proxy trap's
// exception, so Nothing with no exception pending means the object refused the change.
if (exceptionPending(isolate)) return kj::none;
return false;
}

bool local_object_has_property(Isolate* isolate, const Local& object, ::rust::Str key, bool& has) {
if (exceptionPending(isolate)) return false;
auto v8_obj = local_as_ref_from_ffi<v8::Object>(object);
Expand Down
4 changes: 4 additions & 0 deletions src/rust/jsg/ffi.h
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,10 @@ bool local_object_set_property(Isolate* isolate, Local& object, ::rust::Str key,
// The same for a key held in a `v8::Global<v8::Name>`, such as a cached struct field name.
bool local_object_set_property_by_global_name(
Isolate* isolate, const Local& object, const Global& name, Local value);
// `Object::SetPrototype`: true if the prototype changed, false if the object refused the change
// (a cycle, a non-extensible object, or a Proxy whose trap refused or threw), or none if an
// exception or a termination is pending. `prototype` is an object or null.
kj::Maybe<bool> local_object_set_prototype(Isolate* isolate, const Local& object, Local prototype);
// Stores in `has` whether `key` is in the object, and returns true, or returns false if a Proxy
// trap threw, leaving the exception pending.
bool local_object_has_property(Isolate* isolate, const Local& object, ::rust::Str key, bool& has);
Expand Down
37 changes: 37 additions & 0 deletions src/rust/jsg/v8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,11 @@ pub mod ffi {
object: &Local,
names: &mut Vec<Local>,
) -> bool;
pub unsafe fn local_object_set_prototype(
isolate: *mut Isolate,
object: &Local,
prototype: Local,
) -> KjMaybe<bool>;

// Local<Promise>
pub unsafe fn local_promise_state(promise: &Local) -> PromiseState;
Expand Down Expand Up @@ -4484,6 +4489,38 @@ impl Object {
}

impl<'s> Local<'s, Object> {
/// Changes this object's prototype to `prototype`, or to null for `None`, as
/// `Object.setPrototypeOf()` does.
///
/// # Errors
/// A `TypeError` if the object refuses the change: the new prototype chain would contain
/// a cycle, the object is not extensible, or it is a Proxy whose `setPrototypeOf` trap
/// refused or threw. A pending exception or termination is propagated.
pub fn set_prototype(self, lock: &mut Lock<'s>, prototype: Option<Self>) -> crate::Result<()> {
self.debug_assert_isolate(lock);
let prototype: Local<'s, Value> = match prototype {
Some(prototype) => {
prototype.debug_assert_isolate(lock);
prototype.into()
}
None => lock.null(),
};
call_into_js(lock, |lock| {
// SAFETY: the isolate is locked, a context is entered and both handles are in scope.
match Option::from(unsafe {
ffi::local_object_set_prototype(
lock.isolate().as_ffi(),
self.raw(),
prototype.into_ffi(),
)
}) {
Some(true) => Ok(Some(())),
Some(false) => Err(Error::new_type_error("Cannot set the object's prototype")),
None => Ok(None),
Comment thread
bartlomieju marked this conversation as resolved.
Resolved
}
})
}

/// Sets `key` to `value`, like JS `obj[key] = value`.
///
/// # Errors
Expand Down
2 changes: 2 additions & 0 deletions src/workerd/api/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ filegroup(
"blob.h",
"bootstrap-utils.h",
"cache.h",
"cache-context-ref.h",
"container.h",
"event-target-bootstrap.h",
"events.h",
Expand Down Expand Up @@ -978,6 +979,7 @@ kj_test(
":streams",
":urlpattern",
":urlpattern-standard",
"//src/rust/jsg-cpp:ffi",
"//src/workerd/io",
"//src/workerd/jsg:rtti",
],
Expand Down
21 changes: 21 additions & 0 deletions src/workerd/api/api-rtti-test.c++
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <workerd/api/urlpattern.h>
#include <workerd/io/compatibility-date.h>
#include <workerd/jsg/rtti.h>
#include <workerd/rust/jsg-cpp/jsg-cpp.h>

#include <capnp/serialize.h>
#include <kj/test.h>
Expand Down Expand Up @@ -78,6 +79,26 @@ KJ_TEST("JsReadableWritablePair delegates its RTTI to ReadableStream::Transform"
type.getStructure().getFullyQualifiedName());
}

struct RustStreamTag {
using JsgRttiDelegate = jsg::Ref<ReadableStream>;
};

KJ_TEST("RustRef delegates its RTTI to the tag's JavaScript type") {
jsg::rtti::Builder builder((CompatibilityFlags::Reader()));
auto type = builder.type<rust::jsg_cpp::RustRef<RustStreamTag>>();
KJ_ASSERT(type.isStructure());
KJ_EXPECT(type.getStructure().getFullyQualifiedName() == "workerd::api::ReadableStream"_kj);
KJ_EXPECT(builder.structure("workerd::api::ReadableStream"_kj) != kj::none);
}

KJ_TEST("ctx.cache retains its CacheContext RTTI with either backend") {
jsg::rtti::Builder builder((CompatibilityFlags::Reader()));
auto type = builder.type<CacheContextRef>();
KJ_ASSERT(type.isStructure());
KJ_EXPECT(type.getStructure().getFullyQualifiedName() == "workerd::api::CacheContext"_kj);
KJ_EXPECT(builder.structure("workerd::api::CacheContext"_kj) != kj::none);
}

KJ_TEST("RTTI export discovers Rust modules and their referenced structs without evaluating JS") {
auto module = jsg::alloc<RTTIModule>();
auto bytes = module->exportTypes(kj::str("2026-01-01"), kj::heapArray<kj::String>(0));
Expand Down
79 changes: 79 additions & 0 deletions src/workerd/api/cache-context-ref.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright (c) 2026 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0

#pragma once

#include <workerd/jsg/jsg.h>
#include <workerd/rust/jsg-cpp/jsg-cpp.h>

namespace workerd::api {

class CacheContext;

// The embedder identifies its Rust implementation of the ctx.cache resource. The C++ type
// remains the RTTI delegate until the ExecutionContext itself is ported to Rust.
struct CacheContextTag {
static constexpr const char* NAME = "CacheContext";
using JsgRttiDelegate = jsg::Ref<CacheContext>;

static kj::Maybe<bool> isInstance(v8::Isolate* isolate, rust::jsg_cpp::Local value);
};

using RustCacheContext = rust::jsg_cpp::RustRef<CacheContextTag>;

class CacheContextRef {
public:
CacheContextRef(jsg::Ref<CacheContext> value);
CacheContextRef(RustCacheContext value);
CacheContextRef(CacheContextRef&&);
~CacheContextRef() noexcept(false);

using JsgRttiDelegate = jsg::Ref<CacheContext>;

static v8::Local<v8::Value> jsgWrap(auto& typeWrapper,
Comment thread
bartlomieju marked this conversation as resolved.
Resolved
jsg::Lock& js,
v8::Local<v8::Context> context,
kj::Maybe<v8::Local<v8::Object>> creator,
CacheContextRef cache) {
KJ_SWITCH_ONEOF(cache.value) {
KJ_CASE_ONEOF(cpp, jsg::Ref<CacheContext>) {
return typeWrapper.wrap(js, context, creator, kj::mv(cpp));
}
KJ_CASE_ONEOF(rust, RustCacheContext) {
return typeWrapper.wrap(js, context, creator, kj::mv(rust));
}
}
KJ_UNREACHABLE;
}

// Only to satisfy SelfConvertible: `ctx.cache` is a getter-only property, so nothing unwraps a
// CacheContextRef.
static kj::Maybe<CacheContextRef> jsgTryUnwrap(auto& typeWrapper,
Comment thread
bartlomieju marked this conversation as resolved.
Resolved
jsg::Lock& js,
v8::Local<v8::Context> context,
v8::Local<v8::Value> handle,
kj::Maybe<v8::Local<v8::Object>> parentObject) {
KJ_IF_SOME(cpp,
typeWrapper.tryUnwrap(
js, context, handle, static_cast<jsg::Ref<CacheContext>*>(nullptr), parentObject)) {
return CacheContextRef(kj::mv(cpp));
}
KJ_IF_SOME(rust,
typeWrapper.tryUnwrap(
js, context, handle, static_cast<RustCacheContext*>(nullptr), parentObject)) {
return CacheContextRef(kj::mv(rust));
}
return kj::none;
}

private:
kj::OneOf<jsg::Ref<CacheContext>, RustCacheContext> value;
};

// The `ctx.cache` of the current request: the embedder's Rust implementation if it supplies one
// (Worker::Api::getCtxCacheRustProperty()), otherwise its C++ one (getCtxCacheProperty()), or
// none outside a request or when the embedder supplies neither.
jsg::Optional<CacheContextRef> currentCacheContext(jsg::Lock& js);

} // namespace workerd::api
Loading
Loading