iceoryx2-cal 0.9.0

iceoryx2: [internal] high-level traits and implementations that represents OS primitives in an exchangeable fashion
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
// 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

//! **Non inter-process capable** [`CommunicationChannel`] which can be used only in a
//! process-local context.

use crate::communication_channel::*;
use crate::static_storage::file::NamedConceptConfiguration;

use core::fmt::Debug;
use core::ptr::NonNull;

use alloc::collections::BTreeMap;
use alloc::format;
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;

use iceoryx2_bb_concurrency::lazy_lock::LazyLock;
use iceoryx2_bb_lock_free::spsc::safely_overflowing_index_queue::*;
use iceoryx2_bb_posix::mutex::*;
use iceoryx2_bb_system_types::file_path::FilePath;
use iceoryx2_bb_system_types::path::Path;
use iceoryx2_log::{fail, fatal_panic, warn};

#[derive(Debug)]
pub(crate) struct Management {
    queue: SafelyOverflowingIndexQueue,
    enable_safe_overflow: bool,
}

impl Management {
    fn new(enable_safe_overflow: bool, capacity: usize) -> Self {
        Self {
            queue: SafelyOverflowingIndexQueue::new(capacity),
            enable_safe_overflow,
        }
    }
}

#[derive(Debug)]
struct StorageEntry {
    content: Arc<Management>,
}

static PROCESS_LOCAL_MTX_HANDLE: LazyLock<MutexHandle<BTreeMap<FilePath, StorageEntry>>> =
    LazyLock::new(MutexHandle::new);

static PROCESS_LOCAL_CHANNELS: LazyLock<Mutex<'static, 'static, BTreeMap<FilePath, StorageEntry>>> =
    LazyLock::new(|| {
        fatal_panic!(from "PROCESS_LOCAL_CHANNELS",
            when MutexBuilder::new()
                .is_interprocess_capable(false)
                .create(BTreeMap::new(), &PROCESS_LOCAL_MTX_HANDLE),
            "Failed to create process global communication channels")
    });

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Configuration {
    suffix: FileName,
    prefix: FileName,
    path_hint: Path,
}

impl Default for Configuration {
    fn default() -> Self {
        Self {
            suffix: Channel::default_suffix(),
            prefix: Channel::default_prefix(),
            path_hint: Channel::default_path_hint(),
        }
    }
}

impl NamedConceptConfiguration for Configuration {
    fn prefix(mut self, value: &FileName) -> Self {
        self.prefix = *value;
        self
    }

    fn get_prefix(&self) -> &FileName {
        &self.prefix
    }

    fn suffix(mut self, value: &FileName) -> Self {
        self.suffix = *value;
        self
    }

    fn path_hint(mut self, value: &Path) -> Self {
        self.path_hint = *value;
        self
    }

    fn get_suffix(&self) -> &FileName {
        &self.suffix
    }

    fn get_path_hint(&self) -> &Path {
        &self.path_hint
    }
}

#[derive(Debug)]
pub struct Creator {
    name: FileName,
    enable_safe_overflow: bool,
    buffer_size: usize,
    config: Configuration,
}

impl NamedConceptBuilder<Channel> for Creator {
    fn new(channel_name: &FileName) -> Self {
        Self {
            name: *channel_name,
            enable_safe_overflow: false,
            buffer_size: DEFAULT_RECEIVER_BUFFER_SIZE,
            config: Configuration::default(),
        }
    }

    fn config(mut self, config: &Configuration) -> Self {
        self.config = config.clone();
        self
    }
}

impl CommunicationChannelCreator<u64, Channel> for Creator {
    fn enable_safe_overflow(mut self) -> Self {
        self.enable_safe_overflow = true;
        self
    }

    fn buffer_size(mut self, value: usize) -> Self {
        self.buffer_size = value;
        self
    }

    fn create_receiver(self) -> Result<Duplex, CommunicationChannelCreateError> {
        let msg = "Failed to create receiver";

        let mut guard = fail!(from self, when PROCESS_LOCAL_CHANNELS.lock(),
            with CommunicationChannelCreateError::InternalFailure,
            "{} due to a failure while acquiring the lock.", msg);
        let full_name = self.config.path_for(&self.name);
        let entry = guard.get_mut(&full_name);
        if entry.is_some() {
            fail!(from self, with CommunicationChannelCreateError::AlreadyExists,
                "{} since the channel with the name \"{}\" already exists.", msg, self.name);
        }

        guard.insert(
            full_name,
            StorageEntry {
                content: Arc::new(Management::new(self.enable_safe_overflow, self.buffer_size)),
            },
        );

        let entry = guard.get_mut(&full_name).unwrap();

        Ok(Duplex::new_owning(
            self.name,
            entry.content.clone(),
            self.config,
        ))
    }
}

#[derive(Debug)]
pub struct Connector {
    name: FileName,
    config: Configuration,
}

impl NamedConceptBuilder<Channel> for Connector {
    fn new(channel_name: &FileName) -> Self {
        Self {
            name: *channel_name,
            config: Configuration::default(),
        }
    }

    fn config(mut self, config: &Configuration) -> Self {
        self.config = config.clone();
        self
    }
}

impl CommunicationChannelConnector<u64, Channel> for Connector {
    fn open_sender(self) -> Result<Duplex, CommunicationChannelOpenError> {
        let msg = "Failed to open sender";
        let origin = format!("{self:?}");
        let name = self.name;
        match self.try_open_sender() {
            Err(CommunicationChannelOpenError::DoesNotExist) => {
                fail!(from origin, with CommunicationChannelOpenError::DoesNotExist,
                                "{} since the channel \"{}\" does not exist.", msg, name);
            }
            Ok(v) => Ok(v),
            Err(v) => {
                fail!(from origin, with v,
                                "{} since an unknown failure occurred ({:?}).", msg, v);
            }
        }
    }

    fn try_open_sender(self) -> Result<Duplex, CommunicationChannelOpenError> {
        let msg = "Failed to open sender";

        let mut guard = fail!(from self, when PROCESS_LOCAL_CHANNELS.lock(),
            with CommunicationChannelOpenError::InternalFailure,
            "{} due to a failure while acquiring the lock.", msg);
        let full_name = self.config.path_for(&self.name);
        let entry = guard.get_mut(&full_name);
        if entry.is_none() {
            return Err(CommunicationChannelOpenError::DoesNotExist);
        }

        Ok(Duplex::new_non_owning(
            self.name,
            entry.as_ref().unwrap().content.clone(),
            self.config,
        ))
    }
}

#[derive(Debug)]
pub struct Duplex {
    name: FileName,
    management: Arc<Management>,
    config: Configuration,
    pub(crate) has_ownership: bool,
}

impl Abandonable for Duplex {
    unsafe fn abandon_in_place(mut this: NonNull<Self>) {
        let this = unsafe { this.as_mut() };
        this.has_ownership = false;
        unsafe { core::ptr::drop_in_place(this) };
    }
}

impl Drop for Duplex {
    fn drop(&mut self) {
        if self.has_ownership {
            let msg = "Failed to remove";
            let origin = "communication_channel::process_local::Duplex::remove()";

            let mut guard = fatal_panic!(from origin, when PROCESS_LOCAL_CHANNELS.lock(),
            "{} due to a failure while acquiring the lock.", msg);

            let full_name = self.config.path_for(&self.name);
            if guard.remove(&full_name).is_none() {
                warn!(from origin,
                "{} since the entry was not existing anymore. Someone else removed a communication channel that was owned by this object!", msg);
            }
        }
    }
}

impl Duplex {
    fn new(
        name: FileName,
        management: Arc<Management>,
        has_ownership: bool,
        config: Configuration,
    ) -> Self {
        Self {
            name,
            management,
            has_ownership,
            config,
        }
    }

    pub(crate) fn new_owning(
        name: FileName,
        management: Arc<Management>,
        config: Configuration,
    ) -> Self {
        Self::new(name, management, true, config)
    }

    pub(crate) fn new_non_owning(
        name: FileName,
        management: Arc<Management>,
        config: Configuration,
    ) -> Self {
        Self::new(name, management, false, config)
    }
}

impl NamedConcept for Duplex {
    fn name(&self) -> &FileName {
        &self.name
    }
}

impl CommunicationChannelSender<u64> for Duplex {
    fn send(&self, data: &u64) -> Result<Option<u64>, CommunicationChannelSendError> {
        let msg = "Unable to send data";
        match self.try_send(data) {
            Err(CommunicationChannelSendError::ReceiverCacheIsFull) => {
                fail!(from self, with CommunicationChannelSendError::ReceiverCacheIsFull,
                "{} since the receiver cache is full.", msg);
            }
            Err(e) => {
                fail!(from self, with e,
                    "{} due to an unknown failure ({:?}).", msg, e);
            }
            Ok(s) => Ok(s),
        }
    }

    fn try_send(&self, data: &u64) -> Result<Option<u64>, CommunicationChannelSendError> {
        if !self.management.enable_safe_overflow && self.management.queue.is_full() {
            return Err(CommunicationChannelSendError::ReceiverCacheIsFull);
        }

        let result = self
            .management
            .queue
            .acquire_producer()
            .unwrap()
            .push(*data);

        Ok(result)
    }
}

impl CommunicationChannelParticipant for Duplex {
    fn does_enable_safe_overflow(&self) -> bool {
        self.management.enable_safe_overflow
    }
}

impl CommunicationChannelReceiver<u64> for Duplex {
    fn buffer_size(&self) -> usize {
        self.management.queue.capacity()
    }

    fn receive(&self) -> Result<Option<u64>, CommunicationChannelReceiveError> {
        Ok(self.management.queue.acquire_consumer().unwrap().pop())
    }
}

#[derive(Debug)]
pub struct Channel {}

impl NamedConceptMgmt for Channel {
    type Configuration = Configuration;

    fn does_exist_cfg(
        name: &FileName,
        cfg: &Self::Configuration,
    ) -> Result<bool, crate::static_storage::file::NamedConceptDoesExistError> {
        let msg = "Unable to check if communication_channel::process_local exists";
        let origin = "communication_channel::process_local::Channel::does_exist_cfg()";

        let guard = fatal_panic!(from origin,
                        when PROCESS_LOCAL_CHANNELS.lock(),
                        "{} since the lock could not be acquired.", msg);

        match guard.get(&cfg.path_for(name)) {
            Some(_) => Ok(true),
            None => Ok(false),
        }
    }

    fn list_cfg(
        cfg: &Self::Configuration,
    ) -> Result<Vec<FileName>, crate::static_storage::file::NamedConceptListError> {
        let msg = "Unable to list all communication_channel::process_local";
        let origin = "communication_channel::process_local::Channel::list_cfg()";

        let guard = fatal_panic!(from origin,
                                 when PROCESS_LOCAL_CHANNELS.lock(),
                                "{} since the lock could not be acquired.", msg);

        let mut result = vec![];
        for storage_name in guard.keys() {
            if let Some(v) = cfg.extract_name_from_path(storage_name) {
                result.push(v);
            }
        }

        Ok(result)
    }

    unsafe fn remove_cfg(
        name: &FileName,
        cfg: &Self::Configuration,
    ) -> Result<bool, crate::static_storage::file::NamedConceptRemoveError> {
        let storage_name = cfg.path_for(name);
        let msg = "Unable to remove communication_channel::process_local";
        let origin = "communication_channel::process_local::Channel::remove_cfg()";

        let guard = PROCESS_LOCAL_CHANNELS.lock();
        if guard.is_err() {
            fatal_panic!(from origin,
                "{} since the lock could not be acquired.", msg);
        }

        Ok(guard.unwrap().remove(&storage_name).is_some())
    }

    fn remove_path_hint(
        _value: &Path,
    ) -> Result<(), crate::named_concept::NamedConceptPathHintRemoveError> {
        Ok(())
    }
}

impl CommunicationChannel<u64> for Channel {
    type Sender = Duplex;
    type Connector = Connector;
    type Creator = Creator;
    type Receiver = Duplex;

    fn does_support_safe_overflow() -> bool {
        true
    }

    fn has_configurable_buffer_size() -> bool {
        true
    }
}