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
//! This module implements a delegation system for the agent.

use ::std::borrow::Borrow;
use std::thread;
use std::time::{Duration, Instant};

#[cfg(feature = "mqtt")]
pub mod mqtt;

pub mod transport;
pub mod transport_messages;

use futures::join;
use yaaral::RuntimeInterface;

use crate::{agent, decision, delegation, module, uuid, Result};

//   ____   _____   ____
//  / ___| |  ___| |  _ \
// | |     | |_    | |_) |
// | |___  |  _|   |  __/
//  \____| |_|     |_|

/// Represents a call for proposal
#[derive(Clone, serde::Deserialize, serde::Serialize)]
pub struct CFP
{
  /// uuid of the CFP
  pub uuid: uuid::Uuid,
  /// URI for the agent which resuest the delegation of the task.
  pub requester_uri: String,
  /// the URI of the team
  pub team_uri: Option<String>,
  /// the URI for the type of the task
  pub task_type: String,
  /// a string description of a task
  pub task_description: String,
  /// a cryptographic dignature for the CFP
  pub signature: Vec<u8>,
}

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

/// Represents a proposal to compmete a CFP.
#[derive(Clone, serde::Deserialize, serde::Serialize)]
pub struct Proposal
{
  /// uri of this agent
  pub agent_uri: String,
  /// cost for executing the given task
  pub cost: f32,
  /// uuid of the CFP/Task
  pub task_uuid: uuid::Uuid,
  /// signature it ingludes the agent_uri, cost, uuid and description
  pub signature: Vec<u8>,
}

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

/// Enum representing the statuts of a delegation and its execution
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum Status
{
  /// The CFP was sent
  SendCFP,
  /// A number of proposals have been received
  ReceivedProposals(usize),
  /// A proposal was accepted
  ProposalAccepted,
  /// No proposals were received before the timeout
  NoReceivedProposals,
  /// No proposal was accepted
  NoAcceptedProposal,
  /// The execution started
  ExecutionStarted,
  /// The execution of a specific node started
  NodeExecutionStarted
  {
    /// uuid of the executed node
    node: uuid::Uuid,
  },
  /// The execution of a specific node was completed
  NodeExecutionCompleted
  {
    /// uuid of the completed node
    node: uuid::Uuid,
  },
}

//  _____                 _
// |_   _|   __ _   ___  | | __
//   | |    / _` | / __| | |/ /
//   | |   | (_| | \__ \ |   <
//   |_|    \__,_| |___/ |_|\_\

/// Base trait for representing tasks in the delegation
pub trait Task: Sized
{
  /// Create a task from a text description (aka json string...)
  fn from_description(task_type: &String, description: &String) -> Result<Self>;
  /// The type of the task (tst, goalspec...)
  fn task_type(&self) -> &str;
  /// Convert into a string representation
  fn to_description(&self) -> String;
  /// An UUID for the task
  fn task_id(&self) -> uuid::Uuid;
}

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

/// Input message from the delegation module
#[derive(Clone)]
pub enum InputMessage
{
  /// Tell the delegation module to start a delegation
  StartDelegation
  {
    /// Call for proposal
    cfp: CFP,
  },
}

impl InputMessage
{
  /// Convenience function for creating a CFP and wrap it into a start delegation message
  pub(crate) fn create_start_delegation(
    requester_uri: String,
    task: impl Task,
    team_uri: Option<String>,
  ) -> InputMessage
  {
    InputMessage::StartDelegation {
      cfp: CFP {
        uuid: task.task_id(),
        requester_uri,
        team_uri,
        task_type: task.task_type().into(),
        task_description: task.to_description(),
        signature: Vec::<u8>::default(),
      },
    }
  }
}

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

/// Output message from the delegation module
#[derive(Clone)]
pub enum OutputMessage
{
  /// Status of the delegation
  Status
  {
    /// Uuid of the task
    uuid: uuid::Uuid,
    /// Status
    status: Status,
  },
}

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

/// Module interface for the delegation modue
pub type ModuleInterface = module::ModuleInterface<InputMessage, OutputMessage>;

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

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

/// This structure implements a delegation module
pub(crate) struct Module {}

impl Module
{
  /// Create a new delegation module
  pub(crate) async fn start(
    agent_data: agent::AgentData,
    module_interfaces: (
      crate::module::ModuleInterface<InputMessage, OutputMessage>,
      ModulePrivateInterface,
    ),
    transport_interface: transport::ModuleInterface,
    decision_interface: decision::ModuleInterface,
  ) -> ()
  {
    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;
    let transport_interface = transport_interface;

    let ir_fut = {
      let agent_data = agent_data.clone();
      let transport_interface = transport_interface.clone();
      async move {
        loop
        {
          let msg = input_receiver.recv().await;
          if let Ok(msg) = msg
          {
            match msg
            {
              InputMessage::StartDelegation { cfp } =>
              {
                let output_sender = output_sender.clone();
                let transport_input_sender = transport_interface.input_sender();
                let mut transport_output_receiver = transport_interface.output_receiver();
                let delegation = async move {
                  let cfp_uuid = cfp.uuid.to_owned();

                  // Send CFP to transport
                  match transport_input_sender
                    .broadcast_direct(transport::InputMessage::SendCFP { cfp: cfp })
                    .await
                  {
                    Ok(_) =>
                    {}
                    Err(e) => println!("While sending CFP: {:?}", e),
                  }

                  // Accumulate proposals
                  let mut proposals = Vec::<delegation::Proposal>::new();
                  let start = Instant::now();
                  while start.elapsed().as_secs() < 30
                  {
                    let msg = async_std::future::timeout(
                      Duration::from_millis(60 * 1000 - start.elapsed().as_millis() as u64),
                      transport_output_receiver.recv(),
                    )
                    .await;
                    if let Ok(Ok(msg)) = msg
                    {
                      match msg
                      {
                        transport::OutputMessage::ReceivedProposal { proposal } =>
                        {
                          if proposal.task_uuid == cfp_uuid
                          {
                            proposals.push(proposal);
                          }
                        }
                        _ =>
                        {}
                      }
                    }
                  }
                  log::info!(
                    "Received {} proposals for delegation {:?}",
                    proposals.len(),
                    cfp_uuid
                  );

                  // Sort proposals
                  println!("sorting");
                  proposals.sort_by(|a, b| a.cost.partial_cmp(b.cost.borrow()).unwrap());
                  println!("done sorting");
                  if proposals.is_empty()
                  {
                    println!("empty proposals");
                    output_sender
                      .broadcast_direct(OutputMessage::Status {
                        uuid: cfp_uuid,
                        status: Status::NoReceivedProposals,
                      })
                      .await;
                    return;
                  }
                  else
                  {
                    println!("send status update");
                    output_sender.broadcast(OutputMessage::Status {
                      uuid: cfp_uuid.to_owned(),
                      status: Status::ReceivedProposals(proposals.len()),
                    });
                    println!("finish sending statu update");
                  }

                  // Select proposals
                  for p in proposals
                  {
                    println!("selected proposals");
                    transport_input_sender
                      .broadcast(transport::InputMessage::SendProposalAcceptance {
                        acceptance: delegation::transport_messages::Acceptance {
                          agent_uri: p.agent_uri.to_owned(),
                          acceptance: true,
                          uuid: p.task_uuid,
                          signature: Default::default(),
                        },
                      })
                      .await;
                    println!("wait for confirmation");
                    let start = Instant::now();
                    while start.elapsed().as_secs() < 10
                    {
                      let msg = async_std::future::timeout(
                        Duration::from_millis(10 * 1000 - start.elapsed().as_millis() as u64),
                        transport_output_receiver.recv(),
                      )
                      .await;
                      println!("confirmation maybe received");
                      if let Ok(Ok(msg)) = msg
                      {
                        match msg
                        {
                          transport::OutputMessage::ReceivedProposalAccepted { acceptance } =>
                          {
                            if acceptance.uuid == cfp_uuid
                            {
                              if (acceptance.acceptance)
                              {
                                output_sender
                                  .broadcast(OutputMessage::Status {
                                    uuid: cfp_uuid,
                                    status: Status::ProposalAccepted,
                                  })
                                  .await;
                                println!("delegation finished");
                                return;
                              }
                              else
                              {
                                break;
                              }
                            }
                          }
                          _ =>
                          {}
                        }
                      }
                    }
                    println!("cancel acceptance");
                    // Cancel the acceptance
                    transport_input_sender
                      .broadcast(transport::InputMessage::SendCancelAcceptance {
                        cancel_acceptance: transport_messages::CancelAcceptance {
                          agent_uri: p.agent_uri,
                          uuid: p.task_uuid,
                          signature: Default::default(),
                        },
                      })
                      .await;
                  }
                  // No proposal was accepted, delegation failed
                  output_sender
                    .broadcast(OutputMessage::Status {
                      uuid: cfp_uuid.to_owned(),
                      status: Status::NoAcceptedProposal,
                    })
                    .await;
                };
                agent_data.async_runtime.spawn_task(delegation);
              }
            }
          }
          else
          {
            return;
          }
        }
      }
    };
    let tr_fut = {
      let agent_data = agent_data.clone();
      let decision_input_sender = decision_interface.input_sender();
      let mut transport_output_receiver = transport_interface.output_receiver();
      async move {
        loop
        {
          match transport_output_receiver.recv().await
          {
            Ok(msg) => match msg
            {
              transport::OutputMessage::ReceivedCFP { cfp } =>
              {
                decision_input_sender
                  .broadcast(decision::InputMessage::DecideCFPAcceptance { cfp: cfp })
                  .await;
              }
              transport::OutputMessage::ReceivedProposalAccepted { acceptance } =>
              {
                if acceptance.agent_uri == agent_data.agent_uri
                {
                  decision_input_sender
                    .broadcast(decision::InputMessage::QueueExecution {
                      uuid: acceptance.uuid,
                    })
                    .await;
                }
              }
              transport::OutputMessage::ReceivedCancelAcceptance { cancel_acceptance } =>
              {
                if cancel_acceptance.agent_uri == agent_data.agent_uri
                {
                  decision_input_sender
                    .broadcast(decision::InputMessage::CancelExecution {
                      uuid: cancel_acceptance.uuid,
                    })
                    .await;
                }
              }
              _ =>
              {}
            },
            Err(_) =>
            {
              return;
            }
          }
        }
      }
    };
    let dr_fut = {
      let mut decision_output_receiver = decision_interface.output_receiver();
      let transport_input_sender = transport_interface.input_sender();
      async move {
        loop
        {
          match decision_output_receiver.recv().await
          {
            Ok(msg) => match msg
            {
              decision::OutputMessage::CFPProposal { proposal } =>
              {
                transport_input_sender
                  .broadcast(transport::InputMessage::SendProposal { proposal })
                  .await;
              }
              decision::OutputMessage::QueueExecutionResult { uuid, accepted } =>
              {
                transport_input_sender
                  .broadcast(transport::InputMessage::SendExecutionAcceptance {
                    acceptance: transport_messages::Acceptance {
                      agent_uri: agent_data.agent_uri.to_owned(),
                      acceptance: accepted,
                      uuid: uuid,
                      signature: Default::default(),
                    },
                  })
                  .await;
              }
            },
            Err(_) =>
            {
              return;
            }
          }
        }
      }
    };
    join!(ir_fut, tr_fut, dr_fut);
  }
}

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