Files @ c1b2442f23b2
Branch filter:

Location: CSY/reowolf/src/runtime/native.rs

c1b2442f23b2 22.2 KiB application/rls-services+xml Show Annotation Show as Raw Download as Raw
MH
Remove references to old runtime and stale code
  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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, Condvar};

use crate::protocol::ComponentCreationError;
use crate::protocol::eval::ValueGroup;
use crate::runtime::consensus::RoundConclusion;

use super::{ConnectorId, RuntimeInner};
use super::branch::{BranchId, FakeTree, QueueKind, SpeculativeState};
use super::scheduler::{SchedulerCtx, ComponentCtx, MessageTicket};
use super::port::{Port, PortIdLocal, Channel, PortKind};
use super::consensus::{Consensus, Consistency, find_ports_in_value_group};
use super::connector::{ConnectorScheduling, ConnectorPDL};
use super::inbox::{
    Message, DataMessage,
    SyncCompMessage, SyncPortMessage,
    ControlContent, ControlMessage
};

/// Generic connector interface from the scheduler's point of view.
pub(crate) trait Connector {
    /// Should run the connector's behaviour up until the next blocking point.
    /// One should generally request and handle new messages from the component
    /// context. Then perform any logic the component has to do, and in the
    /// process perhaps queue up some state changes using the same context.
    fn run(&mut self, sched_ctx: SchedulerCtx, comp_ctx: &mut ComponentCtx) -> ConnectorScheduling;
}

pub(crate) struct FinishedSync {
    // In the order of the `get` calls
    success: bool,
    inbox: Vec<ValueGroup>,
}

type SyncDone = Arc<(Mutex<Option<FinishedSync>>, Condvar)>;
type JobQueue = Arc<Mutex<VecDeque<ApplicationJob>>>;

enum ApplicationJob {
    NewChannel((Port, Port)),
    NewConnector(ConnectorPDL, Vec<PortIdLocal>),
    SyncRound(Vec<ApplicationSyncAction>),
    Shutdown,
}

// -----------------------------------------------------------------------------
// ConnectorApplication
// -----------------------------------------------------------------------------

/// The connector which an application can directly interface with. Once may set
/// up the next synchronous round, and retrieve the data afterwards.
// TODO: Strong candidate for logic reduction in handling put/get. A lot of code
//  is an approximate copy-pasta from the regular component logic. I'm going to
//  wait until I'm implementing more native components to see which logic is
//  truly common.
pub struct ConnectorApplication {
    // Communicating about new jobs and setting up sync rounds
    sync_done: SyncDone,
    job_queue: JobQueue,
    is_in_sync: bool,
    // Handling current sync round
    sync_desc: Vec<ApplicationSyncAction>,
    tree: FakeTree,
    consensus: Consensus,
    last_finished_handled: Option<BranchId>,
    branch_extra: Vec<usize>, // instruction counter per branch
}

impl Connector for ConnectorApplication {
    fn run(&mut self, sched_ctx: SchedulerCtx, comp_ctx: &mut ComponentCtx) -> ConnectorScheduling {
        if self.is_in_sync {
            let scheduling = self.run_in_sync_mode(sched_ctx, comp_ctx);
            let mut iter_id = self.last_finished_handled.or(self.tree.get_queue_first(QueueKind::FinishedSync));
            while let Some(branch_id) = iter_id {
                iter_id = self.tree.get_queue_next(branch_id);
                self.last_finished_handled = Some(branch_id);

                if let Some(conclusion) = self.consensus.handle_new_finished_sync_branch(branch_id, comp_ctx) {
                    // Can finish sync round immediately
                    self.collapse_sync_to_conclusion(conclusion, comp_ctx);
                    return ConnectorScheduling::Immediate;
                }
            }

            return scheduling;
        } else {
            return self.run_in_deterministic_mode(sched_ctx, comp_ctx);
        }
    }
}

impl ConnectorApplication {
    pub(crate) fn new(runtime: Arc<RuntimeInner>) -> (Self, ApplicationInterface) {
        let sync_done = Arc::new(( Mutex::new(None), Condvar::new() ));
        let job_queue = Arc::new(Mutex::new(VecDeque::with_capacity(32)));

        let connector = ConnectorApplication {
            sync_done: sync_done.clone(),
            job_queue: job_queue.clone(),
            is_in_sync: false,
            sync_desc: Vec::new(),
            tree: FakeTree::new(),
            consensus: Consensus::new(),
            last_finished_handled: None,
            branch_extra: vec![0],
        };
        let interface = ApplicationInterface::new(sync_done, job_queue, runtime);

        return (connector, interface);
    }

    fn handle_new_messages(&mut self, comp_ctx: &mut ComponentCtx) {
        while let Some(ticket) = comp_ctx.get_next_message_ticket() {
            let message = comp_ctx.read_message_using_ticket(ticket);
            if let Message::Data(_) = message {
                self.handle_new_data_message(ticket, comp_ctx)
            } else {
                match comp_ctx.take_message_using_ticket(ticket) {
                    Message::Data(message) => unreachable!(),
                    Message::SyncComp(message) => self.handle_new_sync_comp_message(message, comp_ctx),
                    Message::SyncPort(message) => self.handle_new_sync_port_message(message, comp_ctx),
                    Message::SyncControl(message) => todo!("implement"),
                    Message::Control(_) => unreachable!("control message in native API component"),
                }
            }
        }
    }

    pub(crate) fn handle_new_data_message(&mut self, ticket: MessageTicket, ctx: &mut ComponentCtx) {
        // Go through all branches that are awaiting new messages and see if
        // there is one that can receive this message.
        if !self.consensus.handle_new_data_message(ticket, ctx) {
            // Old message, so drop it
            return;
        }

        let mut iter_id = self.tree.get_queue_first(QueueKind::AwaitingMessage);
        while let Some(branch_id) = iter_id {
            let message = ctx.read_message_using_ticket(ticket).as_data();
            iter_id = self.tree.get_queue_next(branch_id);

            let branch = &self.tree[branch_id];
            if branch.awaiting_port != message.data_header.target_port { continue; }
            if !self.consensus.branch_can_receive(branch_id, &message) { continue; }

            // This branch can receive, so fork and given it the message
            let receiving_branch_id = self.tree.fork_branch(branch_id);
            debug_assert!(receiving_branch_id.index as usize == self.branch_extra.len());
            self.branch_extra.push(self.branch_extra[branch_id.index as usize]); // copy instruction index
            self.consensus.notify_of_new_branch(branch_id, receiving_branch_id);
            let receiving_branch = &mut self.tree[receiving_branch_id];

            receiving_branch.insert_message(message.data_header.target_port, message.content.clone());
            self.consensus.notify_of_received_message(receiving_branch_id, &message, ctx);

            // And prepare the branch for running
            self.tree.push_into_queue(QueueKind::Runnable, receiving_branch_id);
        }
    }

    pub(crate) fn handle_new_sync_comp_message(&mut self, message: SyncCompMessage, ctx: &mut ComponentCtx) {
        if let Some(conclusion) = self.consensus.handle_new_sync_comp_message(message, ctx) {
            self.collapse_sync_to_conclusion(conclusion, ctx);
        }
    }

    pub(crate) fn handle_new_sync_port_message(&mut self, message: SyncPortMessage, ctx: &mut ComponentCtx) {
        self.consensus.handle_new_sync_port_message(message, ctx);
    }

    fn run_in_sync_mode(&mut self, _sched_ctx: SchedulerCtx, comp_ctx: &mut ComponentCtx) -> ConnectorScheduling {
        debug_assert!(self.is_in_sync);

        self.handle_new_messages(comp_ctx);

        let branch_id = self.tree.pop_from_queue(QueueKind::Runnable);
        if branch_id.is_none() {
            return ConnectorScheduling::NotNow;
        }

        let branch_id = branch_id.unwrap();
        let branch = &mut self.tree[branch_id];
        let mut instruction_idx = self.branch_extra[branch_id.index as usize];

        if instruction_idx >= self.sync_desc.len() {
            // Performed last instruction, so this branch is officially at the
            // end of the synchronous interaction.
            let consistency = self.consensus.notify_of_finished_branch(branch_id);
            if consistency == Consistency::Valid {
                branch.sync_state = SpeculativeState::ReachedSyncEnd;
                self.tree.push_into_queue(QueueKind::FinishedSync, branch_id);
            } else {
                branch.sync_state = SpeculativeState::Inconsistent;
            }
        } else {
            // We still have instructions to perform
            let cur_instruction = &self.sync_desc[instruction_idx];
            self.branch_extra[branch_id.index as usize] += 1;

            match &cur_instruction {
                ApplicationSyncAction::Put(port_id, content) => {
                    let port_id = *port_id;

                    let (sync_header, data_header) = self.consensus.handle_message_to_send(branch_id, port_id, &content, comp_ctx);
                    let message = Message::Data(DataMessage {
                        sync_header,
                        data_header,
                        content: content.clone(),
                    });
                    comp_ctx.submit_message(message);
                    self.tree.push_into_queue(QueueKind::Runnable, branch_id);
                    return ConnectorScheduling::Immediate;
                },
                ApplicationSyncAction::Get(port_id) => {
                    let port_id = *port_id;

                    branch.sync_state = SpeculativeState::HaltedAtBranchPoint;
                    branch.awaiting_port = port_id;
                    self.tree.push_into_queue(QueueKind::AwaitingMessage, branch_id);

                    let mut any_message_received = false;
                    for message in comp_ctx.get_read_data_messages(port_id) {
                        if self.consensus.branch_can_receive(branch_id, &message) {
                            // This branch can receive the message, so we do the
                            // fork-and-receive dance
                            let receiving_branch_id = self.tree.fork_branch(branch_id);
                            let branch = &mut self.tree[receiving_branch_id];
                            debug_assert!(receiving_branch_id.index as usize == self.branch_extra.len());
                            self.branch_extra.push(instruction_idx + 1);

                            branch.insert_message(port_id, message.content.clone());

                            self.consensus.notify_of_new_branch(branch_id, receiving_branch_id);
                            self.consensus.notify_of_received_message(receiving_branch_id, &message, comp_ctx);
                            self.tree.push_into_queue(QueueKind::Runnable, receiving_branch_id);

                            any_message_received = true;
                        }
                    }

                    if any_message_received {
                        return ConnectorScheduling::Immediate;
                    }
                }
            }
        }

        if self.tree.queue_is_empty(QueueKind::Runnable) {
            return ConnectorScheduling::NotNow;
        } else {
            return ConnectorScheduling::Later;
        }
    }

    fn run_in_deterministic_mode(&mut self, _sched_ctx: SchedulerCtx, comp_ctx: &mut ComponentCtx) -> ConnectorScheduling {
        debug_assert!(!self.is_in_sync);

        // In non-sync mode the application component doesn't really do anything
        // except performing jobs submitted from the API. This is the only
        // case where we expect to be woken up.
        // Note that we have to communicate to the scheduler when we've received
        // ports or created components (hence: given away ports) *before* we
        // enter a sync round.
        let mut queue = self.job_queue.lock().unwrap();
        while let Some(job) = queue.pop_front() {
            match job {
                ApplicationJob::NewChannel((endpoint_a, endpoint_b)) => {
                    comp_ctx.push_port(endpoint_a);
                    comp_ctx.push_port(endpoint_b);

                    return ConnectorScheduling::Immediate;
                }
                ApplicationJob::NewConnector(connector, initial_ports) => {
                    comp_ctx.push_component(connector, initial_ports);

                    return ConnectorScheduling::Later;
                },
                ApplicationJob::SyncRound(mut description) => {
                    // Entering sync mode
                    comp_ctx.notify_sync_start();
                    self.sync_desc = description;
                    self.is_in_sync = true;
                    debug_assert!(self.last_finished_handled.is_none());
                    debug_assert!(self.branch_extra.len() == 1);

                    let first_branch_id = self.tree.start_sync();
                    self.tree.push_into_queue(QueueKind::Runnable, first_branch_id);
                    debug_assert!(first_branch_id.index == 1);
                    self.consensus.start_sync(comp_ctx);
                    self.consensus.notify_of_new_branch(BranchId::new_invalid(), first_branch_id);
                    self.branch_extra.push(0); // set first branch to first instruction

                    return ConnectorScheduling::Immediate;
                },
                ApplicationJob::Shutdown => {
                    debug_assert!(queue.is_empty());

                    return ConnectorScheduling::Exit;
                }
            }
        }

        // Queue was empty
        return ConnectorScheduling::NotNow;
    }

    fn collapse_sync_to_conclusion(&mut self, conclusion: RoundConclusion, comp_ctx: &mut ComponentCtx) {
        // Notifying tree, consensus algorithm and context of ending sync
        let mut fake_vec = Vec::new();

        let (branch_id, success) = match conclusion {
            RoundConclusion::Success(branch_id) => {
                debug_assert!(self.branch_extra[branch_id.index as usize] >= self.sync_desc.len()); // finished program provided by API
                (branch_id, true)
            },
            RoundConclusion::Failure => (BranchId::new_invalid(), false),
        };

        let mut solution_branch = self.tree.end_sync(branch_id);
        self.consensus.end_sync(branch_id, &mut fake_vec);
        debug_assert!(fake_vec.is_empty());

        comp_ctx.notify_sync_end(&[]);

        // Turning hashmapped inbox into vector of values
        let mut inbox = Vec::with_capacity(solution_branch.inbox.len());
        for action in &self.sync_desc {
            match action {
                ApplicationSyncAction::Put(_, _) => {},
                ApplicationSyncAction::Get(port_id) => {
                    debug_assert!(solution_branch.inbox.contains_key(port_id));
                    inbox.push(solution_branch.inbox.remove(port_id).unwrap());
                },
            }
        }

        // Notifying interface of ending sync
        self.is_in_sync = false;
        self.sync_desc.clear();
        self.branch_extra.truncate(1);
        self.last_finished_handled = None;

        let (results, notification) = &*self.sync_done;
        let mut results = results.lock().unwrap();
        *results = Some(FinishedSync{ success, inbox });
        notification.notify_one();
    }
}

// -----------------------------------------------------------------------------
// ApplicationInterface
// -----------------------------------------------------------------------------

#[derive(Debug)]
pub enum ChannelCreationError {
    InSync,
}

#[derive(Debug)]
pub enum ApplicationStartSyncError {
    AlreadyInSync,
    NoSyncActions,
    IncorrectPortKind,
    UnownedPort,
}

#[derive(Debug)]
pub enum ApplicationEndSyncError {
    NotInSync,
    Failure,
}

pub enum ApplicationSyncAction {
    Put(PortIdLocal, ValueGroup),
    Get(PortIdLocal),
}

/// The interface to a `ApplicationConnector`. This allows setting up the
/// interactions the `ApplicationConnector` performs within a synchronous round.
pub struct ApplicationInterface {
    sync_done: SyncDone,
    job_queue: JobQueue,
    runtime: Arc<RuntimeInner>,
    is_in_sync: bool,
    connector_id: ConnectorId,
    owned_ports: Vec<(PortKind, PortIdLocal)>,
}

impl ApplicationInterface {
    fn new(sync_done: SyncDone, job_queue: JobQueue, runtime: Arc<RuntimeInner>) -> Self {
        return Self{
            sync_done, job_queue, runtime,
            is_in_sync: false,
            connector_id: ConnectorId::new_invalid(),
            owned_ports: Vec::new(),
        }
    }

    /// Creates a new channel. Can only fail if the application interface is
    /// currently in sync mode.
    pub fn create_channel(&mut self) -> Result<Channel, ChannelCreationError> {
        if self.is_in_sync {
            return Err(ChannelCreationError::InSync);
        }

        let (getter_port, putter_port) = self.runtime.create_channel(self.connector_id);
        debug_assert_eq!(getter_port.kind, PortKind::Getter);
        let getter_id = getter_port.self_id;
        let putter_id = putter_port.self_id;

        {
            let mut lock = self.job_queue.lock().unwrap();
            lock.push_back(ApplicationJob::NewChannel((getter_port, putter_port)));
        }

        // Add to owned ports for error checking while creating a connector
        self.owned_ports.reserve(2);
        self.owned_ports.push((PortKind::Putter, putter_id));
        self.owned_ports.push((PortKind::Getter, getter_id));

        return Ok(Channel{ putter_id, getter_id });
    }

    /// Creates a new connector. Note that it is not scheduled immediately, but
    /// depends on the `ApplicationConnector` to run, followed by the created
    /// connector being scheduled.
    pub fn create_connector(&mut self, module: &str, routine: &str, arguments: ValueGroup) -> Result<(), ComponentCreationError> {
        if self.is_in_sync {
            return Err(ComponentCreationError::InSync);
        }

        // Retrieve ports and make sure that we own the ones that are currently
        // specified. This is also checked by the scheduler, but that is done
        // asynchronously.
        let mut initial_ports = Vec::new();
        find_ports_in_value_group(&arguments, &mut initial_ports);
        for initial_port in &initial_ports {
            if !self.owned_ports.iter().any(|(_, v)| v == initial_port) {
                return Err(ComponentCreationError::UnownedPort);
            }
        }

        // We own all ports, so remove them on this side
        for initial_port in &initial_ports {
            let position = self.owned_ports.iter().position(|(_, v)| v == initial_port).unwrap();
            self.owned_ports.remove(position);
        }

        let prompt = self.runtime.protocol_description.new_component(module.as_bytes(), routine.as_bytes(), arguments)?;
        let connector = ConnectorPDL::new(prompt);

        // Put on job queue
        {
            let mut queue = self.job_queue.lock().unwrap();
            queue.push_back(ApplicationJob::NewConnector(connector, initial_ports));
        }

        self.wake_up_connector_with_ping();

        return Ok(());
    }

    /// Queues up a description of a synchronous round to run. Will not actually
    /// run the synchronous behaviour in blocking fashion. The results *must* be
    /// retrieved using `try_wait` or `wait` for the interface to be considered
    /// in non-sync mode.
    pub fn perform_sync_round(&mut self, actions: Vec<ApplicationSyncAction>) -> Result<(), ApplicationStartSyncError> {
        if self.is_in_sync {
            return Err(ApplicationStartSyncError::AlreadyInSync);
        }

        // Check the action ports for consistency
        for action in &actions {
            let (port_id, expected_kind) = match action {
                ApplicationSyncAction::Put(port_id, _) => (*port_id, PortKind::Putter),
                ApplicationSyncAction::Get(port_id) => (*port_id, PortKind::Getter),
            };

            match self.find_port_by_id(port_id) {
                Some(port_kind) => {
                    if port_kind != expected_kind {
                        return Err(ApplicationStartSyncError::IncorrectPortKind)
                    }
                },
                None => {
                    return Err(ApplicationStartSyncError::UnownedPort);
                }
            }
        }

        // Everything is consistent, go into sync mode and send the actions off
        // to the component that will actually perform the sync round
        self.is_in_sync = true;
        {
            let (is_done, _) = &*self.sync_done;
            let mut lock = is_done.lock().unwrap();
            *lock = None;
        }

        {
            let mut lock = self.job_queue.lock().unwrap();
            lock.push_back(ApplicationJob::SyncRound(actions));
        }

        self.wake_up_connector_with_ping();
        return Ok(())
    }

    /// Wait until the next sync-round is finished, returning the received
    /// messages in order of `get` calls.
    pub fn wait(&mut self) -> Result<Vec<ValueGroup>, ApplicationEndSyncError> {
        if !self.is_in_sync {
            return Err(ApplicationEndSyncError::NotInSync);
        }

        let (is_done, condition) = &*self.sync_done;
        let mut lock = is_done.lock().unwrap();
        lock = condition.wait_while(lock, |v| v.is_none()).unwrap(); // wait while not done

        self.is_in_sync = false;
        let result = lock.take().unwrap();
        if result.success {
            return Ok(result.inbox);
        } else {
            return Err(ApplicationEndSyncError::Failure);
        }
    }

    /// Called by runtime to set associated connector's ID.
    pub(crate) fn set_connector_id(&mut self, id: ConnectorId) {
        self.connector_id = id;
    }

    fn wake_up_connector_with_ping(&self) {
        let message = ControlMessage {
            id: 0,
            sending_component_id: self.connector_id,
            content: ControlContent::Ping,
        };
        self.runtime.send_message_maybe_destroyed(self.connector_id, Message::Control(message));
    }

    fn find_port_by_id(&self, port_id: PortIdLocal) -> Option<PortKind> {
        return self.owned_ports.iter()
            .find(|(_, owned_id)| *owned_id == port_id)
            .map(|(port_kind, _)| *port_kind);
    }
}

impl Drop for ApplicationInterface {
    fn drop(&mut self) {
        {
            let mut lock = self.job_queue.lock().unwrap();
            lock.push_back(ApplicationJob::Shutdown);
        }

        self.wake_up_connector_with_ping();
        self.runtime.decrement_active_interfaces();
    }
}