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