Skip to main content

qcs_api_client_openapi/apis/
deployments_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 [`get_endpoint_accessors`]
40#[cfg(feature = "clap")]
41#[derive(Debug, clap::Args)]
42pub struct GetEndpointAccessorsClapParams {
43    #[arg(long)]
44    pub endpoint_id: String,
45}
46
47#[cfg(feature = "clap")]
48impl GetEndpointAccessorsClapParams {
49    pub async fn execute(
50        self,
51        configuration: &configuration::Configuration,
52    ) -> Result<models::ListQuantumProcessorAccessorsResponse, miette::Error> {
53        get_endpoint_accessors(configuration, self.endpoint_id.as_str())
54            .await
55            .into_diagnostic()
56    }
57}
58
59/// struct for typed errors of method [`get_endpoint_accessors`]
60#[derive(Debug, Clone, Serialize, Deserialize)]
61#[serde(untagged)]
62pub enum GetEndpointAccessorsError {
63    Status422(models::ValidationError),
64    DefaultResponse(models::Error),
65    UnknownValue(serde_json::Value),
66}
67
68async fn get_endpoint_accessors_inner(
69    configuration: &configuration::Configuration,
70    backoff: &mut ExponentialBackoff,
71    endpoint_id: &str,
72) -> Result<models::ListQuantumProcessorAccessorsResponse, Error<GetEndpointAccessorsError>> {
73    let local_var_configuration = configuration;
74    // add a prefix to parameters to efficiently prevent name collisions
75    let p_path_endpoint_id = endpoint_id;
76
77    let local_var_client = &local_var_configuration.client;
78
79    let local_var_uri_str = format!(
80        "{}/v1/endpoints/{endpoint_id}/accessors",
81        local_var_configuration.qcs_config.api_url(),
82        endpoint_id = crate::apis::urlencode(p_path_endpoint_id)
83    );
84    let mut local_var_req_builder =
85        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());
86
87    #[cfg(feature = "tracing")]
88    {
89        // Ignore parsing errors if the URL is invalid for some reason.
90        // If it is invalid, it will turn up as an error later when actually making the request.
91        let local_var_do_tracing = local_var_uri_str
92            .parse::<::url::Url>()
93            .ok()
94            .is_none_or(|url| {
95                configuration
96                    .qcs_config
97                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
98            });
99
100        if local_var_do_tracing {
101            ::tracing::debug!(
102                url=%local_var_uri_str,
103                method="GET",
104                "making get_endpoint_accessors request",
105            );
106        }
107    }
108
109    // Use the QCS Bearer token if a client OAuthSession is present,
110    // but do not require one when the security schema says it is optional.
111    {
112        use qcs_api_client_common::configuration::TokenError;
113
114        #[allow(
115            clippy::nonminimal_bool,
116            clippy::eq_op,
117            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
118        )]
119        let is_jwt_bearer_optional: bool = false || "JWTBearerOptional" == "JWTBearerOptional";
120
121        let token = local_var_configuration
122            .qcs_config
123            .get_bearer_access_token()
124            .await;
125
126        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
127            // the client is configured without any OAuthSession, but this call does not require one.
128            #[cfg(feature = "tracing")]
129            tracing::debug!(
130                "No client credentials found, but this call does not require authentication."
131            );
132        } else {
133            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
134        }
135    }
136
137    let local_var_req = local_var_req_builder.build()?;
138    let local_var_resp = local_var_client.execute(local_var_req).await?;
139
140    let local_var_status = local_var_resp.status();
141    let local_var_raw_content_type = local_var_resp
142        .headers()
143        .get("content-type")
144        .and_then(|v| v.to_str().ok())
145        .unwrap_or("application/octet-stream")
146        .to_string();
147    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());
148
149    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
150        let local_var_content = local_var_resp.text().await?;
151        match local_var_content_type {
152            ContentType::Json => serde_path_to_error::deserialize(
153                &mut serde_json::Deserializer::from_str(&local_var_content),
154            )
155            .map_err(Error::from),
156            ContentType::Text => Err(Error::InvalidContentType {
157                content_type: local_var_raw_content_type,
158                return_type: "models::ListQuantumProcessorAccessorsResponse",
159            }),
160            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
161                content_type: unknown_type,
162                return_type: "models::ListQuantumProcessorAccessorsResponse",
163            }),
164        }
165    } else {
166        let local_var_retry_delay =
167            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
168        let local_var_content = local_var_resp.text().await?;
169        let local_var_entity: Option<GetEndpointAccessorsError> =
170            serde_json::from_str(&local_var_content).ok();
171        let local_var_error = ResponseContent {
172            status: local_var_status,
173            content: local_var_content,
174            entity: local_var_entity,
175            retry_delay: local_var_retry_delay,
176        };
177        Err(Error::ResponseError(local_var_error))
178    }
179}
180
181pub async fn get_endpoint_accessors(
182    configuration: &configuration::Configuration,
183    endpoint_id: &str,
184) -> Result<models::ListQuantumProcessorAccessorsResponse, Error<GetEndpointAccessorsError>> {
185    let mut backoff = configuration.backoff.clone();
186    let mut refreshed_credentials = false;
187    let method = reqwest::Method::GET;
188    loop {
189        let result =
190            get_endpoint_accessors_inner(configuration, &mut backoff, endpoint_id.clone()).await;
191
192        match result {
193            Ok(result) => return Ok(result),
194            Err(Error::ResponseError(response)) => {
195                if !refreshed_credentials
196                    && matches!(
197                        response.status,
198                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
199                    )
200                {
201                    // Attempt to refresh credentials
202                    match configuration.qcs_config.refresh().await {
203                        Ok(_) => {
204                            refreshed_credentials = true;
205                            continue;
206                        }
207                        Err(::qcs_api_client_common::configuration::TokenError::Write {
208                            error,
209                            oauth_session: _,
210                        }) => {
211                            // Token refresh succeeded but persistence failed
212                            // The token is already in memory and will be used for this request
213                            #[cfg(feature = "tracing")]
214                            tracing::warn!(
215                                "Token refresh succeeded but failed to persist: {}. Continuing with in-memory token.",
216                                error
217                            );
218                            refreshed_credentials = true;
219                            continue;
220                        }
221                        Err(e) => return Err(e.into()),
222                    }
223                } else if let Some(duration) = response.retry_delay {
224                    tokio::time::sleep(duration).await;
225                    continue;
226                }
227
228                return Err(Error::ResponseError(response));
229            }
230            Err(Error::Reqwest(error)) => {
231                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
232                    tokio::time::sleep(duration).await;
233                    continue;
234                }
235
236                return Err(Error::Reqwest(error));
237            }
238            Err(Error::Io(error)) => {
239                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
240                    tokio::time::sleep(duration).await;
241                    continue;
242                }
243
244                return Err(Error::Io(error));
245            }
246            Err(error) => return Err(error),
247        }
248    }
249}