Skip to main content

pork_proto/
lib.rs

1//! Shared protocol primitives for applications built on top of `pork`.
2//!
3//! This crate defines the control-plane messages exchanged between a parent
4//! process and a managed child process, plus optional built-in codecs for
5//! serializing those messages on the dedicated control channel.
6//!
7//! # What this crate gives you
8//!
9//! - `protocol::PorkControlMessage` for framework-level coordination
10//! - `protocol::PorkIpcMessage<T>` for wrapping your own protocol payloads
11//! - `protocol::PorkControlCodec` for choosing how control messages are encoded
12//! - feature-gated codec implementations in [`codecs`] for custom payloads
13//! - environment helpers so parent and child agree on the selected codec
14//!
15//! # Feature flags
16//!
17//! - `codec-json` enables the JSON codec implementation
18//! - `codec-postcard` enables the Postcard codec implementation
19//!
20//! You can enable one or both features depending on the transport format you
21//! want to expose to consumers.
22//!
23//! # Example: wrap your own messages
24//!
25//! ```rust
26//! use pork_proto::protocol::{PorkControlMessage, PorkIpcMessage};
27//! use serde::{Deserialize, Serialize};
28//!
29//! #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30//! struct AppMessage {
31//!     command: String,
32//! }
33//!
34//! // Wrap application data without mixing it into the control plane.
35//! let app_message = PorkIpcMessage::Custom(AppMessage {
36//!     command: "ping".to_owned(),
37//! });
38//!
39//! let shutdown = PorkIpcMessage::<AppMessage>::Control(PorkControlMessage::GracefulShutdown);
40//! let restart = PorkIpcMessage::<AppMessage>::Control(PorkControlMessage::Restart);
41//!
42//! assert!(matches!(app_message, PorkIpcMessage::Custom(_)));
43//! assert!(matches!(shutdown, PorkIpcMessage::Control(PorkControlMessage::GracefulShutdown)));
44//! assert!(matches!(restart, PorkIpcMessage::Control(PorkControlMessage::Restart)));
45//! ```
46//!
47//! # Example: encode and decode control messages
48//!
49//! ```rust
50//! # #[cfg(feature = "codec-json")]
51//! # fn main() -> Result<(), pork_proto::protocol::PorkProtoCodecError> {
52//! use pork_proto::protocol::{PorkControlCodec, PorkControlMessage};
53//!
54//! // Host and child must use the same control-message codec.
55//! let codec = PorkControlCodec::Json;
56//! let shutdown = codec.encode_control_message(PorkControlMessage::GracefulShutdown)?;
57//! let restart = codec.encode_restart()?;
58//!
59//! assert_eq!(
60//!     codec.decode_control_message(&shutdown)?,
61//!     PorkControlMessage::GracefulShutdown,
62//! );
63//! assert!(codec.is_restart_message(&restart));
64//! # Ok(())
65//! # }
66//! # #[cfg(not(feature = "codec-json"))]
67//! # fn main() {}
68//! ```
69//!
70//! # Example: serialize your own payload with the JSON codec
71//!
72//! ```rust
73//! # #[cfg(feature = "codec-json")]
74//! # fn main() -> Result<(), pork_proto::protocol::PorkProtoCodecError> {
75//! use pork_proto::codecs::json::JsonCodec;
76//! use pork_proto::protocol::{PorkCodec, PorkIpcMessage};
77//! use serde::{Deserialize, Serialize};
78//!
79//! #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80//! struct AppMessage {
81//!     command: String,
82//! }
83//!
84//! let original = PorkIpcMessage::Custom(AppMessage {
85//!     command: "reload".to_owned(),
86//! });
87//!
88//! // Encode the shared envelope before sending it over the data channel.
89//! let bytes = JsonCodec::encode(&original)?;
90//! let decoded: PorkIpcMessage<AppMessage> = JsonCodec::decode(&bytes)?;
91//!
92//! assert_eq!(decoded, original);
93//! # Ok(())
94//! # }
95//! # #[cfg(not(feature = "codec-json"))]
96//! # fn main() {}
97//! ```
98//!
99//! # Example: host/child control-plane contract
100//!
101//! The host and child must agree on one codec and encode all control-plane
102//! messages (`GracefulShutdown`, `Restart`, `StatusUpdate`) with that codec.
103//!
104//! ```rust
105//! # #[cfg(feature = "codec-json")]
106//! # fn main() -> Result<(), pork_proto::protocol::PorkProtoCodecError> {
107//! use pork_proto::protocol::{PorkChildStatus, PorkControlCodec, PorkControlMessage, PorkStatusUpdate};
108//!
109//! // Status updates travel over the dedicated control channel.
110//! let codec = PorkControlCodec::Json;
111//! let status_payload = codec.encode_control_message(PorkControlMessage::StatusUpdate(
112//!     PorkStatusUpdate {
113//!         status: PorkChildStatus::Running,
114//!         timestamp_ms: 123,
115//!     },
116//! ))?;
117//!
118//! assert!(matches!(
119//!     codec.decode_control_message(&status_payload)?,
120//!     PorkControlMessage::StatusUpdate(PorkStatusUpdate {
121//!         status: PorkChildStatus::Running,
122//!         timestamp_ms: 123,
123//!     })
124//! ));
125//! # Ok(())
126//! # }
127//! # #[cfg(not(feature = "codec-json"))]
128//! # fn main() {}
129//! ```
130//!
131//! # Example: agree on a codec through the environment
132//!
133//! The parent process can write the selected codec into
134//! `protocol::PORK_CONTROL_CODEC_ENV`, and the child can read it back with
135//! `protocol::control_codec_from_env()`.
136//!
137//! ```rust
138//! use pork_proto::protocol::{control_codec_from_env, PORK_CONTROL_CODEC_ENV, PorkControlCodec};
139//!
140//! // In a real process bootstrap flow, the parent would set this before spawning the child.
141//! unsafe {
142//!     std::env::set_var(PORK_CONTROL_CODEC_ENV, "postcard");
143//! }
144//!
145//! // The child resolves the codec selected by the parent process.
146//! let codec = control_codec_from_env()?;
147//! assert_eq!(codec, PorkControlCodec::Postcard);
148//!
149//! unsafe {
150//!     std::env::remove_var(PORK_CONTROL_CODEC_ENV);
151//! }
152//! # Ok::<(), pork_proto::protocol::ParsePorkControlCodecError>(())
153//! ```
154//!
155//! If the environment variable is missing, `control_codec_from_env()` falls back
156//! to `PorkControlCodec::Json`.
157#![deny(missing_docs)]
158#![deny(clippy::unwrap_used)]
159#![deny(clippy::expect_used)]
160#![deny(unsafe_code)]
161
162/// Feature-gated codec implementations for encoding and decoding
163/// [`protocol::PorkIpcMessage`] payloads through concrete [`protocol::PorkCodec`]
164/// implementations such as [`codecs::json::JsonCodec`] and
165/// [`codecs::postcard::PostcardCodec`].
166pub mod codecs;
167
168/// Shared protocol models, codec selection, parsing, and environment helpers.
169pub mod protocol {
170    use std::fmt;
171    use std::str::FromStr;
172
173    use serde::{Deserialize, Serialize};
174
175    /// Environment variable used by parent and child processes to agree on the
176    /// control-message codec.
177    pub const PORK_CONTROL_CODEC_ENV: &str = "PORK_CONTROL_CODEC";
178
179    /// Lifecycle state of a managed child process.
180    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
181    pub enum PorkChildStatus {
182        /// The managed child is fully running and available.
183        Running,
184        /// The managed child is in the process of starting.
185        Starting,
186        /// The managed child is in the process of stopping.
187        Stopping,
188        /// The managed child is fully stopped.
189        Stopped,
190        /// The managed child is in the process of restarting.
191        Restarting,
192    }
193
194    /// Child process status update sent over the control channel.
195    ///
196    /// Contains the current lifecycle state and a child-generated timestamp. Hosts
197    /// may cache or interpret these updates however they choose; `pork` itself stores
198    /// only the latest reported update.
199    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
200    pub struct PorkStatusUpdate {
201        /// Current lifecycle status of the child process.
202        pub status: PorkChildStatus,
203        /// Unix timestamp (milliseconds) when this status update was generated.
204        pub timestamp_ms: u64,
205    }
206
207    /// Host-to-child and child-to-host control-plane messages shared by all
208    /// Pork-based IPC protocols.
209    ///
210    /// Control messages travel over a dedicated control channel, separate from
211    /// application data payloads. This provides a clean separation of concerns and
212    /// allows framework-level coordination to be independent of application logic.
213    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214    pub enum PorkControlMessage {
215        /// Host to child: request a graceful shutdown.
216        GracefulShutdown,
217        /// Host to child: request a graceful exit before the host starts a replacement process.
218        Restart,
219        /// Child to host: report the current lifecycle state and timestamp.
220        StatusUpdate(PorkStatusUpdate),
221    }
222
223    /// Shared wrapper for Pork IPC traffic.
224    ///
225    /// `Control` is reserved for framework-level coordination between host and
226    /// child. `Custom` allows applications to embed their own protocol payloads
227    /// while reusing the shared control plane.
228    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
229    pub enum PorkIpcMessage<T> {
230        /// A framework-defined control message.
231        Control(PorkControlMessage),
232        /// An application-defined payload.
233        Custom(T),
234    }
235
236    impl<T> PorkIpcMessage<T> {
237        /// Creates a new framework-level control message wrapper.
238        pub fn control(message: PorkControlMessage) -> Self {
239            Self::Control(message)
240        }
241
242        /// Creates a new application-defined payload wrapper.
243        pub fn custom(message: T) -> Self {
244            Self::Custom(message)
245        }
246
247        /// Returns the wrapped control message when this is a control envelope.
248        pub fn as_control(&self) -> Option<&PorkControlMessage> {
249            match self {
250                Self::Control(message) => Some(message),
251                Self::Custom(_) => None,
252            }
253        }
254
255        /// Returns the wrapped custom payload when this is an application envelope.
256        pub fn as_custom(&self) -> Option<&T> {
257            match self {
258                Self::Control(_) => None,
259                Self::Custom(message) => Some(message),
260            }
261        }
262
263        /// Returns `true` when this envelope contains a framework control message.
264        pub fn is_control(&self) -> bool {
265            matches!(self, Self::Control(_))
266        }
267
268        /// Returns `true` when this envelope contains an application-defined payload.
269        pub fn is_custom(&self) -> bool {
270            matches!(self, Self::Custom(_))
271        }
272
273        /// Converts the envelope into the wrapped custom payload, if present.
274        pub fn into_custom(self) -> Option<T> {
275            match self {
276                Self::Control(_) => None,
277                Self::Custom(message) => Some(message),
278            }
279        }
280    }
281
282    /// Errors returned by built-in codec helpers.
283    #[derive(Debug)]
284    pub enum PorkProtoCodecError {
285        /// JSON encoding or decoding failed.
286        #[cfg(feature = "codec-json")]
287        Json(serde_json::Error),
288        /// Postcard encoding or decoding failed.
289        #[cfg(feature = "codec-postcard")]
290        Postcard(String),
291        /// The requested codec is unavailable because the corresponding feature
292        /// is disabled or the payload shape does not match the requested
293        /// control-message operation.
294        UnsupportedCodec,
295    }
296
297    impl fmt::Display for PorkProtoCodecError {
298        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299            match self {
300                #[cfg(feature = "codec-json")]
301                Self::Json(error) => write!(f, "json codec error: {error}"),
302                #[cfg(feature = "codec-postcard")]
303                Self::Postcard(error) => write!(f, "postcard codec error: {error}"),
304                Self::UnsupportedCodec => write!(f, "requested codec is not enabled"),
305            }
306        }
307    }
308
309    impl std::error::Error for PorkProtoCodecError {}
310
311    #[cfg(feature = "codec-json")]
312    impl From<serde_json::Error> for PorkProtoCodecError {
313        fn from(value: serde_json::Error) -> Self {
314            Self::Json(value)
315        }
316    }
317
318    #[cfg(feature = "codec-postcard")]
319    impl PorkProtoCodecError {
320        pub(crate) fn from_postcard_error<E>(value: E) -> Self
321        where
322            E: fmt::Display,
323        {
324            Self::Postcard(value.to_string())
325        }
326    }
327
328    /// Built-in control-message codec selection shared between host and child.
329    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
330    pub enum PorkControlCodec {
331        /// Encode control messages as JSON.
332        #[default]
333        Json,
334        /// Encode control messages as Postcard.
335        Postcard,
336    }
337
338    impl PorkControlCodec {
339        /// Returns the canonical environment-variable value for this codec.
340        pub fn as_env_value(self) -> &'static str {
341            match self {
342                Self::Json => "json",
343                Self::Postcard => "postcard",
344            }
345        }
346
347        /// Serializes a control message using the selected codec.
348        pub fn encode_control_message(
349            self,
350            message: PorkControlMessage,
351        ) -> Result<Vec<u8>, PorkProtoCodecError> {
352            let message = PorkIpcMessage::<Vec<u8>>::control(message);
353
354            match self {
355                Self::Json => {
356                    #[cfg(feature = "codec-json")]
357                    {
358                        crate::codecs::json::JsonCodec::encode(&message)
359                    }
360                    #[cfg(not(feature = "codec-json"))]
361                    {
362                        let _ = message;
363                        Err(PorkProtoCodecError::UnsupportedCodec)
364                    }
365                }
366                Self::Postcard => {
367                    #[cfg(feature = "codec-postcard")]
368                    {
369                        crate::codecs::postcard::PostcardCodec::encode(&message)
370                    }
371                    #[cfg(not(feature = "codec-postcard"))]
372                    {
373                        let _ = message;
374                        Err(PorkProtoCodecError::UnsupportedCodec)
375                    }
376                }
377            }
378        }
379
380        /// Deserializes a control message using the selected codec.
381        pub fn decode_control_message(
382            self,
383            bytes: &[u8],
384        ) -> Result<PorkControlMessage, PorkProtoCodecError> {
385            match self {
386                Self::Json => {
387                    #[cfg(feature = "codec-json")]
388                    {
389                        match crate::codecs::json::JsonCodec::decode::<Vec<u8>>(bytes)? {
390                            PorkIpcMessage::Control(control) => Ok(control),
391                            PorkIpcMessage::Custom(_) => Err(PorkProtoCodecError::UnsupportedCodec),
392                        }
393                    }
394                    #[cfg(not(feature = "codec-json"))]
395                    {
396                        let _ = bytes;
397                        Err(PorkProtoCodecError::UnsupportedCodec)
398                    }
399                }
400                Self::Postcard => {
401                    #[cfg(feature = "codec-postcard")]
402                    {
403                        match crate::codecs::postcard::PostcardCodec::decode::<Vec<u8>>(bytes)? {
404                            PorkIpcMessage::Control(control) => Ok(control),
405                            PorkIpcMessage::Custom(_) => Err(PorkProtoCodecError::UnsupportedCodec),
406                        }
407                    }
408                    #[cfg(not(feature = "codec-postcard"))]
409                    {
410                        let _ = bytes;
411                        Err(PorkProtoCodecError::UnsupportedCodec)
412                    }
413                }
414            }
415        }
416
417        /// Returns `true` when this codec is currently available in the compiled crate.
418        ///
419        /// A codec is available only when its corresponding feature flag is enabled.
420        pub fn is_available(self) -> bool {
421            match self {
422                Self::Json => cfg!(feature = "codec-json"),
423                Self::Postcard => cfg!(feature = "codec-postcard"),
424            }
425        }
426
427        /// Returns all built-in codecs that are available in the compiled crate.
428        pub fn available() -> Vec<Self> {
429            [Self::Json, Self::Postcard]
430                .into_iter()
431                .filter(|codec| codec.is_available())
432                .collect()
433        }
434
435        /// Returns `true` when the given message is a graceful-shutdown control message.
436        pub fn is_graceful_shutdown(self, message: &PorkControlMessage) -> bool {
437            let _ = self;
438            matches!(message, PorkControlMessage::GracefulShutdown)
439        }
440
441        /// Serializes a graceful-shutdown control message using the selected codec.
442        pub fn encode_graceful_shutdown(self) -> Result<Vec<u8>, PorkProtoCodecError> {
443            self.encode_control_message(PorkControlMessage::GracefulShutdown)
444        }
445
446        /// Returns `true` when the given message requests a restart.
447        pub fn is_restart(self, message: &PorkControlMessage) -> bool {
448            let _ = self;
449            matches!(message, PorkControlMessage::Restart)
450        }
451
452        /// Serializes a restart control message using the selected codec.
453        pub fn encode_restart(self) -> Result<Vec<u8>, PorkProtoCodecError> {
454            self.encode_control_message(PorkControlMessage::Restart)
455        }
456
457        /// Returns `true` when the given bytes decode to a graceful-shutdown
458        /// control message.
459        pub fn is_graceful_shutdown_message(self, bytes: &[u8]) -> bool {
460            matches!(
461                self.decode_control_message(bytes),
462                Ok(message) if self.is_graceful_shutdown(&message)
463            )
464        }
465
466        /// Returns `true` when the given bytes decode to a restart control message.
467        pub fn is_restart_message(self, bytes: &[u8]) -> bool {
468            matches!(
469                self.decode_control_message(bytes),
470                Ok(message) if self.is_restart(&message)
471            )
472        }
473    }
474
475    impl fmt::Display for PorkControlCodec {
476        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477            f.write_str(self.as_env_value())
478        }
479    }
480
481    /// Error returned when parsing a [`PorkControlCodec`] from a string fails.
482    #[derive(Debug, Clone, PartialEq, Eq)]
483    pub struct ParsePorkControlCodecError {
484        value: String,
485    }
486
487    impl ParsePorkControlCodecError {
488        /// Returns the unsupported codec value that failed to parse.
489        pub fn value(&self) -> &str {
490            &self.value
491        }
492    }
493
494    impl fmt::Display for ParsePorkControlCodecError {
495        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
496            write!(f, "unsupported control codec '{}'", self.value)
497        }
498    }
499
500    impl std::error::Error for ParsePorkControlCodecError {}
501
502    impl FromStr for PorkControlCodec {
503        type Err = ParsePorkControlCodecError;
504
505        fn from_str(value: &str) -> Result<Self, Self::Err> {
506            match value {
507                "json" => Ok(Self::Json),
508                "postcard" => Ok(Self::Postcard),
509                _ => Err(ParsePorkControlCodecError {
510                    value: value.to_owned(),
511                }),
512            }
513        }
514    }
515
516    /// Resolves the control codec from [`PORK_CONTROL_CODEC_ENV`].
517    ///
518    /// If the variable is missing, this function returns [`PorkControlCodec::Json`].
519    pub fn control_codec_from_env() -> Result<PorkControlCodec, ParsePorkControlCodecError> {
520        match std::env::var(PORK_CONTROL_CODEC_ENV) {
521            Ok(value) => value.parse(),
522            Err(_) => Ok(PorkControlCodec::default()),
523        }
524    }
525
526    /// Shared codec trait for feature-gated built-in encoders.
527    ///
528    /// Implementations are provided by the built-in codec marker types in the
529    /// [`crate::codecs`] module when the respective feature is enabled.
530    pub trait PorkCodec {
531        /// Serializes a wrapped IPC message into the codec's wire format.
532        fn encode<T>(message: &PorkIpcMessage<T>) -> Result<Vec<u8>, PorkProtoCodecError>
533        where
534            T: Serialize;
535
536        /// Deserializes a wrapped IPC message from the codec's wire format.
537        fn decode<T>(bytes: &[u8]) -> Result<PorkIpcMessage<T>, PorkProtoCodecError>
538        where
539            T: for<'de> Deserialize<'de>;
540    }
541}