nv-redfish-core 0.22.2

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
// 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.

//! Baseboard Management Controller (BMC) client abstraction
//!
//! This module defines the transport-agnostic [`Bmc`] trait — a minimal
//! interface for interacting with Redfish services. Implementors provide
//! asynchronous operations to retrieve and expand entities, create/update
//! resources, delete entities, and invoke actions.
//!
//! Key concepts:
//! - Entity identity: Every entity is identified by an `@odata.id` ([`crate::ODataId`]).
//! - Entity reference: Generated types implement [`crate::EntityTypeRef`], which
//!   exposes `id()` and optional `etag()` accessors.
//! - Arc-based sharing: Read operations return `Arc<T>` to enable cheap sharing
//!   and caching while keeping values immutable.
//! - Expansion: [`crate::Expandable`] entities can request inline expansion using
//!   [`crate::query::ExpandQuery`], matching Redfish DSP0266 semantics for `$expand`.
//! - Actions: Actions are described by [`crate::Action<T, R>`] and are invoked via
//!   the `action` method.
//!
//! Operation semantics:
//! - `get` fetches the entity at the given `@odata.id`.
//! - `expand` fetches the entity with the provided `$expand` query.
//! - `create` typically performs a POST to a collection identified by `id` and
//!   returns the server-provided representation (`R`).
//! - `update` typically performs a PATCH on an entity identified by `id` and
//!   returns the updated representation (`R`).
//! - `delete` removes the entity at `id`.
//! - `action` posts to an action endpoint (`Action.target`).
//! - `get_repaired`, `expand_repaired` and `filter_repaired` read like `get`,
//!   `expand` and `filter`, with a [`crate::Repair`] applied to the document
//!   before it is deserialized.
//!
//! Notes for implementors:
//! - The trait is `Send + Sync` and returns `Send` futures to support use in
//!   async runtimes and multithreaded contexts.
//! - Implementations may include client-side caching or conditional requests;
//!   these details are intentionally abstracted behind the trait.
//! - Errors should implement `std::error::Error` and be safely transferable
//!   across threads.

use serde::Deserialize;
use serde::Serialize;

use crate::query::ExpandQuery;
use crate::Action;
use crate::BoxTryStream;
use crate::DecodeError;
use crate::EntityTypeRef;
use crate::Expandable;
use crate::FilterQuery;
use crate::HttpPushUriUpdateRequest;
use crate::ModificationResponse;
use crate::ODataETag;
use crate::ODataId;
use crate::Repair;
use crate::RepairError;
use crate::SessionCreateResponse;
use std::error::Error as StdError;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;

use futures_core::Stream;

use crate::MultipartUpdateRequest;
use crate::UploadReader;

/// Classification of a BMC operation error for resource-level policy.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum BmcErrorClass {
    /// The operation received an HTTP response that was treated as an error.
    HttpResponse {
        /// HTTP response status code.
        status: u16,
    },

    /// The response could not be parsed into the requested model.
    ResponseParse,

    /// The request failed before a usable response was received.
    Transport,

    /// The error has no more specific classification.
    Other,
}

/// Error returned by a [`Bmc`] implementation.
///
/// Implementations can classify errors for resource-level policy without
/// exposing transport-specific error types to Redfish resource code.
pub trait BmcError: StdError + Send + Sync {
    /// Classifies the error for resource-level policy decisions.
    ///
    /// The default returns [`BmcErrorClass::Other`] when the implementation
    /// does not expose a more specific classification.
    fn error_class(&self) -> BmcErrorClass {
        BmcErrorClass::Other
    }

    /// The body of the HTTP response this error treats as one, when it has
    /// one: a [`BmcErrorClass::HttpResponse`] whose body a layer above may
    /// read in a platform's terms. The default is never one.
    fn response_body(&self) -> Option<&str> {
        None
    }

    /// The document this error failed to deserialize, when it is that.
    ///
    /// A transport that deserializes documents itself reports its decode
    /// failure here, so a repaired read can tell a document that did not
    /// match its type from a failed request. The default is never one.
    ///
    /// # Errors
    ///
    /// Returns `self` when the error is not a decode failure.
    fn into_decode_error(self) -> Result<DecodeError, Self>
    where
        Self: Sized,
    {
        Err(self)
    }
}

/// BMC trait defines access to a Baseboard Management Controller using
/// the Redfish protocol.
pub trait Bmc: Send + Sync {
    /// BMC Error.
    type Error: BmcError + 'static;

    /// Expand any expandable object (navigation property or entity).
    ///
    /// `T` is structure that is used for return type.
    fn expand<T: Expandable>(
        &self,
        id: &ODataId,
        query: ExpandQuery,
    ) -> impl Future<Output = Result<Arc<T>, Self::Error>> + Send;

    /// Get data of the object (navigation property or entity).
    ///
    /// `T` is structure that is used for return type.
    fn get<T: EntityTypeRef + for<'de> Deserialize<'de> + 'static>(
        &self,
        id: &ODataId,
    ) -> impl Future<Output = Result<Arc<T>, Self::Error>> + Send;

    /// Get and filters data of the object (navigation property or entity).
    ///
    /// `T` is structure that is used for return type.
    fn filter<T: EntityTypeRef + for<'de> Deserialize<'de> + 'static>(
        &self,
        id: &ODataId,
        query: FilterQuery,
    ) -> impl Future<Output = Result<Arc<T>, Self::Error>> + Send;

    /// [`Self::get`], with `repair` applied to the document before it is
    /// deserialized.
    ///
    /// A document that does not deserialize after the repair is
    /// [`RepairError::Decode`]. A transport that deserializes documents
    /// itself repairs in the same pass. If it caches results, it serves a
    /// cached result to every later read of the resource, whatever repair
    /// that read asks for, so all reads of a resource through one transport
    /// should ask for the same repair. Any other transport reads the
    /// document as [`crate::Raw`] and hands it to
    /// [`crate::repair::decode_raw`]; a decorator forwards to the BMC it
    /// wraps.
    fn get_repaired<T: EntityTypeRef + for<'de> Deserialize<'de> + 'static>(
        &self,
        id: &ODataId,
        repair: &impl Repair,
    ) -> impl Future<Output = Result<Arc<T>, RepairError<Self::Error>>> + Send;

    /// [`Self::expand`], with `repair` applied as for
    /// [`Self::get_repaired`].
    fn expand_repaired<T: Expandable>(
        &self,
        id: &ODataId,
        query: ExpandQuery,
        repair: &impl Repair,
    ) -> impl Future<Output = Result<Arc<T>, RepairError<Self::Error>>> + Send;

    /// [`Self::filter`], with `repair` applied as for
    /// [`Self::get_repaired`].
    fn filter_repaired<T: EntityTypeRef + for<'de> Deserialize<'de> + 'static>(
        &self,
        id: &ODataId,
        query: FilterQuery,
        repair: &impl Repair,
    ) -> impl Future<Output = Result<Arc<T>, RepairError<Self::Error>>> + Send;

    /// Creates element of the collection.
    ///
    /// `V` is structure that is used for create.
    /// `R` is structure that is used for return type.
    fn create<V: Send + Sync + Serialize, R: Send + Sync + for<'de> Deserialize<'de>>(
        &self,
        id: &ODataId,
        query: &V,
    ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;

    /// Creates a Redfish session.
    ///
    /// Session creation is special in Redfish: the response body contains the
    /// session entity, `X-Auth-Token` contains the token used for subsequent
    /// requests, and `Location` contains the URI to delete when logging out.
    fn create_session<V: Send + Sync + Serialize, R: Send + Sync + for<'de> Deserialize<'de>>(
        &self,
        id: &ODataId,
        query: &V,
    ) -> impl Future<Output = Result<SessionCreateResponse<R>, Self::Error>> + Send;

    /// Update entity.
    ///
    /// `V` is structure that is used for update.
    /// `R` is structure that is used for return type (updated entity).
    fn update<V: Sync + Send + Serialize, R: Send + Sync + Sized + for<'de> Deserialize<'de>>(
        &self,
        id: &ODataId,
        etag: Option<&ODataETag>,
        update: &V,
    ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;

    /// Delete entity.
    fn delete<R: EntityTypeRef + for<'de> Deserialize<'de>>(
        &self,
        id: &ODataId,
    ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;

    /// Run action.
    ///
    /// Implementations should resolve the action `target` as a Redfish URI
    /// reference. Absolute targets are allowed by Redfish and BMC-relative
    /// targets should remain supported.
    ///
    /// Implementations may reject URI references that violate their outbound
    /// request policy before transport.
    ///
    /// `T` is structure that contains action parameters.
    /// `R` is structure with return type.
    fn action<T: Send + Sync + Serialize, R: Send + Sync + Sized + for<'de> Deserialize<'de>>(
        &self,
        action: &Action<T, R>,
        params: &T,
    ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;

    /// GET a URI of an asynchronous operation, such as a Task Monitor.
    ///
    /// A pending response is a `Task`; without a new location it keeps
    /// `uri`. A finished response is read like a modification response, and a
    /// finished response without a body that names a `Location` is read as
    /// `{"@odata.id": <Location>}`.
    ///
    /// `uri` should be resolved as a Redfish URI reference. Implementations may
    /// reject references that violate their outbound request policy.
    fn poll<R: Send + Sync + Sized + for<'de> Deserialize<'de>>(
        &self,
        uri: &ODataId,
    ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;

    /// POST a Redfish `UpdateService` multipart upload using a named stream.
    ///
    /// `uri` is the service-provided `MultipartHttpPushUri` and should be
    /// resolved as a Redfish URI reference.
    ///
    /// Implementations may reject URI references that violate their outbound
    /// request policy before transport.
    fn multipart_update<U, V, R>(
        &self,
        uri: &str,
        request: MultipartUpdateRequest<'_, U, V>,
    ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send
    where
        U: UploadReader,
        R: Send + Sync + for<'de> Deserialize<'de>,
        V: Send + Sync + Serialize;

    /// POST a raw binary stream to a Redfish `UpdateService` `HttpPushUri`.
    ///
    /// `uri` is the service-provided `HttpPushUri` and should be resolved as a
    /// Redfish URI reference.
    ///
    /// Implementations may reject URI references that violate their outbound
    /// request policy before transport.
    fn http_push_uri_update<U, R>(
        &self,
        uri: &str,
        request: HttpPushUriUpdateRequest<U>,
    ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send
    where
        U: UploadReader,
        R: Send + Sync + for<'de> Deserialize<'de>;

    /// Stream data for the URI.
    ///
    /// `uri` should be resolved as a Redfish URI reference.
    ///
    /// Implementations may reject URI references that violate their outbound
    /// request policy before transport.
    ///
    /// `T` is structure that is used for the stream return type.
    fn stream<T: Sized + for<'de> Deserialize<'de> + Send + 'static>(
        &self,
        uri: &str,
    ) -> impl Future<Output = Result<BoxTryStream<T, Self::Error>, Self::Error>> + Send;

    /// Stream server-sent events from the URI with the id each carries,
    /// resuming after `last_event_id`.
    ///
    /// Same URI rules as [`Bmc::stream`]. Every item is a [`StreamEvent`]:
    /// the event's `data` decoded into `T`, with the event id in effect.
    /// `last_event_id` is the id a consumer kept from an earlier stream of
    /// the same URI, sent as `Last-Event-ID` so a server that retains
    /// history replays the events after it, and in effect on the new stream
    /// until the server sets another; `None`, or an empty id, starts at the
    /// server's live position.
    ///
    /// The default forwards to [`Bmc::stream`]: its events carry no id and
    /// nothing is sent to resume from, which cannot mislead a consumer, since
    /// it only ever holds an id this method gave it. A transport that
    /// surfaces SSE ids overrides it.
    fn stream_events<T: Sized + for<'de> Deserialize<'de> + Send + 'static>(
        &self,
        uri: &str,
        last_event_id: Option<&str>,
    ) -> impl Future<Output = Result<BoxTryStream<StreamEvent<T>, Self::Error>, Self::Error>> + Send
    where
        Self::Error: 'static,
    {
        let _ = last_event_id;
        async move { self.stream::<T>(uri).await.map(without_event_ids) }
    }
}

/// One event a server-sent event stream delivered.
///
/// `data` is the event's payload, decoded into the type the stream was
/// opened with. `last_event_id` is the SSE `id` in effect when the event was
/// dispatched: a server sets it per event, it persists over later events
/// that carry none, and an `id` field with an empty value clears it, as the
/// SSE processing model prescribes. A consumer that reopens the stream hands
/// it back through [`Bmc::stream_events`] to resume after this event. A
/// server that never sets one, or a transport that does not surface ids,
/// leaves it `None` throughout.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamEvent<T> {
    /// The id to resume after this event, if the server set one.
    pub last_event_id: Option<String>,
    /// The event's decoded payload.
    pub data: T,
}

/// `stream` as a stream of [`StreamEvent`]s that carry no id: the view a
/// transport that does not surface SSE ids gives through
/// [`Bmc::stream_events`].
#[must_use]
pub fn without_event_ids<T, E>(stream: BoxTryStream<T, E>) -> BoxTryStream<StreamEvent<T>, E>
where
    T: 'static,
    E: 'static,
{
    Box::pin(WithoutEventIds(stream))
}

struct WithoutEventIds<T, E>(BoxTryStream<T, E>);

impl<T, E> Stream for WithoutEventIds<T, E> {
    type Item = Result<StreamEvent<T>, E>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.0.as_mut().poll_next(cx).map(|item| {
            item.map(|result| {
                result.map(|data| StreamEvent {
                    last_event_id: None,
                    data,
                })
            })
        })
    }
}

#[cfg(test)]
mod tests {
    use std::task::Waker;
    use std::vec::IntoIter;

    use super::*;

    /// A stream over a fixed list of items.
    struct Items(IntoIter<Result<u8, &'static str>>);

    impl Stream for Items {
        type Item = Result<u8, &'static str>;

        fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
            Poll::Ready(self.0.next())
        }
    }

    #[test]
    fn without_ids_keeps_items_and_errors_and_attaches_no_id() {
        let items = Items(vec![Ok(1), Err("lost"), Ok(2)].into_iter());
        let mut events = without_event_ids(Box::pin(items));
        let mut cx = Context::from_waker(Waker::noop());
        let event = |data| {
            Poll::Ready(Some(Ok(StreamEvent {
                last_event_id: None,
                data,
            })))
        };

        assert_eq!(events.as_mut().poll_next(&mut cx), event(1));
        assert_eq!(
            events.as_mut().poll_next(&mut cx),
            Poll::Ready(Some(Err("lost")))
        );
        assert_eq!(events.as_mut().poll_next(&mut cx), event(2));
        assert_eq!(events.as_mut().poll_next(&mut cx), Poll::Ready(None));
    }
}