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
//! Support for the delegation protocol via MQTT.

use bytes::Buf;
use futures::{join, select, FutureExt};
use std::thread::{self, Thread};

use super::{transport, transport_messages, InputMessage};
use crate::{delegation, module, Error, Result};

//  _              _
// | |            (_)
// | |_ ___  _ __  _  ___ ___
// | __/ _ \| '_ \| |/ __/ __|
// | || (_) | |_) | | (__\__ \
//  \__\___/| .__/|_|\___|___/
//          | |
//          |_|

mod topics
{
  pub const CANCEL_ACCEPTANCE: &str = "delegation/cancel_acceptance";
  pub const SEND_CFP: &str = "delegation/send_cfp";
  pub const SEND_EXECUTION_ACCEPTANCE: &str = "delegation/send_execution_acceptance";
  pub const SEND_EXECUTION_STATUS: &str = "delegation/send_execution_status";
  pub const SEND_OFFER: &str = "delegation/send_offer";
  pub const SEND_PROPOSAL_ACCEPTANCE: &str = "delegation/send_proposal_acceptance";
}

//   ____        _   _
//  / __ \      | | (_)
//  | |  | |_ __ | |_ _  ___  _ __  ___
//  | |  | | '_ \| __| |/ _ \| '_ \/ __|
//  | |__| | |_) | |_| | (_) | | | \__ \
//   \____/| .__/ \__|_|\___/|_| |_|___/
//         | |
//         |_|

/// MQTT transport options
pub struct Options
{
  node_id: String,
  hostname: String,
  port: u16,
}

impl Options
{
  /// Create new options. `node_id` should be unique. `hostname` and `port`
  /// correspond to the MQTT broker used for the delegation.
  pub fn new(node_id: String, hostname: String, port: u16) -> Self
  {
    Self {
      node_id,
      hostname,
      port,
    }
  }
}

//  ______
// |  ____|
// | |__   _ __ _ __ ___  _ __
// |  __| | '__| '__/ _ \| '__|
// | |____| |  | | | (_) | |
// |______|_|  |_|  \___/|_|

impl From<rumqttc::v5::ClientError> for Error
{
  fn from(value: rumqttc::v5::ClientError) -> Self
  {
    Error::TransportError(value.to_string())
  }
}

//  __  __               _           _
// |  \/  |   ___     __| |  _   _  | |   ___
// | |\/| |  / _ \   / _` | | | | | | |  / _ \
// | |  | | | (_) | | (_| | | |_| | | | |  __/
// |_|  |_|  \___/   \__,_|  \__,_| |_|  \___|

/// MQTT Module
pub struct Module {}

impl Module
{
  fn send_message<TM: serde::Serialize>(
    client: &rumqttc::v5::AsyncClient,
    topic_name: &str,
    tm: TM,
  ) -> crate::Result<()>
  {
    client.try_publish_with_properties(
      topic_name,
      rumqttc::v5::mqttbytes::QoS::AtLeastOnce,
      true,
      serde_json::to_string(&tm)?,
      rumqttc::v5::mqttbytes::v5::PublishProperties {
        content_type: Some("application/json").map(str::to_string),
        ..Default::default()
      },
    )?;
    Ok(())
  }

  fn handle_input_message(
    msg: transport::InputMessage,
    client: &rumqttc::v5::AsyncClient,
  ) -> crate::Result<()>
  {
    match msg
    {
      transport::InputMessage::SendCFP { cfp } =>
      {
        Module::send_message(&client, topics::SEND_CFP, cfp)
      }
      transport::InputMessage::SendProposal { proposal } =>
      {
        Module::send_message(&client, topics::SEND_OFFER, proposal)
      }
      transport::InputMessage::SendProposalAcceptance { acceptance } =>
      {
        Module::send_message(&client, topics::SEND_PROPOSAL_ACCEPTANCE, acceptance)
      }
      transport::InputMessage::SendExecutionAcceptance { acceptance } =>
      {
        Module::send_message(&client, topics::SEND_EXECUTION_ACCEPTANCE, acceptance)
      }
      transport::InputMessage::SendCancelAcceptance { cancel_acceptance } =>
      {
        Module::send_message(&client, topics::CANCEL_ACCEPTANCE, cancel_acceptance)
      }
    }
  }
  async fn handle_mqtt_events(
    event: std::result::Result<rumqttc::v5::Event, rumqttc::v5::ConnectionError>,
    output_sender: &async_broadcast::Sender<transport::OutputMessage>,
  ) -> Result<()>
  {
    match event?
    {
      rumqttc::v5::Event::Incoming(packet) => match &packet
      {
        rumqttc::v5::Incoming::Publish(pub_msg) =>
        {
          match std::str::from_utf8(&pub_msg.topic.chunk())?
          {
            topics::CANCEL_ACCEPTANCE =>
            {
              let cancel_acceptance = serde_json::from_slice::<transport_messages::CancelAcceptance>(
                pub_msg.payload.chunk(),
              )?;
              output_sender
                .broadcast(transport::OutputMessage::ReceivedCancelAcceptance { cancel_acceptance })
                .await;
            }
            topics::SEND_CFP =>
            {
              let cfp = serde_json::from_slice::<delegation::CFP>(pub_msg.payload.chunk())?;
              output_sender
                .broadcast(transport::OutputMessage::ReceivedCFP { cfp })
                .await;
            }
            topics::SEND_EXECUTION_ACCEPTANCE =>
            {
              let acceptance =
                serde_json::from_slice::<transport_messages::Acceptance>(pub_msg.payload.chunk())?;
              output_sender
                .broadcast(transport::OutputMessage::ReceivedExecutionAccepted { acceptance })
                .await;
            }
            topics::SEND_EXECUTION_STATUS =>
            {
              let status =
                serde_json::from_slice::<transport_messages::Status>(pub_msg.payload.chunk())?;

              output_sender
                .broadcast(transport::OutputMessage::ReceivedStatus { status })
                .await;
            }
            topics::SEND_OFFER =>
            {
              let proposal =
                serde_json::from_slice::<delegation::Proposal>(pub_msg.payload.chunk())?;

              output_sender
                .broadcast(transport::OutputMessage::ReceivedProposal { proposal })
                .await;
            }
            topics::SEND_PROPOSAL_ACCEPTANCE =>
            {
              let acceptance =
                serde_json::from_slice::<transport_messages::Acceptance>(pub_msg.payload.chunk())?;
              output_sender
                .broadcast(transport::OutputMessage::ReceivedProposalAccepted { acceptance })
                .await;
            }
            unhandled_topic =>
            {
              println!("Subscribed to {} but not handled.", unhandled_topic);
            }
          }
        }
        rumqttc::v5::Incoming::ConnAck(_) =>
        {}
        rumqttc::v5::Incoming::SubAck(_) =>
        {}
        rumqttc::v5::Incoming::PubAck(_) =>
        {}
        rumqttc::v5::Incoming::PingResp(_) =>
        {}
        _ =>
        {
          println!("Incoming unhandled packet {packet:?}");
        }
      },
      rumqttc::v5::Event::Outgoing(_) =>
      { /* ignore outgoing event */ }
    }
    Ok(())
  }
}

module::create_module_private_interface!(
  ModulePrivateInterface,
  transport::InputMessage,
  transport::OutputMessage
);

impl module::Module for Module
{
  type InputMessage = transport::InputMessage;
  type OutputMessage = transport::OutputMessage;
  type ModulePrivateInterface = ModulePrivateInterface;
}

impl super::transport::Module for Module
{
  type Options = Options;
  fn start<'a>(
    module_interfaces: (
      module::ModuleInterface<transport::InputMessage, transport::OutputMessage>,
      Self::ModulePrivateInterface,
    ),
    delegation_module_interface: crate::module::ModuleInterface<
      super::InputMessage,
      super::OutputMessage,
    >,

    options: Self::Options,
  ) -> Result<futures::future::BoxFuture<'a, ()>>
  {
    let (module_interface, module_private_interface) = module_interfaces;

    let mut input_receiver = module_private_interface.input_receiver.activate();
    let output_sender = module_private_interface.output_sender;

    // Initialise MQTT
    let mut mqttoptions =
      rumqttc::v5::MqttOptions::new(options.node_id, options.hostname, options.port);
    mqttoptions.set_keep_alive(std::time::Duration::from_secs(5));
    let (client, mut connection) = rumqttc::v5::AsyncClient::new(mqttoptions, 1000);

    let fut = async move {
      // MQTT Reception thread
      let mqtt_reception_future = async move {
        let mut connection = connection;
        let output_sender = output_sender.clone();
        loop
        {
          let recv = connection.poll().await;
          if let Err(e) = Self::handle_mqtt_events(recv, &output_sender).await
          {
            log::error!("An error occured when handling MQTT event: {}", e);
          }
        }
      };

      // Internal thread
      let input_future = async {
        let qos = rumqttc::v5::mqttbytes::QoS::AtLeastOnce;
        client.subscribe(topics::CANCEL_ACCEPTANCE, qos).await;
        client.subscribe(topics::SEND_CFP, qos).await;
        client
          .subscribe(topics::SEND_EXECUTION_ACCEPTANCE, qos)
          .await;
        client.subscribe(topics::SEND_EXECUTION_STATUS, qos).await;
        client.subscribe(topics::SEND_OFFER, qos).await;
        client
          .subscribe(topics::SEND_PROPOSAL_ACCEPTANCE, qos)
          .await;
        loop
        {
          let msg = input_receiver.recv().await;
          if let Ok(msg) = msg
          {
            if let Err(e) = Module::handle_input_message(msg, &client)
            {
              log::error!(
                "An error occured when handling MQTT Transport message: {}",
                e
              );
            }
          }
          else
          {
            return;
          }
        }
      };

      join!(input_future, mqtt_reception_future);
    };
    // Return
    Ok(fut.boxed())
  }
}