nv_redfish_core/bmc.rs
1// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Baseboard Management Controller (BMC) client abstraction
17//!
18//! This module defines the transport-agnostic [`Bmc`] trait — a minimal
19//! interface for interacting with Redfish services. Implementors provide
20//! asynchronous operations to retrieve and expand entities, create/update
21//! resources, delete entities, and invoke actions.
22//!
23//! Key concepts:
24//! - Entity identity: Every entity is identified by an `@odata.id` ([`crate::ODataId`]).
25//! - Entity reference: Generated types implement [`crate::EntityTypeRef`], which
26//! exposes `id()` and optional `etag()` accessors.
27//! - Arc-based sharing: Read operations return `Arc<T>` to enable cheap sharing
28//! and caching while keeping values immutable.
29//! - Expansion: [`crate::Expandable`] entities can request inline expansion using
30//! [`crate::query::ExpandQuery`], matching Redfish DSP0266 semantics for `$expand`.
31//! - Actions: Actions are described by [`crate::Action<T, R>`] and are invoked via
32//! the `action` method.
33//!
34//! Operation semantics:
35//! - `get` fetches the entity at the given `@odata.id`.
36//! - `expand` fetches the entity with the provided `$expand` query.
37//! - `create` typically performs a POST to a collection identified by `id` and
38//! returns the server-provided representation (`R`).
39//! - `update` typically performs a PATCH on an entity identified by `id` and
40//! returns the updated representation (`R`).
41//! - `delete` removes the entity at `id`.
42//! - `action` posts to an action endpoint (`Action.target`).
43//! - `get_repaired`, `expand_repaired` and `filter_repaired` read like `get`,
44//! `expand` and `filter`, with a [`crate::Repair`] applied to the document
45//! before it is deserialized.
46//!
47//! Notes for implementors:
48//! - The trait is `Send + Sync` and returns `Send` futures to support use in
49//! async runtimes and multithreaded contexts.
50//! - Implementations may include client-side caching or conditional requests;
51//! these details are intentionally abstracted behind the trait.
52//! - Errors should implement `std::error::Error` and be safely transferable
53//! across threads.
54
55use serde::Deserialize;
56use serde::Serialize;
57
58use crate::query::ExpandQuery;
59use crate::Action;
60use crate::BoxTryStream;
61use crate::DecodeError;
62use crate::EntityTypeRef;
63use crate::Expandable;
64use crate::FilterQuery;
65use crate::HttpPushUriUpdateRequest;
66use crate::ModificationResponse;
67use crate::ODataETag;
68use crate::ODataId;
69use crate::Repair;
70use crate::RepairError;
71use crate::SessionCreateResponse;
72use std::error::Error as StdError;
73use std::future::Future;
74use std::pin::Pin;
75use std::sync::Arc;
76use std::task::Context;
77use std::task::Poll;
78
79use futures_core::Stream;
80
81use crate::MultipartUpdateRequest;
82use crate::UploadReader;
83
84/// Classification of a BMC operation error for resource-level policy.
85#[derive(Clone, Copy, Debug, Eq, PartialEq)]
86#[non_exhaustive]
87pub enum BmcErrorClass {
88 /// The operation received an HTTP response that was treated as an error.
89 HttpResponse {
90 /// HTTP response status code.
91 status: u16,
92 },
93
94 /// The response could not be parsed into the requested model.
95 ResponseParse,
96
97 /// The request failed before a usable response was received.
98 Transport,
99
100 /// The error has no more specific classification.
101 Other,
102}
103
104/// Error returned by a [`Bmc`] implementation.
105///
106/// Implementations can classify errors for resource-level policy without
107/// exposing transport-specific error types to Redfish resource code.
108pub trait BmcError: StdError + Send + Sync {
109 /// Classifies the error for resource-level policy decisions.
110 ///
111 /// The default returns [`BmcErrorClass::Other`] when the implementation
112 /// does not expose a more specific classification.
113 fn error_class(&self) -> BmcErrorClass {
114 BmcErrorClass::Other
115 }
116
117 /// The body of the HTTP response this error treats as one, when it has
118 /// one: a [`BmcErrorClass::HttpResponse`] whose body a layer above may
119 /// read in a platform's terms. The default is never one.
120 fn response_body(&self) -> Option<&str> {
121 None
122 }
123
124 /// The document this error failed to deserialize, when it is that.
125 ///
126 /// A transport that deserializes documents itself reports its decode
127 /// failure here, so a repaired read can tell a document that did not
128 /// match its type from a failed request. The default is never one.
129 ///
130 /// # Errors
131 ///
132 /// Returns `self` when the error is not a decode failure.
133 fn into_decode_error(self) -> Result<DecodeError, Self>
134 where
135 Self: Sized,
136 {
137 Err(self)
138 }
139}
140
141/// BMC trait defines access to a Baseboard Management Controller using
142/// the Redfish protocol.
143pub trait Bmc: Send + Sync {
144 /// BMC Error.
145 type Error: BmcError + 'static;
146
147 /// Expand any expandable object (navigation property or entity).
148 ///
149 /// `T` is structure that is used for return type.
150 fn expand<T: Expandable>(
151 &self,
152 id: &ODataId,
153 query: ExpandQuery,
154 ) -> impl Future<Output = Result<Arc<T>, Self::Error>> + Send;
155
156 /// Get data of the object (navigation property or entity).
157 ///
158 /// `T` is structure that is used for return type.
159 fn get<T: EntityTypeRef + for<'de> Deserialize<'de> + 'static>(
160 &self,
161 id: &ODataId,
162 ) -> impl Future<Output = Result<Arc<T>, Self::Error>> + Send;
163
164 /// Get and filters data of the object (navigation property or entity).
165 ///
166 /// `T` is structure that is used for return type.
167 fn filter<T: EntityTypeRef + for<'de> Deserialize<'de> + 'static>(
168 &self,
169 id: &ODataId,
170 query: FilterQuery,
171 ) -> impl Future<Output = Result<Arc<T>, Self::Error>> + Send;
172
173 /// [`Self::get`], with `repair` applied to the document before it is
174 /// deserialized.
175 ///
176 /// A document that does not deserialize after the repair is
177 /// [`RepairError::Decode`]. A transport that deserializes documents
178 /// itself repairs in the same pass. If it caches results, it serves a
179 /// cached result to every later read of the resource, whatever repair
180 /// that read asks for, so all reads of a resource through one transport
181 /// should ask for the same repair. Any other transport reads the
182 /// document as [`crate::Raw`] and hands it to
183 /// [`crate::repair::decode_raw`]; a decorator forwards to the BMC it
184 /// wraps.
185 fn get_repaired<T: EntityTypeRef + for<'de> Deserialize<'de> + 'static>(
186 &self,
187 id: &ODataId,
188 repair: &impl Repair,
189 ) -> impl Future<Output = Result<Arc<T>, RepairError<Self::Error>>> + Send;
190
191 /// [`Self::expand`], with `repair` applied as for
192 /// [`Self::get_repaired`].
193 fn expand_repaired<T: Expandable>(
194 &self,
195 id: &ODataId,
196 query: ExpandQuery,
197 repair: &impl Repair,
198 ) -> impl Future<Output = Result<Arc<T>, RepairError<Self::Error>>> + Send;
199
200 /// [`Self::filter`], with `repair` applied as for
201 /// [`Self::get_repaired`].
202 fn filter_repaired<T: EntityTypeRef + for<'de> Deserialize<'de> + 'static>(
203 &self,
204 id: &ODataId,
205 query: FilterQuery,
206 repair: &impl Repair,
207 ) -> impl Future<Output = Result<Arc<T>, RepairError<Self::Error>>> + Send;
208
209 /// Creates element of the collection.
210 ///
211 /// `V` is structure that is used for create.
212 /// `R` is structure that is used for return type.
213 fn create<V: Send + Sync + Serialize, R: Send + Sync + for<'de> Deserialize<'de>>(
214 &self,
215 id: &ODataId,
216 query: &V,
217 ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;
218
219 /// Creates a Redfish session.
220 ///
221 /// Session creation is special in Redfish: the response body contains the
222 /// session entity, `X-Auth-Token` contains the token used for subsequent
223 /// requests, and `Location` contains the URI to delete when logging out.
224 fn create_session<V: Send + Sync + Serialize, R: Send + Sync + for<'de> Deserialize<'de>>(
225 &self,
226 id: &ODataId,
227 query: &V,
228 ) -> impl Future<Output = Result<SessionCreateResponse<R>, Self::Error>> + Send;
229
230 /// Update entity.
231 ///
232 /// `V` is structure that is used for update.
233 /// `R` is structure that is used for return type (updated entity).
234 fn update<V: Sync + Send + Serialize, R: Send + Sync + Sized + for<'de> Deserialize<'de>>(
235 &self,
236 id: &ODataId,
237 etag: Option<&ODataETag>,
238 update: &V,
239 ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;
240
241 /// Delete entity.
242 fn delete<R: EntityTypeRef + for<'de> Deserialize<'de>>(
243 &self,
244 id: &ODataId,
245 ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;
246
247 /// Run action.
248 ///
249 /// Implementations should resolve the action `target` as a Redfish URI
250 /// reference. Absolute targets are allowed by Redfish and BMC-relative
251 /// targets should remain supported.
252 ///
253 /// Implementations may reject URI references that violate their outbound
254 /// request policy before transport.
255 ///
256 /// `T` is structure that contains action parameters.
257 /// `R` is structure with return type.
258 fn action<T: Send + Sync + Serialize, R: Send + Sync + Sized + for<'de> Deserialize<'de>>(
259 &self,
260 action: &Action<T, R>,
261 params: &T,
262 ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;
263
264 /// GET a URI of an asynchronous operation, such as a Task Monitor.
265 ///
266 /// A pending response is a `Task`; without a new location it keeps
267 /// `uri`. A finished response is read like a modification response, and a
268 /// finished response without a body that names a `Location` is read as
269 /// `{"@odata.id": <Location>}`.
270 ///
271 /// `uri` should be resolved as a Redfish URI reference. Implementations may
272 /// reject references that violate their outbound request policy.
273 fn poll<R: Send + Sync + Sized + for<'de> Deserialize<'de>>(
274 &self,
275 uri: &ODataId,
276 ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send;
277
278 /// POST a Redfish `UpdateService` multipart upload using a named stream.
279 ///
280 /// `uri` is the service-provided `MultipartHttpPushUri` and should be
281 /// resolved as a Redfish URI reference.
282 ///
283 /// Implementations may reject URI references that violate their outbound
284 /// request policy before transport.
285 fn multipart_update<U, V, R>(
286 &self,
287 uri: &str,
288 request: MultipartUpdateRequest<'_, U, V>,
289 ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send
290 where
291 U: UploadReader,
292 R: Send + Sync + for<'de> Deserialize<'de>,
293 V: Send + Sync + Serialize;
294
295 /// POST a raw binary stream to a Redfish `UpdateService` `HttpPushUri`.
296 ///
297 /// `uri` is the service-provided `HttpPushUri` and should be resolved as a
298 /// Redfish URI reference.
299 ///
300 /// Implementations may reject URI references that violate their outbound
301 /// request policy before transport.
302 fn http_push_uri_update<U, R>(
303 &self,
304 uri: &str,
305 request: HttpPushUriUpdateRequest<U>,
306 ) -> impl Future<Output = Result<ModificationResponse<R>, Self::Error>> + Send
307 where
308 U: UploadReader,
309 R: Send + Sync + for<'de> Deserialize<'de>;
310
311 /// Stream data for the URI.
312 ///
313 /// `uri` should be resolved as a Redfish URI reference.
314 ///
315 /// Implementations may reject URI references that violate their outbound
316 /// request policy before transport.
317 ///
318 /// `T` is structure that is used for the stream return type.
319 fn stream<T: Sized + for<'de> Deserialize<'de> + Send + 'static>(
320 &self,
321 uri: &str,
322 ) -> impl Future<Output = Result<BoxTryStream<T, Self::Error>, Self::Error>> + Send;
323
324 /// Stream server-sent events from the URI with the id each carries,
325 /// resuming after `last_event_id`.
326 ///
327 /// Same URI rules as [`Bmc::stream`]. Every item is a [`StreamEvent`]:
328 /// the event's `data` decoded into `T`, with the event id in effect.
329 /// `last_event_id` is the id a consumer kept from an earlier stream of
330 /// the same URI, sent as `Last-Event-ID` so a server that retains
331 /// history replays the events after it, and in effect on the new stream
332 /// until the server sets another; `None`, or an empty id, starts at the
333 /// server's live position.
334 ///
335 /// The default forwards to [`Bmc::stream`]: its events carry no id and
336 /// nothing is sent to resume from, which cannot mislead a consumer, since
337 /// it only ever holds an id this method gave it. A transport that
338 /// surfaces SSE ids overrides it.
339 fn stream_events<T: Sized + for<'de> Deserialize<'de> + Send + 'static>(
340 &self,
341 uri: &str,
342 last_event_id: Option<&str>,
343 ) -> impl Future<Output = Result<BoxTryStream<StreamEvent<T>, Self::Error>, Self::Error>> + Send
344 where
345 Self::Error: 'static,
346 {
347 let _ = last_event_id;
348 async move { self.stream::<T>(uri).await.map(without_event_ids) }
349 }
350}
351
352/// One event a server-sent event stream delivered.
353///
354/// `data` is the event's payload, decoded into the type the stream was
355/// opened with. `last_event_id` is the SSE `id` in effect when the event was
356/// dispatched: a server sets it per event, it persists over later events
357/// that carry none, and an `id` field with an empty value clears it, as the
358/// SSE processing model prescribes. A consumer that reopens the stream hands
359/// it back through [`Bmc::stream_events`] to resume after this event. A
360/// server that never sets one, or a transport that does not surface ids,
361/// leaves it `None` throughout.
362#[derive(Clone, Debug, PartialEq, Eq)]
363pub struct StreamEvent<T> {
364 /// The id to resume after this event, if the server set one.
365 pub last_event_id: Option<String>,
366 /// The event's decoded payload.
367 pub data: T,
368}
369
370/// `stream` as a stream of [`StreamEvent`]s that carry no id: the view a
371/// transport that does not surface SSE ids gives through
372/// [`Bmc::stream_events`].
373#[must_use]
374pub fn without_event_ids<T, E>(stream: BoxTryStream<T, E>) -> BoxTryStream<StreamEvent<T>, E>
375where
376 T: 'static,
377 E: 'static,
378{
379 Box::pin(WithoutEventIds(stream))
380}
381
382struct WithoutEventIds<T, E>(BoxTryStream<T, E>);
383
384impl<T, E> Stream for WithoutEventIds<T, E> {
385 type Item = Result<StreamEvent<T>, E>;
386
387 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
388 self.0.as_mut().poll_next(cx).map(|item| {
389 item.map(|result| {
390 result.map(|data| StreamEvent {
391 last_event_id: None,
392 data,
393 })
394 })
395 })
396 }
397}
398
399#[cfg(test)]
400mod tests {
401 use std::task::Waker;
402 use std::vec::IntoIter;
403
404 use super::*;
405
406 /// A stream over a fixed list of items.
407 struct Items(IntoIter<Result<u8, &'static str>>);
408
409 impl Stream for Items {
410 type Item = Result<u8, &'static str>;
411
412 fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
413 Poll::Ready(self.0.next())
414 }
415 }
416
417 #[test]
418 fn without_ids_keeps_items_and_errors_and_attaches_no_id() {
419 let items = Items(vec![Ok(1), Err("lost"), Ok(2)].into_iter());
420 let mut events = without_event_ids(Box::pin(items));
421 let mut cx = Context::from_waker(Waker::noop());
422 let event = |data| {
423 Poll::Ready(Some(Ok(StreamEvent {
424 last_event_id: None,
425 data,
426 })))
427 };
428
429 assert_eq!(events.as_mut().poll_next(&mut cx), event(1));
430 assert_eq!(
431 events.as_mut().poll_next(&mut cx),
432 Poll::Ready(Some(Err("lost")))
433 );
434 assert_eq!(events.as_mut().poll_next(&mut cx), event(2));
435 assert_eq!(events.as_mut().poll_next(&mut cx), Poll::Ready(None));
436 }
437}