qcs 0.26.2-rc.0

High level interface for running Quil on a QPU
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
//! This module provides access to the QCS QPU API
use std::{convert::TryFrom, fmt, time::Duration};

use tonic::codec::CompressionEncoding;

#[cfg(feature = "stubs")]
use pyo3_stub_gen::derive::{gen_stub_pyclass, gen_stub_pyclass_complex_enum, gen_stub_pymethods};

#[deny(clippy::module_name_repetitions)]
pub use ::pbjson_types::Duration as QpuApiDuration;
use async_trait::async_trait;
use cached::proc_macro::cached;
use derive_builder::Builder;
use qcs_api_client_common::configuration::TokenError;
#[cfg(feature = "grpc-web")]
use qcs_api_client_grpc::tonic::wrap_channel_with_grpc_web;
#[cfg(feature = "tracing")]
use qcs_api_client_grpc::tonic::wrap_channel_with_tracing;
pub use qcs_api_client_grpc::tonic::Error as GrpcError;
use qcs_api_client_grpc::{
    get_channel_with_timeout,
    models::controller::{
        controller_job_execution_result, data_value::Value, ControllerJobExecutionResult,
        DataValue, EncryptedControllerJob, JobExecutionConfiguration, RealDataValue,
    },
    services::controller::{
        cancel_controller_jobs_request, controller_client::ControllerClient,
        execute_controller_job_request, get_controller_job_results_request,
        CancelControllerJobsRequest, ExecuteControllerJobRequest,
        ExecutionOptions as InnerApiExecutionOptions, GetControllerJobResultsRequest,
    },
    tonic::{parse_uri, wrap_channel_with, wrap_channel_with_retry},
};
pub use qcs_api_client_openapi::apis::Error as OpenApiError;
use qcs_api_client_openapi::models::QuantumProcessorAccessorType;
use qcs_api_client_openapi::{
    apis::{
        endpoints_api::{
            get_default_endpoint as api_get_default_endpoint, get_endpoint,
            GetDefaultEndpointError, GetEndpointError,
        },
        quantum_processors_api::{
            get_quantum_processor_accessors, GetQuantumProcessorAccessorsError,
        },
    },
    models::QuantumProcessorAccessor,
};

use crate::executable::Parameters;

use crate::client::{GrpcClientError, GrpcConnection, Qcs};

#[cfg(feature = "python")]
pub mod python;

/// The maximum size of a gRPC request to the controller service, in bytes.
const MAX_CONTROLLER_OUTBOUND_REQUEST_SIZE: usize = 250 * 1024 * 1024;

pub(crate) fn params_into_job_execution_configuration(
    params: &Parameters,
) -> JobExecutionConfiguration {
    let memory_values = params
        .iter()
        .map(|(str, value)| {
            (
                str.as_ref().into(),
                DataValue {
                    value: Some(Value::Real(RealDataValue {
                        data: value.clone(),
                    })),
                },
            )
        })
        .collect();

    JobExecutionConfiguration { memory_values }
}

/// The QCS Job ID. Useful for debugging or retrieving results later.
#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "python", derive(pyo3::FromPyObject, pyo3::IntoPyObject))]
pub struct JobId(pub(crate) String);

impl fmt::Display for JobId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <String as fmt::Display>::fmt(&self.0, f)
    }
}

impl From<String> for JobId {
    fn from(value: String) -> Self {
        Self(value)
    }
}

#[expect(clippy::missing_errors_doc)]
/// Execute compiled program on a QPU.
///
/// See [`ExecuteControllerJobRequest`] for more details.
///
/// # Arguments
///
/// * `quantum_processor_id` - The quantum processor to execute the job on. This parameter
///   is required unless using [`ConnectionStrategy::EndpointId`] or
///   [`ConnectionStrategy::EndpointAddress`] in `execution_options`
///   to target a specific endpoint ID.
/// * `program` - The compiled program as an [`EncryptedControllerJob`]
/// * `patch_values` - The parameters to use for the execution. See [`submit_with_parameter_batch`]
///   if you need to execute with multiple sets of parameters.
/// * `client` - The [`Qcs`] client to use.
/// * `execution_options` - The [`ExecutionOptions`] to use. If the connection strategy used
///   is [`ConnectionStrategy::EndpointId`] or [`ConnectionStrategy::EndpointAddress`] then direct
///   access to that endpoint overrides the `quantum_processor_id` parameter.
pub async fn submit(
    quantum_processor_id: Option<&str>,
    program: EncryptedControllerJob,
    patch_values: &Parameters,
    client: &Qcs,
    execution_options: &ExecutionOptions,
) -> Result<JobId, QpuApiError> {
    submit_with_parameter_batch(
        quantum_processor_id,
        program,
        std::iter::once(patch_values),
        client,
        execution_options,
    )
    .await?
    .pop()
    .ok_or_else(|| GrpcClientError::ResponseEmpty("Job Execution ID".into()))
    .map_err(QpuApiError::from)
}

/// Execute a compiled program on a QPU with multiple sets of `patch_values`.
///
/// See [`ExecuteControllerJobRequest`] for more details.
///
/// # Arguments
///
/// * `quantum_processor_id` - The quantum processor to execute the job on. This parameter
///   is required unless using [`ConnectionStrategy::EndpointId`] or
///   [`ConnectionStrategy::EndpointAddress`] in `execution_options`
///   to target a specific endpoint ID.
/// * `program` - The compiled program as an [`EncryptedControllerJob`]
/// * `patch_values` - The parameters to use for the execution. The job will be run once for each
///   given set of [`Parameters`].
/// * `client` - The [`Qcs`] client to use.
/// * `execution_options` - The [`ExecutionOptions`] to use. If the connection strategy used
///   is [`ConnectionStrategy::EndpointId`] or [`ConnectionStrategy::EndpointAddress`]
///   then direct access to that endpoint overrides the `quantum_processor_id` parameter.
///
/// # Errors
///
/// Returns a [`QpuApiError`] if:
/// * Any of the jobs fail to be queued.
/// * The provided `patch_values` iterator is empty.
pub async fn submit_with_parameter_batch<'a, I>(
    quantum_processor_id: Option<&str>,
    program: EncryptedControllerJob,
    patch_values: I,
    client: &Qcs,
    execution_options: &ExecutionOptions,
) -> Result<Vec<JobId>, QpuApiError>
where
    I: IntoIterator<Item = &'a Parameters>,
{
    #[cfg(feature = "tracing")]
    tracing::debug!(
        "submitting job to {:?} using options {:?}",
        quantum_processor_id,
        execution_options
    );

    let mut patch_values = patch_values.into_iter().peekable();
    if patch_values.peek().is_none() {
        return Err(QpuApiError::EmptyPatchValues);
    }

    let request = ExecuteControllerJobRequest {
        execution_configurations: patch_values
            .map(params_into_job_execution_configuration)
            .collect(),
        job: Some(execute_controller_job_request::Job::Encrypted(program)),
        target: execution_options.get_job_target(quantum_processor_id),
        options: execution_options.api_options().copied(),
    };

    let mut controller_client = execution_options
        .get_controller_client(client, quantum_processor_id)
        .await?;

    Ok(controller_client
        .execute_controller_job(request)
        .await
        .map_err(GrpcClientError::RequestFailed)?
        .into_inner()
        .job_execution_ids
        .into_iter()
        .map(JobId)
        .collect())
}

/// Cancel all given jobs that have yet to begin executing.
///
/// This action is *not* atomic, and will attempt to cancel every job even when some jobs cannot be
/// cancelled. A job can be cancelled only if it has not yet started executing.
///
/// Cancellation is not guaranteed, as it is based on job state at the time of cancellation, and is
/// completed on a best effort basis.
///
/// # Arguments
///
/// * `quantum_processor_id` - The quantum processor to execute the job on. This parameter
///   is required unless using [`ConnectionStrategy::EndpointId`] or
///   [`ConnectionStrategy::EndpointAddress`] in `execution_options`
///   to target a specific endpoint ID.
/// * `job_ids` - The [`JobId`]s to cancel.
/// * `client` - The [`Qcs`] client to use.
/// * `execution_options` - The [`ExecutionOptions`] to use. If the connection strategy used
///   is [`ConnectionStrategy::EndpointId`] or [`ConnectionStrategy::EndpointAddress`]
///   overrides the `quantum_processor_id` parameter.
///
/// # Errors
///
/// * Returns [`QpuApiError::GrpcClientError`] with [`GrpcClientError::RequestFailed`] if any of
///   the jobs could not be cancelled.
pub async fn cancel_jobs(
    job_ids: Vec<JobId>,
    quantum_processor_id: Option<&str>,
    client: &Qcs,
    execution_options: &ExecutionOptions,
) -> Result<(), QpuApiError> {
    let mut controller_client = execution_options
        .get_controller_client(client, quantum_processor_id)
        .await?;

    let request = CancelControllerJobsRequest {
        job_ids: job_ids.into_iter().map(|id| id.0).collect(),
        target: execution_options.get_cancel_target(quantum_processor_id),
    };

    controller_client
        .cancel_controller_jobs(request)
        .await
        .map_err(GrpcClientError::RequestFailed)?;

    Ok(())
}

/// Cancel a job that has yet to begin executing.
///
/// This action is *not* atomic, and will attempt to cancel a job even if it cannot be cancelled. A
/// job can be cancelled only if it has not yet started executing.
///
/// Cancellation is not guaranteed, as it is based on job state at the time of cancellation, and is
/// completed on a best effort basis.
///
/// # Arguments
///
/// * `quantum_processor_id` - The quantum processor to execute the job on. This parameter is
///   required unless using [`ConnectionStrategy::EndpointId`] or
///   [`ConnectionStrategy::EndpointAddress`] in `execution_options` to target
///   a specific endpoint ID.
/// * `job_ids` - The [`JobId`]s to cancel.
/// * `client` - The [`Qcs`] client to use.
/// * `execution_options` - The [`ExecutionOptions`] to use. If the connection strategy used is
///   [`ConnectionStrategy::EndpointId`] or [`ConnectionStrategy::EndpointAddress`]
///   then direct access to that endpoint overrides the
///   `quantum_processor_id` parameter.
///
/// # Errors
///
/// * Returns [`QpuApiError::GrpcClientError`] with [`GrpcClientError::RequestFailed`] if the
///   job could not be cancelled.
pub async fn cancel_job(
    job_id: JobId,
    quantum_processor_id: Option<&str>,
    client: &Qcs,
    execution_options: &ExecutionOptions,
) -> Result<(), QpuApiError> {
    cancel_jobs(
        vec![job_id],
        quantum_processor_id,
        client,
        execution_options,
    )
    .await
}

#[expect(clippy::missing_errors_doc)]
/// Fetch results from QPU job execution.
///
/// # Arguments
///
/// * `job_id` - The [`JobId`] to retrieve results for.
/// * `quantum_processor_id` - The quantum processor the job was run on. This parameter
///   is required unless using [`ConnectionStrategy::EndpointId`] or
///   [`ConnectionStrategy::EndpointAddress`] in `execution_options`
///   to target a specific endpoint ID.
/// * `client` - The [`Qcs`] client to use.
/// * `execution_options` - The [`ExecutionOptions`] to use. If the connection strategy used
///   is [`ConnectionStrategy::EndpointId`] or [`ConnectionStrategy::EndpointAddress`]
///   then direct access to that endpoint overrides the `quantum_processor_id` parameter.
pub async fn retrieve_results(
    job_id: JobId,
    quantum_processor_id: Option<&str>,
    client: &Qcs,
    execution_options: &ExecutionOptions,
) -> Result<ControllerJobExecutionResult, QpuApiError> {
    #[cfg(feature = "tracing")]
    tracing::debug!(
        "retrieving job results for {} on {:?} using options {:?}",
        job_id,
        quantum_processor_id,
        execution_options,
    );

    let request = GetControllerJobResultsRequest {
        job_execution_id: job_id.0,
        target: execution_options.get_results_target(quantum_processor_id),
    };

    let mut controller_client = execution_options
        .get_controller_client(client, quantum_processor_id)
        .await?;

    controller_client
        .get_controller_job_results(request)
        .await
        .map_err(GrpcClientError::RequestFailed)?
        .into_inner()
        .result
        .ok_or_else(|| GrpcClientError::ResponseEmpty("Job Execution Results".into()))
        .map_err(QpuApiError::from)
        .and_then(
            |result| match controller_job_execution_result::Status::try_from(result.status) {
                Ok(controller_job_execution_result::Status::Success) => Ok(result),
                Ok(status) => Err(QpuApiError::JobExecutionFailed {
                    status: status.as_str_name().to_string(),
                    message: result
                        .status_message
                        .unwrap_or("No message provided.".to_string()),
                }),
                Err(s) => Err(QpuApiError::InvalidJobStatus {
                    status: result.status,
                    message: s.to_string(),
                }),
            },
        )
}

/// Options available when connecting to a QPU.
///
/// Use [`Default`] to get a reasonable set of defaults, or start with [`QpuConnectionOptionsBuilder`]
/// to build a custom set of options.
// These are aliases because the ExecutionOptions are actually generic over all QPU operations.
pub type QpuConnectionOptions = ExecutionOptions;
/// Builder for setting up [`QpuConnectionOptions`].
pub type QpuConnectionOptionsBuilder = ExecutionOptionsBuilder;

/// Options available when executing a job on a QPU.
///
/// Use [`Default`] to get a reasonable set of defaults, or start with [`ExecutionOptionsBuilder`]
/// to build a custom set of options.
#[derive(Builder, Clone, Debug, PartialEq)]
#[cfg_attr(
    not(feature = "stubs"),
    builder_struct_attr(optipy::strip_pyo3(only_stubs)),
    builder_field_attr(stub_gen(skip)),
    optipy::strip_pyo3(only_stubs)
)]
#[cfg_attr(
    not(feature = "python"),
    builder_struct_attr(optipy::strip_pyo3),
    optipy::strip_pyo3
)]
#[cfg_attr(
    feature = "stubs",
    builder_struct_attr(gen_stub_pyclass),
    gen_stub_pyclass
)]
#[cfg_attr(
    feature = "python",
    builder_struct_attr(pyo3::pyclass(module = "qcs_sdk.qpu.api")),
    pyo3::pyclass(module = "qcs_sdk.qpu.api", eq)
)]
pub struct ExecutionOptions {
    #[pyo3(get)]
    #[doc = "The [`ConnectionStrategy`] to use to establish a connection to the QPU."]
    #[builder(default)]
    connection_strategy: ConnectionStrategy,

    #[doc = "The timeout to use for the request, defaults to 30 seconds. If set to `None`, then there is no timeout."]
    #[builder(default = "Some(Duration::from_secs(30))")]
    timeout: Option<Duration>,

    #[doc = "Options available when executing a job on a QPU, particular to the execution service's API."]
    #[builder(default = "None")]
    api_options: Option<InnerApiExecutionOptions>,
}

impl Default for ExecutionOptions {
    fn default() -> Self {
        ExecutionOptionsBuilder::default().build().expect(
            "Should be able to derive a default set of the ExecutionOptions from the builder.",
        )
    }
}

impl Eq for ExecutionOptions {}

/// Options available when executing a job on a QPU, particular to the execution service's API.
///
/// This is a conventent alias for [`InnerApiExecutionOptions`] which provides a builder.
///
/// Use [`Default`] to get a reasonable set of defaults, or start with [`ApiExecutionOptionsBuilder`]
/// to build a custom set of options.
#[derive(Builder, Clone, Copy, Debug, Default, PartialEq)]
#[cfg_attr(
    feature = "stubs",
    builder_struct_attr(gen_stub_pyclass),
    gen_stub_pyclass
)]
#[cfg_attr(
    feature = "python",
    builder_struct_attr(pyo3::pyclass(
        name = "APIExecutionOptionsBuilder",
        module = "qcs_sdk.qpu.api"
    )),
    pyo3::pyclass(name = "APIExecutionOptions", module = "qcs_sdk.qpu.api")
)]
#[allow(clippy::module_name_repetitions)]
pub struct ApiExecutionOptions {
    /// the inner proto representation
    inner: InnerApiExecutionOptions,
}

impl Eq for ApiExecutionOptions {}

#[cfg_attr(not(feature = "python"), optipy::strip_pyo3)]
#[cfg_attr(feature = "stubs", gen_stub_pymethods)]
#[cfg_attr(feature = "python", pyo3::pymethods)]
impl ApiExecutionOptions {
    /// Get an [`ExecutionOptionsBuilder`] that can be used to build a custom [`ExecutionOptions`].
    #[staticmethod]
    #[must_use]
    pub fn builder() -> ApiExecutionOptionsBuilder {
        ApiExecutionOptionsBuilder::default()
    }

    /// Get the configured `bypass_settings_protection` value.
    #[getter]
    #[must_use]
    pub fn bypass_settings_protection(&self) -> bool {
        self.inner.bypass_settings_protection
    }
}

impl ApiExecutionOptions {
    /// Get the configured `timeout` value.
    ///
    /// Note, this is the timeout while running a job; the job will be evicted from
    /// the hardware once this time has elapsed.
    ///
    /// If unset, the job's estimated duration will be used;
    /// if the job does not have an estimated duration, the default
    /// timeout is selected by the service.
    ///
    /// The service may also enforce a maximum value for this field.
    #[must_use]
    pub fn timeout(&self) -> Option<::pbjson_types::Duration> {
        self.inner.timeout
    }
}

impl From<ApiExecutionOptions> for InnerApiExecutionOptions {
    fn from(options: ApiExecutionOptions) -> Self {
        options.inner
    }
}

impl From<InnerApiExecutionOptions> for ApiExecutionOptions {
    fn from(inner: InnerApiExecutionOptions) -> Self {
        Self { inner }
    }
}

impl ApiExecutionOptionsBuilder {
    /// Set the `bypass_settings_protection` value.
    pub fn bypass_settings_protection(&mut self, bypass_settings_protection: bool) -> &mut Self {
        self.inner
            .get_or_insert(InnerApiExecutionOptions::default())
            .bypass_settings_protection = bypass_settings_protection;
        self
    }

    /// Set the `timeout` value. See [`ApiExecutionOptions::timeout`] for more information.
    pub fn timeout(&mut self, timeout: Option<::pbjson_types::Duration>) -> &mut Self {
        self.inner
            .get_or_insert(InnerApiExecutionOptions::default())
            .timeout = timeout;
        self
    }
}

impl ExecutionOptions {
    /// Get an [`ExecutionOptionsBuilder`] that can be used to build a custom [`ExecutionOptions`].
    #[must_use]
    pub fn builder() -> ExecutionOptionsBuilder {
        ExecutionOptionsBuilder::default()
    }

    /// Get the [`ConnectionStrategy`].
    #[must_use]
    pub fn connection_strategy(&self) -> &ConnectionStrategy {
        &self.connection_strategy
    }

    /// Get the timeout.
    #[must_use]
    pub fn timeout(&self) -> Option<Duration> {
        self.timeout
    }

    /// Get the [`ApiExecutionOptions`].
    #[must_use]
    pub fn api_options(&self) -> Option<&InnerApiExecutionOptions> {
        self.api_options.as_ref()
    }
}

/// The connection strategy to use when submitting and retrieving jobs from a QPU.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "stubs", gen_stub_pyclass_complex_enum)]
#[cfg_attr(feature = "python", pyo3::pyclass(module = "qcs_sdk.qpu.api", eq))]
pub enum ConnectionStrategy {
    /// Connect through the publicly accessible gateway.
    Gateway(),
    /// Connect directly to the default endpoint, bypassing the gateway. Should only be used when you
    /// have direct network access and an active reservation.
    DirectAccess(),
    /// Connect directly to a specific endpoint using its ID.
    EndpointId(String),
    /// Connect directly to a specific endpoint by its gRPC address, bypassing the gateway.
    ///
    /// Should only be used when you have direct network access.
    EndpointAddress(String),
}

impl Default for ConnectionStrategy {
    fn default() -> Self {
        Self::Gateway()
    }
}

/// An `ExecutionTarget` provides methods to establish the appropriate connection to the execution
/// service.
///
/// Implementors provide a [`ConnectionStrategy`] and timeout, the trait provides default
/// implementation for getting connections and execution targets.
#[async_trait]
pub trait ExecutionTarget<'a> {
    /// The [`ConnectionStrategy`] to use to determine the connection target.
    fn connection_strategy(&'a self) -> &'a ConnectionStrategy;
    /// The timeout to use for requests to the target.
    fn timeout(&self) -> Option<Duration>;

    /// Get the [`execute_controller_job_request::Target`] for the given quantum processor ID.
    fn get_job_target(
        &'a self,
        quantum_processor_id: Option<&str>,
    ) -> Option<execute_controller_job_request::Target> {
        match self.connection_strategy() {
            ConnectionStrategy::EndpointId(endpoint_id) => Some(
                execute_controller_job_request::Target::EndpointId(endpoint_id.clone()),
            ),
            ConnectionStrategy::Gateway()
            | ConnectionStrategy::DirectAccess()
            | ConnectionStrategy::EndpointAddress(_) => quantum_processor_id
                .map(String::from)
                .map(execute_controller_job_request::Target::QuantumProcessorId),
        }
    }

    /// Get the [`get_controller_job_results_request::Target`] for the given quantum processor ID.
    fn get_results_target(
        &'a self,
        quantum_processor_id: Option<&str>,
    ) -> Option<get_controller_job_results_request::Target> {
        match self.connection_strategy() {
            ConnectionStrategy::EndpointId(endpoint_id) => Some(
                get_controller_job_results_request::Target::EndpointId(endpoint_id.clone()),
            ),
            ConnectionStrategy::Gateway()
            | ConnectionStrategy::DirectAccess()
            | ConnectionStrategy::EndpointAddress(_) => quantum_processor_id
                .map(String::from)
                .map(get_controller_job_results_request::Target::QuantumProcessorId),
        }
    }

    /// Get the [`cancel_controller_jobs_request::Target`] for the given quantum processor ID.
    fn get_cancel_target(
        &'a self,
        quantum_processor_id: Option<&str>,
    ) -> Option<cancel_controller_jobs_request::Target> {
        match self.connection_strategy() {
            ConnectionStrategy::EndpointId(endpoint_id) => Some(
                cancel_controller_jobs_request::Target::EndpointId(endpoint_id.clone()),
            ),
            ConnectionStrategy::Gateway()
            | ConnectionStrategy::DirectAccess()
            | ConnectionStrategy::EndpointAddress(_) => quantum_processor_id
                .map(String::from)
                .map(cancel_controller_jobs_request::Target::QuantumProcessorId),
        }
    }

    /// Get a controller client for the given quantum processor ID.
    async fn get_controller_client(
        &'a self,
        client: &Qcs,
        quantum_processor_id: Option<&str>,
    ) -> Result<ControllerClient<GrpcConnection>, QpuApiError> {
        let service = self
            .get_qpu_grpc_connection(client, quantum_processor_id)
            .await?;
        Ok(ControllerClient::new(service)
            .max_encoding_message_size(MAX_CONTROLLER_OUTBOUND_REQUEST_SIZE)
            // do not limit the received response size, although practically the limit is 4Gb due
            // to the frame_length of the message being a u32.
            .max_decoding_message_size(u32::MAX as usize)
            .accept_compressed(CompressionEncoding::Gzip)
            .send_compressed(CompressionEncoding::Gzip))
    }

    /// Get a GRPC connection to a QPU, without specifying the API to use.
    async fn get_qpu_grpc_connection(
        &'a self,
        client: &Qcs,
        quantum_processor_id: Option<&str>,
    ) -> Result<GrpcConnection, QpuApiError> {
        let address = match self.connection_strategy() {
            ConnectionStrategy::EndpointId(endpoint_id) => {
                let endpoint = get_endpoint(&client.get_openapi_client(), endpoint_id).await?;
                endpoint
                    .addresses
                    .grpc
                    .ok_or_else(|| QpuApiError::EndpointNotFound(endpoint_id.into()))?
            }
            ConnectionStrategy::Gateway() => {
                self.get_gateway_address(
                    quantum_processor_id.ok_or(QpuApiError::MissingQpuId)?,
                    client,
                )
                .await?
            }
            ConnectionStrategy::DirectAccess() => {
                self.get_default_endpoint_address(
                    quantum_processor_id.ok_or(QpuApiError::MissingQpuId)?,
                    client,
                )
                .await?
            }
            ConnectionStrategy::EndpointAddress(address) => address.clone(),
        };
        self.grpc_address_to_channel(&address, client)
    }

    #[expect(clippy::missing_errors_doc, clippy::result_large_err)]
    /// Get a channel from the given gRPC address.
    fn grpc_address_to_channel(
        &self,
        address: &str,
        client: &Qcs,
    ) -> Result<GrpcConnection, QpuApiError> {
        let uri = parse_uri(address).map_err(QpuApiError::GrpcError)?;
        let channel = get_channel_with_timeout(uri, self.timeout())
            .map_err(|err| QpuApiError::GrpcError(err.into()))?;

        // First add tracing if enabled
        #[cfg(feature = "tracing")]
        let channel = wrap_channel_with_tracing(
            channel,
            address.to_string(),
            client
                .get_config()
                .tracing_configuration()
                .cloned()
                .unwrap_or_default(),
        );

        // Then wrap with refresh and retry
        let channel = wrap_channel_with(channel, client.get_config().clone());
        let channel = wrap_channel_with_retry(channel);

        // Add grpc-web if enabled
        #[cfg(feature = "grpc-web")]
        let channel = wrap_channel_with_grpc_web(channel);

        Ok(channel)
    }

    /// Get the gateway address for the given quantum processor ID.
    async fn get_gateway_address(
        &self,
        quantum_processor_id: &str,
        client: &Qcs,
    ) -> Result<String, QpuApiError> {
        get_accessor_with_cache(quantum_processor_id, client).await
    }

    /// Get the default endpoint address for the given quantum processor ID.
    async fn get_default_endpoint_address(
        &self,
        quantum_processor_id: &str,
        client: &Qcs,
    ) -> Result<String, QpuApiError> {
        get_default_endpoint_with_cache(quantum_processor_id, client).await
    }
}

/// Methods that help select and configure a controller service client given a set of
/// [`ExecutionOptions`] and QPU ID.
#[async_trait]
impl<'a> ExecutionTarget<'a> for ExecutionOptions {
    fn connection_strategy(&'a self) -> &'a ConnectionStrategy {
        self.connection_strategy()
    }

    fn timeout(&self) -> Option<Duration> {
        self.timeout()
    }
}

#[cached(
    result = true,
    time = 60,
    time_refresh = true,
    sync_writes = true,
    key = "String",
    convert = r"{ String::from(quantum_processor_id)}"
)]
async fn get_accessor_with_cache(
    quantum_processor_id: &str,
    client: &Qcs,
) -> Result<String, QpuApiError> {
    #[cfg(feature = "tracing")]
    tracing::info!(quantum_processor_id=%quantum_processor_id, "get_accessor cache miss");
    get_accessor(quantum_processor_id, client).await
}

async fn get_accessor(quantum_processor_id: &str, client: &Qcs) -> Result<String, QpuApiError> {
    let accessors =
        get_quantum_processor_accessors(&client.get_openapi_client(), quantum_processor_id).await?;

    let min = select_min_accessor(accessors.accessors);

    min.map(|accessor| accessor.url)
        .ok_or_else(|| QpuApiError::GatewayNotFound(quantum_processor_id.to_string()))
}

/// Select the accessor with the lowest rank from a list of accessors.
/// - Prefer `Some({ rank: None })` to `None`.
/// - Prefer the first accessor encountered among those with the same rank value.
fn select_min_accessor(
    accessors: Vec<QuantumProcessorAccessor>,
) -> Option<QuantumProcessorAccessor> {
    accessors
        .into_iter()
        .filter(|accessor| accessor.live)
        .filter(|accessor| accessor.access_type == QuantumProcessorAccessorType::GatewayV1)
        .min_by_key(|accessor| accessor.rank.unwrap_or(i64::MAX))
}

#[cached(
    result = true,
    time = 60,
    time_refresh = true,
    sync_writes = true,
    key = "String",
    convert = r"{ String::from(quantum_processor_id)}"
)]
async fn get_default_endpoint_with_cache(
    quantum_processor_id: &str,
    client: &Qcs,
) -> Result<String, QpuApiError> {
    #[cfg(feature = "tracing")]
    tracing::info!(quantum_processor_id=%quantum_processor_id, "get_default_endpoint cache miss");
    get_default_endpoint(quantum_processor_id, client).await
}

async fn get_default_endpoint(
    quantum_processor_id: &str,
    client: &Qcs,
) -> Result<String, QpuApiError> {
    let default_endpoint =
        api_get_default_endpoint(&client.get_openapi_client(), quantum_processor_id).await?;
    default_endpoint
        .addresses
        .grpc
        .ok_or_else(|| QpuApiError::QpuEndpointNotFound(quantum_processor_id.into()))
}

/// Errors that can occur while attempting to establish a connection to the QPU.
#[derive(Debug, thiserror::Error)]
pub enum QpuApiError {
    /// Error due to a bad gRPC configuration
    #[error("Error configuring gRPC request: {0}")]
    GrpcError(#[from] GrpcError<TokenError>),

    /// Error due to missing gRPC endpoint for endpoint ID
    #[error("Missing gRPC endpoint for endpoint ID: {0}")]
    EndpointNotFound(String),

    /// Error due to missing gRPC endpoint for quantum processor
    #[error("Missing gRPC endpoint for quantum processor: {0}")]
    QpuEndpointNotFound(String),

    /// Error due to failure to get endpoint for quantum processor
    #[error("Failed to get endpoint for quantum processor: {0}")]
    QpuEndpointRequestFailed(#[from] OpenApiError<GetDefaultEndpointError>),

    /// Error due to failure to get accessors for quantum processor
    #[error("Failed to get accessors for quantum processor: {0}")]
    AccessorRequestFailed(#[from] OpenApiError<GetQuantumProcessorAccessorsError>),

    /// Error due to failure to find gateway for quantum processor
    #[error("No gateway found for quantum processor: {0}")]
    GatewayNotFound(String),

    /// Error due to failure to get endpoint for quantum processor
    #[error("Failed to get endpoint for the given ID: {0}")]
    EndpointRequestFailed(#[from] OpenApiError<GetEndpointError>),

    /// Errors that may occur while trying to use a `gRPC` client
    #[error(transparent)]
    GrpcClientError(#[from] GrpcClientError),

    /// Error due to missing quantum processor ID and endpoint ID.
    #[error("A quantum processor ID must be provided if not connecting directly to an endpoint ID with ConnectionStrategy::EndpointId or ConnectionStrategy::EndpointAddress")]
    MissingQpuId,

    /// Error due to user not providing patch values
    #[error("Submitting a job requires at least one set of patch values")]
    EmptyPatchValues,

    /// Error that can occur when controller service fails to execute a job
    #[error("The submitted job failed with status: {status}. {message}")]
    JobExecutionFailed {
        /// The status of the failed job.
        status: String,
        /// The message associated with the failed job.
        message: String,
    },
    /// Error that can occur when the gRPC status code cannot be decoded.
    #[error("The status code could not be decoded: {0}")]
    StatusCodeDecode(String),
    // just for the error type?
    /// Error that can occur if a numeric status identifier cannot be converted
    /// into a known status type.
    #[error("The request returned an invalid status: {status}. {message}")]
    InvalidJobStatus {
        /// The numeric status identifier.
        status: i32,
        /// The message describing the failure to convert the numeric status
        /// identifier into a known status type.
        message: String,
    },
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_default_execution_options() {
        assert_eq!(
            ExecutionOptions::default(),
            ExecutionOptionsBuilder::default().build().unwrap(),
        );
    }

    #[test]
    fn test_select_min_accessor_prefers_some_to_none() {
        let expected = QuantumProcessorAccessor {
            live: true,
            access_type: QuantumProcessorAccessorType::GatewayV1,
            rank: None,
            url: "url".to_string(),
        };

        let accessors = vec![expected.clone()];
        let actual = select_min_accessor(accessors);
        assert_eq!(expected, actual.expect("expected Some accessor"));
    }
}