aboutsummaryrefslogtreecommitdiff
path: root/nearby/presence/np_ffi_core/src/common.rs
blob: 6333db54d21a913e543b0e6e376b9c38159b80e8 (plain)
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
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Common externally-accessible FFI constructs which are needed
//! in order to define the interfaces in this crate's various modules.

use array_view::ArrayView;
use handle_map::HandleNotPresentError;
use lock_adapter::std::RwLock;
use lock_adapter::RwLock as _;
use std::string::String;

const DEFAULT_MAX_HANDLES: u32 = u32::MAX - 1;

/// Configuration for top-level constants to be used
/// by the rest of the FFI which are independent of
/// the programming language which we ultimately
/// interface with at a higher level.
#[repr(C)]
pub struct CommonConfig {
    /// The number of shards to employ in all handle-maps,
    /// or zero if we want to use the default.
    ///
    /// The default number of shards will depend on whether
    /// this crate was compiled with the `std` feature or not:
    /// - If compiled with the `std` feature, the default number
    ///   of shards will be set to
    ///   `min(16, std::thread::available_parallelism().unwrap())`,
    ///   assuming that that call completes successfully.
    /// - In all other cases, 16 shards will be used by default.
    num_shards: u8,

    /// The maximum number of credential slabs which may be active
    /// at any one time. By default, this value will be set to
    /// `u32::MAX - 1`, which is the upper-bound on this value.
    max_num_credential_slabs: u32,

    /// The maximum number of credential books which may be active
    /// at any one time. By default, this value will be set to
    /// `u32::MAX - 1`, which is the upper-bound on this value.
    max_num_credential_books: u32,

    /// The maximum number of deserialized v0 advertisements
    /// which may be active at any one time. By default, this
    /// value will be set to `u32::MAX - 1`, which is the upper-bound
    /// on this value.
    max_num_deserialized_v0_advertisements: u32,

    /// The maximum number of deserialized v1 advertisements
    /// which may be active at any one time. By default, this
    /// value will be set to `u32::MAX - 1`, which is the upper-bound
    /// on this value.
    max_num_deserialized_v1_advertisements: u32,
}

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

impl CommonConfig {
    pub(crate) const fn new() -> Self {
        Self {
            num_shards: 0,
            max_num_credential_slabs: DEFAULT_MAX_HANDLES,
            max_num_credential_books: DEFAULT_MAX_HANDLES,
            max_num_deserialized_v0_advertisements: DEFAULT_MAX_HANDLES,
            max_num_deserialized_v1_advertisements: DEFAULT_MAX_HANDLES,
        }
    }
    #[cfg(feature = "std")]
    pub(crate) fn num_shards(&self) -> u8 {
        if self.num_shards == 0 {
            match std::thread::available_parallelism() {
                Ok(parallelism) => 16u8.min(parallelism),
                Err(_) => 16u8,
            }
        } else {
            self.num_shards
        }
    }
    #[cfg(not(feature = "std"))]
    pub(crate) fn num_shards(&self) -> u8 {
        if self.num_shards == 0 {
            16u8
        } else {
            self.num_shards
        }
    }
    pub(crate) fn max_num_credential_slabs(&self) -> u32 {
        self.max_num_credential_slabs
    }
    pub(crate) fn max_num_credential_books(&self) -> u32 {
        self.max_num_credential_books
    }
    pub(crate) fn max_num_deserialized_v0_advertisements(&self) -> u32 {
        self.max_num_deserialized_v0_advertisements
    }
    pub(crate) fn max_num_deserialized_v1_advertisements(&self) -> u32 {
        self.max_num_deserialized_v1_advertisements
    }
    pub(crate) fn set_num_shards(&mut self, num_shards: u8) {
        self.num_shards = num_shards
    }

    /// Sets the maximum number of active handles to credential-books
    /// which may be active at any one time.
    /// Max value: `u32::MAX - 1`.
    pub fn set_max_num_credential_books(&mut self, max_num_credential_books: u32) {
        self.max_num_credential_books = DEFAULT_MAX_HANDLES.min(max_num_credential_books)
    }

    /// Sets the maximum number of active handles to credential-slabs
    /// which may be active at any one time.
    /// Max value: `u32::MAX - 1`.
    pub fn set_max_num_credential_slabs(&mut self, max_num_credential_slabs: u32) {
        self.max_num_credential_slabs = DEFAULT_MAX_HANDLES.min(max_num_credential_slabs)
    }

    /// Sets the maximum number of active handles to deserialized v0
    /// advertisements which may be active at any one time.
    /// Max value: `u32::MAX - 1`.
    pub fn set_max_num_deserialized_v0_advertisements(
        &mut self,
        max_num_deserialized_v0_advertisements: u32,
    ) {
        self.max_num_deserialized_v0_advertisements =
            DEFAULT_MAX_HANDLES.min(max_num_deserialized_v0_advertisements)
    }

    /// Sets the maximum number of active handles to deserialized v0
    /// advertisements which may be active at any one time.
    /// Max value: `u32::MAX - 1`.
    pub fn set_max_num_deserialized_v1_advertisements(
        &mut self,
        max_num_deserialized_v1_advertisements: u32,
    ) {
        self.max_num_deserialized_v1_advertisements =
            DEFAULT_MAX_HANDLES.min(max_num_deserialized_v1_advertisements)
    }
}

static COMMON_CONFIG: RwLock<CommonConfig> = RwLock::new(CommonConfig::new());

pub(crate) fn global_num_shards() -> u8 {
    COMMON_CONFIG.read().num_shards()
}
pub(crate) fn global_max_num_credential_slabs() -> u32 {
    COMMON_CONFIG.read().max_num_credential_slabs()
}
pub(crate) fn global_max_num_credential_books() -> u32 {
    COMMON_CONFIG.read().max_num_credential_books()
}
pub(crate) fn global_max_num_deserialized_v0_advertisements() -> u32 {
    COMMON_CONFIG.read().max_num_deserialized_v0_advertisements()
}
pub(crate) fn global_max_num_deserialized_v1_advertisements() -> u32 {
    COMMON_CONFIG.read().max_num_deserialized_v1_advertisements()
}

/// Sets an override to the number of shards to employ in the NP FFI's
/// internal handle-maps, which places an upper bound on the number
/// of writing threads which may make progress at any one time
/// when concurrently accessing handles of the same type.
///
/// By default, this value will be set to 16, or in `std` environments,
/// the minimum of 16 and the number of available hardware threads.
/// A shard value override of zero will be interpreted the same
/// as this default.
///
/// Setting this value will have no effect if the handle-maps for the
/// API have already begun being used by the client code, and any
/// values set will take effect upon the first usage of _any_ non-`global_config_set`
/// API call.
pub fn global_config_set_num_shards(num_shards: u8) {
    let mut config = COMMON_CONFIG.write();
    config.set_num_shards(num_shards);
}

/// Sets the maximum number of active handles to credential slabs
/// which may be active at any one time. Max value: `u32::MAX - 1`.
///
/// Setting this value will have no effect if the handle-maps for the
/// API have already begun being used by the client code, and any
/// values set will take effect upon the first usage of any API
/// call utilizing credential slabs.
pub fn global_config_set_max_num_credential_slabs(max_num_credential_slabs: u32) {
    let mut config = COMMON_CONFIG.write();
    config.set_max_num_credential_slabs(max_num_credential_slabs);
}
/// Sets the maximum number of active handles to credential books
/// which may be active at any one time. Max value: `u32::MAX - 1`.
///
/// Setting this value will have no effect if the handle-maps for the
/// API have already begun being used by the client code, and any
/// values set will take effect upon the first usage of any API
/// call utilizing credential books.
pub fn global_config_set_max_num_credential_books(max_num_credential_books: u32) {
    let mut config = COMMON_CONFIG.write();
    config.set_max_num_credential_books(max_num_credential_books);
}

/// Sets the maximum number of active handles to deserialized v0
/// advertisements which may be active at any one time.
/// Max value: `u32::MAX - 1`.
///
/// Setting this value will have no effect if the handle-maps for the
/// API have already begun being used by the client code, and any
/// values set will take effect upon the first usage of any API
/// call which references or returns a deserialized V0 advertisement.
pub fn global_config_set_max_num_deserialized_v0_advertisements(
    max_num_deserialized_v0_advertisements: u32,
) {
    let mut config = COMMON_CONFIG.write();
    config.set_max_num_deserialized_v0_advertisements(max_num_deserialized_v0_advertisements);
}

/// Sets the maximum number of active handles to deserialized v1
/// advertisements which may be active at any one time.
/// Max value: `u32::MAX - 1`.
///
/// Setting this value will have no effect if the handle-maps for the
/// API have already begun being used by the client code, and any
/// values set will take effect upon the first usage of any API
/// call which references or returns a deserialized V1 advertisement.
pub fn global_config_set_max_num_deserialized_v1_advertisements(
    max_num_deserialized_v1_advertisements: u32,
) {
    let mut config = COMMON_CONFIG.write();
    config.set_max_num_deserialized_v1_advertisements(max_num_deserialized_v1_advertisements);
}

// API surfaces:

/// A result-type enum which tells the caller whether/not a deallocation
/// succeeded or failed due to the requested handle not being present.
#[repr(C)]
pub enum DeallocateResult {
    /// The requested handle to deallocate was not present in the map
    NotPresent = 0,
    /// The object behind the handle was successfully deallocated
    Success = 1,
}

impl From<Result<(), HandleNotPresentError>> for DeallocateResult {
    fn from(result: Result<(), HandleNotPresentError>) -> Self {
        match result {
            Ok(_) => DeallocateResult::Success,
            Err(_) => DeallocateResult::NotPresent,
        }
    }
}

/// Represents the raw contents of the service payload data
/// under the Nearby Presence service UUID
#[repr(C)]
pub struct RawAdvertisementPayload {
    bytes: ByteBuffer<255>,
}

impl RawAdvertisementPayload {
    /// Yields a slice of the bytes in this raw advertisement payload.
    pub fn as_slice(&self) -> &[u8] {
        self.bytes.as_slice()
    }
}

/// A byte-string with a maximum size of N,
/// where only the first `len` bytes are considered
/// to contain the actual payload. N is only
/// permitted to be between 0 and 255.
#[derive(Clone)]
#[repr(C)]
// TODO: Once generic const exprs are stabilized,
// we could instead make N into a compile-time u8.
pub struct ByteBuffer<const N: usize> {
    len: u8,
    bytes: [u8; N],
}

impl<const N: usize> ByteBuffer<N> {
    /// Constructs a byte-buffer from a Rust-side-derived
    /// ArrayView, which is assumed to be trusted to be
    /// properly initialized, and with a size-bound
    /// under 255 bytes.
    pub(crate) fn from_array_view(array_view: ArrayView<u8, N>) -> Self {
        let (len, bytes) = array_view.into_raw_parts();
        let len = len as u8;
        Self { len, bytes }
    }
    /// Yields a slice of the first `self.len` bytes of `self.bytes`.
    pub fn as_slice(&self) -> &[u8] {
        &self.bytes[..(self.len as usize)]
    }
}

/// The DE type for an encrypted identity
#[derive(Clone, Copy)]
#[repr(u8)]
pub enum EncryptedIdentityType {
    /// Identity for broadcasts to nearby devices with the same
    /// logged-in-account (for some account).
    Private = 1,
    /// Identity for broadcasts to nearby devices which this
    /// device has declared to trust.
    Trusted = 2,
    /// Identity for broadcasts to devices which have been provisioned
    /// offline with this device.
    Provisioned = 4,
}

impl From<np_adv::de_type::EncryptedIdentityDataElementType> for EncryptedIdentityType {
    fn from(value: np_adv::de_type::EncryptedIdentityDataElementType) -> Self {
        use np_adv::de_type::EncryptedIdentityDataElementType;
        match value {
            EncryptedIdentityDataElementType::Private => Self::Private,
            EncryptedIdentityDataElementType::Trusted => Self::Trusted,
            EncryptedIdentityDataElementType::Provisioned => Self::Provisioned,
        }
    }
}

/// Error raised when attempting to cast an enum to
/// one of its variants, but the value is actually
/// of a different variant than the requested one.
pub struct EnumCastError {
    pub(crate) projection_method_name: String,
    pub(crate) variant_enum_name: String,
    pub(crate) variant_type_name: String,
}

impl core::fmt::Debug for EnumCastError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "Attempted to cast a non-{} to a {} via {}",
            &self.variant_enum_name, &self.variant_type_name, &self.projection_method_name
        )
    }
}