//! An implementation of the Bevy Remote Protocol, to allow for remote control of a Bevy app.1//!2//! Adding the [`RemotePlugin`] to your [`App`] will setup everything needed without3//! starting any transports. To start accepting remote connections you will need to4//! add a second plugin like the [`RemoteHttpPlugin`](http::RemoteHttpPlugin) to enable communication5//! over HTTP. These *remote clients* can inspect and alter the state of the6//! entity-component system.7//!8//! The Bevy Remote Protocol is based on the JSON-RPC 2.0 protocol.9//!10//! ## Request objects11//!12//! A typical client request might look like this:13//!14//! ```json15//! {16//! "method": "world.get_components",17//! "id": 0,18//! "params": {19//! "entity": 4294967298,20//! "components": [21//! "bevy_transform::components::transform::Transform"22//! ]23//! }24//! }25//! ```26//!27//! The `id` and `method` fields are required. The `params` field may be omitted28//! for certain methods:29//!30//! * `id` is arbitrary JSON data. The server completely ignores its contents,31//! and the client may use it for any purpose. It will be copied via32//! serialization and deserialization (so object property order, etc. can't be33//! relied upon to be identical) and sent back to the client as part of the34//! response.35//!36//! * `method` is a string that specifies one of the possible [`BrpRequest`]37//! variants: `world.query`, `world.get_components`, `world.insert_components`, etc. It's case-sensitive.38//!39//! * `params` is parameter data specific to the request.40//!41//! For more information, see the documentation for [`BrpRequest`].42//! [`BrpRequest`] is serialized to JSON via `serde`, so [the `serde`43//! documentation] may be useful to clarify the correspondence between the Rust44//! structure and the JSON format.45//!46//! ## Response objects47//!48//! A response from the server to the client might look like this:49//!50//! ```json51//! {52//! "jsonrpc": "2.0",53//! "id": 0,54//! "result": {55//! "bevy_transform::components::transform::Transform": {56//! "rotation": { "x": 0.0, "y": 0.0, "z": 0.0, "w": 1.0 },57//! "scale": { "x": 1.0, "y": 1.0, "z": 1.0 },58//! "translation": { "x": 0.0, "y": 0.5, "z": 0.0 }59//! }60//! }61//! }62//! ```63//!64//! The `id` field will always be present. The `result` field will be present if the65//! request was successful. Otherwise, an `error` field will replace it.66//!67//! * `id` is the arbitrary JSON data that was sent as part of the request. It68//! will be identical to the `id` data sent during the request, modulo69//! serialization and deserialization. If there's an error reading the `id` field,70//! it will be `null`.71//!72//! * `result` will be present if the request succeeded and will contain the response73//! specific to the request.74//!75//! * `error` will be present if the request failed and will contain an error object76//! with more information about the cause of failure.77//!78//! ## Error objects79//!80//! An error object might look like this:81//!82//! ```json83//! {84//! "code": -32602,85//! "message": "Missing \"entity\" field"86//! }87//! ```88//!89//! The `code` and `message` fields will always be present. There may also be a `data` field.90//!91//! * `code` is an integer representing the kind of an error that happened. Error codes documented92//! in the [`error_codes`] module.93//!94//! * `message` is a short, one-sentence human-readable description of the error.95//!96//! * `data` is an optional field of arbitrary type containing additional information about the error.97//!98//! ## Built-in methods99//!100//! The Bevy Remote Protocol includes a number of built-in methods for accessing and modifying data101//! in the ECS.102//!103//! ### `world.get_components`104//!105//! Retrieve the values of one or more components from an entity.106//!107//! `params`:108//! - `entity`: The ID of the entity whose components will be fetched.109//! - `components`: An array of [fully-qualified type names] of components to fetch.110//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the111//! components is not present or can not be reflected. Defaults to false.112//!113//! If `strict` is false:114//!115//! `result`:116//! - `components`: A map associating each type name to its value on the requested entity.117//! - `errors`: A map associating each type name with an error if it was not on the entity118//! or could not be reflected.119//!120//! If `strict` is true:121//!122//! `result`: A map associating each type name to its value on the requested entity.123//!124//! ### `world.query`125//!126//! Perform a query over components in the ECS, returning all matching entities and their associated127//! component values.128//!129//! All of the arrays that comprise this request are optional, and when they are not provided, they130//! will be treated as if they were empty.131//!132//! `params`:133//! - `data`:134//! - `components` (optional): An array of [fully-qualified type names] of components to fetch,135//! see _below_ example for a query to list all the type names in **your** project.136//! - `option` (optional): An array of fully-qualified type names of components to fetch optionally.137//! to fetch all reflectable components, you can pass in the string `"all"`.138//! - `has` (optional): An array of fully-qualified type names of components whose presence will be139//! reported as boolean values.140//! - `filter` (optional):141//! - `with` (optional): An array of fully-qualified type names of components that must be present142//! on entities in order for them to be included in results.143//! - `without` (optional): An array of fully-qualified type names of components that must *not* be144//! present on entities in order for them to be included in results.145//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the components146//! is not present or can not be reflected. Defaults to false.147//!148//! `result`: An array, each of which is an object containing:149//! - `entity`: The ID of a query-matching entity.150//! - `components`: A map associating each type name from `components`/`option` to its value on the matching151//! entity if the component is present.152//! - `has`: A map associating each type name from `has` to a boolean value indicating whether or not the153//! entity has that component. If `has` was empty or omitted, this key will be omitted in the response.154//!155//! #### Example156//! To use the query API and retrieve Transform data for all entities that have a Transform157//! use this query:158//!159//! ```json160//! {161//! "jsonrpc": "2.0",162//! "method": "bevy/query",163//! "id": 0,164//! "params": {165//! "data": {166//! "components": ["bevy_transform::components::transform::Transform"]167//! "option": [],168//! "has": []169//! },170//! "filter": {171//! "with": [],172//! "without": []173//! },174//! "strict": false175//! }176//! }177//! ```178//!179//!180//! To query all entities and all of their Reflectable components (and retrieve their values), you can pass in "all" for the option field:181//! ```json182//! {183//! "jsonrpc": "2.0",184//! "method": "bevy/query",185//! "id": 0,186//! "params": {187//! "data": {188//! "components": []189//! "option": "all",190//! "has": []191//! },192//! "filter": {193//! "with": [],194//! "without": []195//! },196//! "strict": false197//! }198//! }199//! ```200//!201//! This should return you something like the below (in a larger list):202//! ```json203//! {204//! "components": {205//! "bevy_camera::Camera3d": {206//! "depth_load_op": {207//! "Clear": 0.0208//! },209//! "depth_texture_usages": 16,210//! "screen_space_specular_transmission_quality": "Medium",211//! "screen_space_specular_transmission_steps": 1212//! },213//! "bevy_core_pipeline::tonemapping::DebandDither": "Enabled",214//! "bevy_core_pipeline::tonemapping::Tonemapping": "TonyMcMapface",215//! "bevy_light::cluster::ClusterConfig": {216//! "FixedZ": {217//! "dynamic_resizing": true,218//! "total": 4096,219//! "z_config": {220//! "far_z_mode": "MaxClusterableObjectRange",221//! "first_slice_depth": 5.0222//! },223//! "z_slices": 24224//! }225//! },226//! "bevy_camera::Camera": {227//! "clear_color": "Default",228//! "is_active": true,229//! "msaa_writeback": true,230//! "order": 0,231//! "sub_camera_view": null,232//! "target": {233//! "Window": "Primary"234//! },235//! "viewport": null236//! },237//! "bevy_camera::Projection": {238//! "Perspective": {239//! "aspect_ratio": 1.7777777910232544,240//! "far": 1000.0,241//! "fov": 0.7853981852531433,242//! "near": 0.10000000149011612243//! }244//! },245//! "bevy_camera::primitives::Frustum": {},246//! "bevy_render::sync_world::RenderEntity": 4294967291,247//! "bevy_render::sync_world::SyncToRenderWorld": {},248//! "bevy_render::view::Msaa": "Sample4",249//! "bevy_camera::visibility::InheritedVisibility": true,250//! "bevy_camera::visibility::ViewVisibility": false,251//! "bevy_camera::visibility::Visibility": "Inherited",252//! "bevy_camera::visibility::VisibleEntities": {},253//! "bevy_transform::components::global_transform::GlobalTransform": [254//! 0.9635179042816162,255//! -3.725290298461914e-9,256//! 0.26764383912086487,257//! 0.11616238951683044,258//! 0.9009039402008056,259//! -0.4181846082210541,260//! -0.24112138152122495,261//! 0.4340185225009918,262//! 0.8680371046066284,263//! -2.5,264//! 4.5,265//! 9.0266//! ],267//! "bevy_transform::components::transform::Transform": {268//! "rotation": [269//! -0.22055435180664065,270//! -0.13167093694210052,271//! -0.03006339818239212,272//! 0.9659786224365234273//! ],274//! "scale": [275//! 1.0,276//! 1.0,277//! 1.0278//! ],279//! "translation": [280//! -2.5,281//! 4.5,282//! 9.0283//! ]284//! },285//! "bevy_transform::components::transform::TransformTreeChanged": null286//! },287//! "entity": 4294967261288//!},289//! ```290//!291//! ### `world.spawn_entity`292//!293//! Create a new entity with the provided components and return the resulting entity ID.294//!295//! `params`:296//! - `components`: A map associating each component's [fully-qualified type name] with its value.297//!298//! `result`:299//! - `entity`: The ID of the newly spawned entity.300//!301//! ### `world.despawn_entity`302//!303//! Despawn the entity with the given ID.304//!305//! `params`:306//! - `entity`: The ID of the entity to be despawned.307//!308//! `result`: null.309//!310//! ### `world.remove_components`311//!312//! Delete one or more components from an entity.313//!314//! `params`:315//! - `entity`: The ID of the entity whose components should be removed.316//! - `components`: An array of [fully-qualified type names] of components to be removed.317//!318//! `result`: null.319//!320//! ### `world.insert_components`321//!322//! Insert one or more components into an entity.323//!324//! `params`:325//! - `entity`: The ID of the entity to insert components into.326//! - `components`: A map associating each component's fully-qualified type name with its value.327//!328//! `result`: null.329//!330//! ### `world.mutate_components`331//!332//! Mutate a field in a component.333//!334//! `params`:335//! - `entity`: The ID of the entity with the component to mutate.336//! - `component`: The component's [fully-qualified type name].337//! - `path`: The path of the field within the component. See338//! [`GetPath`](bevy_reflect::GetPath#syntax) for more information on formatting this string.339//! - `value`: The value to insert at `path`.340//!341//! `result`: null.342//!343//! ### `world.reparent_entities`344//!345//! Assign a new parent to one or more entities.346//!347//! `params`:348//! - `entities`: An array of entity IDs of entities that will be made children of the `parent`.349//! - `parent` (optional): The entity ID of the parent to which the child entities will be assigned.350//! If excluded, the given entities will be removed from their parents.351//!352//! `result`: null.353//!354//! ### `world.list_components`355//!356//! List all registered components or all components present on an entity.357//!358//! When `params` is not provided, this lists all registered components. If `params` is provided,359//! this lists only those components present on the provided entity.360//!361//! `params` (optional):362//! - `entity`: The ID of the entity whose components will be listed.363//!364//! `result`: An array of fully-qualified type names of components.365//!366//! ### `world.get_components+watch`367//!368//! Watch the values of one or more components from an entity.369//!370//! `params`:371//! - `entity`: The ID of the entity whose components will be fetched.372//! - `components`: An array of [fully-qualified type names] of components to fetch.373//! - `strict` (optional): A flag to enable strict mode which will fail if any one of the374//! components is not present or can not be reflected. Defaults to false.375//!376//! If `strict` is false:377//!378//! `result`:379//! - `components`: A map of components added or changed in the last tick associating each type380//! name to its value on the requested entity.381//! - `removed`: An array of fully-qualified type names of components removed from the entity382//! in the last tick.383//! - `errors`: A map associating each type name with an error if it was not on the entity384//! or could not be reflected.385//!386//! If `strict` is true:387//!388//! `result`:389//! - `components`: A map of components added or changed in the last tick associating each type390//! name to its value on the requested entity.391//! - `removed`: An array of fully-qualified type names of components removed from the entity392//! in the last tick.393//!394//! ### `world.list_components+watch`395//!396//! Watch all components present on an entity.397//!398//! When `params` is not provided, this lists all registered components. If `params` is provided,399//! this lists only those components present on the provided entity.400//!401//! `params`:402//! - `entity`: The ID of the entity whose components will be listed.403//!404//! `result`:405//! - `added`: An array of fully-qualified type names of components added to the entity in the406//! last tick.407//! - `removed`: An array of fully-qualified type names of components removed from the entity408//! in the last tick.409//!410//! ### `world.get_resources`411//!412//! Extract the value of a given resource from the world.413//!414//! `params`:415//! - `resource`: The [fully-qualified type name] of the resource to get.416//!417//! `result`:418//! - `value`: The value of the resource in the world.419//!420//! ### `world.insert_resources`421//!422//! Insert the given resource into the world with the given value.423//!424//! `params`:425//! - `resource`: The [fully-qualified type name] of the resource to insert.426//! - `value`: The value of the resource to be inserted.427//!428//! `result`: null.429//!430//! ### `world.remove_resources`431//!432//! Remove the given resource from the world.433//!434//! `params`435//! - `resource`: The [fully-qualified type name] of the resource to remove.436//!437//! `result`: null.438//!439//! ### `world.mutate_resources`440//!441//! Mutate a field in a resource.442//!443//! `params`:444//! - `resource`: The [fully-qualified type name] of the resource to mutate.445//! - `path`: The path of the field within the resource. See446//! [`GetPath`](bevy_reflect::GetPath#syntax) for more information on formatting this string.447//! - `value`: The value to be inserted at `path`.448//!449//! `result`: null.450//!451//! ### `world.list_resources`452//!453//! List all reflectable registered resource types. This method has no parameters.454//!455//! `result`: An array of [fully-qualified type names] of registered resource types.456//!457//! ### `registry.schema`458//!459//! Retrieve schema information about registered types in the Bevy app's type registry.460//!461//! `params` (optional):462//! - `with_crates`: An array of crate names to include in the results. When empty or omitted, types from all crates will be included.463//! - `without_crates`: An array of crate names to exclude from the results. When empty or omitted, no crates will be excluded.464//! - `type_limit`: Additional type constraints:465//! - `with`: An array of [fully-qualified type names] that must be present for a type to be included466//! - `without`: An array of [fully-qualified type names] that must not be present for a type to be excluded467//!468//! `result`: A map associating each type's [fully-qualified type name] to a [`JsonSchemaBevyType`](crate::schemas::json_schema::JsonSchemaBevyType).469//! This contains schema information about that type, including field definitions, type information, reflect type information, and other metadata470//! helpful for understanding the structure of the type.471//!472//! ### `rpc.discover`473//!474//! Discover available remote methods and server information. This follows the [`OpenRPC` specification for service discovery](https://spec.open-rpc.org/#service-discovery-method).475//!476//! This method takes no parameters.477//!478//! `result`: An `OpenRPC` document containing:479//! - Information about all available remote methods480//! - Server connection information (when using HTTP transport)481//! - `OpenRPC` specification version482//!483//! ## Custom methods484//!485//! In addition to the provided methods, the Bevy Remote Protocol can be extended to include custom486//! methods. This is primarily done during the initialization of [`RemotePlugin`], although the487//! methods may also be extended at runtime using the [`RemoteMethods`] resource.488//!489//! ### Example490//! ```ignore491//! fn main() {492//! App::new()493//! .add_plugins(DefaultPlugins)494//! .add_plugins(495//! // `default` adds all of the built-in methods, while `with_method` extends them496//! RemotePlugin::default()497//! .with_method("super_user/cool_method", path::to::my::cool::handler)498//! // ... more methods can be added by chaining `with_method`499//! )500//! .add_systems(501//! // ... standard application setup502//! )503//! .run();504//! }505//! ```506//!507//! The handler is expected to be a system-convertible function which takes optional JSON parameters508//! as input and returns a [`BrpResult`]. This means that it should have a type signature which looks509//! something like this:510//! ```511//! # use serde_json::Value;512//! # use bevy_ecs::prelude::{In, World};513//! # use bevy_remote::BrpResult;514//! fn handler(In(params): In<Option<Value>>, world: &mut World) -> BrpResult {515//! todo!()516//! }517//! ```518//!519//! Arbitrary system parameters can be used in conjunction with the optional `Value` input. The520//! handler system will always run with exclusive `World` access.521//!522//! [the `serde` documentation]: https://serde.rs/523//! [fully-qualified type names]: bevy_reflect::TypePath::type_path524//! [fully-qualified type name]: bevy_reflect::TypePath::type_path525526extern crate alloc;527528use async_channel::{Receiver, Sender};529use bevy_app::{prelude::*, MainScheduleOrder};530use bevy_derive::{Deref, DerefMut};531use bevy_ecs::{532entity::Entity,533resource::Resource,534schedule::{IntoScheduleConfigs, ScheduleLabel, SystemSet},535system::{Commands, In, IntoSystem, ResMut, System, SystemId},536world::World,537};538use bevy_platform::collections::HashMap;539use bevy_utils::prelude::default;540use serde::{Deserialize, Serialize};541use serde_json::Value;542use std::sync::RwLock;543544pub mod builtin_methods;545#[cfg(feature = "http")]546pub mod http;547pub mod schemas;548549const CHANNEL_SIZE: usize = 16;550551/// Add this plugin to your [`App`] to allow remote connections to inspect and modify entities.552///553/// This the main plugin for `bevy_remote`. See the [crate-level documentation] for details on554/// the available protocols and its default methods.555///556/// [crate-level documentation]: crate557pub struct RemotePlugin {558/// The verbs that the server will recognize and respond to.559methods: RwLock<Vec<(String, RemoteMethodHandler)>>,560}561562impl RemotePlugin {563/// Create a [`RemotePlugin`] with the default address and port but without564/// any associated methods.565fn empty() -> Self {566Self {567methods: RwLock::new(vec![]),568}569}570571/// Add a remote method to the plugin using the given `name` and `handler`.572#[must_use]573pub fn with_method<M>(574mut self,575name: impl Into<String>,576handler: impl IntoSystem<In<Option<Value>>, BrpResult, M>,577) -> Self {578self.methods.get_mut().unwrap().push((579name.into(),580RemoteMethodHandler::Instant(Box::new(IntoSystem::into_system(handler))),581));582self583}584585/// Add a remote method with a watching handler to the plugin using the given `name`.586#[must_use]587pub fn with_watching_method<M>(588mut self,589name: impl Into<String>,590handler: impl IntoSystem<In<Option<Value>>, BrpResult<Option<Value>>, M>,591) -> Self {592self.methods.get_mut().unwrap().push((593name.into(),594RemoteMethodHandler::Watching(Box::new(IntoSystem::into_system(handler))),595));596self597}598}599600impl Default for RemotePlugin {601fn default() -> Self {602Self::empty()603.with_method(604builtin_methods::BRP_GET_COMPONENTS_METHOD,605builtin_methods::process_remote_get_components_request,606)607.with_method(608builtin_methods::BRP_QUERY_METHOD,609builtin_methods::process_remote_query_request,610)611.with_method(612builtin_methods::BRP_SPAWN_ENTITY_METHOD,613builtin_methods::process_remote_spawn_entity_request,614)615.with_method(616builtin_methods::BRP_INSERT_COMPONENTS_METHOD,617builtin_methods::process_remote_insert_components_request,618)619.with_method(620builtin_methods::BRP_REMOVE_COMPONENTS_METHOD,621builtin_methods::process_remote_remove_components_request,622)623.with_method(624builtin_methods::BRP_DESPAWN_COMPONENTS_METHOD,625builtin_methods::process_remote_despawn_entity_request,626)627.with_method(628builtin_methods::BRP_REPARENT_ENTITIES_METHOD,629builtin_methods::process_remote_reparent_entities_request,630)631.with_method(632builtin_methods::BRP_LIST_COMPONENTS_METHOD,633builtin_methods::process_remote_list_components_request,634)635.with_method(636builtin_methods::BRP_MUTATE_COMPONENTS_METHOD,637builtin_methods::process_remote_mutate_components_request,638)639.with_method(640builtin_methods::RPC_DISCOVER_METHOD,641builtin_methods::process_remote_list_methods_request,642)643.with_watching_method(644builtin_methods::BRP_GET_COMPONENTS_AND_WATCH_METHOD,645builtin_methods::process_remote_get_components_watching_request,646)647.with_watching_method(648builtin_methods::BRP_LIST_COMPONENTS_AND_WATCH_METHOD,649builtin_methods::process_remote_list_components_watching_request,650)651.with_method(652builtin_methods::BRP_GET_RESOURCE_METHOD,653builtin_methods::process_remote_get_resources_request,654)655.with_method(656builtin_methods::BRP_INSERT_RESOURCE_METHOD,657builtin_methods::process_remote_insert_resources_request,658)659.with_method(660builtin_methods::BRP_REMOVE_RESOURCE_METHOD,661builtin_methods::process_remote_remove_resources_request,662)663.with_method(664builtin_methods::BRP_MUTATE_RESOURCE_METHOD,665builtin_methods::process_remote_mutate_resources_request,666)667.with_method(668builtin_methods::BRP_LIST_RESOURCES_METHOD,669builtin_methods::process_remote_list_resources_request,670)671.with_method(672builtin_methods::BRP_REGISTRY_SCHEMA_METHOD,673builtin_methods::export_registry_types,674)675}676}677678impl Plugin for RemotePlugin {679fn build(&self, app: &mut App) {680let mut remote_methods = RemoteMethods::new();681682let plugin_methods = &mut *self.methods.write().unwrap();683for (name, handler) in plugin_methods.drain(..) {684remote_methods.insert(685name,686match handler {687RemoteMethodHandler::Instant(system) => RemoteMethodSystemId::Instant(688app.main_mut().world_mut().register_boxed_system(system),689),690RemoteMethodHandler::Watching(system) => RemoteMethodSystemId::Watching(691app.main_mut().world_mut().register_boxed_system(system),692),693},694);695}696697app.init_schedule(RemoteLast)698.world_mut()699.resource_mut::<MainScheduleOrder>()700.insert_after(Last, RemoteLast);701702app.insert_resource(remote_methods)703.init_resource::<schemas::SchemaTypesMetadata>()704.init_resource::<RemoteWatchingRequests>()705.add_systems(PreStartup, setup_mailbox_channel)706.configure_sets(707RemoteLast,708(RemoteSystems::ProcessRequests, RemoteSystems::Cleanup).chain(),709)710.add_systems(711RemoteLast,712(713(process_remote_requests, process_ongoing_watching_requests)714.chain()715.in_set(RemoteSystems::ProcessRequests),716remove_closed_watching_requests.in_set(RemoteSystems::Cleanup),717),718);719}720}721722/// Schedule that contains all systems to process Bevy Remote Protocol requests723#[derive(ScheduleLabel, Clone, Debug, PartialEq, Eq, Hash, Default)]724pub struct RemoteLast;725726/// The systems sets of the [`RemoteLast`] schedule.727///728/// These can be useful for ordering.729#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]730pub enum RemoteSystems {731/// Processing of remote requests.732ProcessRequests,733/// Cleanup (remove closed watchers etc)734Cleanup,735}736737/// Deprecated alias for [`RemoteSystems`].738#[deprecated(since = "0.17.0", note = "Renamed to `RemoteSystems`.")]739pub type RemoteSet = RemoteSystems;740741/// A type to hold the allowed types of systems to be used as method handlers.742#[derive(Debug)]743pub enum RemoteMethodHandler {744/// A handler that only runs once and returns one response.745Instant(Box<dyn System<In = In<Option<Value>>, Out = BrpResult>>),746/// A handler that watches for changes and response when a change is detected.747Watching(Box<dyn System<In = In<Option<Value>>, Out = BrpResult<Option<Value>>>>),748}749750/// The [`SystemId`] of a function that implements a remote instant method (`world.get_components`, `world.query`, etc.)751///752/// The first parameter is the JSON value of the `params`. Typically, an753/// implementation will deserialize these as the first thing they do.754///755/// The returned JSON value will be returned as the response. Bevy will756/// automatically populate the `id` field before sending.757pub type RemoteInstantMethodSystemId = SystemId<In<Option<Value>>, BrpResult>;758759/// The [`SystemId`] of a function that implements a remote watching method (`world.get_components+watch`, `world.list_components+watch`, etc.)760///761/// The first parameter is the JSON value of the `params`. Typically, an762/// implementation will deserialize these as the first thing they do.763///764/// The optional returned JSON value will be sent as a response. If no765/// changes were detected this should be [`None`]. Re-running of this766/// handler is done in the [`RemotePlugin`].767pub type RemoteWatchingMethodSystemId = SystemId<In<Option<Value>>, BrpResult<Option<Value>>>;768769/// The [`SystemId`] of a function that can be used as a remote method.770#[derive(Debug, Clone, Copy)]771pub enum RemoteMethodSystemId {772/// A handler that only runs once and returns one response.773Instant(RemoteInstantMethodSystemId),774/// A handler that watches for changes and response when a change is detected.775Watching(RemoteWatchingMethodSystemId),776}777778/// Holds all implementations of methods known to the server.779///780/// Custom methods can be added to this list using [`RemoteMethods::insert`].781#[derive(Debug, Resource, Default)]782pub struct RemoteMethods(HashMap<String, RemoteMethodSystemId>);783784impl RemoteMethods {785/// Creates a new [`RemoteMethods`] resource with no methods registered in it.786pub fn new() -> Self {787default()788}789790/// Adds a new method, replacing any existing method with that name.791///792/// If there was an existing method with that name, returns its handler.793pub fn insert(794&mut self,795method_name: impl Into<String>,796handler: RemoteMethodSystemId,797) -> Option<RemoteMethodSystemId> {798self.0.insert(method_name.into(), handler)799}800801/// Get a [`RemoteMethodSystemId`] with its method name.802pub fn get(&self, method: &str) -> Option<&RemoteMethodSystemId> {803self.0.get(method)804}805806/// Get a [`Vec<String>`] with method names.807pub fn methods(&self) -> Vec<String> {808self.0.keys().cloned().collect()809}810}811812/// Holds the [`BrpMessage`]'s of all ongoing watching requests along with their handlers.813#[derive(Debug, Resource, Default)]814pub struct RemoteWatchingRequests(Vec<(BrpMessage, RemoteWatchingMethodSystemId)>);815816/// A single request from a Bevy Remote Protocol client to the server,817/// serialized in JSON.818///819/// The JSON payload is expected to look like this:820///821/// ```json822/// {823/// "jsonrpc": "2.0",824/// "method": "world.get_components",825/// "id": 0,826/// "params": {827/// "entity": 4294967298,828/// "components": [829/// "bevy_transform::components::transform::Transform"830/// ]831/// }832/// }833/// ```834/// Or, to list all the fully-qualified type paths in **your** project, pass Null to the835/// `params`.836/// ```json837/// {838/// "jsonrpc": "2.0",839/// "method": "world.list_components",840/// "id": 0,841/// "params": null842///}843///```844///845/// In Rust:846/// ```ignore847/// let req = BrpRequest {848/// jsonrpc: "2.0".to_string(),849/// method: BRP_LIST_METHOD.to_string(), // All the methods have consts850/// id: Some(ureq::json!(0)),851/// params: None,852/// };853/// ```854#[derive(Debug, Serialize, Deserialize, Clone)]855pub struct BrpRequest {856/// This field is mandatory and must be set to `"2.0"` for the request to be accepted.857pub jsonrpc: String,858859/// The action to be performed.860pub method: String,861862/// Arbitrary data that will be returned verbatim to the client as part of863/// the response.864#[serde(skip_serializing_if = "Option::is_none")]865pub id: Option<Value>,866867/// The parameters, specific to each method.868///869/// These are passed as the first argument to the method handler.870/// Sometimes params can be omitted.871#[serde(skip_serializing_if = "Option::is_none")]872pub params: Option<Value>,873}874875/// A response according to BRP.876#[derive(Debug, Serialize, Deserialize, Clone)]877pub struct BrpResponse {878/// This field is mandatory and must be set to `"2.0"`.879pub jsonrpc: &'static str,880881/// The id of the original request.882pub id: Option<Value>,883884/// The actual response payload.885#[serde(flatten)]886pub payload: BrpPayload,887}888889impl BrpResponse {890/// Generates a [`BrpResponse`] from an id and a `Result`.891#[must_use]892pub fn new(id: Option<Value>, result: BrpResult) -> Self {893Self {894jsonrpc: "2.0",895id,896payload: BrpPayload::from(result),897}898}899}900901/// A result/error payload present in every response.902#[derive(Debug, Serialize, Deserialize, Clone)]903#[serde(rename_all = "snake_case")]904pub enum BrpPayload {905/// `Ok` variant906Result(Value),907/// `Err` variant908Error(BrpError),909}910911impl From<BrpResult> for BrpPayload {912fn from(value: BrpResult) -> Self {913match value {914Ok(v) => Self::Result(v),915Err(err) => Self::Error(err),916}917}918}919920/// An error a request might return.921#[derive(Debug, Serialize, Deserialize, Clone)]922pub struct BrpError {923/// Defines the general type of the error.924pub code: i16,925/// Short, human-readable description of the error.926pub message: String,927/// Optional additional error data.928#[serde(skip_serializing_if = "Option::is_none")]929pub data: Option<Value>,930}931932impl BrpError {933/// Entity wasn't found.934#[must_use]935pub fn entity_not_found(entity: Entity) -> Self {936Self {937code: error_codes::ENTITY_NOT_FOUND,938message: format!("Entity {entity} not found"),939data: None,940}941}942943/// Component wasn't found in an entity.944#[must_use]945pub fn component_not_present(component: &str, entity: Entity) -> Self {946Self {947code: error_codes::COMPONENT_NOT_PRESENT,948message: format!("Component `{component}` not present in Entity {entity}"),949data: None,950}951}952953/// An arbitrary component error. Possibly related to reflection.954#[must_use]955pub fn component_error<E: ToString>(error: E) -> Self {956Self {957code: error_codes::COMPONENT_ERROR,958message: error.to_string(),959data: None,960}961}962963/// Resource was not present in the world.964#[must_use]965pub fn resource_not_present(resource: &str) -> Self {966Self {967code: error_codes::RESOURCE_NOT_PRESENT,968message: format!("Resource `{resource}` not present in the world"),969data: None,970}971}972973/// An arbitrary resource error. Possibly related to reflection.974#[must_use]975pub fn resource_error<E: ToString>(error: E) -> Self {976Self {977code: error_codes::RESOURCE_ERROR,978message: error.to_string(),979data: None,980}981}982983/// An arbitrary internal error.984#[must_use]985pub fn internal<E: ToString>(error: E) -> Self {986Self {987code: error_codes::INTERNAL_ERROR,988message: error.to_string(),989data: None,990}991}992993/// Attempt to reparent an entity to itself.994#[must_use]995pub fn self_reparent(entity: Entity) -> Self {996Self {997code: error_codes::SELF_REPARENT,998message: format!("Cannot reparent Entity {entity} to itself"),999data: None,1000}1001}1002}10031004/// Error codes used by BRP.1005pub mod error_codes {1006// JSON-RPC errors1007// Note that the range -32728 to -32000 (inclusive) is reserved by the JSON-RPC specification.10081009/// Invalid JSON.1010pub const PARSE_ERROR: i16 = -32700;10111012/// JSON sent is not a valid request object.1013pub const INVALID_REQUEST: i16 = -32600;10141015/// The method does not exist / is not available.1016pub const METHOD_NOT_FOUND: i16 = -32601;10171018/// Invalid method parameter(s).1019pub const INVALID_PARAMS: i16 = -32602;10201021/// Internal error.1022pub const INTERNAL_ERROR: i16 = -32603;10231024// Bevy errors (i.e. application errors)10251026/// Entity not found.1027pub const ENTITY_NOT_FOUND: i16 = -23401;10281029/// Could not reflect or find component.1030pub const COMPONENT_ERROR: i16 = -23402;10311032/// Could not find component in entity.1033pub const COMPONENT_NOT_PRESENT: i16 = -23403;10341035/// Cannot reparent an entity to itself.1036pub const SELF_REPARENT: i16 = -23404;10371038/// Could not reflect or find resource.1039pub const RESOURCE_ERROR: i16 = -23501;10401041/// Could not find resource in the world.1042pub const RESOURCE_NOT_PRESENT: i16 = -23502;1043}10441045/// The result of a request.1046pub type BrpResult<T = Value> = Result<T, BrpError>;10471048/// The requests may occur on their own or in batches.1049/// Actual parsing is deferred for the sake of proper1050/// error reporting.1051#[derive(Debug, Clone, Serialize, Deserialize)]1052#[serde(untagged)]1053pub enum BrpBatch {1054/// Multiple requests with deferred parsing.1055Batch(Vec<Value>),1056/// A single request with deferred parsing.1057Single(Value),1058}10591060/// A message from the Bevy Remote Protocol server thread to the main world.1061///1062/// This is placed in the [`BrpReceiver`].1063#[derive(Debug, Clone)]1064pub struct BrpMessage {1065/// The request method.1066pub method: String,10671068/// The request params.1069pub params: Option<Value>,10701071/// The channel on which the response is to be sent.1072///1073/// The value sent here is serialized and sent back to the client.1074pub sender: Sender<BrpResult>,1075}10761077/// A resource holding the matching sender for the [`BrpReceiver`]'s receiver.1078#[derive(Debug, Resource, Deref, DerefMut)]1079pub struct BrpSender(Sender<BrpMessage>);10801081/// A resource that receives messages sent by Bevy Remote Protocol clients.1082///1083/// Every frame, the `process_remote_requests` system drains this mailbox and1084/// processes the messages within.1085#[derive(Debug, Resource, Deref, DerefMut)]1086pub struct BrpReceiver(Receiver<BrpMessage>);10871088fn setup_mailbox_channel(mut commands: Commands) {1089// Create the channel and the mailbox.1090let (request_sender, request_receiver) = async_channel::bounded(CHANNEL_SIZE);1091commands.insert_resource(BrpSender(request_sender));1092commands.insert_resource(BrpReceiver(request_receiver));1093}10941095/// A system that receives requests placed in the [`BrpReceiver`] and processes1096/// them, using the [`RemoteMethods`] resource to map each request to its handler.1097///1098/// This needs exclusive access to the [`World`] because clients can manipulate1099/// anything in the ECS.1100fn process_remote_requests(world: &mut World) {1101if !world.contains_resource::<BrpReceiver>() {1102return;1103}11041105while let Ok(message) = world.resource_mut::<BrpReceiver>().try_recv() {1106// Fetch the handler for the method. If there's no such handler1107// registered, return an error.1108let Some(&handler) = world.resource::<RemoteMethods>().get(&message.method) else {1109let _ = message.sender.force_send(Err(BrpError {1110code: error_codes::METHOD_NOT_FOUND,1111message: format!("Method `{}` not found", message.method),1112data: None,1113}));1114return;1115};11161117match handler {1118RemoteMethodSystemId::Instant(id) => {1119let result = match world.run_system_with(id, message.params) {1120Ok(result) => result,1121Err(error) => {1122let _ = message.sender.force_send(Err(BrpError {1123code: error_codes::INTERNAL_ERROR,1124message: format!("Failed to run method handler: {error}"),1125data: None,1126}));1127continue;1128}1129};11301131let _ = message.sender.force_send(result);1132}1133RemoteMethodSystemId::Watching(id) => {1134world1135.resource_mut::<RemoteWatchingRequests>()1136.01137.push((message, id));1138}1139}1140}1141}11421143/// A system that checks all ongoing watching requests for changes that should be sent1144/// and handles it if so.1145fn process_ongoing_watching_requests(world: &mut World) {1146world.resource_scope::<RemoteWatchingRequests, ()>(|world, requests| {1147for (message, system_id) in requests.0.iter() {1148let handler_result = process_single_ongoing_watching_request(world, message, system_id);1149let sender_result = match handler_result {1150Ok(Some(value)) => message.sender.try_send(Ok(value)),1151Err(err) => message.sender.try_send(Err(err)),1152Ok(None) => continue,1153};11541155if sender_result.is_err() {1156// The [`remove_closed_watching_requests`] system will clean this up.1157message.sender.close();1158}1159}1160});1161}11621163fn process_single_ongoing_watching_request(1164world: &mut World,1165message: &BrpMessage,1166system_id: &RemoteWatchingMethodSystemId,1167) -> BrpResult<Option<Value>> {1168world1169.run_system_with(*system_id, message.params.clone())1170.map_err(|error| BrpError {1171code: error_codes::INTERNAL_ERROR,1172message: format!("Failed to run method handler: {error}"),1173data: None,1174})?1175}11761177fn remove_closed_watching_requests(mut requests: ResMut<RemoteWatchingRequests>) {1178for i in (0..requests.0.len()).rev() {1179let Some((message, _)) = requests.0.get(i) else {1180unreachable!()1181};11821183if message.sender.is_closed() {1184requests.0.swap_remove(i);1185}1186}1187}118811891190