iceoryx2 0.9.0

iceoryx2: Lock-Free Zero-Copy Interprocess Communication
Documentation
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
560
561
562
563
564
565
566
567
568
569
570
// Copyright (c) 2023 Contributors to the Eclipse Foundation
//
// See the NOTICE file(s) distributed with this work for additional
// information regarding copyright ownership.
//
// This program and the accompanying materials are made available under the
// terms of the Apache Software License 2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
// which is available at https://opensource.org/licenses/MIT.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! # Example
//!
//! ```
//! use iceoryx2::prelude::*;
//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
//! let node = NodeBuilder::new().create::<ipc::Service>()?;
//! let event = node.service_builder(&"MyEventName".try_into()?)
//!     .event()
//!     .open_or_create()?;
//!
//! let notifier = event
//!     .notifier_builder()
//!     .default_event_id(EventId::new(12))
//!     .create()?;
//!
//! // notify with default event id 123
//! notifier.notify()?;
//!
//! // notify with some custom event id
//! notifier.notify_with_custom_event_id(EventId::new(6))?;
//!
//! # Ok(())
//! # }
//! ```

use core::ptr::NonNull;
use core::time::Duration;

use alloc::vec;
use alloc::vec::Vec;

use iceoryx2_bb_concurrency::atomic::Ordering;
use iceoryx2_bb_concurrency::cell::UnsafeCell;
use iceoryx2_bb_elementary::CallbackProgression;
use iceoryx2_bb_elementary_traits::non_null::NonNullCompat;
use iceoryx2_bb_elementary_traits::testing::abandonable::Abandonable;
use iceoryx2_bb_lock_free::mpmc::container::{ContainerHandle, ContainerState};
use iceoryx2_cal::{
    arc_sync_policy::ArcSyncPolicy, dynamic_storage::DynamicStorage, event::NotifierBuilder,
};
use iceoryx2_cal::{event::Event, named_concept::NamedConceptBuilder};
use iceoryx2_log::{debug, fail, warn};

use crate::service::SharedServiceState;
use crate::{
    identifiers::{UniqueListenerId, UniqueNodeId, UniqueNotifierId},
    port::update_connections::UpdateConnections,
    service::{
        self, NoResource,
        config_scheme::event_config,
        dynamic_config::event::{ListenerDetails, NotifierDetails},
        naming_scheme::event_concept_name,
    },
};

use super::event_id::EventId;

/// Failures that can occur when a new [`Notifier`] is created with the
/// [`crate::service::port_factory::notifier::PortFactoryNotifier`].
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum NotifierCreateError {
    /// The maximum amount of [`Notifier`]s that can connect to a
    /// [`Service`](crate::service::Service) is
    /// defined in [`crate::config::Config`]. When this is exceeded no more [`Notifier`]s
    /// can be created for a specific [`Service`](crate::service::Service).
    ExceedsMaxSupportedNotifiers,
    /// Caused by a failure when instantiating a [`ArcSyncPolicy`] defined in the
    /// [`Service`](crate::service::Service) as `ArcThreadSafetyPolicy`.
    FailedToDeployThreadsafetyPolicy,
    /// The tracking port tag, required for cleanup, could not be created.
    UnableToCreatePortTag,
}

impl core::fmt::Display for NotifierCreateError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "NotifierCreateError::{self:?}")
    }
}

impl core::error::Error for NotifierCreateError {}

/// Defines the failures that can occur while a [`Notifier::notify()`] call.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum NotifierNotifyError {
    /// A [`Notifier::notify_with_custom_event_id()`] was called and the provided [`EventId`]
    /// is greater than the maximum supported [`EventId`] by the
    /// [`Service`](crate::service::Service)
    EventIdOutOfBounds,
    /// The notification was delivered to all [`Listener`](crate::port::listener::Listener) ports
    /// but the deadline contract, the maximum time span between two notifications, of the
    /// [`Service`](crate::service::Service) was violated.
    MissedDeadline,
    /// The notification was delivered but the elapsed system time could not be acquired.
    /// Therefore, it is unknown if the deadline was missed or not.
    UnableToAcquireElapsedTime,
}

impl core::fmt::Display for NotifierNotifyError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "NotifierNotifyError::{self:?}")
    }
}

impl core::error::Error for NotifierNotifyError {}

#[derive(Debug)]
struct Connection<Service: service::Service> {
    notifier: <Service::Event as Event>::Notifier,
    listener_id: UniqueListenerId,
    node_id: UniqueNodeId,
}

#[derive(Debug)]
struct ListenerConnections<Service: service::Service> {
    #[allow(clippy::type_complexity)]
    connections: Vec<UnsafeCell<Option<Connection<Service>>>>,
    service_state: SharedServiceState<Service, NoResource>,
    list_state: UnsafeCell<ContainerState<ListenerDetails>>,
}

impl<Service: service::Service> Abandonable for ListenerConnections<Service> {
    unsafe fn abandon_in_place(mut this: NonNull<Self>) {
        let this = unsafe { this.as_mut() };
        unsafe {
            SharedServiceState::abandon_in_place(NonNull::iox2_from_mut(&mut this.service_state))
        };
    }
}

impl<Service: service::Service> ListenerConnections<Service> {
    fn new(
        size: usize,
        service_state: SharedServiceState<Service, NoResource>,
        list_state: UnsafeCell<ContainerState<ListenerDetails>>,
    ) -> Self {
        let mut new_self = Self {
            connections: vec![],
            service_state,
            list_state,
        };

        new_self.connections.reserve(size);
        for _ in 0..size {
            new_self.connections.push(UnsafeCell::new(None))
        }

        new_self
    }

    fn create(&self, index: usize, listener_id: UniqueListenerId, node_id: UniqueNodeId) {
        let msg = "Unable to establish connection to listener";
        let event_name = event_concept_name(&listener_id);
        let event_config = event_config::<Service>(self.service_state.shared_node().config());
        if self.get(index).is_none() {
            match <Service::Event as iceoryx2_cal::event::Event>::NotifierBuilder::new(&event_name)
                .config(&event_config)
                .open()
            {
                Ok(notifier) => {
                    *self.get_mut(index) = Some(Connection {
                        notifier,
                        listener_id,
                        node_id,
                    });
                }
                Err(
                    iceoryx2_cal::event::NotifierCreateError::DoesNotExist
                    | iceoryx2_cal::event::NotifierCreateError::InitializationNotYetFinalized,
                ) => (),
                Err(iceoryx2_cal::event::NotifierCreateError::VersionMismatch) => {
                    warn!(from self,
                        "{} since a version mismatch was detected! All entities must use the same iceoryx2 version!",
                        msg);
                }
                Err(iceoryx2_cal::event::NotifierCreateError::InsufficientPermissions) => {
                    warn!(from self, "{} since the permissions do not match. The service or the participants are maybe misconfigured.", msg);
                }
                Err(iceoryx2_cal::event::NotifierCreateError::Interrupt) => {
                    debug!(from self, "{} since an interrupt signal was received.", msg);
                }
                Err(iceoryx2_cal::event::NotifierCreateError::InternalFailure) => {
                    debug!(from self, "{} due to an internal failure.", msg);
                }
            }
        }
    }

    fn get(&self, index: usize) -> &Option<Connection<Service>> {
        unsafe { &(*self.connections[index].get()) }
    }

    #[allow(clippy::mut_from_ref)]
    fn get_mut(&self, index: usize) -> &mut Option<Connection<Service>> {
        unsafe { &mut (*self.connections[index].get()) }
    }

    fn len(&self) -> usize {
        self.connections.len()
    }

    fn remove(&self, index: usize) {
        *self.get_mut(index) = None;
    }

    fn update_connections(&self) {
        if unsafe {
            self.service_state
                .dynamic_storage()
                .get()
                .event()
                .listeners
                .update_state(&mut *self.list_state.get())
        } {
            self.populate_listener_channels();
        }
    }

    fn populate_listener_channels(&self) {
        let mut visited_indices = vec![];
        visited_indices.resize(self.len(), None);

        unsafe {
            (*self.list_state.get()).for_each(|index, listener_id| {
                visited_indices[index] = Some(*listener_id);
                CallbackProgression::Continue
            })
        };

        for (i, index) in visited_indices.iter().enumerate() {
            match index {
                Some(details) => {
                    let create_connection = match self.get(i) {
                        None => true,
                        Some(connection) => {
                            let is_connected = connection.listener_id != details.listener_id;
                            if is_connected {
                                self.remove(i);
                            }
                            is_connected
                        }
                    };

                    if create_connection {
                        self.create(i, details.listener_id, details.node_id);
                    }
                }
                None => self.remove(i),
            }
        }
    }
}

/// Represents the sending endpoint of an event based communication.
#[derive(Debug)]
pub struct Notifier<Service: service::Service> {
    listener_connections: Service::ArcThreadSafetyPolicy<ListenerConnections<Service>>,
    default_event_id: EventId,
    event_id_max_value: usize,
    dynamic_notifier_handle: Option<ContainerHandle>,
    notifier_id: UniqueNotifierId,
    on_drop_notification: Option<EventId>,
    node_id: UniqueNodeId,
    // IMPORTANT!
    // Fields of a rust struct are dropped in declaration order. Since this tag is our marker that the
    // port exists and might require cleanup after a crash, the tag must be defined as last member of
    // the struct.
    // Otherwise the process might crash during cleanup, has already removed the tag but other resources
    // are still existing. This would make a cleanup from another process impossible.
    port_tag: Service::StaticStorage,
}

unsafe impl<Service: service::Service> Send for Notifier<Service> where
    Service::ArcThreadSafetyPolicy<ListenerConnections<Service>>: Send + Sync
{
}

unsafe impl<Service: service::Service> Sync for Notifier<Service> where
    Service::ArcThreadSafetyPolicy<ListenerConnections<Service>>: Send + Sync
{
}

impl<Service: service::Service> Abandonable for Notifier<Service> {
    unsafe fn abandon_in_place(mut this: NonNull<Self>) {
        let this = unsafe { this.as_mut() };
        unsafe {
            Service::ArcThreadSafetyPolicy::abandon_in_place(NonNull::iox2_from_mut(
                &mut this.listener_connections,
            ))
        };
        unsafe {
            Service::StaticStorage::abandon_in_place(NonNull::iox2_from_mut(&mut this.port_tag));
        }
    }
}

impl<Service: service::Service> Drop for Notifier<Service> {
    fn drop(&mut self) {
        if let Some(event_id) = self.on_drop_notification {
            if let Err(e) = self.notify_with_custom_event_id(event_id) {
                warn!(from self, "Unable to send notifier_dropped_event {:?} due to ({:?}).",
                    event_id, e);
            }
        }

        if let Some(handle) = self.dynamic_notifier_handle {
            self.listener_connections
                .lock()
                .service_state
                .dynamic_storage()
                .get()
                .event()
                .release_notifier_handle(handle)
        }
    }
}

impl<Service: service::Service> UpdateConnections for Notifier<Service> {
    fn update_connections(&self) -> Result<(), super::update_connections::ConnectionFailure> {
        self.listener_connections.lock().update_connections();
        Ok(())
    }
}

impl<Service: service::Service> Notifier<Service> {
    pub(crate) fn new(
        service: SharedServiceState<Service, NoResource>,
        default_event_id: EventId,
    ) -> Result<Self, NotifierCreateError> {
        let mut new_self =
            Self::new_without_auto_event_emission(service.clone(), default_event_id)?;

        let static_config = service.static_config().event();
        new_self.on_drop_notification = static_config
            .notifier_dropped_event
            .map(EventId::new)
            .into();

        if let Some(event_id) = static_config.notifier_created_event() {
            match new_self.notify_with_custom_event_id(event_id) {
                Ok(_)
                | Err(
                    NotifierNotifyError::MissedDeadline
                    | NotifierNotifyError::UnableToAcquireElapsedTime,
                ) => (),
                Err(e) => {
                    warn!(from new_self,
                        "The new notifier was unable to send out the notifier_created_event: {:?} due to ({:?}).",
                        event_id, e);
                }
            }
        }

        Ok(new_self)
    }

    pub(crate) fn new_without_auto_event_emission(
        service: SharedServiceState<Service, NoResource>,
        default_event_id: EventId,
    ) -> Result<Self, NotifierCreateError> {
        let msg = "Unable to create Notifier port";
        let origin = "Notifier::new()";
        let notifier_id = UniqueNotifierId::new();

        // !MUST! be the first thing that is created when a new port is instantiated otherwise the
        // port resources might leak if this process is killed in between.
        let port_tag = match service.shared_node().create_port_tag(
            origin,
            msg,
            notifier_id.0.value(),
        ) {
            Ok(port_tag) => port_tag,
            Err(e) => {
                fail!(from origin, with NotifierCreateError::UnableToCreatePortTag,
                        "{msg} since the port tag, that is required for cleanup, could not be created. [{e:?}]");
            }
        };

        let listener_list = &service.dynamic_storage().get().event().listeners;

        let node_id = *service.shared_node().id();
        let static_config = service.static_config().event();
        let listener_connections = Service::ArcThreadSafetyPolicy::new(ListenerConnections::new(
            listener_list.capacity(),
            service.clone(),
            UnsafeCell::new(unsafe { listener_list.get_state() }),
        ));

        let listener_connections = match listener_connections {
            Ok(v) => v,
            Err(e) => {
                fail!(from origin, with NotifierCreateError::FailedToDeployThreadsafetyPolicy,
                      "{msg} since the threadsafety policy could not be instantiated ({e:?}).");
            }
        };

        let mut new_self = Self {
            port_tag,
            listener_connections,
            default_event_id,
            event_id_max_value: static_config.event_id_max_value,
            dynamic_notifier_handle: None,
            notifier_id,
            on_drop_notification: None,
            node_id,
        };

        new_self
            .listener_connections
            .lock()
            .populate_listener_channels();

        core::sync::atomic::compiler_fence(Ordering::SeqCst);

        // !MUST! be the last task otherwise a notifier is added to the dynamic config without
        // the creation of all required channels
        let dynamic_notifier_handle = match new_self
            .listener_connections
            .lock()
            .service_state
            .dynamic_storage()
            .get()
            .event()
            .add_notifier_id(NotifierDetails {
                notifier_id,
                node_id,
            }) {
            Some(handle) => handle,
            None => {
                fail!(from origin, with NotifierCreateError::ExceedsMaxSupportedNotifiers,
                            "{} since it would exceed the maximum supported amount of notifiers of {}.",
                            msg, service.static_config().event().max_notifiers);
            }
        };
        new_self.dynamic_notifier_handle = Some(dynamic_notifier_handle);

        Ok(new_self)
    }

    /// Returns the [`UniqueNotifierId`] of the [`Notifier`]
    pub fn id(&self) -> UniqueNotifierId {
        self.notifier_id
    }

    /// Notifies all [`crate::port::listener::Listener`] connected to the service with the default
    /// event id provided on creation.
    /// On success the number of
    /// [`crate::port::listener::Listener`]s that were notified otherwise it returns
    /// [`NotifierNotifyError`].
    pub fn notify(&self) -> Result<usize, NotifierNotifyError> {
        self.notify_with_custom_event_id(self.default_event_id)
    }

    /// Returns the deadline of the corresponding [`Service`](crate::service::Service).
    pub fn deadline(&self) -> Option<Duration> {
        self.listener_connections
            .lock()
            .service_state
            .static_config()
            .event()
            .deadline
            .map(|v| v.value.into())
            .into()
    }

    /// Notifies all [`crate::port::listener::Listener`] connected to the service with a custom
    /// [`EventId`].
    /// On success the number of
    /// [`crate::port::listener::Listener`]s that were notified otherwise it returns
    /// [`NotifierNotifyError`].
    pub fn notify_with_custom_event_id(
        &self,
        value: EventId,
    ) -> Result<usize, NotifierNotifyError> {
        self.__internal_notify(value, false)
    }

    /// Notifies all [`crate::port::listener::Listener`] connected to the service with a custom
    /// [`EventId`].
    /// On success the number of
    /// [`crate::port::listener::Listener`]s that were notified otherwise it returns
    /// [`NotifierNotifyError`].
    ///
    /// When `skip_self_deliver` is set to true the [`Notifier`] will only notify
    /// [`crate::port::listener::Listener`]s that were NOT created by the same node (have the same
    /// [`crate::node::NodeId`])
    #[doc(hidden)]
    pub fn __internal_notify(
        &self,
        value: EventId,
        skip_self_deliver: bool,
    ) -> Result<usize, NotifierNotifyError> {
        let msg = "Unable to notify event";
        let listener_connections = self.listener_connections.lock();
        listener_connections.update_connections();

        use iceoryx2_cal::event::Notifier;
        let mut number_of_triggered_listeners = 0;

        if self.event_id_max_value < value.as_value() {
            fail!(from self, with NotifierNotifyError::EventIdOutOfBounds,
                            "{} since the EventId {:?} exceeds the maximum supported EventId value of {}.",
                            msg, value, self.event_id_max_value);
        }

        for i in 0..listener_connections.len() {
            if let Some(connection) = listener_connections.get(i) {
                if !(skip_self_deliver && connection.node_id == self.node_id) {
                    match connection.notifier.notify(value) {
                        Err(iceoryx2_cal::event::NotifierNotifyError::Disconnected) => {
                            listener_connections.remove(i);
                        }
                        Err(e) => {
                            warn!(from self, "Unable to send notification via connection {:?} due to {:?}.",
                                    connection, e)
                        }
                        Ok(_) => {
                            number_of_triggered_listeners += 1;
                        }
                    }
                }
            }
        }

        if let Some(deadline) = listener_connections
            .service_state
            .static_config()
            .event()
            .deadline
            .as_option_ref()
        {
            let msg = "The notification was sent";
            let duration_since_creation = fail!(from self, when deadline.creation_time.elapsed(),
                                with NotifierNotifyError::UnableToAcquireElapsedTime,
                                "{} but the elapsed system time could not be acquired which is required for deadline handling.",
                                msg);

            let previous_duration_since_creation = listener_connections
                .service_state
                .dynamic_storage()
                .get()
                .event()
                .elapsed_time_since_last_notification
                .swap(duration_since_creation.as_nanos() as u64, Ordering::Relaxed);

            let duration_since_last_notification = Duration::from_nanos(
                duration_since_creation.as_nanos() as u64 - previous_duration_since_creation,
            );

            if duration_since_last_notification > deadline.value.into() {
                fail!(from self, with NotifierNotifyError::MissedDeadline,
                "{} but the deadline was hit. The service requires a notification after {:?} but {:?} passed without a notification.",
                msg, deadline.value, duration_since_last_notification);
            }
        }

        Ok(number_of_triggered_listeners)
    }
}