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
use std::{sync::Arc, time::Duration};
use crate::{
helpers::network::{NetworkMessage, service::NetworkSender},
model::{common::emit_fail, network::RetryNetwork},
};
use crate::helpers::network::ActorMessage;
use async_trait::async_trait;
use ave_common::identity::{HashAlgorithm, PublicKey, Signed, hash_borsh};
use ave_network::ComunicateInfo;
use ave_actors::{
Actor, ActorContext, ActorError, ActorPath, ChildAction,
FixedIntervalStrategy, Handler, Message, NotPersistentActor, RetryActor,
RetryMessage, Strategy,
};
use tracing::{Span, debug, error, info_span, warn};
use super::{
Evaluation, EvaluationMessage, request::EvaluationReq,
response::EvaluationRes,
};
/// A struct representing a EvalCoordinator actor.
#[derive(Clone, Debug)]
pub struct EvalCoordinator {
node_key: PublicKey,
request_id: String,
version: u64,
network: Arc<NetworkSender>,
hash: HashAlgorithm,
}
impl EvalCoordinator {
pub const fn new(
node_key: PublicKey,
request_id: String,
version: u64,
network: Arc<NetworkSender>,
hash: HashAlgorithm,
) -> Self {
Self {
node_key,
request_id,
version,
network,
hash,
}
}
fn verify_result_response(
&self,
result: &super::response::EvaluationResult,
result_hash: &ave_common::identity::DigestIdentifier,
result_hash_signature: &ave_common::identity::Signature,
) -> Result<(), ActorError> {
let hash = hash_borsh(&*self.hash.hasher(), result).map_err(|e| {
error!(
msg_type = "NetworkResponse",
error = %e,
"Failed to create evaluation result hash"
);
ActorError::Functional {
description: format!("Can not verify signature: {}", e),
}
})?;
if &hash != result_hash {
error!(
msg_type = "NetworkResponse",
result_hash = %result_hash,
generated_hash = %hash,
"Result hash is invalid"
);
return Err(ActorError::Functional {
description: "Result hash is invalid".to_string(),
});
}
result_hash_signature.verify(result_hash).map_err(|e| {
error!(
msg_type = "NetworkResponse",
error = %e,
"Failed to verify evaluation result hash signature"
);
ActorError::Functional {
description: format!("Can not verify signature: {}", e),
}
})?;
if result_hash_signature.signer != self.node_key {
error!(
msg_type = "NetworkResponse",
expected_signer = %self.node_key,
actual_signer = %result_hash_signature.signer,
"Evaluation result hash signature signer mismatch"
);
return Err(ActorError::Functional {
description: "Evaluation result hash signature signer mismatch"
.to_string(),
});
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub enum EvalCoordinatorMessage {
EndRetry,
NetworkEvaluation {
evaluation_req: Box<Signed<EvaluationReq>>,
node_key: PublicKey,
},
NetworkResponse {
evaluation_res: Box<EvaluationRes>,
request_id: String,
version: u64,
sender: PublicKey,
},
}
impl Message for EvalCoordinatorMessage {}
#[async_trait]
impl Actor for EvalCoordinator {
type Event = ();
type Message = EvalCoordinatorMessage;
type Response = ();
fn get_span(id: &str, parent_span: Option<Span>) -> tracing::Span {
parent_span.map_or_else(
|| info_span!("EvalCoordinator", id),
|parent_span| info_span!(parent: parent_span, "EvalCoordinator", id),
)
}
}
impl NotPersistentActor for EvalCoordinator {}
#[async_trait]
impl Handler<Self> for EvalCoordinator {
async fn handle_message(
&mut self,
_sender: ActorPath,
msg: EvalCoordinatorMessage,
ctx: &mut ActorContext<Self>,
) -> Result<(), ActorError> {
match msg {
EvalCoordinatorMessage::EndRetry => {
warn!(
node_key = %self.node_key,
request_id = %self.request_id,
version = self.version,
"Retry exhausted, notifying parent and stopping"
);
match ctx.get_parent::<Evaluation>().await {
Ok(evaluation_actor) => {
if let Err(e) = evaluation_actor
.tell(EvaluationMessage::Response {
evaluation_res: EvaluationRes::TimeOut,
sender: self.node_key.clone(),
})
.await
{
error!(
error = %e,
"Failed to send timeout response to evaluation actor"
);
emit_fail(ctx, e).await;
} else {
debug!(
request_id = %self.request_id,
version = self.version,
"Timeout response sent to evaluation actor"
);
}
}
Err(e) => {
error!(
error = %e,
path = %ctx.path().parent(),
"Evaluation actor not found"
);
emit_fail(ctx, e).await;
}
}
ctx.stop(None).await;
}
EvalCoordinatorMessage::NetworkEvaluation {
evaluation_req,
node_key,
} => {
let receiver_actor =
if evaluation_req.content().schema_id.is_gov() {
format!(
"/user/node/subject_manager/{}/evaluator",
evaluation_req.content().governance_id
)
} else {
format!(
"/user/node/subject_manager/{}/{}_evaluation",
evaluation_req.content().governance_id,
evaluation_req.content().schema_id
)
};
// Lanzar evento donde lanzar los retrys
let message = NetworkMessage {
info: ComunicateInfo {
request_id: self.request_id.clone(),
version: self.version,
receiver: node_key.clone(),
receiver_actor,
},
message: ActorMessage::EvaluationReq {
req: evaluation_req,
},
};
let target = RetryNetwork::new(self.network.clone());
#[cfg(any(test, feature = "test"))]
let strategy = Strategy::FixedInterval(
FixedIntervalStrategy::new(1, Duration::from_secs(20)),
);
#[cfg(not(any(test, feature = "test")))]
let strategy = Strategy::FixedInterval(
FixedIntervalStrategy::new(3, Duration::from_secs(60)),
);
let retry_actor = RetryActor::new_with_parent_message::<Self>(
target,
message,
strategy,
EvalCoordinatorMessage::EndRetry,
);
let retry = match ctx
.create_child::<RetryActor<RetryNetwork>, _>(
"retry",
retry_actor,
)
.await
{
Ok(retry) => retry,
Err(e) => {
error!(
msg_type = "NetworkEvaluation",
error = %e,
"Failed to create retry actor"
);
return Err(emit_fail(ctx, e).await);
}
};
if let Err(e) = retry.tell(RetryMessage::Retry).await {
error!(
msg_type = "NetworkEvaluation",
error = %e,
"Failed to send retry message to retry actor"
);
return Err(emit_fail(ctx, e).await);
};
debug!(
msg_type = "NetworkEvaluation",
request_id = %self.request_id,
version = self.version,
node_key = %node_key,
"Evaluation request sent to network with retry"
);
}
EvalCoordinatorMessage::NetworkResponse {
evaluation_res,
request_id,
version,
sender,
} => {
if request_id == self.request_id && version == self.version {
if self.node_key != sender {
error!(
msg_type = "NetworkResponse",
expected_node = %self.node_key,
network_sender = %sender,
"Evaluation response sender mismatch"
);
return Err(ActorError::Functional {
description:
"We received an evaluation response from an unexpected sender"
.to_string(),
});
}
if let EvaluationRes::Response {
result,
result_hash,
result_hash_signature,
} = &*evaluation_res
{
self.verify_result_response(
result,
result_hash,
result_hash_signature,
)?;
}
// Evaluation actor.
match ctx.get_parent::<Evaluation>().await {
Ok(evaluation_actor) => {
if let Err(e) = evaluation_actor
.tell(EvaluationMessage::Response {
evaluation_res: *evaluation_res,
sender: self.node_key.clone(),
})
.await
{
error!(
msg_type = "NetworkResponse",
error = %e,
"Failed to send response to evaluation actor"
);
return Err(emit_fail(ctx, e).await);
}
}
Err(e) => {
error!(
msg_type = "NetworkResponse",
error = %e,
path = %ctx.path().parent(),
"Evaluation actor not found"
);
return Err(emit_fail(ctx, e).await);
}
}
'retry: {
let Ok(retry) = ctx
.get_child::<RetryActor<RetryNetwork>>("retry")
.await
else {
debug!(
msg_type = "NetworkResponse",
sender = %sender,
"Retry actor not found while closing evaluation coordinator"
);
// Aquí me da igual, porque al parar este actor para el hijo
break 'retry;
};
if let Err(e) = retry.tell(RetryMessage::End).await {
warn!(
msg_type = "NetworkResponse",
error = %e,
"Failed to end retry actor"
);
// Aquí me da igual, porque al parar este actor para el hijo
break 'retry;
};
}
debug!(
msg_type = "NetworkResponse",
request_id = %self.request_id,
version = self.version,
sender = %sender,
"Evaluation response processed successfully"
);
ctx.stop(None).await;
} else {
warn!(
msg_type = "NetworkResponse",
expected_request_id = %self.request_id,
expected_version = self.version,
received_request_id = %request_id,
received_version = version,
"Response with mismatched request id or version"
);
}
}
}
Ok(())
}
async fn on_child_fault(
&mut self,
error: ActorError,
ctx: &mut ActorContext<Self>,
) -> ChildAction {
error!(
request_id = %self.request_id,
version = self.version,
node_key = %self.node_key,
error = %error,
"Child fault in evaluation coordinator"
);
emit_fail(ctx, error).await;
ChildAction::Stop
}
}