nv-redfish-core 0.11.0

Semantic-unaware foundation used by code generated from CSDL for nv-redfish
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
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// 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.

//! Core Redfish foundation library used by code generated from the CSDL compiler.
//!
//! Purpose
//! - Serve as a dependency for autogenerated Redfish types produced by the CSDL compiler.
//! - Provide semantic-unaware primitives that generated code relies on.
//! - Avoid any knowledge of specific Redfish services, schemas, or OEM semantics.
//!
//! Scope (building blocks only)
//! - Identity and metadata: [`ODataId`], [`ODataETag`]
//! - EDM value wrappers: [`EdmDateTimeOffset`], [`EdmDuration`]
//! - Navigation properties: [`NavProperty<T>`]
//! - Generic operation traits: [`Creatable`], [`Updatable`], [`Deletable`]
//! - Entity contracts: [`EntityTypeRef`], [`Expandable`]
//! - Action envelope: [`Action<T, R>`]
//! - Client abstraction: [`Bmc`] (transport-agnostic interface used by generated code)
//!
//! Non-goals
//! - No service- or schema-specific models are defined here.
//! - No business logic or policy decisions are embedded here.
//! - No transport specification
//!
//! How generated code uses these primitives
//! - Each generated entity struct implements [`EntityTypeRef`].
//! - Navigation properties in generated code are wrapped in [`NavProperty<T>`].
//! - Generated actions are represented as [`Action<T, R>`].
//! - If the schema allows it, generated types implement [`Creatable`], [`Updatable`], and/or
//!   [`Deletable`] and route operations through a user-provided [`Bmc`] implementation.

#![deny(
    clippy::all,
    clippy::pedantic,
    clippy::nursery,
    clippy::suspicious,
    clippy::complexity,
    clippy::perf
)]
#![deny(
    clippy::absolute_paths,
    clippy::todo,
    clippy::unimplemented,
    clippy::tests_outside_test_module,
    clippy::panic,
    clippy::unwrap_used,
    clippy::unwrap_in_result,
    clippy::unused_trait_names,
    clippy::print_stdout,
    clippy::print_stderr
)]
#![deny(missing_docs)]

/// Action-related types.
pub mod action;
/// BMC trait and credentials.
pub mod bmc;
/// Custom deserialization helpers.
pub mod deserialize;
/// Dynamic properties support.
pub mod dynamic_properties;
/// `Edm.DateTimeOffset` type.
pub mod edm_date_time_offset;
/// `Edm.Duration` type.
pub mod edm_duration;
/// `Edm.PrimitiveType` type.
pub mod edm_primitive_type;
/// Navigation property wrapper.
pub mod nav_property;
/// Type for `@odata.id` identifier.
pub mod odata;
/// Support of redfish queries
pub mod query;
/// Upload data types.
pub mod upload;

use crate::query::ExpandQuery;
use futures_core::TryStream;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::pin::Pin;
use std::time::Duration;
use std::{future::Future, sync::Arc};

#[doc(inline)]
pub use action::Action;
#[doc(inline)]
pub use action::ActionError;
#[doc(inline)]
pub use bmc::Bmc;
#[doc(inline)]
pub use deserialize::de_optional_nullable;
#[doc(inline)]
pub use deserialize::de_required_nullable;
#[doc(inline)]
pub use dynamic_properties::DynamicProperties;
#[doc(inline)]
pub use edm_date_time_offset::EdmDateTimeOffset;
#[doc(inline)]
pub use edm_duration::EdmDuration;
#[doc(inline)]
pub use edm_primitive_type::EdmPrimitiveType;
#[doc(inline)]
pub use nav_property::NavProperty;
#[doc(inline)]
pub use nav_property::Reference;
#[doc(inline)]
pub use nav_property::ReferenceLeaf;
#[doc(inline)]
pub use odata::ODataETag;
#[doc(inline)]
pub use odata::ODataId;
#[doc(inline)]
pub use query::FilterQuery;
#[doc(inline)]
pub use query::ToFilterLiteral;
#[doc(inline)]
pub use serde_json::Value as AdditionalProperties;
#[doc(inline)]
pub use upload::DataStream;
#[cfg(feature = "update-service-deprecated")]
#[doc(inline)]
pub use upload::HttpPushUriUpdateRequest;
#[doc(inline)]
pub use upload::MultipartUpdateRequest;
#[doc(inline)]
pub use upload::OemMultipartPart;
#[doc(inline)]
pub use upload::OemMultipartPartNameError;
#[doc(inline)]
pub use upload::OemMultipartPartReader;
#[doc(inline)]
pub use upload::UploadReader;
#[cfg(feature = "update-service-deprecated")]
#[doc(inline)]
pub use upload::UploadStream;
#[doc(inline)]
pub use uuid::Uuid as EdmGuid;

/// Entity type reference trait implemented by the CSDL compiler
/// for all generated entity types and for all [`NavProperty<T>`] where
/// `T` is a struct for an entity type.
pub trait EntityTypeRef: Send + Sync + Sized {
    /// Value of `@odata.id` field of the Entity.
    fn odata_id(&self) -> &ODataId;

    /// Value of `@odata.etag` field of the Entity.
    fn etag(&self) -> Option<&ODataETag>;

    /// Refresh the entity by fetching it again from the BMC.
    fn refresh<B: Bmc>(&self, bmc: &B) -> impl Future<Output = Result<Arc<Self>, B::Error>> + Send
    where
        Self: for<'de> Deserialize<'de> + 'static,
    {
        bmc.get::<Self>(self.odata_id())
    }
}

/// Defines entity types that support `$expand` via query parameters.
pub trait Expandable: EntityTypeRef + for<'de> Deserialize<'de> + 'static {
    /// Expand the entity according to the provided query.
    fn expand<B: Bmc>(
        &self,
        bmc: &B,
        query: ExpandQuery,
    ) -> impl Future<Output = Result<Arc<Self>, B::Error>> + Send {
        bmc.expand::<Self>(self.odata_id(), query)
    }
}

/// Boxed fallible stream used by BMC streaming APIs.
pub type BoxTryStream<T, E> =
    Pin<Box<dyn TryStream<Ok = T, Error = E, Item = Result<T, E>> + Send>>;

/// Location of an asynchronous task monitor.
///
/// Wraps the `Location` returned for an operation that is completing
/// asynchronously.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct AsyncTaskLocation(
    /// `OData` URI returned in the async response `Location` header.
    pub ODataId,
);

impl From<ODataId> for AsyncTaskLocation {
    fn from(value: ODataId) -> Self {
        Self(value)
    }
}

/// Outcome of a mutating Redfish operation that can complete asynchronously.
#[derive(Debug)]
pub struct AsyncTask {
    /// Location to use for polling completion.
    pub location: AsyncTaskLocation,

    /// Recommended duration to wait before polling again.
    pub retry_after: Option<Duration>,
}

/// Outcome of a mutating Redfish operation.
#[must_use = "mutating Redfish responses may contain an asynchronous task handle"]
#[derive(Debug)]
pub enum ModificationResponse<T> {
    /// Request completed synchronously.
    Entity(T),

    /// Request is completing asynchronously with the provided task location.
    Task(AsyncTask),

    /// Request completed successfully with no response body.
    Empty,
}

impl<T> ModificationResponse<T> {
    /// Maps an entity outcome while preserving task and empty outcomes.
    pub fn map_entity<U, F>(self, f: F) -> ModificationResponse<U>
    where
        F: FnOnce(T) -> U,
    {
        match self {
            Self::Entity(entity) => ModificationResponse::Entity(f(entity)),
            Self::Task(task) => ModificationResponse::Task(task),
            Self::Empty => ModificationResponse::Empty,
        }
    }

    /// Maps an entity outcome with a fallible function while preserving task
    /// and empty outcomes.
    ///
    /// # Errors
    ///
    /// Returns the error produced by `f` when this response contains an entity.
    pub fn try_map_entity<U, E, F>(self, f: F) -> Result<ModificationResponse<U>, E>
    where
        F: FnOnce(T) -> Result<U, E>,
    {
        match self {
            Self::Entity(entity) => f(entity).map(ModificationResponse::Entity),
            Self::Task(task) => Ok(ModificationResponse::Task(task)),
            Self::Empty => Ok(ModificationResponse::Empty),
        }
    }

    /// Asynchronously maps an entity outcome with a fallible function while
    /// preserving task and empty outcomes.
    ///
    /// # Errors
    ///
    /// Returns the error produced by `f` when this response contains an entity.
    pub async fn try_map_entity_async<U, E, F, Fut>(
        self,
        f: F,
    ) -> Result<ModificationResponse<U>, E>
    where
        F: FnOnce(T) -> Fut,
        Fut: Future<Output = Result<U, E>>,
    {
        match self {
            Self::Entity(entity) => f(entity).await.map(ModificationResponse::Entity),
            Self::Task(task) => Ok(ModificationResponse::Task(task)),
            Self::Empty => Ok(ModificationResponse::Empty),
        }
    }
}

/// Redfish session creation returns the session resource in the response body,
/// the authentication token in the `X-Auth-Token` header, and the session URI in
/// the `Location` header.
pub struct SessionCreateResponse<T> {
    /// Created session entity.
    pub entity: T,
    /// Authentication token from `X-Auth-Token`.
    pub auth_token: String,
    /// Session resource URI from `Location`.
    pub location: ODataId,
}

impl<T: fmt::Debug> fmt::Debug for SessionCreateResponse<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SessionCreateResponse")
            .field("entity", &self.entity)
            .field("auth_token", &"[REDACTED]")
            .field("location", &self.location)
            .finish()
    }
}

/// This trait is assigned to the collections that are marked as
/// creatable in the CSDL specification.
pub trait Creatable<V: Send + Sync + Serialize, R: Send + Sync + for<'de> Deserialize<'de>>:
    EntityTypeRef
{
    /// Create an entity using `create` as payload.
    fn create<B: Bmc>(
        &self,
        bmc: &B,
        create: &V,
    ) -> impl Future<Output = Result<ModificationResponse<R>, B::Error>> + Send {
        bmc.create::<V, R>(self.odata_id(), create)
    }
}

/// This trait is assigned to entity types that are marked as
/// updatable in the CSDL specification.
pub trait Updatable<V: Sync + Send + Serialize>: EntityTypeRef + for<'de> Deserialize<'de> {
    /// Update an entity using `update` as payload.
    fn update<B: Bmc>(
        &self,
        bmc: &B,
        update: &V,
    ) -> impl Future<Output = Result<ModificationResponse<Self>, B::Error>> + Send {
        bmc.update::<V, Self>(self.odata_id(), self.etag(), update)
    }
}

/// This trait is assigned to entity types that are marked as
/// deletable in the CSDL specification.
pub trait Deletable: EntityTypeRef + for<'de> Deserialize<'de> {
    /// Delete current entity.
    fn delete<B: Bmc>(
        &self,
        bmc: &B,
    ) -> impl Future<Output = Result<ModificationResponse<Self>, B::Error>> + Send {
        bmc.delete::<Self>(self.odata_id())
    }
}

/// This trait is assigned to updatable entity types to support
/// @Redfish.Settings workflow.
pub trait RedfishSettings<E: EntityTypeRef>: Sized {
    /// Reference to the enity type object.
    fn settings_object(&self) -> Option<NavProperty<E>>;
}

/// Trait for converting enum variants to `snake_case` strings
pub trait ToSnakeCase {
    /// Convert this enum variant to a `snake_case` string
    fn to_snake_case(&self) -> &'static str;
}

/// Trait for types that can be used as filter properties in `OData` queries
pub trait FilterProperty {
    /// Returns the `OData` property path for this property
    fn property_path(&self) -> &str;
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_entity(
        response: ModificationResponse<u32>,
        expected: u32,
    ) -> Result<(), &'static str> {
        let ModificationResponse::Entity(value) = response else {
            return Err("expected an entity response");
        };

        assert_eq!(value, expected);

        Ok(())
    }

    fn assert_task<T>(response: ModificationResponse<T>) -> Result<(), &'static str> {
        let ModificationResponse::Task(task) = response else {
            return Err("expected a task response");
        };

        assert_eq!(
            task.location.0.to_string(),
            "/redfish/v1/TaskService/Tasks/1"
        );

        Ok(())
    }

    fn assert_empty<T>(response: ModificationResponse<T>) -> Result<(), &'static str> {
        if !matches!(response, ModificationResponse::Empty) {
            return Err("expected an empty response");
        }

        Ok(())
    }

    fn task_response() -> ModificationResponse<()> {
        ModificationResponse::Task(AsyncTask {
            location: ODataId::from("/redfish/v1/TaskService/Tasks/1".to_string()).into(),
            retry_after: None,
        })
    }

    #[test]
    fn map_entity_maps_entity_and_preserves_task_and_empty() -> Result<(), &'static str> {
        assert_entity(
            ModificationResponse::Entity(21_u32).map_entity(|value| value * 2),
            42,
        )?;

        assert_task(task_response().map_entity(|()| 42_u32))?;
        assert_empty(ModificationResponse::<()>::Empty.map_entity(|()| 42_u32))?;

        Ok(())
    }

    #[test]
    fn try_map_entity_maps_entity_and_propagates_error() -> Result<(), &'static str> {
        assert_entity(
            ModificationResponse::Entity(21_u32).try_map_entity(|value| Ok(value * 2))?,
            42,
        )?;

        let error = ModificationResponse::Entity(21_u32)
            .try_map_entity(|_| Err::<u32, _>("mapping failed"));

        assert!(matches!(error, Err("mapping failed")));

        Ok(())
    }

    #[test]
    fn try_map_entity_preserves_task_and_empty() -> Result<(), &'static str> {
        assert_task(task_response().try_map_entity(|()| Ok::<u32, &'static str>(42))?)?;

        assert_empty(
            ModificationResponse::<()>::Empty.try_map_entity(|()| Ok::<u32, &'static str>(42))?,
        )?;

        Ok(())
    }

    #[tokio::test]
    async fn try_map_entity_async_maps_entity_and_preserves_task_and_empty(
    ) -> Result<(), &'static str> {
        assert_entity(
            ModificationResponse::Entity(21_u32)
                .try_map_entity_async(|value| async move { Ok(value * 2) })
                .await?,
            42,
        )?;

        assert_task(
            task_response()
                .try_map_entity_async(|()| async { Ok::<u32, &'static str>(42) })
                .await?,
        )?;

        assert_empty(
            ModificationResponse::<()>::Empty
                .try_map_entity_async(|()| async { Ok::<u32, &'static str>(42) })
                .await?,
        )?;

        Ok(())
    }

    #[tokio::test]
    async fn try_map_entity_async_propagates_mapper_error() {
        let response = ModificationResponse::Entity(21_u32);

        let mapped = response
            .try_map_entity_async(|_| async { Err::<u32, _>("mapping failed") })
            .await;

        assert!(matches!(mapped, Err("mapping failed")));
    }
}