iceoryx2/service/
attribute.rs

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
// Copyright (c) 2024 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

//! Attributes can be defined for a [`crate::service::Service`]. They define features that do not
//! change during the lifetime of the [`crate::service::Service`] and are accessible by anyone that
//! is allowed to open the [`crate::service::Service`].
//!
//! ## Create Service With Attributes
//!
//! ```
//! use iceoryx2::prelude::*;
//! use iceoryx2::config::Config;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let node = NodeBuilder::new().create::<ipc::Service>()?;
//!
//! let service_creator = node.service_builder(&"My/Funk/ServiceName".try_into()?)
//!     .publish_subscribe::<u64>()
//!     .create_with_attributes(
//!         // all attributes that are defined when creating a new service are stored in the
//!         // static config of the service
//!         &AttributeSpecifier::new()
//!             .define("some attribute key", "some attribute value")
//!             .define("some attribute key", "another attribute value for the same key")
//!             .define("another key", "another value")
//!     )?;
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## Open Service With Attribute Requirements
//!
//! ```no_run
//! use iceoryx2::prelude::*;
//! use iceoryx2::config::Config;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let node = NodeBuilder::new().create::<ipc::Service>()?;
//!
//! let service_open = node.service_builder(&"My/Funk/ServiceName".try_into()?)
//!     .publish_subscribe::<u64>()
//!     .open_with_attributes(
//!         // All attributes that are defined when opening a new service interpreted as
//!         // requirements.
//!         // If a attribute key as either a different value or is not set at all, the service
//!         // cannot be opened. If not specific attributes are required one can skip them completely.
//!         &AttributeVerifier::new()
//!             .require("another key", "another value")
//!             .require_key("some attribute key")
//!     )?;
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## List Attributes Of A Service
//!
//! ```no_run
//! use iceoryx2::prelude::*;
//! use iceoryx2::config::Config;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let node = NodeBuilder::new().create::<ipc::Service>()?;
//! let service = node.service_builder(&"My/Funk/ServiceName".try_into()?)
//!     .publish_subscribe::<u64>()
//!     .open()?;
//!
//! for attribute in service.attributes().iter() {
//!     println!("key {}, value {}", attribute.key(), attribute.value());
//! }
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## List Attributes Of All Services In Discovery
//!
//! ```
//! use iceoryx2::prelude::*;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let services = ipc::Service::list(Config::global_config(), |service| {
//!     println!("\n{:#?}", &service.static_details.attributes());
//!     CallbackProgression::Continue
//! })?;
//! # Ok(())
//! # }
//! ```

use serde::{Deserialize, Serialize};
use std::ops::Deref;

/// Represents a single service attribute (key-value) pair that can be defined when the service
/// is being created.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone, PartialOrd, Ord)]
pub struct Attribute {
    key: String,
    value: String,
}

impl Attribute {
    /// Acquires the service attribute key
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Acquires the service attribute value
    pub fn value(&self) -> &str {
        &self.value
    }
}

/// Represents the set of [`Attribute`]s that are defined when the [`crate::service::Service`]
/// is created.
pub struct AttributeSpecifier(pub(crate) AttributeSet);

impl Default for AttributeSpecifier {
    fn default() -> Self {
        Self(AttributeSet::new())
    }
}

impl AttributeSpecifier {
    /// Creates a new empty set of [`Attribute`]s
    pub fn new() -> Self {
        Self::default()
    }

    /// Defines a value for a specific key. A key is allowed to have multiple values.
    pub fn define(mut self, key: &str, value: &str) -> Self {
        self.0.add(key, value);
        self
    }

    /// Returns the underlying [`AttributeSet`]
    pub fn attributes(&self) -> &AttributeSet {
        &self.0
    }
}

/// Represents the set of [`Attribute`]s that are required when the [`crate::service::Service`]
/// is opened.
#[derive(Debug)]
pub struct AttributeVerifier {
    attribute_set: AttributeSet,
    required_keys: Vec<String>,
}

impl Default for AttributeVerifier {
    fn default() -> Self {
        Self {
            attribute_set: AttributeSet::new(),
            required_keys: Vec::new(),
        }
    }
}

impl AttributeVerifier {
    /// Creates a new empty set of [`Attribute`]s
    pub fn new() -> Self {
        Self::default()
    }

    /// Requires a value for a specific key. A key is allowed to have multiple values.
    pub fn require(mut self, key: &str, value: &str) -> Self {
        self.attribute_set.add(key, value);
        self
    }

    /// Requires that a specific key is defined.
    pub fn require_key(mut self, key: &str) -> Self {
        self.required_keys.push(key.into());
        self
    }

    /// Returns the underlying required [`AttributeSet`]
    pub fn attributes(&self) -> &AttributeSet {
        &self.attribute_set
    }

    /// Returns the underlying required keys
    pub fn keys(&self) -> &Vec<String> {
        &self.required_keys
    }

    /// Verifies if the [`AttributeSet`] contains all required keys and key-value pairs.
    pub fn verify_requirements(&self, rhs: &AttributeSet) -> Result<(), &str> {
        let is_subset = |lhs: Vec<&str>, rhs: Vec<&str>| lhs.iter().all(|v| rhs.contains(v));

        for attribute in self.attributes().iter() {
            let lhs_values = self.attribute_set.get(&attribute.key);
            let rhs_values = rhs.get(&attribute.key);

            if !is_subset(lhs_values, rhs_values) {
                return Err(&attribute.key);
            }
        }

        for key in self.keys() {
            if rhs.get(key).is_empty() {
                return Err(key);
            }
        }

        Ok(())
    }
}

/// Represents all service attributes. They can be set when the service is created.
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
pub struct AttributeSet(Vec<Attribute>);

impl Deref for AttributeSet {
    type Target = [Attribute];

    fn deref(&self) -> &Self::Target {
        self.0.as_slice()
    }
}

impl AttributeSet {
    pub(crate) fn new() -> Self {
        Self(Vec::new())
    }

    pub(crate) fn add(&mut self, key: &str, value: &str) {
        self.0.push(Attribute {
            key: key.into(),
            value: value.into(),
        });
        self.0.sort();
    }

    /// Returns all values to a specific key
    pub fn get(&self, key: &str) -> Vec<&str> {
        self.0
            .iter()
            .filter(|p| p.key == key)
            .map(|p| p.value.as_str())
            .collect()
    }
}