postcard_rpc/lib.rs
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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
//! The goal of `postcard-rpc` is to make it easier for a
//! host PC to talk to a constrained device, like a microcontroller.
//!
//! See [the repo] for examples
//!
//! [the repo]: https://github.com/jamesmunns/postcard-rpc
//! [the overview]: https://github.com/jamesmunns/postcard-rpc/blob/main/docs/overview.md
//!
//! ## Architecture overview
//!
//! ```text
//! ┌──────────┐ ┌─────────┐ ┌───────────┐
//! │ Endpoint │ │ Publish │ │ Subscribe │
//! └──────────┘ └─────────┘ └───────────┘
//! │ ▲ message│ │ ▲
//! ┌────────┐ rqst│ │resp │ subscribe│ │messages
//! ┌─┤ CLIENT ├─────┼─────┼──────────────┼────────────────┼────────┼──┐
//! │ └────────┘ ▼ │ ▼ ▼ │ │
//! │ ┌─────────────────────────────────────────────────────┐ │ │
//! │ │ HostClient │ │ │
//! │ └─────────────────────────────────────────────────────┘ │ │
//! │ │ │ ▲ │ | │
//! │ │ │ │ │ │ │
//! │ │ │ │ ▼ │ │
//! │ │ │ ┌──────────────┬──────────────┐│
//! │ │ └─────▶│ Pending Resp │ Subscription ││
//! │ │ └──────────────┴──────────────┘│
//! │ │ ▲ ▲ │
//! │ │ └───────┬──────┘ │
//! │ ▼ │ │
//! │ ┌────────────────────┐ ┌────────────────────┐ │
//! │ ││ Task: out_worker │ │ Task: in_worker ▲│ │
//! │ ├┼───────────────────┤ ├───────────────────┼┤ │
//! │ │▼ Trait: WireTx │ │ Trait: WireRx ││ │
//! └──────┴────────────────────┴────────────┴────────────────────┴────┘
//! │ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ▲
//! │ The Server + Client WireRx │
//! │ │ and WireTx traits can be │ │
//! │ impl'd for any wire │
//! │ │ transport like USB, TCP, │ │
//! │ I2C, UART, etc. │
//! ▼ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ │
//! ┌─────┬────────────────────┬────────────┬────────────────────┬─────┐
//! │ ││ Trait: WireRx │ │ Trait: WireTx ▲│ │
//! │ ├┼───────────────────┤ ├───────────────────┼┤ │
//! │ ││ Server │ ┌───▶│ Sender ││ │
//! │ ├┼───────────────────┤ │ └────────────────────┘ │
//! │ │▼ Macro: Dispatch │ │ ▲ │
//! │ └────────────────────┘ │ │ │
//! │ ┌─────────┐ │ ┌──────────┐ │ ┌───────────┐ │ ┌───────────┐ │
//! │ │ Topic │ │ │ Endpoint │ │ │ Publisher │ │ │ Publisher │ │
//! │ │ fn │◀┼▶│ async fn │────┤ │ Task │─┼─│ Task │ │
//! │ │ Handler │ │ │ Handler │ │ └───────────┘ │ └───────────┘ │
//! │ └─────────┘ │ └──────────┘ │ │ │
//! │ ┌─────────┐ │ ┌──────────┐ │ ┌───────────┐ │ ┌───────────┐ │
//! │ │ Topic │ │ │ Endpoint │ │ │ Publisher │ │ │ Publisher │ │
//! │ │async fn │◀┴▶│ task │────┘ │ Task │─┴─│ Task │ │
//! │ │ Handler │ │ Handler │ └───────────┘ └───────────┘ │
//! │ └─────────┘ └──────────┘ │
//! │ ┌────────┐ │
//! └─┤ SERVER ├───────────────────────────────────────────────────────┘
//! └────────┘
//! ```
//!
//! ## Defining a schema
//!
//! Typically, you will define your "wire types" in a shared schema crate. This
//! crate essentially defines the protocol used between two or more devices.
//!
//! A schema consists of a couple of necessary items:
//!
//! ### Wire types
//!
//! We will need to define all of the types that we will use within our protocol.
//! We specify normal Rust types, which will need to implement or derive three
//! important traits:
//!
//! * [`serde`]'s [`Serialize`] trait - which defines how we can
//! convert a type into bytes on the wire
//! * [`serde`]'s [`Deserialize`] trait - which defines how we
//! can convert bytes on the wire into a type
//! * [`postcard_schema`]'s [`Schema`] trait - which generates a reflection-style
//! schema value for a given type.
//!
//! ### Endpoints
//!
//! Now that we have some basic types that will be used on the wire, we need
//! to start building our protocol. The first thing we can build are [Endpoint]s,
//! which represent a bidirectional "Request"/"Response" relationship. One of our
//! devices will act as a Client (who makes a request, and receives a response),
//! and the other device will act as a Server (who receives a request, and sends
//! a response). Every request should be followed (eventually) by exactly one response.
//!
//! An endpoint consists of:
//!
//! * The type of the Request
//! * The type of the Response
//! * A string "path", like an HTTP URI that uniquely identifies the endpoint.
//!
//! ### Topics
//!
//! Sometimes, you would just like to send data in a single direction, with no
//! response. This could be for reasons like asynchronous logging, blindly sending
//! sensor data periodically, or any other reason you can think of.
//!
//! Topics have no "client" or "server" role, either device may decide to send a
//! message on a given topic.
//!
//! A topic consists of:
//!
//! * The type of the Message
//! * A string "path", like an HTTP URI that uniquely identifies the topic.
#![cfg_attr(not(any(test, feature = "use-std")), no_std)]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
use header::{VarKey, VarKeyKind};
use postcard_schema::{schema::NamedType, Schema};
use serde::{Deserialize, Serialize};
pub mod hash;
pub mod header;
mod macros;
pub mod server;
pub mod standard_icd;
pub mod uniques;
#[cfg(feature = "cobs")]
pub mod accumulator;
#[cfg(feature = "use-std")]
pub mod host_client;
#[cfg(any(test, feature = "test-utils"))]
pub mod test_utils;
/// The `Key` uniquely identifies what "kind" of message this is.
///
/// In order to generate it, `postcard-rpc` takes two pieces of data:
///
/// * a `&str` "path" URI, similar to how you would use URIs as part of an HTTP path
/// * The schema of the message type itself, using the experimental [schema] feature of `postcard`.
///
/// [schema]: https://docs.rs/postcard/latest/postcard/experimental/index.html#message-schema-generation
///
/// Specifically, we use [`Fnv1a`](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function),
/// and produce a 64-bit digest, by first hashing the path, then hashing the
/// schema. Fnv1a is a non-cryptographic hash function, designed to be reasonably
/// efficient to compute even on small platforms like microcontrollers.
///
/// Changing **anything** about *either* of the path or the schema will produce
/// a drastically different `Key` value.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Serialize, Deserialize, Hash, Schema)]
pub struct Key([u8; 8]);
impl core::fmt::Debug for Key {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Key(")?;
for b in self.0.iter() {
f.write_fmt(format_args!("{} ", b))?;
}
f.write_str(")")
}
}
impl Key {
/// Create a Key for the given type and path
pub const fn for_path<T>(path: &str) -> Self
where
T: Schema + ?Sized,
{
Key(crate::hash::fnv1a64::hash_ty_path::<T>(path))
}
/// Unsafely create a key from a given 8-byte value
///
/// ## Safety
///
/// This MUST only be used with pre-calculated values. Incorrectly
/// created keys could lead to the improper deserialization of
/// messages.
pub const unsafe fn from_bytes(bytes: [u8; 8]) -> Self {
Self(bytes)
}
/// Extract the bytes making up this key
pub const fn to_bytes(&self) -> [u8; 8] {
self.0
}
/// Compare 2 keys in const context.
pub const fn const_cmp(&self, other: &Self) -> bool {
let mut i = 0;
while i < self.0.len() {
if self.0[i] != other.0[i] {
return false;
}
i += 1;
}
true
}
}
#[cfg(feature = "use-std")]
mod key_owned {
use super::*;
use postcard_schema::schema::owned::OwnedNamedType;
impl Key {
/// Calculate the Key for the given path and [`OwnedNamedType`]
pub fn for_owned_schema_path(path: &str, nt: &OwnedNamedType) -> Key {
Key(crate::hash::fnv1a64_owned::hash_ty_path_owned(path, nt))
}
}
}
/// A compacted 2-byte key
///
/// This is defined specifically as the following conversion:
///
/// * Key8 bytes (`[u8; 8]`): `[a, b, c, d, e, f, g, h]`
/// * Key4 bytes (`u8`): `a ^ b ^ c ^ d ^ e ^ f ^ g ^ h`
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Key1(u8);
/// A compacted 2-byte key
///
/// This is defined specifically as the following conversion:
///
/// * Key8 bytes (`[u8; 8]`): `[a, b, c, d, e, f, g, h]`
/// * Key4 bytes (`[u8; 2]`): `[a ^ b ^ c ^ d, e ^ f ^ g ^ h]`
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Key2([u8; 2]);
/// A compacted 4-byte key
///
/// This is defined specifically as the following conversion:
///
/// * Key8 bytes (`[u8; 8]`): `[a, b, c, d, e, f, g, h]`
/// * Key4 bytes (`[u8; 4]`): `[a ^ b, c ^ d, e ^ f, g ^ h]`
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Key4([u8; 4]);
impl Key1 {
/// Convert from a 2-byte key
///
/// This is a lossy conversion, and can never fail
#[inline]
pub const fn from_key2(value: Key2) -> Self {
let [a, b] = value.0;
Self(a ^ b)
}
/// Convert from a 4-byte key
///
/// This is a lossy conversion, and can never fail
#[inline]
pub const fn from_key4(value: Key4) -> Self {
let [a, b, c, d] = value.0;
Self(a ^ b ^ c ^ d)
}
/// Convert from a full size 8-byte key
///
/// This is a lossy conversion, and can never fail
#[inline]
pub const fn from_key8(value: Key) -> Self {
let [a, b, c, d, e, f, g, h] = value.0;
Self(a ^ b ^ c ^ d ^ e ^ f ^ g ^ h)
}
/// Convert to the inner byte representation
#[inline]
pub const fn to_bytes(&self) -> u8 {
self.0
}
/// Create a `Key1` from a [`VarKey`]
///
/// This method can never fail, but has the same API as other key
/// types for consistency reasons.
#[inline]
pub fn try_from_varkey(value: &VarKey) -> Option<Self> {
Some(match value {
VarKey::Key1(key1) => *key1,
VarKey::Key2(key2) => Key1::from_key2(*key2),
VarKey::Key4(key4) => Key1::from_key4(*key4),
VarKey::Key8(key) => Key1::from_key8(*key),
})
}
}
impl Key2 {
/// Convert from a 4-byte key
///
/// This is a lossy conversion, and can never fail
#[inline]
pub const fn from_key4(value: Key4) -> Self {
let [a, b, c, d] = value.0;
Self([a ^ b, c ^ d])
}
/// Convert from a full size 8-byte key
///
/// This is a lossy conversion, and can never fail
#[inline]
pub const fn from_key8(value: Key) -> Self {
let [a, b, c, d, e, f, g, h] = value.0;
Self([a ^ b ^ c ^ d, e ^ f ^ g ^ h])
}
/// Convert to the inner byte representation
#[inline]
pub const fn to_bytes(&self) -> [u8; 2] {
self.0
}
/// Attempt to create a [`Key2`] from a [`VarKey`].
///
/// Only succeeds if `value` is a `VarKey::Key2`, `VarKey::Key4`, or `VarKey::Key8`.
#[inline]
pub fn try_from_varkey(value: &VarKey) -> Option<Self> {
Some(match value {
VarKey::Key1(_) => return None,
VarKey::Key2(key2) => *key2,
VarKey::Key4(key4) => Key2::from_key4(*key4),
VarKey::Key8(key) => Key2::from_key8(*key),
})
}
}
impl Key4 {
/// Convert from a full size 8-byte key
///
/// This is a lossy conversion, and can never fail
#[inline]
pub const fn from_key8(value: Key) -> Self {
let [a, b, c, d, e, f, g, h] = value.0;
Self([a ^ b, c ^ d, e ^ f, g ^ h])
}
/// Convert to the inner byte representation
#[inline]
pub const fn to_bytes(&self) -> [u8; 4] {
self.0
}
/// Attempt to create a [`Key4`] from a [`VarKey`].
///
/// Only succeeds if `value` is a `VarKey::Key4` or `VarKey::Key8`.
#[inline]
pub fn try_from_varkey(value: &VarKey) -> Option<Self> {
Some(match value {
VarKey::Key1(_) => return None,
VarKey::Key2(_) => return None,
VarKey::Key4(key4) => *key4,
VarKey::Key8(key) => Key4::from_key8(*key),
})
}
}
impl Key {
/// This is an identity function, used for consistency
#[inline]
pub const fn from_key8(value: Key) -> Self {
value
}
/// Attempt to create a [`Key`] from a [`VarKey`].
///
/// Only succeeds if `value` is a `VarKey::Key8`.
#[inline]
pub fn try_from_varkey(value: &VarKey) -> Option<Self> {
match value {
VarKey::Key8(key) => Some(*key),
_ => None,
}
}
}
impl From<Key2> for Key1 {
fn from(value: Key2) -> Self {
Self::from_key2(value)
}
}
impl From<Key4> for Key1 {
fn from(value: Key4) -> Self {
Self::from_key4(value)
}
}
impl From<Key> for Key1 {
fn from(value: Key) -> Self {
Self::from_key8(value)
}
}
impl From<Key4> for Key2 {
fn from(value: Key4) -> Self {
Self::from_key4(value)
}
}
impl From<Key> for Key2 {
fn from(value: Key) -> Self {
Self::from_key8(value)
}
}
impl From<Key> for Key4 {
fn from(value: Key) -> Self {
Self::from_key8(value)
}
}
/// A marker trait denoting a single endpoint
///
/// Typically used with the [endpoint] macro.
pub trait Endpoint {
/// The type of the Request (client to server)
type Request: Schema;
/// The type of the Response (server to client)
type Response: Schema;
/// The path associated with this Endpoint
const PATH: &'static str;
/// The unique [Key] identifying the Request
const REQ_KEY: Key;
/// The unique [Key4] identifying the Request
const REQ_KEY4: Key4 = Key4::from_key8(Self::REQ_KEY);
/// The unique [Key2] identifying the Request
const REQ_KEY2: Key2 = Key2::from_key8(Self::REQ_KEY);
/// The unique [Key1] identifying the Request
const REQ_KEY1: Key1 = Key1::from_key8(Self::REQ_KEY);
/// The unique [Key] identifying the Response
const RESP_KEY: Key;
/// The unique [Key4] identifying the Response
const RESP_KEY4: Key4 = Key4::from_key8(Self::RESP_KEY);
/// The unique [Key2] identifying the Response
const RESP_KEY2: Key2 = Key2::from_key8(Self::RESP_KEY);
/// The unique [Key1] identifying the Response
const RESP_KEY1: Key1 = Key1::from_key8(Self::RESP_KEY);
}
/// A marker trait denoting a single topic
///
/// Unlike [Endpoint]s, [Topic]s are unidirectional, and can be sent
/// at any time asynchronously. Messages may be sent client to server,
/// or server to client.
///
/// Typically used with the [topic] macro.
pub trait Topic {
/// The type of the Message (unidirectional)
type Message: Schema + ?Sized;
/// The path associated with this Topic
const PATH: &'static str;
/// The unique [Key] identifying the Message
const TOPIC_KEY: Key;
/// The unique [Key4] identifying the Message
const TOPIC_KEY4: Key4 = Key4::from_key8(Self::TOPIC_KEY);
/// The unique [Key2] identifying the Message
const TOPIC_KEY2: Key2 = Key2::from_key8(Self::TOPIC_KEY);
/// The unique [Key2] identifying the Message
const TOPIC_KEY1: Key1 = Key1::from_key8(Self::TOPIC_KEY);
}
/// The direction of topic messages
#[derive(Debug, PartialEq, Clone, Copy, Schema, Serialize, Deserialize)]
pub enum TopicDirection {
/// Topic messages sent TO the SERVER, FROM the CLIENT
ToServer,
/// Topic messages sent TO the CLIENT, FROM the SERVER
ToClient,
}
/// An overview of all topics (in and out) and endpoints
///
/// Typically generated by the [`define_dispatch!()`] macro. Contains a list
/// of all unique types across endpoints and topics, as well as the endpoints,
/// topics in (client to server), topics out (server to client), as well as a
/// calculated minimum key length required to avoid collisions in either the in
/// or out direction.
pub struct DeviceMap {
/// The set of unique types used by all endpoints and topics in this map
pub types: &'static [&'static NamedType],
/// The list of endpoints by path string, request key, and response key
pub endpoints: &'static [(&'static str, Key, Key)],
/// The list of topics (client to server) by path string and topic key
pub topics_in: &'static [(&'static str, Key)],
/// The list of topics (server to client) by path string and topic key
pub topics_out: &'static [(&'static str, Key)],
/// The minimum key size required to avoid hash collisions
pub min_key_len: VarKeyKind,
}
/// An overview of a list of endpoints
///
/// Typically generated by the [`endpoints!()`] macro. Contains a list of
/// all unique types used by a list of endpoints, as well as the list of these
/// endpoints by path, request key, and response key
#[derive(Debug)]
pub struct EndpointMap {
/// The set of unique types used by all endpoints in this map
pub types: &'static [&'static NamedType],
/// The list of endpoints by path string, request key, and response key
pub endpoints: &'static [(&'static str, Key, Key)],
}
/// An overview of a list of topics
///
/// Typically generated by the [`topics!()`] macro. Contains a list of all
/// unique types used by a list of topics as well as the list of the topics
/// by path and key
#[derive(Debug)]
pub struct TopicMap {
/// The direction of these topic messages
pub direction: TopicDirection,
/// The set of unique types used by all topics in this map
pub types: &'static [&'static NamedType],
/// The list of topics by path string and topic key
pub topics: &'static [(&'static str, Key)],
}