1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
use std::fmt::Debug;
use crate::{
global::{CallbackReturn, EntityId},
internal::{conversion::FromBindgen, executor::EXECUTOR, wit},
};
mod serde;
pub use self::serde::*;
#[cfg(any(feature = "client", feature = "server"))]
use crate::internal::conversion::IntoBindgen;
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
/// Where a message came from.
pub enum Source {
/// This message came from the runtime.
Runtime,
/// This message came from the corresponding serverside package.
#[cfg(feature = "client")]
Server,
/// This message came from the corresponding clientside package and was sent from `user_id`.
#[cfg(feature = "server")]
Client {
/// The user that sent this message.
user_id: String,
},
/// This message came from another package on this side.
Local(EntityId),
}
impl Source {
/// Is this message from the runtime?
pub fn runtime(&self) -> bool {
matches!(self, Source::Runtime)
}
#[cfg(feature = "client")]
/// Is this message from the corresponding serverside package?
pub fn server(&self) -> bool {
matches!(self, Source::Server)
}
#[cfg(feature = "server")]
/// The user that sent this message, if any.
pub fn client_user_id(&self) -> Option<String> {
if let Source::Client { user_id } = self {
Some(user_id.clone())
} else {
None
}
}
#[cfg(feature = "server")]
/// The entity ID of the player that sent this message, if any.
pub fn client_entity_id(&self) -> Option<EntityId> {
let Some(user_id) = self.client_user_id() else {
return None;
};
let Some(player_id) = crate::player::get_by_user_id(&user_id) else {
return None;
};
Some(player_id)
}
/// The module on this side that sent this message, if any.
pub fn local(&self) -> Option<EntityId> {
match self {
Source::Local(id) => Some(*id),
_ => None,
}
}
}
impl FromBindgen for wit::guest::Source {
type Item = Source;
fn from_bindgen(self) -> Self::Item {
match self {
wit::guest::Source::Runtime => Source::Runtime,
#[cfg(feature = "client")]
wit::guest::Source::Server => Source::Server,
#[cfg(feature = "server")]
wit::guest::Source::Client(user_id) => Source::Client { user_id },
wit::guest::Source::Local(entity_id) => Source::Local(entity_id.from_bindgen()),
// cover the other features
#[cfg(not(feature = "client"))]
wit::guest::Source::Server => unreachable!(),
#[cfg(not(feature = "server"))]
wit::guest::Source::Client(_user_id) => unreachable!(),
}
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
/// The target for a originating message.
pub enum Target {
/// A message to all other packages running on this side.
LocalBroadcast {
/// Whether or not the message should be sent to the package that originally sent the message.
include_self: bool,
},
/// A message to a specific package or module running on this side.
Local(EntityId),
// Client
/// An unreliable transmission to the server.
///
/// Not guaranteed to be received, and must be below one kilobyte.
///
/// Unreliable messages are implemented using QUIC datagrams. This makes them ideal
/// for messages that are sent frequently, but are not critical to the functioning
/// of the logic on the server.
///
/// Note that this message will only be received by the corresponding package
/// on the server, and not by any other packages. You will need to explicitly
/// relay the message to other packages on the server.
#[cfg(feature = "client")]
ServerUnreliable,
/// A reliable transmission to the server (guaranteed to be received).
///
/// Reliable messages are implemented using QUIC streams. This makes them ideal
/// for messages that are sent infrequently, but must be received by the server.
///
/// Note that this message will only be received by the corresponding package
/// on the server, and not by any other packages. You will need to explicitly
/// relay the message to other packages on the server.
#[cfg(feature = "client")]
ServerReliable,
// Server
/// An unreliable transmission to all clients.
///
/// Not guaranteed to be received, and must be below one kilobyte.
///
/// Unreliable messages are implemented using QUIC datagrams. This makes them ideal
/// for messages that are sent frequently, but are not critical to the functioning
/// of the logic on the client.
///
/// Note that this message will only be received by the corresponding package
/// on the client, and not by any other packages. You will need to explicitly
/// relay the message to other packages on the client.
#[cfg(feature = "server")]
ClientBroadcastUnreliable,
/// A reliable transmission to all clients (guaranteed to be received).
///
/// Reliable messages are implemented using QUIC streams. This makes them ideal
/// for messages that are sent infrequently, but must be received by the client.
///
/// Note that this message will only be received by the corresponding package
/// on the client, and not by any other packages. You will need to explicitly
/// relay the message to other packages on the client.
#[cfg(feature = "server")]
ClientBroadcastReliable,
/// An unreliable transmission to a specific client.
///
/// Not guaranteed to be received, and must be below one kilobyte.
///
/// Unreliable messages are implemented using QUIC datagrams. This makes them ideal
/// for messages that are sent frequently, but are not critical to the functioning
/// of the logic on the client.
///
/// Note that this message will only be received by the corresponding package
/// on the client, and not by any other packages. You will need to explicitly
/// relay the message to other packages on the client.
#[cfg(feature = "server")]
ClientTargetedUnreliable(
/// The user to send to.
String,
),
/// A reliable transmission to a specific client (guaranteed to be received).
///
/// Reliable messages are implemented using QUIC streams. This makes them ideal
/// for messages that are sent infrequently, but must be received by the client.
///
/// Note that this message will only be received by the corresponding package
/// on the client, and not by any other packages. You will need to explicitly
/// relay the message to other packages on the client.
#[cfg(feature = "server")]
ClientTargetedReliable(
/// The user to send to.
String,
),
}
#[cfg(feature = "client")]
impl IntoBindgen for Target {
type Item = wit::client_message::Target;
fn into_bindgen(self) -> Self::Item {
match self {
Target::ServerUnreliable => Self::Item::ServerUnreliable,
Target::ServerReliable => Self::Item::ServerReliable,
Target::LocalBroadcast { include_self } => Self::Item::LocalBroadcast(include_self),
Target::Local(id) => Self::Item::Local(id.into_bindgen()),
#[cfg(feature = "server")]
_ => unreachable!(),
}
}
}
#[cfg(feature = "server")]
impl<'a> IntoBindgen for &'a Target {
type Item = wit::server_message::Target;
fn into_bindgen(self) -> Self::Item {
match self {
Target::ClientBroadcastUnreliable => Self::Item::ClientBroadcastUnreliable,
Target::ClientBroadcastReliable => Self::Item::ClientBroadcastReliable,
Target::ClientTargetedUnreliable(user_id) => {
Self::Item::ClientTargetedUnreliable(user_id.clone())
}
Target::ClientTargetedReliable(user_id) => {
Self::Item::ClientTargetedReliable(user_id.clone())
}
Target::LocalBroadcast { include_self } => Self::Item::LocalBroadcast(*include_self),
Target::Local(id) => Self::Item::Local(id.into_bindgen()),
#[cfg(feature = "client")]
_ => unreachable!(),
}
}
}
/// Send a message from this package to a specific `target`.
pub fn send<T: Message>(target: Target, data: &T) {
#[cfg(all(feature = "client", not(feature = "server")))]
wit::client_message::send(
target.into_bindgen(),
T::id(),
&data.serialize_message().unwrap(),
);
#[cfg(all(feature = "server", not(feature = "client")))]
wit::server_message::send(
&(&target).into_bindgen(),
T::id(),
&data.serialize_message().unwrap(),
);
#[cfg(any(
all(not(feature = "server"), not(feature = "client")),
all(feature = "server", feature = "client")
))]
let _ = (target, data);
}
/// Handle to a message listener that can be used to stop listening.
pub struct Listener(String, u128);
impl Listener {
/// Stops listening.
pub fn stop(&self) {
EXECUTOR.unregister_callback(&self.0, self.1);
}
}
/// Message context.
pub struct MessageContext {
/// Where the message came from.
pub source: Source,
/// The listener that can be used to stop listening.
pub listener: Listener,
}
impl MessageContext {
/// Is this message from the runtime?
pub fn runtime(&self) -> bool {
self.source.runtime()
}
#[cfg(feature = "client")]
/// Is this message from the corresponding serverside package?
pub fn server(&self) -> bool {
self.source.server()
}
#[cfg(feature = "server")]
/// The user that sent this message, if any.
pub fn client_user_id(&self) -> Option<String> {
self.source.client_user_id()
}
#[cfg(feature = "server")]
/// The entity ID of the player that sent this message, if any.
pub fn client_entity_id(&self) -> Option<EntityId> {
self.source.client_entity_id()
}
/// The module on this side that sent this message, if any.
pub fn local(&self) -> Option<EntityId> {
self.source.local()
}
/// Stops listening.
pub fn stop(&self) {
self.listener.stop()
}
}
impl Debug for MessageContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.source.fmt(f)
}
}
/// Subscribes to a message.
///
/// To unsubscribe from a message, call [Listener::stop] on the returned [Listener],
/// or on the [MessageContext] that is passed to the callback.
#[allow(clippy::collapsible_else_if)]
pub fn subscribe<R: CallbackReturn, T: Message>(
mut callback: impl FnMut(MessageContext, T) -> R + 'static,
) -> Listener {
let id = T::id();
wit::message::subscribe(id);
Listener(
id.to_string(),
EXECUTOR.register_callback(
id.to_string(),
Box::new(move |source, listener_id, data| {
callback(
MessageContext {
source: source.clone().from_bindgen(),
listener: Listener(id.to_string(), listener_id),
},
T::deserialize_message(data)?,
)
.into_result()?;
Ok(())
}),
),
)
}
/// Implemented by all messages that can be sent between modules.
pub trait ModuleMessage: Message {
/// Sends this [Message] to `target`. Wrapper around [self::send].
fn send(&self, target: Target) {
self::send(target, self)
}
/// Sends a message to every package on this side.
///
/// `include_self` controls whether or not the message is sent to the package that originally sent the message.
fn send_local_broadcast(&self, include_self: bool) {
self.send(Target::LocalBroadcast { include_self })
}
/// Sends a message to a specific package or module on this side.
fn send_local(&self, target_id: EntityId) {
self.send(Target::Local(target_id))
}
#[cfg(feature = "client")]
/// Sends an unreliable message to the server.
///
/// Note that this message will only be received by the corresponding package on the server,
/// and not by any other packages. You will need to explicitly relay the message to other
/// packages on the server.
///
/// See [Target::ServerUnreliable] for details.
fn send_server_unreliable(&self) {
self.send(Target::ServerUnreliable)
}
#[cfg(feature = "client")]
/// Sends a reliable message to the server.
///
/// Note that this message will only be received by the corresponding package on the server,
/// and not by any other packages. You will need to explicitly relay the message to other
/// packages on the server.
///
/// See [Target::ServerReliable] for details.
fn send_server_reliable(&self) {
self.send(Target::ServerReliable)
}
#[cfg(feature = "server")]
/// Sends an unreliable message to all clients.
///
/// Note that this message will only be received by the corresponding package on the client,
/// and not by any other packages. You will need to explicitly relay the message to other
/// packages on the client.
///
/// See [Target::ClientBroadcastUnreliable] for details.
fn send_client_broadcast_unreliable(&self) {
self.send(Target::ClientBroadcastUnreliable)
}
#[cfg(feature = "server")]
/// Sends a reliable message to all clients.
///
/// Note that this message will only be received by the corresponding package on the client,
/// and not by any other packages. You will need to explicitly relay the message to other
/// packages on the client.
///
/// See [Target::ClientBroadcastReliable] for details.
fn send_client_broadcast_reliable(&self) {
self.send(Target::ClientBroadcastReliable)
}
#[cfg(feature = "server")]
/// Sends an unreliable message to a specific client.
///
/// Note that this message will only be received by the corresponding package on the client,
/// and not by any other packages. You will need to explicitly relay the message to other
/// packages on the client.
///
/// See [Target::ClientTargetedUnreliable] for details.
fn send_client_targeted_unreliable(&self, user_id: String) {
self.send(Target::ClientTargetedUnreliable(user_id))
}
#[cfg(feature = "server")]
/// Sends a reliable message to a specific client.
///
/// Note that this message will only be received by the corresponding package on the client,
/// and not by any other packages. You will need to explicitly relay the message to other
/// packages on the client.
///
/// See [Target::ClientTargetedReliable] for details.
fn send_client_targeted_reliable(&self, user_id: String) {
self.send(Target::ClientTargetedReliable(user_id))
}
/// Subscribes to this [Message]. Wrapper around [self::subscribe].
fn subscribe<R: CallbackReturn>(
callback: impl FnMut(MessageContext, Self) -> R + 'static,
) -> Listener {
self::subscribe(callback)
}
}
/// Implemented by all messages sent from the runtime.
pub trait RuntimeMessage: Message {
/// Subscribes to this [Message]. Wrapper around [self::subscribe].
fn subscribe<R: CallbackReturn>(mut callback: impl FnMut(Self) -> R + 'static) -> Listener {
self::subscribe(move |_ctx, msg| callback(msg))
}
}