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
use dashmap::DashMap;
use execution_definitions::nando_handle::ActivationOutput;
use location_manager::HostId;
use nando_lib::nando_scheduler::TaskCompletionNotification;
use nando_support::{activation_intent, ecb_id::EcbId, epic_control, iptr::IPtr};
use object_lib::{ObjectId, ObjectVersion};
use ownership_support as ownership;
use tonic::{transport::channel::Channel, Request};
use worker_rpc::worker_api_client::WorkerApiClient;
use worker_rpc::{CacheMapping, FaultCacheRequest, TaskGraph};

type ConcreteWorkerClient = WorkerApiClient<Channel>;

pub mod worker_rpc {
    tonic::include_proto!("ww");
}

#[derive(Debug)]
pub struct WorkerRpcClient {
    server_port: u16,
    host_clients: DashMap<HostId, ConcreteWorkerClient>,
}

// owned by the activation router instance.
impl WorkerRpcClient {
    pub fn new(server_port: u16) -> Self {
        Self {
            server_port,
            host_clients: DashMap::new(),
        }
    }

    async fn get_client(&self, host_id: &HostId) -> Result<ConcreteWorkerClient, String> {
        let key = match std::thread::current().name() {
            Some(ref thread_name) => {
                format!("{}:{}", thread_name.to_string(), host_id)
            }
            None => host_id.to_string(),
        };
        match self.host_clients.get(&key) {
            Some(c) => return Ok(c.value().clone()),
            None => {}
        }

        let server_addr = format!("http://{}:{}", host_id, self.server_port);
        match WorkerApiClient::connect(server_addr).await {
            Ok(client) => {
                let client = client
                    .max_decoding_message_size(512 * 1024 * 1024)
                    .max_encoding_message_size(512 * 1024 * 1024);
                self.host_clients.insert(key, client.clone());

                Ok(client)
            }
            Err(e) => {
                let err_msg = format!(
                    "Failed to establish connection with host {}: {}",
                    host_id, e,
                );
                eprintln!("{}", err_msg);

                Err(err_msg)
            }
        }
    }

    pub async fn forward_task_completion(
        &self,
        task_completion_notification: TaskCompletionNotification,
        host_idx: ownership::HostIdx,
        target_host: &HostId,
    ) -> Result<(), String> {
        let completed_task = task_completion_notification.completed_task_id;
        #[cfg(debug_assertions)]
        println!("About to fwd task completion of {completed_task} to {target_host}");

        let mut request: worker_rpc::TaskCompletion = (&task_completion_notification).into();
        request.subgraph_allocations = task_completion_notification
            .subgraph_allocations
            .iter()
            .map(|a| worker_rpc::Allocation {
                allocation_host_idx: host_idx,
                allocated_object: Some(a.into()),
            })
            .collect();

        let request = Request::new(request);

        let mut target_client = self
            .get_client(target_host)
            .await
            .expect(&format!("failed to get rpc client for {}", target_host));

        match target_client.handle_task_completion(request).await {
            Ok(_) => Ok(()),
            Err(e) => {
                let err_msg = format!(
                    "could not forward task completion for {:?}: {}",
                    completed_task, e
                );
                eprintln!("{}", err_msg);
                Err(err_msg)
            }
        }
    }

    pub async fn schedule_nando(
        &self,
        activation_intent_request: activation_intent::NandoActivationIntent,
        target_host: &HostId,
    ) -> Result<(Vec<ActivationOutput>, Vec<(ObjectId, ObjectVersion)>), String> {
        let request = Request::new((&activation_intent_request).into());
        let mut target_client = self
            .get_client(target_host)
            .await
            .expect(&format!("failed to get rpc client for {}", target_host));

        match target_client.schedule_nando(request).await {
            Ok(resolution_response) => {
                let resolution = resolution_response.get_ref();
                let resolution_status = resolution
                    .status
                    .as_ref()
                    .expect("no status in activation resolution");
                match worker_rpc::NandoStatusKind::try_from(resolution_status.kind) {
                    Ok(worker_rpc::NandoStatusKind::Error) => {
                        Err(resolution_status.error_string.as_ref().unwrap().clone())
                    }
                    Ok(worker_rpc::NandoStatusKind::Success) => {
                        let result = match resolution.result.is_empty() {
                            true => vec![],
                            false => resolution
                                .result
                                .iter()
                                .map(|r| {
                                    let result: ActivationOutput = r.into();
                                    result.into()
                                })
                                .collect(),
                        };

                        Ok((
                            result,
                            resolution
                                .cacheable_objects
                                .iter()
                                .map(|pair| {
                                    (
                                        pair.object_id.parse().expect(&format!(
                                            "failed to parse object id {}",
                                            pair.object_id
                                        )),
                                        pair.version,
                                    )
                                })
                                .collect(),
                        ))
                    }
                    Ok(worker_rpc::NandoStatusKind::RecomputedSite) => {
                        todo!("intra-worker intent relocation")
                    }
                    _ => panic!("unsupported status kind"),
                }
            }
            Err(e) => {
                let err_msg = format!(
                    "could not forward nando for {} to {}: {}",
                    activation_intent_request.name, target_host, e
                );
                eprintln!("{}", err_msg);
                Err(err_msg)
            }
        }
    }

    pub async fn forward_spawned_task(
        &self,
        spawned_task: epic_control::SpawnedTask,
        target_host: &HostId,
    ) -> Result<activation_intent::NandoActivationResolution, String> {
        let request = Request::new((&spawned_task).into());
        let mut target_client = self
            .get_client(target_host)
            .await
            .expect(&format!("failed to get rpc client for {}", target_host));

        match target_client.schedule_spawned_task(request).await {
            Ok(resolution_response) => {
                let resolution = resolution_response.get_ref();
                Ok(resolution.into())
            }
            Err(e) => {
                let err_msg = format!(
                    "could not forward spawned task for {} to {}: {}",
                    spawned_task.intent.name, target_host, e
                );
                eprintln!("{}", err_msg);
                Err(err_msg)
            }
        }
    }

    pub async fn schedule_task_graph(
        &self,
        spawned_tasks: &Vec<epic_control::SpawnedTask>,
        target_host: &HostId,
    ) -> Result<Vec<activation_intent::NandoActivationResolution>, String> {
        let request = Request::new(TaskGraph {
            graph_tasks: spawned_tasks.iter().map(|st| st.into()).collect(),
        });

        let mut target_client = self
            .get_client(target_host)
            .await
            .expect(&format!("failed to get rpc client for {}", target_host));

        match target_client.schedule_task_graph(request).await {
            Ok(resolution_response) => {
                let resolution = resolution_response.get_ref();
                Ok(resolution
                    .activation_resolutions
                    .iter()
                    .map(|r| r.into())
                    .collect())
            }
            Err(e) => {
                let err_msg = format!("could not forward task graph to {}: {}", target_host, e);
                eprintln!("{}", err_msg);
                Err(err_msg)
            }
        }
    }

    pub async fn assume_ownership(
        &self,
        assume_ownership_request: ownership::AssumeOwnershipRequest,
        target_host: &HostId,
    ) -> Result<Vec<u8>, String> {
        let request = Request::new((&assume_ownership_request).into());
        let mut target_client = self
            .get_client(target_host)
            .await
            .expect(&format!("failed to get rpc client for {}", target_host));

        match target_client.assume_ownership(request).await {
            Ok(assume_ownership_response) => {
                let response = assume_ownership_response.get_ref();
                Ok(response.signature.clone())
            }
            Err(e) => {
                let err_msg = format!(
                    "could not forward request to assume ownership of {} to {}: {}",
                    assume_ownership_request.object_id, target_host, e
                );
                eprintln!("{}", err_msg);
                Err(err_msg)
            }
        }
    }

    /*
    pub async fn push_copy(
        &self,
        assume_ownership_request: ownership::AssumeOwnershipRequest,
        target_host: &HostId,
    ) -> Result<Vec<u8>, String> {
        let request = Request::new((&assume_ownership_request).into());
        println!("about to push copy to target host {}", target_host);
        let mut target_client = self
            .get_client(target_host)
            .await
            .expect(&format!("failed to get rpc client for {}", target_host));

        match target_client.push_copy(request).await {
            Ok(assume_ownership_response) => {
                let response = assume_ownership_response.get_ref();
                Ok(response.signature.clone())
            }
            Err(e) => {
                let err_msg = format!(
                    "could not forward request to assume ownership of {} to {}: {}",
                    assume_ownership_request.object_id, target_host, e
                );
                eprintln!("{}", err_msg);
                Err(err_msg)
            }
        }
    }
    */

    pub async fn move_ownership(
        &self,
        move_ownership_request: ownership::MoveOwnershipRequest,
        target_host: &HostId,
    ) -> Result<ownership_support::MoveOwnershipResponse, String> {
        let request = Request::new((&move_ownership_request).into());
        let mut target_client = self
            .get_client(target_host)
            .await
            .expect(&format!("failed to get rpc client for {}", target_host));

        match target_client.move_ownership(request).await {
            Ok(move_ownership_response) => {
                let response = move_ownership_response.get_ref();
                Ok(ownership_support::MoveOwnershipResponse {
                    whomstone_versions: response
                        .whomstone_versions
                        .iter()
                        .map(|pair| {
                            (
                                pair.object_id.parse().expect(&format!(
                                    "failed to parse object id {}",
                                    pair.object_id
                                )),
                                pair.version,
                            )
                        })
                        .collect(),
                })
            }
            Err(e) => {
                let err_msg = format!(
                    "could not forward request to move ownership of {:?} to {}: {}",
                    move_ownership_request.object_refs, target_host, e
                );
                eprintln!("{}", err_msg);
                Err(err_msg)
            }
        }
    }

    pub async fn fault_shared_cache(
        &self,
        host_idx: ownership::HostIdx,
        original_object_id: ObjectId,
        cached_object_id: ObjectId,
        cache_version: ObjectVersion,
        target_host: &HostId,
    ) -> Result<(), String> {
        let request = Request::new(FaultCacheRequest {
            host_idx,
            original_object_id: original_object_id.to_string(),
            cached_object_id: cached_object_id.to_string(),
            version: cache_version,
        });
        let mut target_client = self
            .get_client(target_host)
            .await
            .expect(&format!("failed to get rpc client for {}", target_host));

        match target_client.fault_shared_cache(request).await {
            Ok(_) => Ok(()),
            Err(e) => {
                let err_msg = format!("failed to insert shared cache entry remotely: {}", e);
                eprintln!("{}", err_msg);
                Err(err_msg)
            }
        }
    }

    pub async fn add_cache_mapping(
        &self,
        original_object: &IPtr,
        cache_object: &IPtr,
        version: ObjectVersion,
        target_host: &HostId,
        own_idx: ownership::HostIdx,
    ) -> Result<(), String> {
        let request = Request::new(CacheMapping {
            original_object: Some(original_object.into()),
            cache_object: Some(cache_object.into()),
            version,
            original_owner_idx: own_idx,
        });
        let mut target_client = self
            .get_client(target_host)
            .await
            .expect(&format!("failed to get rpc client for {}", target_host));

        match target_client.add_cache_mapping(request).await {
            Ok(_) => Ok(()),
            Err(e) => {
                let err_msg = format!("failed to add cache mapping remotely: {}", e);
                eprintln!("{}", err_msg);
                Err(err_msg)
            }
        }
    }
}