From 1863805164019e07ec82f6a4158725169f82e511 Mon Sep 17 00:00:00 2001 From: Moti Zilberman Date: Mon, 19 Feb 2024 09:13:24 -0800 Subject: [PATCH] Support limiting CDP bindings to specific contexts (#43089) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/43089 Changelog: [Internal] Completes React Native's support for the [`Runtime.addBinding`](https://cdpstatus.reactnative.dev/devtools-protocol/tot/Runtime#method-addBinding) and [`Runtime.removeBinding`](https://cdpstatus.reactnative.dev/devtools-protocol/tot/Runtime#method-removeBinding) methods (in the modern CDP backend) by handling the optional `executionContextId` and `executionContextName` params. Reviewed By: huntie Differential Revision: D53760393 fbshipit-source-id: 1679fcde64c1125eb3f0f780432fedd6e3c2efc1 --- .../jsinspector-modern/ExecutionContext.cpp | 66 ++++++++++++++ .../jsinspector-modern/ExecutionContext.h | 86 +++++++++++++++++++ .../jsinspector-modern/RuntimeAgent.cpp | 64 ++++++++++++-- .../jsinspector-modern/SessionState.h | 12 ++- .../jsinspector-modern/UniqueMonostate.h | 54 ++++++++++++ 5 files changed, 271 insertions(+), 11 deletions(-) create mode 100644 packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.cpp create mode 100644 packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.cpp b/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.cpp new file mode 100644 index 00000000000..a298816d3af --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.cpp @@ -0,0 +1,66 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "ExecutionContext.h" + +namespace facebook::react::jsinspector_modern { + +namespace { + +template +inline constexpr bool always_false_v = false; + +} // namespace + +bool ExecutionContextSelector::matches( + const ExecutionContextDescription& context) const noexcept { + // Exhaustiveness checking based on the example in + // https://en.cppreference.com/w/cpp/utility/variant/visit. + return std::visit( + [&context](auto&& arg) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + return true; + } else if constexpr (std::is_same_v) { + return context.id == arg; + } else if constexpr (std::is_same_v) { + return context.name == arg; + } else { + static_assert(always_false_v, "non-exhaustive visitor"); + } + }, + value_); + + // Prevent the compiler from thinking always_false_v is unused when the + // visitor is (correctly) exhaustive. + (void)always_false_v; +} + +ExecutionContextSelector ExecutionContextSelector::byId(int32_t id) { + return ExecutionContextSelector{id}; +} + +ExecutionContextSelector ExecutionContextSelector::byName(std::string name) { + return ExecutionContextSelector{std::move(name)}; +} + +ExecutionContextSelector ExecutionContextSelector::all() { + return ExecutionContextSelector{AllContexts{}}; +} + +bool matchesAny( + const ExecutionContextDescription& context, + const ExecutionContextSelectorSet& selectors) { + for (const auto& selector : selectors) { + if (selector.matches(context)) { + return true; + } + } + return false; +} + +} // namespace facebook::react::jsinspector_modern diff --git a/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h b/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h index f397e08f27f..2e23fba10e4 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/ExecutionContext.h @@ -7,9 +7,13 @@ #pragma once +#include "UniqueMonostate.h" + #include #include #include +#include +#include namespace facebook::react::jsinspector_modern { @@ -20,4 +24,86 @@ struct ExecutionContextDescription { std::optional uniqueId; }; +/** + * A type-safe selector for execution contexts. + */ +class ExecutionContextSelector { + public: + /** + * Returns true iff this selector matches \c context. + */ + bool matches(const ExecutionContextDescription& context) const noexcept; + + /** + * Returns a new selector that matches only the given execution context ID. + */ + static ExecutionContextSelector byId(int32_t id); + + /** + * Returns a new selector that matches only the given execution context name. + */ + static ExecutionContextSelector byName(std::string name); + + /** + * Returns a new selector that matches any execution context. + */ + static ExecutionContextSelector all(); + + ExecutionContextSelector() = delete; + ExecutionContextSelector(const ExecutionContextSelector& other) = default; + ExecutionContextSelector(ExecutionContextSelector&& other) noexcept = default; + ExecutionContextSelector& operator=(const ExecutionContextSelector& other) = + default; + ExecutionContextSelector& operator=( + ExecutionContextSelector&& other) noexcept = default; + ~ExecutionContextSelector() = default; + + inline bool operator==(const ExecutionContextSelector& other) const noexcept { + return value_ == other.value_; + } + + private: + /** + * Marker type used to represent "all execution contexts". + * + * Q: What is a UniqueMonostate? + * A: std::monostate, but it's distinct from other UniqueMonostate<...>s, so + * you can use multiple of them in the same variant without ambiguity. + */ + using AllContexts = UniqueMonostate<0>; + using ContextId = int32_t; + using ContextName = std::string; + + using Representation = std::variant; + + explicit inline ExecutionContextSelector(Representation&& r) : value_(r) {} + + Representation value_; + + friend struct std::hash< + facebook::react::jsinspector_modern::ExecutionContextSelector>; +}; + +using ExecutionContextSelectorSet = + std::unordered_set; + +bool matchesAny( + const ExecutionContextDescription& context, + const ExecutionContextSelectorSet& selectors); + } // namespace facebook::react::jsinspector_modern + +namespace std { + +template <> +struct hash<::facebook::react::jsinspector_modern::ExecutionContextSelector> { + size_t operator()( + const ::facebook::react::jsinspector_modern::ExecutionContextSelector& + selector) const { + return hash<::facebook::react::jsinspector_modern:: + ExecutionContextSelector::Representation>{}( + selector.value_); + } +}; + +} // namespace std diff --git a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp index 7879d193959..4ac2f1a4d3a 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp +++ b/packages/react-native/ReactCommon/jsinspector-modern/RuntimeAgent.cpp @@ -20,19 +20,52 @@ RuntimeAgent::RuntimeAgent( sessionState_(sessionState), delegate_(std::move(delegate)), executionContextDescription_(executionContextDescription) { - for (auto& name : sessionState_.subscribedBindingNames) { - targetController_.installBindingHandler(name); + for (auto& [name, contextSelectors] : sessionState_.subscribedBindings) { + if (matchesAny(executionContextDescription_, contextSelectors)) { + targetController_.installBindingHandler(name); + } } } bool RuntimeAgent::handleRequest(const cdp::PreparsedRequest& req) { if (req.method == "Runtime.addBinding") { std::string bindingName = req.params["name"].getString(); - // TODO: Respect @cdp Runtime.addBinding's executionContextId and - // executionContextName params. - sessionState_.subscribedBindingNames.emplace(bindingName); - targetController_.installBindingHandler(bindingName); + ExecutionContextSelector contextSelector = ExecutionContextSelector::all(); + + // TODO: Eventually, move execution context targeting out of RuntimeAgent. + // Right now, there's only ever one context (Runtime) in a Page, so we can + // handle it here for simplicity, and use session state to propagate + // bindings to the next RuntimeAgent. + if (req.params.count("executionContextId")) { + auto executionContextId = req.params["executionContextId"].getInt(); + if (executionContextId < (int64_t)std::numeric_limits::min() || + executionContextId > (int64_t)std::numeric_limits::max()) { + frontendChannel_(folly::toJson(folly::dynamic::object("id", req.id)( + "error", + folly::dynamic::object("code", -32602)( + "message", "Invalid execution context id")))); + return true; + } + contextSelector = + ExecutionContextSelector::byId((int32_t)executionContextId); + + if (req.params.count("executionContextName")) { + frontendChannel_(folly::toJson(folly::dynamic::object("id", req.id)( + "error", + folly::dynamic::object("code", -32602)( + "message", + "executionContextName is mutually exclusive with executionContextId")))); + return true; + } + } else if (req.params.count("executionContextName")) { + contextSelector = ExecutionContextSelector::byName( + req.params["executionContextName"].getString()); + } + if (contextSelector.matches(executionContextDescription_)) { + targetController_.installBindingHandler(bindingName); + } + sessionState_.subscribedBindings[bindingName].insert(contextSelector); folly::dynamic res = folly::dynamic::object("id", req.id)( "result", folly::dynamic::object()); @@ -42,7 +75,12 @@ bool RuntimeAgent::handleRequest(const cdp::PreparsedRequest& req) { return true; } if (req.method == "Runtime.removeBinding") { - sessionState_.subscribedBindingNames.erase(req.params["name"].getString()); + // @cdp Runtime.removeBinding has no targeting by execution context. We + // interpret it to mean "unsubscribe, and stop installing the binding on + // all new contexts". This diverges slightly from V8, which continues + // to install the binding on new contexts after it's "removed", but *only* + // if the subscription is targeted by context name. + sessionState_.subscribedBindings.erase(req.params["name"].getString()); folly::dynamic res = folly::dynamic::object("id", req.id)( "result", folly::dynamic::object()); @@ -60,7 +98,17 @@ bool RuntimeAgent::handleRequest(const cdp::PreparsedRequest& req) { void RuntimeAgent::notifyBindingCalled( const std::string& bindingName, const std::string& payload) { - if (!sessionState_.subscribedBindingNames.count(bindingName)) { + // NOTE: When dispatching @cdp Runtime.bindingCalled notifications, we don't + // re-check whether the session is expecting notifications from the current + // context - only that it's subscribed to that binding name. + // Theoretically, this can result in over-sending notifications from contexts + // that the client no longer cares about, or never cared about to begin with + // (e.g. if the binding handler was installed by a previous session). + // + // React Native intentionally replicates this behavior for the sake of + // bug-for-bug compatibility with Chrome, but clients should probably not rely + // on it. + if (!sessionState_.subscribedBindings.count(bindingName)) { return; } diff --git a/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h b/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h index 9c9aa939ba0..16d6cb1b75c 100644 --- a/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h +++ b/packages/react-native/ReactCommon/jsinspector-modern/SessionState.h @@ -7,8 +7,11 @@ #pragma once +#include "ExecutionContext.h" + #include #include +#include #include namespace facebook::react::jsinspector_modern { @@ -20,13 +23,16 @@ struct SessionState { bool isRuntimeDomainEnabled{false}; /** - * The set of bindings registered during this session using @cdp - * Runtime.addBinding. Even though bindings get added to the global scope as + * A map from binding names (registered during this session using @cdp + * Runtime.addBinding) to execution context selectors. + * + * Even though bindings get added to the global scope as * functions that can outlive a session, they are treated as session state, * matching Chrome's behaviour (a binding not added by the current session * will not emit events on it). */ - std::unordered_set subscribedBindingNames; + std::unordered_map + subscribedBindings; // Here, we will eventually allow RuntimeAgents to store their own arbitrary // state (e.g. some sort of K/V storage of folly::dynamic?) diff --git a/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h b/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h new file mode 100644 index 00000000000..6c13e17dd03 --- /dev/null +++ b/packages/react-native/ReactCommon/jsinspector-modern/UniqueMonostate.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +namespace facebook::react::jsinspector_modern { + +/** + * A template for easily creating empty types that are distinct from one + * another. Useful if you need to generate marker types for use in an + * std::variant, and a single std::monostate won't do. + */ +template +struct UniqueMonostate { + constexpr bool operator==(const UniqueMonostate&) const noexcept { + return true; + } + constexpr bool operator!=(const UniqueMonostate&) const noexcept { + return false; + } + constexpr bool operator<(const UniqueMonostate&) const noexcept { + return false; + } + constexpr bool operator>(const UniqueMonostate&) const noexcept { + return false; + } + constexpr bool operator<=(const UniqueMonostate&) const noexcept { + return true; + } + constexpr bool operator>=(const UniqueMonostate&) const noexcept { + return true; + } +}; + +} // namespace facebook::react::jsinspector_modern + +namespace std { + +template +struct hash<::facebook::react::jsinspector_modern::UniqueMonostate> { + size_t operator()( + const ::facebook::react::jsinspector_modern::UniqueMonostate&) + const noexcept { + return key; + } +}; + +} // namespace std