Struct MessageBody

Source
pub struct MessageBody {
    pub typ: String,
    pub msg_id: u64,
    pub in_reply_to: u64,
    pub extra: Map<String, Value>,
}
Expand description

MessageBody represents the reserved keys for a message body.

Fields§

§typ: String

Message type.

§msg_id: u64

Optional. Message identifier that is unique to the source node.

§in_reply_to: u64

Optional. For request/response, the msg_id of the request.

§extra: Map<String, Value>

All the fields not mentioned here

Implementations§

Source§

impl MessageBody

Source

pub fn new() -> Self

Source

pub fn with_type(self, typ: impl Into<String>) -> Self

Examples found in repository?
examples/echo.rs (line 26)
24    async fn process(&self, runtime: Runtime, req: Message) -> Result<()> {
25        if req.get_type() == "echo" {
26            let echo = req.body.clone().with_type("echo_ok");
27            return runtime.reply(req, echo).await;
28        }
29
30        done(runtime, req)
31    }
Source

pub fn with_reply_to(self, in_reply_to: u64) -> Self

Source

pub fn and_msg_id(self, msg_id: u64) -> Self

Source

pub fn from_extra(extra: Map<String, Value>) -> Self

Source

pub fn is_error(&self) -> bool

Source

pub fn raw(&self) -> Value

use maelstrom::protocol::Message;
use serde_json::Error;

#[derive(serde::Deserialize)]
struct BroadcastRequest {}

fn parse(m: Message) -> Result<BroadcastRequest, Error> {
    serde_json::from_value::<BroadcastRequest>(m.body.raw())
}
Source

pub fn as_obj<'de, T>(&self) -> Result<T>
where T: Deserialize<'de>,

use maelstrom::Result;
use maelstrom::protocol::Message;
use serde_json::Error;

#[derive(serde::Deserialize)]
struct BroadcastRequest {}

fn parse(m: Message) -> Result<BroadcastRequest> {
    m.body.as_obj::<BroadcastRequest>()
}
Examples found in repository?
examples/lin_kv.rs (line 32)
30    async fn process(&self, runtime: Runtime, req: Message) -> Result<()> {
31        let (ctx, _handler) = Context::new();
32        let msg: Result<Request> = req.body.as_obj();
33        match msg {
34            Ok(Request::Read { key }) => {
35                let value = self.s.get(ctx, key.to_string()).await?;
36                return runtime.reply(req, Request::ReadOk { value }).await;
37            }
38            Ok(Request::Write { key, value }) => {
39                self.s.put(ctx, key.to_string(), value).await?;
40                return runtime.reply(req, Request::WriteOk {}).await;
41            }
42            Ok(Request::Cas { key, from, to, put }) => {
43                self.s.cas(ctx, key.to_string(), from, to, put).await?;
44                return runtime.reply(req, Request::CasOk {}).await;
45            }
46            _ => done(runtime, req),
47        }
48    }
More examples
Hide additional examples
examples/broadcast.rs (line 36)
35    async fn process(&self, runtime: Runtime, req: Message) -> Result<()> {
36        let msg: Result<Request> = req.body.as_obj();
37        match msg {
38            Ok(Request::Read {}) => {
39                let data = self.snapshot();
40                let msg = Request::ReadOk { messages: data };
41                return runtime.reply(req, msg).await;
42            }
43            Ok(Request::Broadcast { message: element }) => {
44                if self.try_add(element) {
45                    info!("messages now {}", element);
46                    for node in runtime.neighbours() {
47                        runtime.call_async(node, Request::Broadcast { message: element });
48                    }
49                }
50
51                return runtime.reply_ok(req).await;
52            }
53            Ok(Request::Topology { topology }) => {
54                let neighbours = topology.get(runtime.node_id()).unwrap();
55                self.inner.lock().unwrap().t = neighbours.clone();
56                info!("My neighbors are {:?}", neighbours);
57                return runtime.reply_ok(req).await;
58            }
59            _ => done(runtime, req),
60        }
61    }
examples/g_set.rs (line 32)
31    async fn process(&self, runtime: Runtime, req: Message) -> Result<()> {
32        let msg: Result<Request> = req.body.as_obj();
33        match msg {
34            Ok(Request::Read {}) => {
35                let data = to_seq(&self.s.lock().unwrap());
36                return runtime.reply(req, Request::ReadOk { value: data }).await;
37            }
38            Ok(Request::Add { element }) => {
39                self.s.lock().unwrap().insert(element);
40                return runtime.reply(req, Request::AddOk {}).await;
41            }
42            Ok(Request::ReplicateOne { element }) => {
43                self.s.lock().unwrap().insert(element);
44                return Ok(());
45            }
46            Ok(Request::ReplicateFull { value }) => {
47                let mut s = self.s.lock().unwrap();
48                for v in value {
49                    s.insert(v);
50                }
51                return Ok(());
52            }
53            Ok(Request::Init {}) => {
54                // spawn into tokio (instead of runtime) to not to wait
55                // until it is completed, as it will never be.
56                let (r0, h0) = (runtime.clone(), self.clone());
57                tokio::spawn(async move {
58                    loop {
59                        tokio::time::sleep(Duration::from_secs(5)).await;
60                        debug!("emit replication signal");
61                        let s = h0.s.lock().unwrap();
62                        for n in r0.neighbours() {
63                            let msg = Request::ReplicateFull { value: to_seq(&s) };
64                            drop(r0.send_async(n, msg));
65                        }
66                    }
67                });
68                return Ok(());
69            }
70            _ => done(runtime, req),
71        }
72    }

Trait Implementations§

Source§

impl Clone for MessageBody

Source§

fn clone(&self) -> MessageBody

Returns a duplicate of the value. Read more
1.0.0 · Source§

const fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MessageBody

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for MessageBody

Source§

fn default() -> MessageBody

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for MessageBody

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<&MessageBody> for Error

Source§

fn from(value: &MessageBody) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for MessageBody

Source§

fn eq(&self, other: &MessageBody) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

const fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for MessageBody

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for MessageBody

Source§

impl StructuralPartialEq for MessageBody

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,