Skip to main content

qcs_api_client_openapi/apis/
reservations_api.rs

1// Copyright 2026 Rigetti Computing
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15/*
16 * Rigetti QCS API
17 *
18 * # Introduction  This is the documentation for the Rigetti QCS HTTP API.  You can find out more about Rigetti at [https://rigetti.com](https://rigetti.com), and also interact with QCS via the web at [https://qcs.rigetti.com](https://qcs.rigetti.com).  This API is documented in **OpenAPI format** and so is compatible with the dozens of language-specific client generators available [here](https://github.com/OpenAPITools/openapi-generator) and elsewhere on the web.  # Principles  This API follows REST design principles where appropriate, and otherwise an HTTP RPC paradigm. We adhere to the Google [API Improvement Proposals](https://google.aip.dev/general) where reasonable to provide a consistent, intuitive developer experience. HTTP response codes match their specifications, and error messages fit a common format.  # Authentication  All access to the QCS API requires OAuth2 authentication provided by Okta. You can request access [here](https://www.rigetti.com/get-quantum). Once you have a user account, you can download your access token from QCS [here](https://qcs.rigetti.com/auth/token).   That access token is valid for 24 hours after issuance. The value of `access_token` within the JSON file is the token used for authentication (don't use the entire JSON file).  Authenticate requests using the `Authorization` header and a `Bearer` prefix:  ``` curl --header \"Authorization: Bearer eyJraW...Iow\" ```  # Quantum Processor Access  Access to the quantum processors themselves is not yet provided directly by this HTTP API, but is instead performed over ZeroMQ/[rpcq](https://github.com/rigetti/rpcq). Until that changes, we suggest using [pyquil](https://github.com/rigetti/pyquil) to build and execute quantum programs via the Legacy API.  # Legacy API  Our legacy HTTP API remains accessible at https://forest-server.qcs.rigetti.com, and it shares a source of truth with this API's services. You can use either service with the same user account and means of authentication. We strongly recommend using the API documented here, as the legacy API is on the path to deprecation.
19 *
20 * The version of the OpenAPI document: 2020-07-31
21 * Contact: support@rigetti.com
22 * Generated by: https://openapi-generator.tech
23 */
24
25use super::{ContentType, Error, configuration};
26use crate::{apis::ResponseContent, models};
27use ::qcs_api_client_common::backoff::{
28    BackoffBuilder, ExponentialBackoff, duration_from_io_error, duration_from_reqwest_error,
29    duration_from_response,
30};
31#[cfg(feature = "tracing")]
32use qcs_api_client_common::configuration::tokens::TokenRefresher;
33use qcs_dependencies_client::reqwest::{self, StatusCode};
34use serde::{Deserialize, Serialize};
35
36#[cfg(feature = "clap")]
37#[allow(unused, reason = "not used in all templates, but required in some")]
38use ::{miette::IntoDiagnostic as _, qcs_api_client_common::clap_utils::JsonMaybeStdin};
39
40/// Serialize command-line arguments for [`create_reservation`]
41#[cfg(feature = "clap")]
42#[derive(Debug, clap::Args)]
43pub struct CreateReservationClapParams {
44    pub create_reservation_request: JsonMaybeStdin<crate::models::CreateReservationRequest>,
45    /// Used to specify a subject account ID for a request. Does not take precedence over a corresponding request body field when one is present.
46    #[arg(long)]
47    pub x_qcs_account_id: Option<String>,
48    /// Used to specify the subject account's type for a request in conjunction with the X-QCS-ACCOUNT-ID header. Does not take precedence over a corresponding request body field when one is present.
49    #[arg(long)]
50    pub x_qcs_account_type: Option<models::AccountType>,
51}
52
53#[cfg(feature = "clap")]
54impl CreateReservationClapParams {
55    pub async fn execute(
56        self,
57        configuration: &configuration::Configuration,
58    ) -> Result<models::Reservation, miette::Error> {
59        let request = self.create_reservation_request.into_inner().into_inner();
60
61        create_reservation(
62            configuration,
63            request,
64            self.x_qcs_account_id.as_deref(),
65            self.x_qcs_account_type,
66        )
67        .await
68        .into_diagnostic()
69    }
70}
71
72/// Serialize command-line arguments for [`delete_reservation`]
73#[cfg(feature = "clap")]
74#[derive(Debug, clap::Args)]
75pub struct DeleteReservationClapParams {
76    #[arg(long)]
77    pub reservation_id: i64,
78}
79
80#[cfg(feature = "clap")]
81impl DeleteReservationClapParams {
82    pub async fn execute(
83        self,
84        configuration: &configuration::Configuration,
85    ) -> Result<models::Reservation, miette::Error> {
86        delete_reservation(configuration, self.reservation_id)
87            .await
88            .into_diagnostic()
89    }
90}
91
92/// Serialize command-line arguments for [`find_available_reservations`]
93#[cfg(feature = "clap")]
94#[derive(Debug, clap::Args)]
95pub struct FindAvailableReservationsClapParams {
96    #[arg(long)]
97    pub quantum_processor_id: String,
98    #[arg(long)]
99    pub start_time_from: chrono::DateTime<chrono::FixedOffset>,
100    #[arg(long)]
101    pub duration: String,
102    #[arg(long)]
103    pub page_size: Option<i64>,
104    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
105    #[arg(long)]
106    pub page_token: Option<String>,
107}
108
109#[cfg(feature = "clap")]
110impl FindAvailableReservationsClapParams {
111    pub async fn execute(
112        self,
113        configuration: &configuration::Configuration,
114    ) -> Result<models::FindAvailableReservationsResponse, miette::Error> {
115        find_available_reservations(
116            configuration,
117            self.quantum_processor_id.as_str(),
118            self.start_time_from,
119            self.duration.as_str(),
120            self.page_size,
121            self.page_token.as_deref(),
122        )
123        .await
124        .into_diagnostic()
125    }
126}
127
128/// Serialize command-line arguments for [`get_quantum_processor_calendar`]
129#[cfg(feature = "clap")]
130#[derive(Debug, clap::Args)]
131pub struct GetQuantumProcessorCalendarClapParams {
132    #[arg(long)]
133    pub quantum_processor_id: String,
134}
135
136#[cfg(feature = "clap")]
137impl GetQuantumProcessorCalendarClapParams {
138    pub async fn execute(
139        self,
140        configuration: &configuration::Configuration,
141    ) -> Result<models::QuantumProcessorCalendar, miette::Error> {
142        get_quantum_processor_calendar(configuration, self.quantum_processor_id.as_str())
143            .await
144            .into_diagnostic()
145    }
146}
147
148/// Serialize command-line arguments for [`get_reservation`]
149#[cfg(feature = "clap")]
150#[derive(Debug, clap::Args)]
151pub struct GetReservationClapParams {
152    #[arg(long)]
153    pub reservation_id: i64,
154}
155
156#[cfg(feature = "clap")]
157impl GetReservationClapParams {
158    pub async fn execute(
159        self,
160        configuration: &configuration::Configuration,
161    ) -> Result<models::Reservation, miette::Error> {
162        get_reservation(configuration, self.reservation_id)
163            .await
164            .into_diagnostic()
165    }
166}
167
168/// Serialize command-line arguments for [`list_group_reservations`]
169#[cfg(feature = "clap")]
170#[derive(Debug, clap::Args)]
171pub struct ListGroupReservationsClapParams {
172    /// URL encoded name of group for which to retrieve reservations.
173    #[arg(long)]
174    pub group_name: String,
175    #[arg(long)]
176    pub filter: Option<String>,
177    #[arg(long)]
178    pub order: Option<String>,
179    #[arg(long)]
180    pub page_size: Option<i64>,
181    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
182    #[arg(long)]
183    pub page_token: Option<String>,
184    /// If you wish to include deleted (or cancelled) resources in your response, include `showDeleted=true`.
185    #[arg(long)]
186    pub show_deleted: Option<String>,
187}
188
189#[cfg(feature = "clap")]
190impl ListGroupReservationsClapParams {
191    pub async fn execute(
192        self,
193        configuration: &configuration::Configuration,
194    ) -> Result<models::ListReservationsResponse, miette::Error> {
195        list_group_reservations(
196            configuration,
197            self.group_name.as_str(),
198            self.filter.as_deref(),
199            self.order.as_deref(),
200            self.page_size,
201            self.page_token.as_deref(),
202            self.show_deleted.as_deref(),
203        )
204        .await
205        .into_diagnostic()
206    }
207}
208
209/// Serialize command-line arguments for [`list_reservations`]
210#[cfg(feature = "clap")]
211#[derive(Debug, clap::Args)]
212pub struct ListReservationsClapParams {
213    #[arg(long)]
214    pub filter: Option<String>,
215    #[arg(long)]
216    pub order: Option<String>,
217    #[arg(long)]
218    pub page_size: Option<i64>,
219    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
220    #[arg(long)]
221    pub page_token: Option<String>,
222    /// If you wish to include deleted (or cancelled) resources in your response, include `showDeleted=true`.
223    #[arg(long)]
224    pub show_deleted: Option<String>,
225    /// Used to specify a subject account ID for a request. Does not take precedence over a corresponding request body field when one is present.
226    #[arg(long)]
227    pub x_qcs_account_id: Option<String>,
228    /// Used to specify the subject account's type for a request in conjunction with the X-QCS-ACCOUNT-ID header. Does not take precedence over a corresponding request body field when one is present.
229    #[arg(long)]
230    pub x_qcs_account_type: Option<models::AccountType>,
231}
232
233#[cfg(feature = "clap")]
234impl ListReservationsClapParams {
235    pub async fn execute(
236        self,
237        configuration: &configuration::Configuration,
238    ) -> Result<models::ListReservationsResponse, miette::Error> {
239        list_reservations(
240            configuration,
241            self.filter.as_deref(),
242            self.order.as_deref(),
243            self.page_size,
244            self.page_token.as_deref(),
245            self.show_deleted.as_deref(),
246            self.x_qcs_account_id.as_deref(),
247            self.x_qcs_account_type,
248        )
249        .await
250        .into_diagnostic()
251    }
252}
253
254/// struct for typed errors of method [`create_reservation`]
255#[derive(Debug, Clone, Serialize, Deserialize)]
256#[serde(untagged)]
257pub enum CreateReservationError {
258    Status401(models::Error),
259    Status402(models::Error),
260    Status403(models::Error),
261    Status409(models::Error),
262    Status422(models::Error),
263    UnknownValue(serde_json::Value),
264}
265
266/// struct for typed errors of method [`delete_reservation`]
267#[derive(Debug, Clone, Serialize, Deserialize)]
268#[serde(untagged)]
269pub enum DeleteReservationError {
270    Status401(models::Error),
271    Status403(models::Error),
272    Status404(models::Error),
273    UnknownValue(serde_json::Value),
274}
275
276/// struct for typed errors of method [`find_available_reservations`]
277#[derive(Debug, Clone, Serialize, Deserialize)]
278#[serde(untagged)]
279pub enum FindAvailableReservationsError {
280    Status401(models::Error),
281    Status422(models::Error),
282    UnknownValue(serde_json::Value),
283}
284
285/// struct for typed errors of method [`get_quantum_processor_calendar`]
286#[derive(Debug, Clone, Serialize, Deserialize)]
287#[serde(untagged)]
288pub enum GetQuantumProcessorCalendarError {
289    Status403(models::Error),
290    Status404(models::Error),
291    UnknownValue(serde_json::Value),
292}
293
294/// struct for typed errors of method [`get_reservation`]
295#[derive(Debug, Clone, Serialize, Deserialize)]
296#[serde(untagged)]
297pub enum GetReservationError {
298    Status401(models::Error),
299    Status403(models::Error),
300    Status404(models::Error),
301    UnknownValue(serde_json::Value),
302}
303
304/// struct for typed errors of method [`list_group_reservations`]
305#[derive(Debug, Clone, Serialize, Deserialize)]
306#[serde(untagged)]
307pub enum ListGroupReservationsError {
308    Status401(models::Error),
309    Status422(models::Error),
310    UnknownValue(serde_json::Value),
311}
312
313/// struct for typed errors of method [`list_reservations`]
314#[derive(Debug, Clone, Serialize, Deserialize)]
315#[serde(untagged)]
316pub enum ListReservationsError {
317    Status401(models::Error),
318    Status422(models::Error),
319    UnknownValue(serde_json::Value),
320}
321
322async fn create_reservation_inner(
323    configuration: &configuration::Configuration,
324    backoff: &mut ExponentialBackoff,
325    create_reservation_request: crate::models::CreateReservationRequest,
326    x_qcs_account_id: Option<&str>,
327    x_qcs_account_type: Option<models::AccountType>,
328) -> Result<models::Reservation, Error<CreateReservationError>> {
329    let local_var_configuration = configuration;
330    // add a prefix to parameters to efficiently prevent name collisions
331    let p_body_create_reservation_request = create_reservation_request;
332    let p_header_x_qcs_account_id = x_qcs_account_id;
333    let p_header_x_qcs_account_type = x_qcs_account_type;
334
335    let local_var_client = &local_var_configuration.client;
336
337    let local_var_uri_str = format!(
338        "{}/v1/reservations",
339        local_var_configuration.qcs_config.api_url()
340    );
341    let mut local_var_req_builder =
342        local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str());
343
344    #[cfg(feature = "tracing")]
345    {
346        // Ignore parsing errors if the URL is invalid for some reason.
347        // If it is invalid, it will turn up as an error later when actually making the request.
348        let local_var_do_tracing = local_var_uri_str
349            .parse::<::url::Url>()
350            .ok()
351            .is_none_or(|url| {
352                configuration
353                    .qcs_config
354                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
355            });
356
357        if local_var_do_tracing {
358            ::tracing::debug!(
359                url=%local_var_uri_str,
360                method="POST",
361                "making create_reservation request",
362            );
363        }
364    }
365
366    if let Some(local_var_param_value) = p_header_x_qcs_account_id {
367        local_var_req_builder =
368            local_var_req_builder.header("x-qcs-account-id", local_var_param_value.to_string());
369    }
370    if let Some(local_var_param_value) = p_header_x_qcs_account_type {
371        local_var_req_builder =
372            local_var_req_builder.header("x-qcs-account-type", local_var_param_value.to_string());
373    }
374
375    // Use the QCS Bearer token if a client OAuthSession is present,
376    // but do not require one when the security schema says it is optional.
377    {
378        use qcs_api_client_common::configuration::TokenError;
379
380        #[allow(
381            clippy::nonminimal_bool,
382            clippy::eq_op,
383            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
384        )]
385        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";
386
387        let token = local_var_configuration
388            .qcs_config
389            .get_bearer_access_token()
390            .await;
391
392        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
393            // the client is configured without any OAuthSession, but this call does not require one.
394            #[cfg(feature = "tracing")]
395            tracing::debug!(
396                "No client credentials found, but this call does not require authentication."
397            );
398        } else {
399            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
400        }
401    }
402
403    local_var_req_builder = local_var_req_builder.json(&p_body_create_reservation_request);
404
405    let local_var_req = local_var_req_builder.build()?;
406    let local_var_resp = local_var_client.execute(local_var_req).await?;
407
408    let local_var_status = local_var_resp.status();
409    let local_var_raw_content_type = local_var_resp
410        .headers()
411        .get("content-type")
412        .and_then(|v| v.to_str().ok())
413        .unwrap_or("application/octet-stream")
414        .to_string();
415    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());
416
417    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
418        let local_var_content = local_var_resp.text().await?;
419        match local_var_content_type {
420            ContentType::Json => serde_path_to_error::deserialize(
421                &mut serde_json::Deserializer::from_str(&local_var_content),
422            )
423            .map_err(Error::from),
424            ContentType::Text => Err(Error::InvalidContentType {
425                content_type: local_var_raw_content_type,
426                return_type: "models::Reservation",
427            }),
428            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
429                content_type: unknown_type,
430                return_type: "models::Reservation",
431            }),
432        }
433    } else {
434        let local_var_retry_delay =
435            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
436        let local_var_content = local_var_resp.text().await?;
437        let local_var_entity: Option<CreateReservationError> =
438            serde_json::from_str(&local_var_content).ok();
439        let local_var_error = ResponseContent {
440            status: local_var_status,
441            content: local_var_content,
442            entity: local_var_entity,
443            retry_delay: local_var_retry_delay,
444        };
445        Err(Error::ResponseError(local_var_error))
446    }
447}
448
449/// Create a new reservation.  The following precedence applies when specifying the reservation subject account ID and type: * request body `accountId` field, or if unset then `X-QCS-ACCOUNT-ID` header, or if unset then requesting user's ID. * request body `accountType` field, or if unset then `X-QCS-ACCOUNT-TYPE` header, or if unset then \"user\" type.
450pub async fn create_reservation(
451    configuration: &configuration::Configuration,
452    create_reservation_request: crate::models::CreateReservationRequest,
453    x_qcs_account_id: Option<&str>,
454    x_qcs_account_type: Option<models::AccountType>,
455) -> Result<models::Reservation, Error<CreateReservationError>> {
456    let mut backoff = configuration.backoff.build();
457    let mut refreshed_credentials = false;
458    let method = reqwest::Method::POST;
459    loop {
460        let result = create_reservation_inner(
461            configuration,
462            &mut backoff,
463            create_reservation_request.clone(),
464            x_qcs_account_id.clone(),
465            x_qcs_account_type.clone(),
466        )
467        .await;
468
469        match result {
470            Ok(result) => return Ok(result),
471            Err(Error::ResponseError(response)) => {
472                if !refreshed_credentials
473                    && matches!(
474                        response.status,
475                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
476                    )
477                {
478                    // Attempt to refresh credentials
479                    match configuration.qcs_config.refresh().await {
480                        Ok(_) => {
481                            refreshed_credentials = true;
482                            continue;
483                        }
484                        Err(::qcs_api_client_common::configuration::TokenError::Write {
485                            error,
486                            oauth_session: _,
487                        }) => {
488                            // Token refresh succeeded but persistence failed
489                            // The token is already in memory and will be used for this request
490                            #[cfg(feature = "tracing")]
491                            tracing::warn!(
492                                "Token refresh succeeded but failed to persist: {}. Continuing with in-memory token.",
493                                error
494                            );
495                            refreshed_credentials = true;
496                            continue;
497                        }
498                        Err(e) => return Err(e.into()),
499                    }
500                } else if let Some(duration) = response.retry_delay {
501                    tokio::time::sleep(duration).await;
502                    continue;
503                }
504
505                return Err(Error::ResponseError(response));
506            }
507            Err(Error::Reqwest(error)) => {
508                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
509                    tokio::time::sleep(duration).await;
510                    continue;
511                }
512
513                return Err(Error::Reqwest(error));
514            }
515            Err(Error::Io(error)) => {
516                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
517                    tokio::time::sleep(duration).await;
518                    continue;
519                }
520
521                return Err(Error::Io(error));
522            }
523            Err(error) => return Err(error),
524        }
525    }
526}
527async fn delete_reservation_inner(
528    configuration: &configuration::Configuration,
529    backoff: &mut ExponentialBackoff,
530    reservation_id: i64,
531) -> Result<models::Reservation, Error<DeleteReservationError>> {
532    let local_var_configuration = configuration;
533    // add a prefix to parameters to efficiently prevent name collisions
534    let p_path_reservation_id = reservation_id;
535
536    let local_var_client = &local_var_configuration.client;
537
538    let local_var_uri_str = format!(
539        "{}/v1/reservations/{reservationId}",
540        local_var_configuration.qcs_config.api_url(),
541        reservationId = p_path_reservation_id
542    );
543    let mut local_var_req_builder =
544        local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str());
545
546    #[cfg(feature = "tracing")]
547    {
548        // Ignore parsing errors if the URL is invalid for some reason.
549        // If it is invalid, it will turn up as an error later when actually making the request.
550        let local_var_do_tracing = local_var_uri_str
551            .parse::<::url::Url>()
552            .ok()
553            .is_none_or(|url| {
554                configuration
555                    .qcs_config
556                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
557            });
558
559        if local_var_do_tracing {
560            ::tracing::debug!(
561                url=%local_var_uri_str,
562                method="DELETE",
563                "making delete_reservation request",
564            );
565        }
566    }
567
568    // Use the QCS Bearer token if a client OAuthSession is present,
569    // but do not require one when the security schema says it is optional.
570    {
571        use qcs_api_client_common::configuration::TokenError;
572
573        #[allow(
574            clippy::nonminimal_bool,
575            clippy::eq_op,
576            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
577        )]
578        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";
579
580        let token = local_var_configuration
581            .qcs_config
582            .get_bearer_access_token()
583            .await;
584
585        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
586            // the client is configured without any OAuthSession, but this call does not require one.
587            #[cfg(feature = "tracing")]
588            tracing::debug!(
589                "No client credentials found, but this call does not require authentication."
590            );
591        } else {
592            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
593        }
594    }
595
596    let local_var_req = local_var_req_builder.build()?;
597    let local_var_resp = local_var_client.execute(local_var_req).await?;
598
599    let local_var_status = local_var_resp.status();
600    let local_var_raw_content_type = local_var_resp
601        .headers()
602        .get("content-type")
603        .and_then(|v| v.to_str().ok())
604        .unwrap_or("application/octet-stream")
605        .to_string();
606    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());
607
608    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
609        let local_var_content = local_var_resp.text().await?;
610        match local_var_content_type {
611            ContentType::Json => serde_path_to_error::deserialize(
612                &mut serde_json::Deserializer::from_str(&local_var_content),
613            )
614            .map_err(Error::from),
615            ContentType::Text => Err(Error::InvalidContentType {
616                content_type: local_var_raw_content_type,
617                return_type: "models::Reservation",
618            }),
619            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
620                content_type: unknown_type,
621                return_type: "models::Reservation",
622            }),
623        }
624    } else {
625        let local_var_retry_delay =
626            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
627        let local_var_content = local_var_resp.text().await?;
628        let local_var_entity: Option<DeleteReservationError> =
629            serde_json::from_str(&local_var_content).ok();
630        let local_var_error = ResponseContent {
631            status: local_var_status,
632            content: local_var_content,
633            entity: local_var_entity,
634            retry_delay: local_var_retry_delay,
635        };
636        Err(Error::ResponseError(local_var_error))
637    }
638}
639
640/// Cancel an existing reservation for the user.
641pub async fn delete_reservation(
642    configuration: &configuration::Configuration,
643    reservation_id: i64,
644) -> Result<models::Reservation, Error<DeleteReservationError>> {
645    let mut backoff = configuration.backoff.build();
646    let mut refreshed_credentials = false;
647    let method = reqwest::Method::DELETE;
648    loop {
649        let result =
650            delete_reservation_inner(configuration, &mut backoff, reservation_id.clone()).await;
651
652        match result {
653            Ok(result) => return Ok(result),
654            Err(Error::ResponseError(response)) => {
655                if !refreshed_credentials
656                    && matches!(
657                        response.status,
658                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
659                    )
660                {
661                    // Attempt to refresh credentials
662                    match configuration.qcs_config.refresh().await {
663                        Ok(_) => {
664                            refreshed_credentials = true;
665                            continue;
666                        }
667                        Err(::qcs_api_client_common::configuration::TokenError::Write {
668                            error,
669                            oauth_session: _,
670                        }) => {
671                            // Token refresh succeeded but persistence failed
672                            // The token is already in memory and will be used for this request
673                            #[cfg(feature = "tracing")]
674                            tracing::warn!(
675                                "Token refresh succeeded but failed to persist: {}. Continuing with in-memory token.",
676                                error
677                            );
678                            refreshed_credentials = true;
679                            continue;
680                        }
681                        Err(e) => return Err(e.into()),
682                    }
683                } else if let Some(duration) = response.retry_delay {
684                    tokio::time::sleep(duration).await;
685                    continue;
686                }
687
688                return Err(Error::ResponseError(response));
689            }
690            Err(Error::Reqwest(error)) => {
691                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
692                    tokio::time::sleep(duration).await;
693                    continue;
694                }
695
696                return Err(Error::Reqwest(error));
697            }
698            Err(Error::Io(error)) => {
699                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
700                    tokio::time::sleep(duration).await;
701                    continue;
702                }
703
704                return Err(Error::Io(error));
705            }
706            Err(error) => return Err(error),
707        }
708    }
709}
710async fn find_available_reservations_inner(
711    configuration: &configuration::Configuration,
712    backoff: &mut ExponentialBackoff,
713    quantum_processor_id: &str,
714    start_time_from: chrono::DateTime<chrono::FixedOffset>,
715    duration: &str,
716    page_size: Option<i64>,
717    page_token: Option<&str>,
718) -> Result<models::FindAvailableReservationsResponse, Error<FindAvailableReservationsError>> {
719    let local_var_configuration = configuration;
720    // add a prefix to parameters to efficiently prevent name collisions
721    let p_query_quantum_processor_id = quantum_processor_id;
722    let p_query_start_time_from = start_time_from;
723    let p_query_duration = duration;
724    let p_query_page_size = page_size;
725    let p_query_page_token = page_token;
726
727    let local_var_client = &local_var_configuration.client;
728
729    let local_var_uri_str = format!(
730        "{}/v1/reservations:findAvailable",
731        local_var_configuration.qcs_config.api_url()
732    );
733    let mut local_var_req_builder =
734        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());
735
736    #[cfg(feature = "tracing")]
737    {
738        // Ignore parsing errors if the URL is invalid for some reason.
739        // If it is invalid, it will turn up as an error later when actually making the request.
740        let local_var_do_tracing = local_var_uri_str
741            .parse::<::url::Url>()
742            .ok()
743            .is_none_or(|url| {
744                configuration
745                    .qcs_config
746                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
747            });
748
749        if local_var_do_tracing {
750            ::tracing::debug!(
751                url=%local_var_uri_str,
752                method="GET",
753                "making find_available_reservations request",
754            );
755        }
756    }
757
758    if let Some(ref local_var_str) = p_query_page_size {
759        local_var_req_builder =
760            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
761    }
762    if let Some(ref local_var_str) = p_query_page_token {
763        local_var_req_builder =
764            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
765    }
766    local_var_req_builder = local_var_req_builder.query(&[(
767        "quantumProcessorId",
768        &p_query_quantum_processor_id.to_string(),
769    )]);
770    local_var_req_builder =
771        local_var_req_builder.query(&[("startTimeFrom", &p_query_start_time_from.to_string())]);
772    local_var_req_builder =
773        local_var_req_builder.query(&[("duration", &p_query_duration.to_string())]);
774
775    // Use the QCS Bearer token if a client OAuthSession is present,
776    // but do not require one when the security schema says it is optional.
777    {
778        use qcs_api_client_common::configuration::TokenError;
779
780        #[allow(
781            clippy::nonminimal_bool,
782            clippy::eq_op,
783            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
784        )]
785        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";
786
787        let token = local_var_configuration
788            .qcs_config
789            .get_bearer_access_token()
790            .await;
791
792        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
793            // the client is configured without any OAuthSession, but this call does not require one.
794            #[cfg(feature = "tracing")]
795            tracing::debug!(
796                "No client credentials found, but this call does not require authentication."
797            );
798        } else {
799            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
800        }
801    }
802
803    let local_var_req = local_var_req_builder.build()?;
804    let local_var_resp = local_var_client.execute(local_var_req).await?;
805
806    let local_var_status = local_var_resp.status();
807    let local_var_raw_content_type = local_var_resp
808        .headers()
809        .get("content-type")
810        .and_then(|v| v.to_str().ok())
811        .unwrap_or("application/octet-stream")
812        .to_string();
813    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());
814
815    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
816        let local_var_content = local_var_resp.text().await?;
817        match local_var_content_type {
818            ContentType::Json => serde_path_to_error::deserialize(
819                &mut serde_json::Deserializer::from_str(&local_var_content),
820            )
821            .map_err(Error::from),
822            ContentType::Text => Err(Error::InvalidContentType {
823                content_type: local_var_raw_content_type,
824                return_type: "models::FindAvailableReservationsResponse",
825            }),
826            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
827                content_type: unknown_type,
828                return_type: "models::FindAvailableReservationsResponse",
829            }),
830        }
831    } else {
832        let local_var_retry_delay =
833            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
834        let local_var_content = local_var_resp.text().await?;
835        let local_var_entity: Option<FindAvailableReservationsError> =
836            serde_json::from_str(&local_var_content).ok();
837        let local_var_error = ResponseContent {
838            status: local_var_status,
839            content: local_var_content,
840            entity: local_var_entity,
841            retry_delay: local_var_retry_delay,
842        };
843        Err(Error::ResponseError(local_var_error))
844    }
845}
846
847/// List currently available reservations on the requested Rigetti quantum computer.
848pub async fn find_available_reservations(
849    configuration: &configuration::Configuration,
850    quantum_processor_id: &str,
851    start_time_from: chrono::DateTime<chrono::FixedOffset>,
852    duration: &str,
853    page_size: Option<i64>,
854    page_token: Option<&str>,
855) -> Result<models::FindAvailableReservationsResponse, Error<FindAvailableReservationsError>> {
856    let mut backoff = configuration.backoff.build();
857    let mut refreshed_credentials = false;
858    let method = reqwest::Method::GET;
859    loop {
860        let result = find_available_reservations_inner(
861            configuration,
862            &mut backoff,
863            quantum_processor_id.clone(),
864            start_time_from.clone(),
865            duration.clone(),
866            page_size.clone(),
867            page_token.clone(),
868        )
869        .await;
870
871        match result {
872            Ok(result) => return Ok(result),
873            Err(Error::ResponseError(response)) => {
874                if !refreshed_credentials
875                    && matches!(
876                        response.status,
877                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
878                    )
879                {
880                    // Attempt to refresh credentials
881                    match configuration.qcs_config.refresh().await {
882                        Ok(_) => {
883                            refreshed_credentials = true;
884                            continue;
885                        }
886                        Err(::qcs_api_client_common::configuration::TokenError::Write {
887                            error,
888                            oauth_session: _,
889                        }) => {
890                            // Token refresh succeeded but persistence failed
891                            // The token is already in memory and will be used for this request
892                            #[cfg(feature = "tracing")]
893                            tracing::warn!(
894                                "Token refresh succeeded but failed to persist: {}. Continuing with in-memory token.",
895                                error
896                            );
897                            refreshed_credentials = true;
898                            continue;
899                        }
900                        Err(e) => return Err(e.into()),
901                    }
902                } else if let Some(duration) = response.retry_delay {
903                    tokio::time::sleep(duration).await;
904                    continue;
905                }
906
907                return Err(Error::ResponseError(response));
908            }
909            Err(Error::Reqwest(error)) => {
910                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
911                    tokio::time::sleep(duration).await;
912                    continue;
913                }
914
915                return Err(Error::Reqwest(error));
916            }
917            Err(Error::Io(error)) => {
918                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
919                    tokio::time::sleep(duration).await;
920                    continue;
921                }
922
923                return Err(Error::Io(error));
924            }
925            Err(error) => return Err(error),
926        }
927    }
928}
929async fn get_quantum_processor_calendar_inner(
930    configuration: &configuration::Configuration,
931    backoff: &mut ExponentialBackoff,
932    quantum_processor_id: &str,
933) -> Result<models::QuantumProcessorCalendar, Error<GetQuantumProcessorCalendarError>> {
934    let local_var_configuration = configuration;
935    // add a prefix to parameters to efficiently prevent name collisions
936    let p_path_quantum_processor_id = quantum_processor_id;
937
938    let local_var_client = &local_var_configuration.client;
939
940    let local_var_uri_str = format!(
941        "{}/v1/calendars/{quantumProcessorId}",
942        local_var_configuration.qcs_config.api_url(),
943        quantumProcessorId = crate::apis::urlencode(p_path_quantum_processor_id)
944    );
945    let mut local_var_req_builder =
946        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());
947
948    #[cfg(feature = "tracing")]
949    {
950        // Ignore parsing errors if the URL is invalid for some reason.
951        // If it is invalid, it will turn up as an error later when actually making the request.
952        let local_var_do_tracing = local_var_uri_str
953            .parse::<::url::Url>()
954            .ok()
955            .is_none_or(|url| {
956                configuration
957                    .qcs_config
958                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
959            });
960
961        if local_var_do_tracing {
962            ::tracing::debug!(
963                url=%local_var_uri_str,
964                method="GET",
965                "making get_quantum_processor_calendar request",
966            );
967        }
968    }
969
970    // Use the QCS Bearer token if a client OAuthSession is present,
971    // but do not require one when the security schema says it is optional.
972    {
973        use qcs_api_client_common::configuration::TokenError;
974
975        #[allow(
976            clippy::nonminimal_bool,
977            clippy::eq_op,
978            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
979        )]
980        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";
981
982        let token = local_var_configuration
983            .qcs_config
984            .get_bearer_access_token()
985            .await;
986
987        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
988            // the client is configured without any OAuthSession, but this call does not require one.
989            #[cfg(feature = "tracing")]
990            tracing::debug!(
991                "No client credentials found, but this call does not require authentication."
992            );
993        } else {
994            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
995        }
996    }
997
998    let local_var_req = local_var_req_builder.build()?;
999    let local_var_resp = local_var_client.execute(local_var_req).await?;
1000
1001    let local_var_status = local_var_resp.status();
1002    let local_var_raw_content_type = local_var_resp
1003        .headers()
1004        .get("content-type")
1005        .and_then(|v| v.to_str().ok())
1006        .unwrap_or("application/octet-stream")
1007        .to_string();
1008    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());
1009
1010    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
1011        let local_var_content = local_var_resp.text().await?;
1012        match local_var_content_type {
1013            ContentType::Json => serde_path_to_error::deserialize(
1014                &mut serde_json::Deserializer::from_str(&local_var_content),
1015            )
1016            .map_err(Error::from),
1017            ContentType::Text => Err(Error::InvalidContentType {
1018                content_type: local_var_raw_content_type,
1019                return_type: "models::QuantumProcessorCalendar",
1020            }),
1021            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
1022                content_type: unknown_type,
1023                return_type: "models::QuantumProcessorCalendar",
1024            }),
1025        }
1026    } else {
1027        let local_var_retry_delay =
1028            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
1029        let local_var_content = local_var_resp.text().await?;
1030        let local_var_entity: Option<GetQuantumProcessorCalendarError> =
1031            serde_json::from_str(&local_var_content).ok();
1032        let local_var_error = ResponseContent {
1033            status: local_var_status,
1034            content: local_var_content,
1035            entity: local_var_entity,
1036            retry_delay: local_var_retry_delay,
1037        };
1038        Err(Error::ResponseError(local_var_error))
1039    }
1040}
1041
1042/// Get calendar details for the requested quantum processor.
1043pub async fn get_quantum_processor_calendar(
1044    configuration: &configuration::Configuration,
1045    quantum_processor_id: &str,
1046) -> Result<models::QuantumProcessorCalendar, Error<GetQuantumProcessorCalendarError>> {
1047    let mut backoff = configuration.backoff.build();
1048    let mut refreshed_credentials = false;
1049    let method = reqwest::Method::GET;
1050    loop {
1051        let result = get_quantum_processor_calendar_inner(
1052            configuration,
1053            &mut backoff,
1054            quantum_processor_id.clone(),
1055        )
1056        .await;
1057
1058        match result {
1059            Ok(result) => return Ok(result),
1060            Err(Error::ResponseError(response)) => {
1061                if !refreshed_credentials
1062                    && matches!(
1063                        response.status,
1064                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
1065                    )
1066                {
1067                    // Attempt to refresh credentials
1068                    match configuration.qcs_config.refresh().await {
1069                        Ok(_) => {
1070                            refreshed_credentials = true;
1071                            continue;
1072                        }
1073                        Err(::qcs_api_client_common::configuration::TokenError::Write {
1074                            error,
1075                            oauth_session: _,
1076                        }) => {
1077                            // Token refresh succeeded but persistence failed
1078                            // The token is already in memory and will be used for this request
1079                            #[cfg(feature = "tracing")]
1080                            tracing::warn!(
1081                                "Token refresh succeeded but failed to persist: {}. Continuing with in-memory token.",
1082                                error
1083                            );
1084                            refreshed_credentials = true;
1085                            continue;
1086                        }
1087                        Err(e) => return Err(e.into()),
1088                    }
1089                } else if let Some(duration) = response.retry_delay {
1090                    tokio::time::sleep(duration).await;
1091                    continue;
1092                }
1093
1094                return Err(Error::ResponseError(response));
1095            }
1096            Err(Error::Reqwest(error)) => {
1097                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
1098                    tokio::time::sleep(duration).await;
1099                    continue;
1100                }
1101
1102                return Err(Error::Reqwest(error));
1103            }
1104            Err(Error::Io(error)) => {
1105                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
1106                    tokio::time::sleep(duration).await;
1107                    continue;
1108                }
1109
1110                return Err(Error::Io(error));
1111            }
1112            Err(error) => return Err(error),
1113        }
1114    }
1115}
1116async fn get_reservation_inner(
1117    configuration: &configuration::Configuration,
1118    backoff: &mut ExponentialBackoff,
1119    reservation_id: i64,
1120) -> Result<models::Reservation, Error<GetReservationError>> {
1121    let local_var_configuration = configuration;
1122    // add a prefix to parameters to efficiently prevent name collisions
1123    let p_path_reservation_id = reservation_id;
1124
1125    let local_var_client = &local_var_configuration.client;
1126
1127    let local_var_uri_str = format!(
1128        "{}/v1/reservations/{reservationId}",
1129        local_var_configuration.qcs_config.api_url(),
1130        reservationId = p_path_reservation_id
1131    );
1132    let mut local_var_req_builder =
1133        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());
1134
1135    #[cfg(feature = "tracing")]
1136    {
1137        // Ignore parsing errors if the URL is invalid for some reason.
1138        // If it is invalid, it will turn up as an error later when actually making the request.
1139        let local_var_do_tracing = local_var_uri_str
1140            .parse::<::url::Url>()
1141            .ok()
1142            .is_none_or(|url| {
1143                configuration
1144                    .qcs_config
1145                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
1146            });
1147
1148        if local_var_do_tracing {
1149            ::tracing::debug!(
1150                url=%local_var_uri_str,
1151                method="GET",
1152                "making get_reservation request",
1153            );
1154        }
1155    }
1156
1157    // Use the QCS Bearer token if a client OAuthSession is present,
1158    // but do not require one when the security schema says it is optional.
1159    {
1160        use qcs_api_client_common::configuration::TokenError;
1161
1162        #[allow(
1163            clippy::nonminimal_bool,
1164            clippy::eq_op,
1165            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
1166        )]
1167        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";
1168
1169        let token = local_var_configuration
1170            .qcs_config
1171            .get_bearer_access_token()
1172            .await;
1173
1174        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
1175            // the client is configured without any OAuthSession, but this call does not require one.
1176            #[cfg(feature = "tracing")]
1177            tracing::debug!(
1178                "No client credentials found, but this call does not require authentication."
1179            );
1180        } else {
1181            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
1182        }
1183    }
1184
1185    let local_var_req = local_var_req_builder.build()?;
1186    let local_var_resp = local_var_client.execute(local_var_req).await?;
1187
1188    let local_var_status = local_var_resp.status();
1189    let local_var_raw_content_type = local_var_resp
1190        .headers()
1191        .get("content-type")
1192        .and_then(|v| v.to_str().ok())
1193        .unwrap_or("application/octet-stream")
1194        .to_string();
1195    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());
1196
1197    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
1198        let local_var_content = local_var_resp.text().await?;
1199        match local_var_content_type {
1200            ContentType::Json => serde_path_to_error::deserialize(
1201                &mut serde_json::Deserializer::from_str(&local_var_content),
1202            )
1203            .map_err(Error::from),
1204            ContentType::Text => Err(Error::InvalidContentType {
1205                content_type: local_var_raw_content_type,
1206                return_type: "models::Reservation",
1207            }),
1208            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
1209                content_type: unknown_type,
1210                return_type: "models::Reservation",
1211            }),
1212        }
1213    } else {
1214        let local_var_retry_delay =
1215            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
1216        let local_var_content = local_var_resp.text().await?;
1217        let local_var_entity: Option<GetReservationError> =
1218            serde_json::from_str(&local_var_content).ok();
1219        let local_var_error = ResponseContent {
1220            status: local_var_status,
1221            content: local_var_content,
1222            entity: local_var_entity,
1223            retry_delay: local_var_retry_delay,
1224        };
1225        Err(Error::ResponseError(local_var_error))
1226    }
1227}
1228
1229/// Find an existing reservation by ID.
1230pub async fn get_reservation(
1231    configuration: &configuration::Configuration,
1232    reservation_id: i64,
1233) -> Result<models::Reservation, Error<GetReservationError>> {
1234    let mut backoff = configuration.backoff.build();
1235    let mut refreshed_credentials = false;
1236    let method = reqwest::Method::GET;
1237    loop {
1238        let result =
1239            get_reservation_inner(configuration, &mut backoff, reservation_id.clone()).await;
1240
1241        match result {
1242            Ok(result) => return Ok(result),
1243            Err(Error::ResponseError(response)) => {
1244                if !refreshed_credentials
1245                    && matches!(
1246                        response.status,
1247                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
1248                    )
1249                {
1250                    // Attempt to refresh credentials
1251                    match configuration.qcs_config.refresh().await {
1252                        Ok(_) => {
1253                            refreshed_credentials = true;
1254                            continue;
1255                        }
1256                        Err(::qcs_api_client_common::configuration::TokenError::Write {
1257                            error,
1258                            oauth_session: _,
1259                        }) => {
1260                            // Token refresh succeeded but persistence failed
1261                            // The token is already in memory and will be used for this request
1262                            #[cfg(feature = "tracing")]
1263                            tracing::warn!(
1264                                "Token refresh succeeded but failed to persist: {}. Continuing with in-memory token.",
1265                                error
1266                            );
1267                            refreshed_credentials = true;
1268                            continue;
1269                        }
1270                        Err(e) => return Err(e.into()),
1271                    }
1272                } else if let Some(duration) = response.retry_delay {
1273                    tokio::time::sleep(duration).await;
1274                    continue;
1275                }
1276
1277                return Err(Error::ResponseError(response));
1278            }
1279            Err(Error::Reqwest(error)) => {
1280                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
1281                    tokio::time::sleep(duration).await;
1282                    continue;
1283                }
1284
1285                return Err(Error::Reqwest(error));
1286            }
1287            Err(Error::Io(error)) => {
1288                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
1289                    tokio::time::sleep(duration).await;
1290                    continue;
1291                }
1292
1293                return Err(Error::Io(error));
1294            }
1295            Err(error) => return Err(error),
1296        }
1297    }
1298}
1299async fn list_group_reservations_inner(
1300    configuration: &configuration::Configuration,
1301    backoff: &mut ExponentialBackoff,
1302    group_name: &str,
1303    filter: Option<&str>,
1304    order: Option<&str>,
1305    page_size: Option<i64>,
1306    page_token: Option<&str>,
1307    show_deleted: Option<&str>,
1308) -> Result<models::ListReservationsResponse, Error<ListGroupReservationsError>> {
1309    let local_var_configuration = configuration;
1310    // add a prefix to parameters to efficiently prevent name collisions
1311    let p_path_group_name = group_name;
1312    let p_query_filter = filter;
1313    let p_query_order = order;
1314    let p_query_page_size = page_size;
1315    let p_query_page_token = page_token;
1316    let p_query_show_deleted = show_deleted;
1317
1318    let local_var_client = &local_var_configuration.client;
1319
1320    let local_var_uri_str = format!(
1321        "{}/v1/groups/{groupName}/reservations",
1322        local_var_configuration.qcs_config.api_url(),
1323        groupName = crate::apis::urlencode(p_path_group_name)
1324    );
1325    let mut local_var_req_builder =
1326        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());
1327
1328    #[cfg(feature = "tracing")]
1329    {
1330        // Ignore parsing errors if the URL is invalid for some reason.
1331        // If it is invalid, it will turn up as an error later when actually making the request.
1332        let local_var_do_tracing = local_var_uri_str
1333            .parse::<::url::Url>()
1334            .ok()
1335            .is_none_or(|url| {
1336                configuration
1337                    .qcs_config
1338                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
1339            });
1340
1341        if local_var_do_tracing {
1342            ::tracing::debug!(
1343                url=%local_var_uri_str,
1344                method="GET",
1345                "making list_group_reservations request",
1346            );
1347        }
1348    }
1349
1350    if let Some(ref local_var_str) = p_query_filter {
1351        local_var_req_builder =
1352            local_var_req_builder.query(&[("filter", &local_var_str.to_string())]);
1353    }
1354    if let Some(ref local_var_str) = p_query_order {
1355        local_var_req_builder =
1356            local_var_req_builder.query(&[("order", &local_var_str.to_string())]);
1357    }
1358    if let Some(ref local_var_str) = p_query_page_size {
1359        local_var_req_builder =
1360            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
1361    }
1362    if let Some(ref local_var_str) = p_query_page_token {
1363        local_var_req_builder =
1364            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
1365    }
1366    if let Some(ref local_var_str) = p_query_show_deleted {
1367        local_var_req_builder =
1368            local_var_req_builder.query(&[("showDeleted", &local_var_str.to_string())]);
1369    }
1370
1371    // Use the QCS Bearer token if a client OAuthSession is present,
1372    // but do not require one when the security schema says it is optional.
1373    {
1374        use qcs_api_client_common::configuration::TokenError;
1375
1376        #[allow(
1377            clippy::nonminimal_bool,
1378            clippy::eq_op,
1379            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
1380        )]
1381        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";
1382
1383        let token = local_var_configuration
1384            .qcs_config
1385            .get_bearer_access_token()
1386            .await;
1387
1388        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
1389            // the client is configured without any OAuthSession, but this call does not require one.
1390            #[cfg(feature = "tracing")]
1391            tracing::debug!(
1392                "No client credentials found, but this call does not require authentication."
1393            );
1394        } else {
1395            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
1396        }
1397    }
1398
1399    let local_var_req = local_var_req_builder.build()?;
1400    let local_var_resp = local_var_client.execute(local_var_req).await?;
1401
1402    let local_var_status = local_var_resp.status();
1403    let local_var_raw_content_type = local_var_resp
1404        .headers()
1405        .get("content-type")
1406        .and_then(|v| v.to_str().ok())
1407        .unwrap_or("application/octet-stream")
1408        .to_string();
1409    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());
1410
1411    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
1412        let local_var_content = local_var_resp.text().await?;
1413        match local_var_content_type {
1414            ContentType::Json => serde_path_to_error::deserialize(
1415                &mut serde_json::Deserializer::from_str(&local_var_content),
1416            )
1417            .map_err(Error::from),
1418            ContentType::Text => Err(Error::InvalidContentType {
1419                content_type: local_var_raw_content_type,
1420                return_type: "models::ListReservationsResponse",
1421            }),
1422            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
1423                content_type: unknown_type,
1424                return_type: "models::ListReservationsResponse",
1425            }),
1426        }
1427    } else {
1428        let local_var_retry_delay =
1429            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
1430        let local_var_content = local_var_resp.text().await?;
1431        let local_var_entity: Option<ListGroupReservationsError> =
1432            serde_json::from_str(&local_var_content).ok();
1433        let local_var_error = ResponseContent {
1434            status: local_var_status,
1435            content: local_var_content,
1436            entity: local_var_entity,
1437            retry_delay: local_var_retry_delay,
1438        };
1439        Err(Error::ResponseError(local_var_error))
1440    }
1441}
1442
1443/// List existing reservations for the requested group.  Available filter fields include:  * `startTime` - timestamp * `endTime` - timestamp * `createdTime` - timestamp * `price` - integer * `quantumProcessorId` - string  Available order fields include:  * `startTime` - timestamp * `endTime` - timestamp * `createdTime` - timestamp * `price` - integer
1444pub async fn list_group_reservations(
1445    configuration: &configuration::Configuration,
1446    group_name: &str,
1447    filter: Option<&str>,
1448    order: Option<&str>,
1449    page_size: Option<i64>,
1450    page_token: Option<&str>,
1451    show_deleted: Option<&str>,
1452) -> Result<models::ListReservationsResponse, Error<ListGroupReservationsError>> {
1453    let mut backoff = configuration.backoff.build();
1454    let mut refreshed_credentials = false;
1455    let method = reqwest::Method::GET;
1456    loop {
1457        let result = list_group_reservations_inner(
1458            configuration,
1459            &mut backoff,
1460            group_name.clone(),
1461            filter.clone(),
1462            order.clone(),
1463            page_size.clone(),
1464            page_token.clone(),
1465            show_deleted.clone(),
1466        )
1467        .await;
1468
1469        match result {
1470            Ok(result) => return Ok(result),
1471            Err(Error::ResponseError(response)) => {
1472                if !refreshed_credentials
1473                    && matches!(
1474                        response.status,
1475                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
1476                    )
1477                {
1478                    // Attempt to refresh credentials
1479                    match configuration.qcs_config.refresh().await {
1480                        Ok(_) => {
1481                            refreshed_credentials = true;
1482                            continue;
1483                        }
1484                        Err(::qcs_api_client_common::configuration::TokenError::Write {
1485                            error,
1486                            oauth_session: _,
1487                        }) => {
1488                            // Token refresh succeeded but persistence failed
1489                            // The token is already in memory and will be used for this request
1490                            #[cfg(feature = "tracing")]
1491                            tracing::warn!(
1492                                "Token refresh succeeded but failed to persist: {}. Continuing with in-memory token.",
1493                                error
1494                            );
1495                            refreshed_credentials = true;
1496                            continue;
1497                        }
1498                        Err(e) => return Err(e.into()),
1499                    }
1500                } else if let Some(duration) = response.retry_delay {
1501                    tokio::time::sleep(duration).await;
1502                    continue;
1503                }
1504
1505                return Err(Error::ResponseError(response));
1506            }
1507            Err(Error::Reqwest(error)) => {
1508                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
1509                    tokio::time::sleep(duration).await;
1510                    continue;
1511                }
1512
1513                return Err(Error::Reqwest(error));
1514            }
1515            Err(Error::Io(error)) => {
1516                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
1517                    tokio::time::sleep(duration).await;
1518                    continue;
1519                }
1520
1521                return Err(Error::Io(error));
1522            }
1523            Err(error) => return Err(error),
1524        }
1525    }
1526}
1527async fn list_reservations_inner(
1528    configuration: &configuration::Configuration,
1529    backoff: &mut ExponentialBackoff,
1530    filter: Option<&str>,
1531    order: Option<&str>,
1532    page_size: Option<i64>,
1533    page_token: Option<&str>,
1534    show_deleted: Option<&str>,
1535    x_qcs_account_id: Option<&str>,
1536    x_qcs_account_type: Option<models::AccountType>,
1537) -> Result<models::ListReservationsResponse, Error<ListReservationsError>> {
1538    let local_var_configuration = configuration;
1539    // add a prefix to parameters to efficiently prevent name collisions
1540    let p_query_filter = filter;
1541    let p_query_order = order;
1542    let p_query_page_size = page_size;
1543    let p_query_page_token = page_token;
1544    let p_query_show_deleted = show_deleted;
1545    let p_header_x_qcs_account_id = x_qcs_account_id;
1546    let p_header_x_qcs_account_type = x_qcs_account_type;
1547
1548    let local_var_client = &local_var_configuration.client;
1549
1550    let local_var_uri_str = format!(
1551        "{}/v1/reservations",
1552        local_var_configuration.qcs_config.api_url()
1553    );
1554    let mut local_var_req_builder =
1555        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());
1556
1557    #[cfg(feature = "tracing")]
1558    {
1559        // Ignore parsing errors if the URL is invalid for some reason.
1560        // If it is invalid, it will turn up as an error later when actually making the request.
1561        let local_var_do_tracing = local_var_uri_str
1562            .parse::<::url::Url>()
1563            .ok()
1564            .is_none_or(|url| {
1565                configuration
1566                    .qcs_config
1567                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
1568            });
1569
1570        if local_var_do_tracing {
1571            ::tracing::debug!(
1572                url=%local_var_uri_str,
1573                method="GET",
1574                "making list_reservations request",
1575            );
1576        }
1577    }
1578
1579    if let Some(ref local_var_str) = p_query_filter {
1580        local_var_req_builder =
1581            local_var_req_builder.query(&[("filter", &local_var_str.to_string())]);
1582    }
1583    if let Some(ref local_var_str) = p_query_order {
1584        local_var_req_builder =
1585            local_var_req_builder.query(&[("order", &local_var_str.to_string())]);
1586    }
1587    if let Some(ref local_var_str) = p_query_page_size {
1588        local_var_req_builder =
1589            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
1590    }
1591    if let Some(ref local_var_str) = p_query_page_token {
1592        local_var_req_builder =
1593            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
1594    }
1595    if let Some(ref local_var_str) = p_query_show_deleted {
1596        local_var_req_builder =
1597            local_var_req_builder.query(&[("showDeleted", &local_var_str.to_string())]);
1598    }
1599    if let Some(local_var_param_value) = p_header_x_qcs_account_id {
1600        local_var_req_builder =
1601            local_var_req_builder.header("x-qcs-account-id", local_var_param_value.to_string());
1602    }
1603    if let Some(local_var_param_value) = p_header_x_qcs_account_type {
1604        local_var_req_builder =
1605            local_var_req_builder.header("x-qcs-account-type", local_var_param_value.to_string());
1606    }
1607
1608    // Use the QCS Bearer token if a client OAuthSession is present,
1609    // but do not require one when the security schema says it is optional.
1610    {
1611        use qcs_api_client_common::configuration::TokenError;
1612
1613        #[allow(
1614            clippy::nonminimal_bool,
1615            clippy::eq_op,
1616            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
1617        )]
1618        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";
1619
1620        let token = local_var_configuration
1621            .qcs_config
1622            .get_bearer_access_token()
1623            .await;
1624
1625        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
1626            // the client is configured without any OAuthSession, but this call does not require one.
1627            #[cfg(feature = "tracing")]
1628            tracing::debug!(
1629                "No client credentials found, but this call does not require authentication."
1630            );
1631        } else {
1632            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
1633        }
1634    }
1635
1636    let local_var_req = local_var_req_builder.build()?;
1637    let local_var_resp = local_var_client.execute(local_var_req).await?;
1638
1639    let local_var_status = local_var_resp.status();
1640    let local_var_raw_content_type = local_var_resp
1641        .headers()
1642        .get("content-type")
1643        .and_then(|v| v.to_str().ok())
1644        .unwrap_or("application/octet-stream")
1645        .to_string();
1646    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());
1647
1648    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
1649        let local_var_content = local_var_resp.text().await?;
1650        match local_var_content_type {
1651            ContentType::Json => serde_path_to_error::deserialize(
1652                &mut serde_json::Deserializer::from_str(&local_var_content),
1653            )
1654            .map_err(Error::from),
1655            ContentType::Text => Err(Error::InvalidContentType {
1656                content_type: local_var_raw_content_type,
1657                return_type: "models::ListReservationsResponse",
1658            }),
1659            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
1660                content_type: unknown_type,
1661                return_type: "models::ListReservationsResponse",
1662            }),
1663        }
1664    } else {
1665        let local_var_retry_delay =
1666            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
1667        let local_var_content = local_var_resp.text().await?;
1668        let local_var_entity: Option<ListReservationsError> =
1669            serde_json::from_str(&local_var_content).ok();
1670        let local_var_error = ResponseContent {
1671            status: local_var_status,
1672            content: local_var_content,
1673            entity: local_var_entity,
1674            retry_delay: local_var_retry_delay,
1675        };
1676        Err(Error::ResponseError(local_var_error))
1677    }
1678}
1679
1680/// List existing reservations for the authenticated user, or a target user when specifying `X-QCS-ACCOUNT-ID` and `X-QCS-ACCOUNT-TYPE` headers.  Available filter fields include:  * `startTime` - timestamp * `endTime` - timestamp * `createdTime` - timestamp * `price` - integer * `cancelled` - boolean (deprecated, use `showDeleted` parameter) * `quantumProcessorId` - string  Available order fields include:  * `startTime` - timestamp * `endTime` - timestamp * `createdTime` - timestamp * `price` - integer
1681pub async fn list_reservations(
1682    configuration: &configuration::Configuration,
1683    filter: Option<&str>,
1684    order: Option<&str>,
1685    page_size: Option<i64>,
1686    page_token: Option<&str>,
1687    show_deleted: Option<&str>,
1688    x_qcs_account_id: Option<&str>,
1689    x_qcs_account_type: Option<models::AccountType>,
1690) -> Result<models::ListReservationsResponse, Error<ListReservationsError>> {
1691    let mut backoff = configuration.backoff.build();
1692    let mut refreshed_credentials = false;
1693    let method = reqwest::Method::GET;
1694    loop {
1695        let result = list_reservations_inner(
1696            configuration,
1697            &mut backoff,
1698            filter.clone(),
1699            order.clone(),
1700            page_size.clone(),
1701            page_token.clone(),
1702            show_deleted.clone(),
1703            x_qcs_account_id.clone(),
1704            x_qcs_account_type.clone(),
1705        )
1706        .await;
1707
1708        match result {
1709            Ok(result) => return Ok(result),
1710            Err(Error::ResponseError(response)) => {
1711                if !refreshed_credentials
1712                    && matches!(
1713                        response.status,
1714                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
1715                    )
1716                {
1717                    // Attempt to refresh credentials
1718                    match configuration.qcs_config.refresh().await {
1719                        Ok(_) => {
1720                            refreshed_credentials = true;
1721                            continue;
1722                        }
1723                        Err(::qcs_api_client_common::configuration::TokenError::Write {
1724                            error,
1725                            oauth_session: _,
1726                        }) => {
1727                            // Token refresh succeeded but persistence failed
1728                            // The token is already in memory and will be used for this request
1729                            #[cfg(feature = "tracing")]
1730                            tracing::warn!(
1731                                "Token refresh succeeded but failed to persist: {}. Continuing with in-memory token.",
1732                                error
1733                            );
1734                            refreshed_credentials = true;
1735                            continue;
1736                        }
1737                        Err(e) => return Err(e.into()),
1738                    }
1739                } else if let Some(duration) = response.retry_delay {
1740                    tokio::time::sleep(duration).await;
1741                    continue;
1742                }
1743
1744                return Err(Error::ResponseError(response));
1745            }
1746            Err(Error::Reqwest(error)) => {
1747                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
1748                    tokio::time::sleep(duration).await;
1749                    continue;
1750                }
1751
1752                return Err(Error::Reqwest(error));
1753            }
1754            Err(Error::Io(error)) => {
1755                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
1756                    tokio::time::sleep(duration).await;
1757                    continue;
1758                }
1759
1760                return Err(Error::Io(error));
1761            }
1762            Err(error) => return Err(error),
1763        }
1764    }
1765}