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
//! This module defines a default decision module.

use async_broadcast::Sender;
use async_std::task;

use crate::definitions::agent as definitions_agent;
use crate::definitions::task as definitions_task;
use crate::delegation::Task as DelTask;
use crate::knowledge_base::{KnowledgeBase, KnowledgeBaseInterface};
use crate::{agent, decision, delegation, execution, knowledge_base, module, utils, Result};

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

/// Options for the default decision module
pub struct Options {}

impl Options
{
  /// Create options for the default decision module
  pub fn new() -> Self
  {
    Self {}
  }
}

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

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

/// This structure implements a decision module
pub struct Module {}

impl Module
{
  async fn handle_input_message(
    msg: decision::InputMessage,
    agent_data: &agent::AgentData,
    output_sender: &Sender<decision::OutputMessage>,
    execution_input_sender: &Sender<execution::InputMessage>,
  ) -> Result<()>
  {
    match msg
    {
      decision::InputMessage::DecideCFPAcceptance { cfp } =>
      {
        let task = definitions_task::Task::from_description(&cfp.task_type, &cfp.task_description)?;
        agent_data
          .knowledge_base
          .insert("tasks", cfp.uuid.to_hex(), &task)?;

        match task.get_container()
        {
          definitions_task::TaskContainer::Tst(tst) =>
          {
            let sr = crate::simulation::tst::simulate_execution(
              agent_data.states.to_owned_states()?,
              agent_data.capabilities.clone(),
              tst.clone(),
            )
            .await?;
            output_sender
              .broadcast(decision::OutputMessage::CFPProposal {
                proposal: delegation::Proposal {
                  agent_uri: agent_data.agent_uri.to_owned(),
                  cost: sr.get_estimated_cost(),
                  signature: Default::default(),
                  task_uuid: task.task_id(),
                },
              })
              .await;
          }
        }
      }
      decision::InputMessage::QueueExecution { uuid } =>
      {
        execution_input_sender
          .broadcast(execution::InputMessage::QueueExecution { uuid })
          .await;
        output_sender
          .broadcast(decision::OutputMessage::QueueExecutionResult {
            uuid,
            accepted: true,
          })
          .await;
      }
      decision::InputMessage::CancelExecution { uuid } =>
      {
        execution_input_sender
          .broadcast(execution::InputMessage::CancelExecution {
            uuid: uuid.to_owned(),
          })
          .await;
      }
    }
    Ok(())
  }
}

impl decision::Module for Module
{
  type Options = Options;
  fn start(
    agent_data: agent::AgentData,
    module_interfaces: (decision::ModuleInterface, ModulePrivateInterface),
    execution_interface: execution::ModuleInterface,
    _: Options,
  ) -> impl std::future::Future<Output = ()> + std::marker::Send + 'static
  {
    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 execution_input_sender = execution_interface.input_sender();

    async move {
      loop
      {
        let msg = input_receiver.recv().await;
        if let Ok(msg) = msg
        {
          if let Err(e) =
            Self::handle_input_message(msg, &agent_data, &output_sender, &execution_input_sender)
              .await
          {
            log::error!(
              "An error occured for agent {} when handling decision message: {}",
              agent_data.agent_uri,
              e
            );
          }
        }
        else
        {
          log::info!("Decision loop for {:?} is closing", agent_data.agent_uri);
          return;
        }
      }
    }
  }
}

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