waxosuit_guest/
msg.rs

1// Copyright 2015-2019 Capital One Services, LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! # Message Broker
16//!
17//! This module contains the message broker struct through which guest modules access
18//! the currently bound `wascap:messaging` capability provider
19
20use crate::protobytes;
21use wapc_guest::host_call;
22
23use crate::Result;
24use codec::messaging::{
25    BrokerMessage, PublishMessage, RequestMessage, OP_PERFORM_REQUEST, OP_PUBLISH_MESSAGE,
26};
27use waxosuit_codec as codec;
28
29/// Exposes message broker functionality to guest modules
30pub struct MessageBroker {}
31
32impl MessageBroker {
33    pub(crate) fn new() -> MessageBroker {
34        MessageBroker {}
35    }
36
37    /// Publishes a new message on the given subject with an optional reply-to
38    pub fn publish(&self, subject: &str, reply_to: Option<&str>, payload: &[u8]) -> Result<()> {
39        let cmd = PublishMessage {
40            message: Some(BrokerMessage {
41                subject: subject.to_string(),
42                reply_to: reply_to.map_or("".to_string(), |r| r.to_string()),
43                body: payload.to_vec(),
44            }),
45        };
46
47        host_call(OP_PUBLISH_MESSAGE, &protobytes(cmd)?).map(|_vec| ())
48    }
49
50    /// Publishes a message on the given subject and awaits a reply on an inbox subject
51    pub fn request(&self, subject: &str, payload: &[u8], timeout_ms: u64) -> Result<Vec<u8>> {
52        let cmd = RequestMessage {
53            subject: subject.to_string(),
54            timeout_ms: timeout_ms as _,
55            body: payload.to_vec(),
56        };
57
58        // The broker plugin applies no wrapper around the response from the broker, the
59        // raw payload is delivered.
60        host_call(OP_PERFORM_REQUEST, &protobytes(cmd)?)
61    }
62}