Skip to main content

one/
client.rs

1use crate::{
2    retry::{RetrySchedule, Retryable},
3    transport::types::PaginatedVaultConnectionView,
4    webhooks::Webhooks
5};
6use bytes::Bytes;
7use handlebars::Handlebars;
8use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
9use reqwest::{
10    Client as HttpClient, Error as ReqwestError, RequestBuilder,
11    header::{AUTHORIZATION, CONTENT_TYPE, HeaderMap, RETRY_AFTER}
12};
13pub use reqwest::{Method, StatusCode};
14use secrecy::{ExposeSecret, SecretBox, SecretString};
15use serde::{Serialize, de::DeserializeOwned};
16use serde_json::{Error as JsonError, Map, Value, from_slice, to_value, to_vec};
17use std::{
18    collections::BTreeMap,
19    env::var,
20    error::Error as StdError,
21    fmt,
22    marker::PhantomData,
23    slice::from_ref,
24    sync::{Arc, Once},
25    time::Duration
26};
27
28use rustls::{ClientConfig, RootCertStore, crypto::ring::default_provider};
29use tokio::time::sleep;
30use webpki_roots::TLS_SERVER_ROOTS;
31
32/// A connection record from the vault, typed straight from the One API schema.
33pub use crate::transport::types::PaginatedVaultConnectionViewRowsItem as Connection;
34
35const SECRET_HEADER: &str = "X-One-Secret";
36const BEARER_PREFIX: &str = "Bearer ";
37const CONNECTION_KEY_HEADER: &str = "X-One-Connection-Key";
38const ACTION_ID_HEADER: &str = "X-One-Action-Id";
39const ORGANIZATION_ID_HEADER: &str = "X-One-Organization-Id";
40const PROJECT_ID_HEADER: &str = "X-One-Project-Id";
41const DEFAULT_BASE_URL: &str = "https://api.picaos.com";
42const SECRET_ENV: &str = "ONE_SECRET";
43const ACCESS_TOKEN_ENV: &str = "ONE_ACCESS_TOKEN";
44const BASE_URL_ENV: &str = "ONE_BASE_URL";
45const VAULT_CONNECTIONS_PATH: &str = "/v1/vault/connections";
46const CONNECTION_KEY_PARAM: &str = "key";
47const PAGE_PARAM: &str = "page";
48const LIMIT_PARAM: &str = "limit";
49const APPLICATION_JSON: &str = "application/json";
50const NON_OBJECT_INPUT: &str = "the input must be a JSON object";
51
52/// Characters to percent-encode in a path-parameter value: everything except
53/// the RFC 3986 unreserved set (`ALPHA / DIGIT / - . _ ~`). This keeps a value
54/// like `a/b` as a single path segment (`a%2Fb`) instead of letting `/`, `?`,
55/// `#`, or spaces re-shape the URL.
56pub(crate) const PATH_SEGMENT: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'.').remove(b'_').remove(b'~');
57
58/// The value of an environment variable that was actually configured, treating
59/// "set but blank" as unset.
60///
61/// A leftover `ONE_SECRET=` in a shell profile, a compose file, or a CI matrix
62/// is how an environment says *not this one* - but `env::var` reports it as a
63/// present value, so it would win the credential precedence over the
64/// `ONE_ACCESS_TOKEN` sitting beside it and then fail the build as a missing
65/// secret. Nothing here has a meaningful blank value, so every read goes
66/// through this.
67fn configured(key: &str) -> Option<String> {
68    var(key).ok().filter(|value| !value.trim().is_empty())
69}
70
71/// Errors returned by SDK calls.
72///
73/// `#[non_exhaustive]`: new variants may be added in future releases, so
74/// downstream `match` statements must include a `_ =>` arm.
75#[derive(Debug, thiserror::Error)]
76#[non_exhaustive]
77pub enum Error {
78    /// The request could not be sent (DNS, TLS, connect).
79    #[error("transport error: {0}")]
80    Transport(ReqwestError),
81    /// The request exceeded its configured timeout.
82    #[error("request timed out")]
83    Timeout,
84    /// The response body could not be read.
85    #[error("failed to read response body: {0}")]
86    Body(ReqwestError),
87    /// The platform returned a non-2xx status; the raw body is preserved.
88    #[error("upstream returned status {status}")]
89    Status { status: StatusCode, body: Bytes },
90    /// A response body could not be deserialized into the requested type.
91    #[error("failed to decode response: {0}")]
92    Decode(JsonError),
93    /// No connection matched the requested key.
94    #[error("no connection found for the given key")]
95    NotFound,
96    /// The client was built without a credential.
97    #[error(
98        "a credential is required: a secret key (.secret() or ONE_SECRET) or an OAuth access token (.access_token() \
99         or ONE_ACCESS_TOKEN)"
100    )]
101    MissingSecret,
102    /// A path template referenced a variable not supplied in the path object.
103    #[error("path template error: {0}")]
104    PathTemplate(String),
105    /// A generated action's input is missing a required field or holds an
106    /// invalid value; the source is the builder's or the router's own error.
107    #[error("invalid action input: {0}")]
108    InvalidInput(#[source] Box<dyn StdError + Send + Sync>)
109}
110
111/// A part of an action request that a flat input field is routed into.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
113pub enum Part {
114    Path,
115    Query,
116    Headers,
117    Body
118}
119
120/// Where one field of a generated action's flat input goes in the request.
121#[derive(Debug, Clone, Copy)]
122pub struct Route {
123    /// The field's name in the serialized input.
124    pub field: &'static str,
125    /// The request part it belongs to.
126    pub part:  Part,
127    /// Its key within that part, or `None` when the field is the whole part.
128    pub key:   Option<&'static str>
129}
130
131/// How a generated action's flat input maps onto its request.
132#[derive(Debug, Clone, Copy)]
133pub struct Routing {
134    /// Where each field goes.
135    pub routes:         &'static [Route],
136    /// Object parts the action requires, sent as `{}` when no field sets them.
137    pub required_parts: &'static [Part]
138}
139
140/// Anything [`ConnectionScope::run`] executes: an [`Operation`], or a
141/// generated action's input or builder.
142pub trait IntoOperation {
143    /// The type the response decodes to.
144    type Output;
145
146    /// Builds the operation, failing when the input does not validate.
147    fn into_operation(self) -> Result<Operation<Self::Output>, Error>;
148}
149
150impl<Out> IntoOperation for Operation<Out> {
151    type Output = Out;
152
153    fn into_operation(self) -> Result<Self, Error> {
154        Ok(self)
155    }
156}
157
158impl Retryable for Error {
159    fn is_transient(&self) -> bool {
160        match self {
161            Self::Transport(e) => e.is_timeout() || e.is_connect() || e.is_request(),
162            Self::Timeout => true,
163            Self::Status { status, .. } => status.is_server_error() || *status == StatusCode::TOO_MANY_REQUESTS,
164            Self::Body(_)
165            | Self::Decode(_)
166            | Self::NotFound
167            | Self::MissingSecret
168            | Self::PathTemplate(_)
169            | Self::InvalidInput(_) => false
170        }
171    }
172}
173
174/// A successful (2xx) response, tagged with the action's default output type
175/// `Out` (the io_schema output, or [`Value`] for raw calls). Holds the raw
176/// body; [`CallResponse::output`] decodes the default, [`CallResponse::json`]
177/// any caller type.
178pub struct CallResponse<Out = Value> {
179    status:  StatusCode,
180    headers: BTreeMap<String, String>,
181    body:    Bytes,
182    _out:    PhantomData<fn() -> Out>
183}
184
185impl<Out> Clone for CallResponse<Out> {
186    fn clone(&self) -> Self {
187        Self {
188            status:  self.status,
189            headers: self.headers.clone(),
190            body:    self.body.clone(),
191            _out:    PhantomData
192        }
193    }
194}
195
196impl<Out> CallResponse<Out> {
197    /// The HTTP status of the response.
198    pub fn status(&self) -> StatusCode {
199        self.status
200    }
201
202    /// The response headers (rate-limit, request-id, `ETag`, `Link`, …), header
203    /// names mapped to their value.
204    pub fn headers(&self) -> &BTreeMap<String, String> {
205        &self.headers
206    }
207
208    /// The raw response body.
209    pub fn bytes(&self) -> &Bytes {
210        &self.body
211    }
212
213    /// The response body as a UTF-8 string (lossy).
214    pub fn text(&self) -> String {
215        String::from_utf8_lossy(&self.body).into_owned()
216    }
217
218    /// Decodes the body into a caller-supplied type — the override for when the
219    /// synced output is wrong.
220    pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> {
221        from_slice(&self.body).map_err(Error::Decode)
222    }
223
224    /// Re-tags the response with a different output type. The engine attaches
225    /// the operation's `Out` here.
226    fn retype<U>(self) -> CallResponse<U> {
227        CallResponse {
228            status:  self.status,
229            headers: self.headers,
230            body:    self.body,
231            _out:    PhantomData
232        }
233    }
234}
235
236impl<Out: DeserializeOwned> CallResponse<Out> {
237    /// Decodes the body into the action's default output type.
238    pub fn output(&self) -> Result<Out, Error> {
239        from_slice(&self.body).map_err(Error::Decode)
240    }
241}
242
243type SuccessHook = Arc<dyn Fn(&CallResponse) + Send + Sync>;
244type ErrorHook = Arc<dyn Fn(&Error) + Send + Sync>;
245
246/// What the client authenticates with.
247///
248/// Two credentials reach the same API by different headers, and a request
249/// carries exactly one. Modelling it as a choice rather than two optional
250/// fields means "both set" and "neither set" are states that cannot be built.
251///
252/// Both arms hold the value in [`SecretBox`], so a credential is redacted in
253/// `Debug` and zeroized on drop. It is exposed only in [`Self::apply`], at the
254/// moment the header is written.
255#[derive(Clone)]
256pub enum Credential {
257    /// A One secret key, sent as `X-One-Secret`. The long-lived agency
258    /// credential.
259    Secret(Arc<SecretBox<String>>),
260    /// An OAuth access token, sent as `Authorization: Bearer`. What an app
261    /// holding an end user's grant uses; the reachable surface is whatever that
262    /// grant consented to, not the whole account.
263    AccessToken(Arc<SecretBox<String>>)
264}
265
266impl fmt::Debug for Credential {
267    /// Names which credential is in play and never its value, so a client
268    /// dumped into a log or a panic cannot leak the token.
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        match self {
271            Self::Secret(_) => f.write_str("Credential::Secret(<redacted>)"),
272            Self::AccessToken(_) => f.write_str("Credential::AccessToken(<redacted>)")
273        }
274    }
275}
276
277impl Credential {
278    /// A One secret key.
279    pub fn secret(secret: impl Into<String>) -> Self {
280        Self::Secret(Arc::new(SecretBox::new(Box::new(secret.into()))))
281    }
282
283    /// An OAuth access token.
284    pub fn access_token(token: impl Into<String>) -> Self {
285        Self::AccessToken(Arc::new(SecretBox::new(Box::new(token.into()))))
286    }
287
288    /// Adds this credential to a request. The one place either header is
289    /// written, and the only place the value is exposed.
290    fn apply(&self, request: RequestBuilder) -> RequestBuilder {
291        match self {
292            Self::Secret(secret) => request.header(SECRET_HEADER, secret.expose_secret()),
293            Self::AccessToken(token) => {
294                request.header(AUTHORIZATION, format!("{BEARER_PREFIX}{}", token.expose_secret()))
295            }
296        }
297    }
298
299    /// Whether this carries nothing usable.
300    ///
301    /// Blank counts, matching [`configured`]: a credential of spaces is a
302    /// misconfiguration however it arrives, and the builder exists to catch it
303    /// here rather than at the first 401. The two doors must agree - the same
304    /// `"  "` cannot be unset when it comes from the environment and a valid
305    /// secret when it comes from the builder.
306    fn is_empty(&self) -> bool {
307        match self {
308            Self::Secret(value) | Self::AccessToken(value) => value.expose_secret().trim().is_empty()
309        }
310    }
311}
312
313/// The tenant a request acts within: an organization, optionally narrowed to
314/// one of its projects. Empty means the caller's own personal scope.
315///
316/// **A secret key does not need this and an access token does.** A key is
317/// bound to its tenant server-side, so the API reads tenancy off the key and
318/// ignores what the request claims. A bearer is not: one token can hold grants
319/// on several organizations, so the tenant is decided per request from these
320/// headers - and a request that sends neither resolves to the personal tier no
321/// matter what the token was granted. That is why an org-owned connection is
322/// simply absent from a bearer's results until this is set.
323#[derive(Clone, Debug, Default)]
324pub struct Tenancy {
325    organization: Option<String>,
326    project:      Option<String>
327}
328
329impl Tenancy {
330    /// Adds the tenant headers to a request. The one place either is written.
331    fn apply(&self, request: RequestBuilder) -> RequestBuilder {
332        let request = match &self.organization {
333            Some(id) => request.header(ORGANIZATION_ID_HEADER, id),
334            None => request
335        };
336        match &self.project {
337            Some(id) => request.header(PROJECT_ID_HEADER, id),
338            None => request
339        }
340    }
341}
342
343/// The One SDK client.
344///
345/// Holds the credential, base URL, default retry schedule, and global
346/// success/error hooks. Cheap to clone; wraps a shared `reqwest` client.
347#[derive(Clone)]
348pub struct One {
349    http:       HttpClient,
350    base_url:   String,
351    credential: Credential,
352    tenancy:    Tenancy,
353    retry:      RetrySchedule,
354    timeout:    Option<Duration>,
355    on_success: Option<SuccessHook>,
356    on_error:   Option<ErrorHook>
357}
358
359impl One {
360    /// Starts a request carrying this client's credential and tenant scope.
361    ///
362    /// The one door every call goes through, so a new endpoint cannot ship
363    /// having attached one and forgotten the other - which for tenancy fails
364    /// silently, as a request with no tenant headers is a valid personal-scope
365    /// request that simply cannot see the tenant's rows.
366    fn request(&self, method: Method, url: &str) -> RequestBuilder {
367        self.tenancy
368            .apply(self.credential.apply(self.http.request(method, url)))
369    }
370
371    /// Creates a client from a One secret key, targeting the default base URL.
372    /// Panics if `secret` is empty; use [`OneBuilder::build`] for a fallible
373    /// path.
374    pub fn new(secret: impl Into<String>) -> Self {
375        Self::builder()
376            .secret(secret)
377            .build()
378            .expect("One::new requires a non-empty secret")
379    }
380
381    /// Creates a client from the environment: a credential (required) and
382    /// `ONE_BASE_URL` (optional, defaults to the production base URL).
383    ///
384    /// The credential is `ONE_SECRET`, or `ONE_ACCESS_TOKEN` for an OAuth
385    /// grant. `ONE_SECRET` wins if both are set, because it is the
386    /// longer-standing variable and silently preferring the newer one would
387    /// change what an existing environment authenticates as. Set-but-blank does
388    /// not count as set - see [`configured`].
389    pub fn from_env() -> Result<Self, Error> {
390        let credential = configured(SECRET_ENV)
391            .map(Credential::secret)
392            .or_else(|| configured(ACCESS_TOKEN_ENV).map(Credential::access_token))
393            .ok_or(Error::MissingSecret)?;
394
395        let mut builder = Self::builder().credential(credential);
396        if let Some(base_url) = configured(BASE_URL_ENV) {
397            builder = builder.base_url(base_url);
398        }
399        builder.build()
400    }
401
402    /// Starts building a client with full configuration.
403    pub fn builder() -> OneBuilder {
404        OneBuilder::default()
405    }
406
407    /// Scopes subsequent calls to a connection by its key.
408    pub fn connection(&self, key: impl Into<String>) -> ConnectionScope<'_> {
409        ConnectionScope {
410            one: self,
411            key: key.into()
412        }
413    }
414
415    /// Starts building a webhook listener, verified with `signing_secret`.
416    ///
417    /// The listener owns a clone of this client: it is mounted into an HTTP
418    /// server and outlives any single request, so it cannot borrow.
419    pub fn webhooks(&self, signing_secret: SecretString) -> Webhooks {
420        Webhooks::new(self.clone(), signing_secret)
421    }
422
423    /// Sends an authenticated `PUT` with a JSON body to a One API path and
424    /// preserves the response metadata for the webhook bindings.
425    pub(crate) async fn put_json_response<B: Serialize, Out>(
426        &self,
427        path: &str,
428        body: &B
429    ) -> Result<CallResponse<Out>, Error> {
430        let url = format!("{}{path}", self.base_url);
431        let payload = to_vec(body).map_err(Error::Decode)?;
432
433        let response = self
434            .execute(self.retry, None, &[], || {
435                let mut request = self
436                    .request(Method::PUT, &url)
437                    .header(CONTENT_TYPE, APPLICATION_JSON)
438                    .body(payload.clone());
439                if let Some(timeout) = self.timeout {
440                    request = request.timeout(timeout);
441                }
442                request
443            })
444            .await?;
445
446        Ok(response.retype())
447    }
448
449    /// The one place a request is sent, retried, and reported.
450    ///
451    /// Applies `retry` honoring `Retry-After`, treats the transient set plus
452    /// `retry_on` as retryable, and fires the client hooks followed by the
453    /// per-call ones. Both the action engine and the management calls route
454    /// through this, so a transport or retry fix lands once.
455    pub(crate) async fn execute<F>(
456        &self,
457        retry: RetrySchedule,
458        on_call: Option<(&Option<SuccessHook>, &Option<ErrorHook>)>,
459        retry_on: &[StatusCode],
460        build: F
461    ) -> Result<CallResponse<Value>, Error>
462    where
463        F: Fn() -> reqwest::RequestBuilder
464    {
465        let send = || {
466            let request = build();
467            async move {
468                let response = match request.send().await {
469                    Ok(response) => response,
470                    Err(error) => {
471                        let mapped = if error.is_timeout() {
472                            Error::Timeout
473                        } else {
474                            Error::Transport(error)
475                        };
476                        return Err((mapped, None));
477                    }
478                };
479                let status = response.status();
480                let headers: BTreeMap<String, String> = response
481                    .headers()
482                    .iter()
483                    .filter_map(|(name, value)| {
484                        value
485                            .to_str()
486                            .ok()
487                            .map(|value| (name.as_str().to_string(), value.to_string()))
488                    })
489                    .collect();
490                let retry_after = Self::retry_after(response.headers());
491                let body = match response.bytes().await {
492                    Ok(body) => body,
493                    Err(error) => return Err((Error::Body(error), None))
494                };
495                if status.is_success() {
496                    Ok(CallResponse {
497                        status,
498                        headers,
499                        body,
500                        _out: PhantomData
501                    })
502                } else {
503                    Err((Error::Status { status, body }, retry_after))
504                }
505            }
506        };
507
508        let attempts = retry.max_attempts.max(1);
509        let result: Result<CallResponse<Value>, Error> = 'attempts: {
510            for attempt in 1..=attempts {
511                match send().await {
512                    Ok(response) => break 'attempts Ok(response),
513                    Err((error, retry_after)) => {
514                        if attempt == attempts || !Self::is_retryable(&error, retry_on) {
515                            break 'attempts Err(error);
516                        }
517                        sleep(retry_after.unwrap_or_else(|| retry.delay(attempt))).await;
518                    }
519                }
520            }
521            unreachable!("loop runs at least once and breaks on every path")
522        };
523
524        match &result {
525            Ok(response) => {
526                if let Some(hook) = &self.on_success {
527                    hook(response);
528                }
529                if let Some(hook) = on_call.and_then(|(success, _)| success.as_ref()) {
530                    hook(response);
531                }
532            }
533            Err(error) => self.notify_error(on_call.and_then(|(_, failure)| failure.as_ref()), error)
534        }
535
536        result
537    }
538
539    /// Fires the client's error hook, then the call's own when it has one.
540    fn notify_error(&self, per_call: Option<&ErrorHook>, error: &Error) {
541        for hook in [self.on_error.as_ref(), per_call].into_iter().flatten() {
542            hook(error);
543        }
544    }
545
546    /// Whether a failed attempt should be retried: the general transient set
547    /// plus any per-call `retry_on` statuses.
548    fn is_retryable(error: &Error, retry_on: &[StatusCode]) -> bool {
549        error.is_transient() || matches!(error, Error::Status { status, .. } if retry_on.contains(status))
550    }
551
552    /// Parses a `Retry-After` header expressed as a whole number of seconds.
553    fn retry_after(headers: &HeaderMap) -> Option<Duration> {
554        headers
555            .get(RETRY_AFTER)?
556            .to_str()
557            .ok()?
558            .trim()
559            .parse::<u64>()
560            .ok()
561            .map(Duration::from_secs)
562    }
563}
564
565/// Builder for [`One`].
566#[derive(Default)]
567pub struct OneBuilder {
568    base_url:   Option<String>,
569    credential: Option<Credential>,
570    tenancy:    Tenancy,
571    retry:      Option<RetrySchedule>,
572    timeout:    Option<Duration>,
573    on_success: Option<SuccessHook>,
574    on_error:   Option<ErrorHook>
575}
576
577impl OneBuilder {
578    /// Sets the secret key (`X-One-Secret`).
579    pub fn secret(mut self, secret: impl Into<String>) -> Self {
580        self.credential = Some(Credential::secret(secret));
581        self
582    }
583
584    /// Sets the credential directly, for callers that already have one in
585    /// hand. [`Self::secret`] and [`Self::access_token`] are the usual doors.
586    pub fn credential(mut self, credential: Credential) -> Self {
587        self.credential = Some(credential);
588        self
589    }
590
591    /// Acts within an organization the caller has access to.
592    ///
593    /// **Required to reach an organization's connections with an access
594    /// token.** A token can hold grants on several organizations, so the API
595    /// decides which one a request means from this - and a request that omits
596    /// it means the user's personal scope, where an organization-owned
597    /// connection simply is not present. A secret key already carries its
598    /// tenant, so setting this alongside one changes nothing.
599    pub fn organization(mut self, organization_id: impl Into<String>) -> Self {
600        self.tenancy.organization = Some(organization_id.into());
601        self
602    }
603
604    /// Narrows [`Self::organization`] to one of its projects.
605    ///
606    /// A project is always qualified by its organization, so this is only
607    /// meaningful beside one; on its own the request still resolves to the
608    /// personal scope.
609    pub fn project(mut self, project_id: impl Into<String>) -> Self {
610        self.tenancy.project = Some(project_id.into());
611        self
612    }
613
614    /// Authenticates with an OAuth access token instead of a secret key.
615    ///
616    /// The reachable surface is whatever the end user consented to for this
617    /// app, not the whole account. Calling this after [`Self::secret`] (or the
618    /// reverse) replaces the credential rather than adding one: a request
619    /// carries exactly one.
620    pub fn access_token(mut self, token: impl Into<String>) -> Self {
621        self.credential = Some(Credential::access_token(token));
622        self
623    }
624
625    /// Overrides the base URL (e.g. a self-hosted or local instance).
626    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
627        self.base_url = Some(base_url.into());
628        self
629    }
630
631    /// Sets the default retry schedule, applied to operations that don't
632    /// declare their own.
633    pub fn retry(mut self, schedule: RetrySchedule) -> Self {
634        self.retry = Some(schedule);
635        self
636    }
637
638    /// Sets the default per-request timeout, applied to operations that don't
639    /// declare their own.
640    pub fn timeout(mut self, timeout: Duration) -> Self {
641        self.timeout = Some(timeout);
642        self
643    }
644
645    /// Registers a global hook invoked after every successful call.
646    pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
647        self.on_success = Some(Arc::new(hook));
648        self
649    }
650
651    /// Registers a global hook invoked after every failed call.
652    pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
653        self.on_error = Some(Arc::new(hook));
654        self
655    }
656
657    /// Builds the client, applying defaults for any unset field.
658    ///
659    /// Fails fast with [`Error::MissingSecret`] when no credential was
660    /// configured, rather than deferring the misconfiguration to a runtime auth
661    /// failure. **Either credential satisfies it** - a secret key from
662    /// [`Self::secret`] or an OAuth access token from [`Self::access_token`] -
663    /// and a configured-but-empty one counts as absent, since an empty header
664    /// would fail at the API rather than here.
665    pub fn build(self) -> Result<One, Error> {
666        let credential = self
667            .credential
668            .filter(|credential| !credential.is_empty())
669            .ok_or(Error::MissingSecret)?;
670        Self::ensure_crypto_provider();
671        let http = HttpClient::builder()
672            .use_preconfigured_tls(Self::tls_config())
673            .build()
674            .map_err(Error::Transport)?;
675        Ok(One {
676            http,
677            base_url: self
678                .base_url
679                .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
680                .trim_end_matches('/')
681                .to_string(),
682            credential,
683            tenancy: self.tenancy,
684            retry: self.retry.unwrap_or_default(),
685            timeout: self.timeout,
686            on_success: self.on_success,
687            on_error: self.on_error
688        })
689    }
690
691    /// Installs the process-default rustls crypto provider (`ring`) once. The
692    /// reqwest client uses rustls without a built-in provider, so one must be
693    /// registered before the first TLS handshake; `ring` is chosen over
694    /// `aws-lc-rs` because it cross-compiles cleanly to every published target.
695    fn ensure_crypto_provider() {
696        static ONCE: Once = Once::new();
697        ONCE.call_once(|| {
698            let _ = default_provider().install_default();
699        });
700    }
701
702    /// A rustls config that trusts the bundled Mozilla root certificates, so
703    /// the client establishes TLS without a system certificate store —
704    /// required in minimal container images that ship no CA bundle.
705    fn tls_config() -> ClientConfig {
706        let roots = RootCertStore {
707            roots: TLS_SERVER_ROOTS.to_vec()
708        };
709        ClientConfig::builder()
710            .with_root_certificates(roots)
711            .with_no_client_auth()
712    }
713}
714
715/// A declarative description of an action invocation.
716///
717/// You describe *what* you want — which action (`system_id`), the request
718/// shape, and the retry policy — and the engine ([`ConnectionScope::run`])
719/// resolves *how* to execute it. The action's verb and path are part of the
720/// description; once discovery lands they are filled from the action itself
721/// rather than supplied by hand.
722pub struct Operation<Out = Value> {
723    system_id:  String,
724    method:     Method,
725    path:       String,
726    query:      Value,
727    headers:    BTreeMap<String, String>,
728    body:       Bytes,
729    retry:      Option<RetrySchedule>,
730    retry_on:   Vec<StatusCode>,
731    timeout:    Option<Duration>,
732    on_success: Option<SuccessHook>,
733    on_error:   Option<ErrorHook>,
734    _out:       PhantomData<fn() -> Out>
735}
736
737impl<Out> Clone for Operation<Out> {
738    fn clone(&self) -> Self {
739        Self {
740            system_id:  self.system_id.clone(),
741            method:     self.method.clone(),
742            path:       self.path.clone(),
743            query:      self.query.clone(),
744            headers:    self.headers.clone(),
745            body:       self.body.clone(),
746            retry:      self.retry,
747            retry_on:   self.retry_on.clone(),
748            timeout:    self.timeout,
749            on_success: self.on_success.clone(),
750            on_error:   self.on_error.clone(),
751            _out:       PhantomData
752        }
753    }
754}
755
756impl Operation<Value> {
757    /// Starts a typed action operation from its `system_id`, HTTP method, and
758    /// path template. Envelope parts are attached with the `with_*` setters,
759    /// which take the typed parts directly — the envelope contract is the typed
760    /// fields passed by name, not keys fished out of a serialized blob. Output
761    /// defaults to [`Value`]; generated actions re-tag it via
762    /// [`Operation::returns`].
763    pub fn action(system_id: impl Into<String>, method: Method, path_template: impl Into<String>) -> Self {
764        Self {
765            system_id: system_id.into(),
766            method,
767            path: path_template.into(),
768            query: Value::Null,
769            headers: BTreeMap::new(),
770            body: Bytes::new(),
771            retry: None,
772            retry_on: Vec::new(),
773            timeout: None,
774            on_success: None,
775            on_error: None,
776            _out: PhantomData
777        }
778    }
779}
780
781impl<Out> Operation<Out> {
782    /// Declares the retry policy for this operation, overriding the client
783    /// default. Part of the description — the engine resolves it.
784    pub fn retry(mut self, schedule: RetrySchedule) -> Self {
785        self.retry = Some(schedule);
786        self
787    }
788
789    /// Adds HTTP status codes that should be retried for this call, on top of
790    /// the always-retried transient set (network errors, 5xx, 429). HTTP-only —
791    /// status classification has no meaning outside an API call.
792    pub fn retry_on(mut self, statuses: impl IntoIterator<Item = StatusCode>) -> Self {
793        self.retry_on = statuses.into_iter().collect();
794        self
795    }
796
797    /// Sets a per-request timeout for this call, overriding the client default.
798    pub fn timeout(mut self, timeout: Duration) -> Self {
799        self.timeout = Some(timeout);
800        self
801    }
802
803    /// Registers a per-call success hook, run in addition to the client's
804    /// global `on_success`.
805    pub fn on_success<F: Fn(&CallResponse) + Send + Sync + 'static>(mut self, hook: F) -> Self {
806        self.on_success = Some(Arc::new(hook));
807        self
808    }
809
810    /// Registers a per-call error hook, run in addition to the client's global
811    /// `on_error`.
812    pub fn on_error<F: Fn(&Error) + Send + Sync + 'static>(mut self, hook: F) -> Self {
813        self.on_error = Some(Arc::new(hook));
814        self
815    }
816
817    /// Re-tags the operation's output type. Generated actions attach the
818    /// io_schema's `Output`; callers can override a wrong synced output.
819    pub fn returns<Out2>(self) -> Operation<Out2> {
820        Operation {
821            system_id:  self.system_id,
822            method:     self.method,
823            path:       self.path,
824            query:      self.query,
825            headers:    self.headers,
826            body:       self.body,
827            retry:      self.retry,
828            retry_on:   self.retry_on,
829            timeout:    self.timeout,
830            on_success: self.on_success,
831            on_error:   self.on_error,
832            _out:       PhantomData
833        }
834    }
835
836    /// Fills the path template's `{{name}}` placeholders from the typed path
837    /// part.
838    pub fn with_path<P: Serialize>(mut self, path: &P) -> Result<Self, Error> {
839        let value = to_value(path).map_err(Error::Decode)?;
840        self.path = Self::resolve_path(&self.path, Some(&value))?;
841        Ok(self)
842    }
843
844    /// Attaches the typed query part; serde lowers it to query parameters.
845    pub fn with_query<Q: Serialize>(mut self, query: &Q) -> Result<Self, Error> {
846        self.query = to_value(query).map_err(Error::Decode)?;
847        Ok(self)
848    }
849
850    /// Attaches the typed headers part as request headers.
851    pub fn with_headers<H: Serialize>(mut self, headers: &H) -> Result<Self, Error> {
852        let value = to_value(headers).map_err(Error::Decode)?;
853        self.headers = header_map(&value);
854        Ok(self)
855    }
856
857    /// Serializes the typed body part as the request payload. An omitted
858    /// optional body (`Option<Body>` left unset) serializes to the literal
859    /// `null`; treat that as "no body" and leave the payload empty so the
860    /// engine omits it rather than sending `null` bytes upstream.
861    pub fn with_body<B: Serialize>(mut self, body: &B) -> Result<Self, Error> {
862        let bytes = to_vec(body).map_err(Error::Decode)?;
863        if bytes != b"null" {
864            self.body = Bytes::from(bytes);
865        }
866        Ok(self)
867    }
868
869    /// Distributes a generated action's flat input into its request parts:
870    /// an unkeyed route supplies the whole part, a keyed route then sets one
871    /// entry of its part, and a field the input leaves out is skipped. A
872    /// required part with nothing set is sent as `{}`, and the path template is
873    /// always rendered, so a missing path value fails here instead of going
874    /// upstream.
875    pub fn with_routed<I: Serialize>(self, input: &I, routing: &Routing) -> Result<Self, Error> {
876        let Value::Object(mut fields) = to_value(input).map_err(Error::Decode)? else {
877            return Err(Error::InvalidInput(NON_OBJECT_INPUT.into()));
878        };
879        let mut parts: BTreeMap<Part, Value> = routing
880            .required_parts
881            .iter()
882            .chain([&Part::Path])
883            .map(|part| (*part, Value::Object(Map::new())))
884            .collect();
885        let (whole, keyed): (Vec<&Route>, Vec<&Route>) = routing.routes.iter().partition(|route| route.key.is_none());
886        for route in whole {
887            if let Some(value) = fields.remove(route.field) {
888                parts.insert(route.part, value);
889            }
890        }
891        for route in keyed {
892            let (Some(key), Some(value)) = (route.key, fields.remove(route.field)) else {
893                continue;
894            };
895            match parts.entry(route.part).or_insert_with(|| Value::Object(Map::new())) {
896                Value::Object(entries) => {
897                    entries.insert(key.to_string(), value);
898                }
899                _ => {
900                    let message = format!("`{}` needs `{key}` set on an object", route.field);
901                    return Err(Error::InvalidInput(message.into()));
902                }
903            }
904        }
905        parts.into_iter().try_fold(self, |operation, (part, value)| match part {
906            Part::Path => operation.with_path(&value),
907            Part::Query => operation.with_query(&value),
908            Part::Headers => operation.with_headers(&value),
909            Part::Body => operation.with_body(&value)
910        })
911    }
912
913    /// Sets the request body to raw bytes, for non-JSON payloads. The typed
914    /// `with_body` is preferred for action calls.
915    pub fn raw_body(mut self, body: impl Into<Bytes>) -> Self {
916        self.body = body.into();
917        self
918    }
919
920    /// Merges extra fields into the request body, on top of the typed body —
921    /// the escape hatch for attributes a stale or incomplete io_schema omits.
922    pub fn merge_body(mut self, extra: Value) -> Result<Self, Error> {
923        let mut body: Value = if self.body.is_empty() {
924            Value::Object(Default::default())
925        } else {
926            from_slice(&self.body).map_err(Error::Decode)?
927        };
928        Self::merge(&mut body, extra);
929        self.body = Bytes::from(to_vec(&body).map_err(Error::Decode)?);
930        Ok(self)
931    }
932
933    /// Merges extra parameters on top of the typed query.
934    pub fn merge_query(mut self, extra: Value) -> Self {
935        Self::merge(&mut self.query, extra);
936        self
937    }
938
939    /// Merges extra headers on top of the typed headers, matching names as
940    /// HTTP does, without case; a `null` one unsets that header, as
941    /// `merge_query` does for a query parameter.
942    pub fn merge_headers(mut self, extra: Value) -> Self {
943        if let Value::Object(entries) = extra {
944            for (key, value) in entries {
945                self.headers.retain(|name, _| !name.eq_ignore_ascii_case(&key));
946                if let Some(rendered) = header_value(&value) {
947                    self.headers.insert(key, rendered);
948                }
949            }
950        }
951        self
952    }
953
954    /// Removes a header — e.g. to drop one injected from a busted `const`.
955    pub fn remove_header(mut self, name: &str) -> Self {
956        self.headers.retain(|key, _| !key.eq_ignore_ascii_case(name));
957        self
958    }
959
960    /// Removes a query parameter.
961    pub fn remove_query(mut self, name: &str) -> Self {
962        if let Some(object) = self.query.as_object_mut() {
963            object.remove(name);
964        }
965        self
966    }
967
968    /// The action's system id (sent as `X-One-Action-Id`).
969    pub fn system_id(&self) -> &str {
970        &self.system_id
971    }
972
973    /// The resolved HTTP method.
974    pub fn method(&self) -> &Method {
975        &self.method
976    }
977
978    /// The resolved upstream path, with placeholders filled in.
979    pub fn path(&self) -> &str {
980        &self.path
981    }
982
983    /// The resolved query parameters.
984    pub fn query(&self) -> &Value {
985        &self.query
986    }
987
988    /// The resolved request headers, including injected `const` headers.
989    pub fn headers(&self) -> &BTreeMap<String, String> {
990        &self.headers
991    }
992
993    /// The serialized request body.
994    pub fn body(&self) -> &Bytes {
995        &self.body
996    }
997
998    /// Shallow-merges the entries of `extra` into `target` when both are
999    /// objects, or replaces `target` if it was null.
1000    fn merge(target: &mut Value, extra: Value) {
1001        if target.is_null() {
1002            *target = extra;
1003        } else if let (Some(base), Value::Object(entries)) = (target.as_object_mut(), extra) {
1004            for (key, value) in entries {
1005                base.insert(key, value);
1006            }
1007        }
1008    }
1009
1010    /// Fills a path template from a `path` object, rendering it with the same
1011    /// Handlebars engine the platform uses so every template form resolves the
1012    /// way the server expects: `{{name}}` percent-encodes its value into a
1013    /// single path segment, `{{{name}}}` emits it raw (unescaped), and dotted
1014    /// paths (`{{a.b}}`) resolve into the object. Strict mode: a variable the
1015    /// template references but the path object does not supply is an error —
1016    /// the client renders the final route, so a missing value cannot be filled
1017    /// later; fail fast rather than ship `//` or stray braces upstream.
1018    fn resolve_path(template: &str, path: Option<&Value>) -> Result<String, Error> {
1019        let mut renderer = Handlebars::new();
1020        renderer.set_strict_mode(true);
1021        renderer.register_escape_fn(|raw| utf8_percent_encode(raw, PATH_SEGMENT).to_string());
1022        let context = path.cloned().unwrap_or(Value::Null);
1023        renderer
1024            .render_template(template, &context)
1025            .map_err(|error| Error::PathTemplate(error.to_string()))
1026    }
1027}
1028
1029impl<Out> fmt::Debug for Operation<Out> {
1030    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1031        formatter
1032            .debug_struct("Operation")
1033            .field("system_id", &self.system_id)
1034            .field("method", &self.method.as_str())
1035            .field("path", &self.path)
1036            .field("query", &self.query)
1037            .field("headers", &self.headers)
1038            .field("body", &String::from_utf8_lossy(&self.body))
1039            .finish()
1040    }
1041}
1042
1043/// A connection-scoped handle. The engine ([`ConnectionScope::run`]) executes
1044/// declarative [`Operation`]s against this connection.
1045pub struct ConnectionScope<'a> {
1046    one: &'a One,
1047    key: String
1048}
1049
1050impl ConnectionScope<'_> {
1051    /// The engine: resolves and executes a declarative [`Operation`] against
1052    /// this connection. Signs the request with the secret + connection-key +
1053    /// action-id headers, applies the operation's retry/timeout policy (or the
1054    /// client defaults), retries transient HTTP failures (network, 5xx, 429,
1055    /// and any `retry_on` statuses) honoring `Retry-After`, and fires the
1056    /// client + per-call success/error hooks.
1057    pub async fn run<O: IntoOperation>(&self, operation: O) -> Result<CallResponse<O::Output>, Error> {
1058        let operation = operation
1059            .into_operation()
1060            .inspect_err(|error| self.one.notify_error(None, error))?;
1061        let query = query_pairs(&operation.query)
1062            .inspect_err(|error| self.one.notify_error(operation.on_error.as_ref(), error))?;
1063        let Operation {
1064            system_id,
1065            method,
1066            path,
1067            headers,
1068            body,
1069            retry,
1070            retry_on,
1071            timeout,
1072            on_success,
1073            on_error,
1074            ..
1075        } = operation;
1076        let retry = retry.unwrap_or(self.one.retry);
1077        let timeout = timeout.or(self.one.timeout);
1078        let url =
1079            format!("{}/v1/passthrough/{}", self.one.base_url, without_replaced(&path, &query).trim_start_matches('/'));
1080
1081        let response = self
1082            .one
1083            .execute(retry, Some((&on_success, &on_error)), &retry_on, || {
1084                let mut request = self
1085                    .one
1086                    .request(method.clone(), &url)
1087                    .header(CONNECTION_KEY_HEADER, &self.key)
1088                    .header(ACTION_ID_HEADER, &system_id);
1089                if let Some(timeout) = timeout {
1090                    request = request.timeout(timeout);
1091                }
1092                if !body.is_empty() {
1093                    request = request.body(body.clone());
1094                }
1095                if !query.is_empty() {
1096                    request = request.query(&query);
1097                }
1098                for (name, value) in &headers {
1099                    request = request.header(name.as_str(), value.as_str());
1100                }
1101                request
1102            })
1103            .await;
1104
1105        response.map(|response| response.retype())
1106    }
1107
1108    /// Fetches this connection's record from the vault by key, including its
1109    /// metadata. Returns [`Error::NotFound`] if no connection matches.
1110    ///
1111    /// **The lookup happens within the client's tenant scope, not across every
1112    /// tenant.** A secret key carries its tenant server-side, so this is
1113    /// scope-agnostic for one. A bearer is not: the vault resolves the tenant
1114    /// from the request's headers, so a client built without
1115    /// [`OneBuilder::organization`] looks in the user's personal connections
1116    /// and an organization-owned connection reads as absent.
1117    pub async fn get(&self) -> Result<Connection, Error> {
1118        let url = format!("{}{VAULT_CONNECTIONS_PATH}", self.one.base_url);
1119        let response = self
1120            .one
1121            .request(Method::GET, &url)
1122            .query(&[
1123                (CONNECTION_KEY_PARAM, self.key.as_str()),
1124                (PAGE_PARAM, "1"),
1125                (LIMIT_PARAM, "1")
1126            ])
1127            .send()
1128            .await
1129            .map_err(|error| {
1130                if error.is_timeout() {
1131                    Error::Timeout
1132                } else {
1133                    Error::Transport(error)
1134                }
1135            })?;
1136        let status = response.status();
1137        let body = response.bytes().await.map_err(Error::Body)?;
1138        if !status.is_success() {
1139            return Err(Error::Status { status, body });
1140        }
1141        let page: PaginatedVaultConnectionView = from_slice(&body).map_err(Error::Decode)?;
1142        page.rows.into_iter().next().ok_or(Error::NotFound)
1143    }
1144}
1145
1146/// Renders a JSON object into header values, leaving out a `null` one.
1147fn header_map(object: &Value) -> BTreeMap<String, String> {
1148    object
1149        .as_object()
1150        .into_iter()
1151        .flatten()
1152        .filter_map(|(key, value)| header_value(value).map(|rendered| (key.clone(), rendered)))
1153        .collect()
1154}
1155
1156/// A header's value, `None` for `null`. An array goes as its non-null items
1157/// joined by commas, OpenAPI's default `simple` style; any other value goes
1158/// as its text, an object as its JSON.
1159fn header_value(value: &Value) -> Option<String> {
1160    match value {
1161        Value::Null => None,
1162        Value::Array(items) => Some(
1163            items
1164                .iter()
1165                .filter(|item| !item.is_null())
1166                .map(rendered)
1167                .collect::<Vec<_>>()
1168                .join(",")
1169        ),
1170        single => Some(rendered(single))
1171    }
1172}
1173
1174/// Lowers the query part to the pairs sent on the wire, in OpenAPI's default
1175/// `form` style: an array repeats its key per item, and `null` is left out. A
1176/// nested object or array has no encoding a platform reads one way, so it is
1177/// refused rather than guessed at.
1178fn query_pairs(query: &Value) -> Result<Vec<(String, String)>, Error> {
1179    query
1180        .as_object()
1181        .into_iter()
1182        .flatten()
1183        .flat_map(|(name, value)| {
1184            let items = match value {
1185                Value::Array(items) => items.as_slice(),
1186                single => from_ref(single)
1187            };
1188            items.iter().filter(|item| !item.is_null()).map(move |item| match item {
1189                Value::Object(_) | Value::Array(_) => Err(Error::InvalidInput(
1190                    format!("query parameter `{name}` holds a nested value, which has no query encoding").into()
1191                )),
1192                scalar => Ok((name.clone(), rendered(scalar)))
1193            })
1194        })
1195        .collect()
1196}
1197
1198/// `path` without the pieces of its own query whose key `query` sets, so a
1199/// caller's value replaces the action template's rather than going beside it.
1200/// Pieces split at `&` and `;` as core splits a template's, and the fragment,
1201/// which is never sent, is dropped first so it cannot hide a key.
1202fn without_replaced(path: &str, query: &[(String, String)]) -> String {
1203    let path = path.split('#').next().unwrap_or_default();
1204    let Some((route, own)) = path.split_once('?') else {
1205        return path.to_string();
1206    };
1207    let key = |piece: &str| {
1208        let raw = piece.split('=').next().unwrap_or_default().replace('+', " ");
1209        percent_decode_str(&raw).decode_utf8_lossy().into_owned()
1210    };
1211    let replaced = |piece: &&str| query.iter().any(|(name, _)| *name == key(piece));
1212    let kept = own
1213        .split('&')
1214        .map(|pair| {
1215            pair.split(';')
1216                .filter(|piece| !piece.is_empty() && !replaced(piece))
1217                .collect::<Vec<_>>()
1218                .join(";")
1219        })
1220        .filter(|pair| !pair.is_empty())
1221        .collect::<Vec<_>>()
1222        .join("&");
1223    match kept.is_empty() {
1224        true => route.to_string(),
1225        false => format!("{route}?{kept}")
1226    }
1227}
1228
1229/// A JSON value as text: a string as itself, anything else as its JSON.
1230fn rendered(value: &Value) -> String {
1231    value.as_str().map(str::to_string).unwrap_or_else(|| value.to_string())
1232}
1233
1234#[cfg(test)]
1235mod tests {
1236    use std::env::{remove_var, set_var};
1237
1238    use super::{ACCESS_TOKEN_ENV, Credential, One, SECRET_ENV, without_replaced};
1239
1240    #[test]
1241    fn test_client_without_replaced_drops_the_templates_pair_a_caller_sets() {
1242        let query = [("attributes".to_string(), "id".to_string())];
1243        assert_eq!(without_replaced("/contacts/1?attributes=all&v=2", &query), "/contacts/1?v=2");
1244        assert_eq!(without_replaced("/contacts/1?attributes=all", &query), "/contacts/1");
1245        assert_eq!(without_replaced("/contacts/1?a%74tributes=all&v", &query), "/contacts/1?v");
1246        assert_eq!(without_replaced("/contacts/1", &query), "/contacts/1");
1247        assert_eq!(without_replaced("/contacts/1?v=2", &[]), "/contacts/1?v=2");
1248        assert_eq!(without_replaced("/contacts/1?x=1;attributes=all", &query), "/contacts/1?x=1");
1249        assert_eq!(without_replaced("/contacts/1?v=2&attributes#stream", &query), "/contacts/1?v=2");
1250    }
1251
1252    /// Reads the credential `from_env` picks for one pair of variable values,
1253    /// leaving the environment as it found it.
1254    ///
1255    /// **One test drives every case, and the restore is not an assertion's
1256    /// job.** The environment is process-global: two tests setting these
1257    /// concurrently decide each other's outcome under a plain `cargo test`, and
1258    /// a cleanup written after the `assert!` never runs on the failing path
1259    /// that most needs it - leaking the variables into every test that follows.
1260    fn credential_from(secret: Option<&str>, access_token: Option<&str>) -> Option<Credential> {
1261        unsafe {
1262            match secret {
1263                Some(value) => set_var(SECRET_ENV, value),
1264                None => remove_var(SECRET_ENV)
1265            }
1266            match access_token {
1267                Some(value) => set_var(ACCESS_TOKEN_ENV, value),
1268                None => remove_var(ACCESS_TOKEN_ENV)
1269            }
1270        }
1271
1272        let credential = One::from_env().ok().map(|one| one.credential);
1273
1274        unsafe {
1275            remove_var(SECRET_ENV);
1276            remove_var(ACCESS_TOKEN_ENV);
1277        }
1278
1279        credential
1280    }
1281
1282    /// `ONE_SECRET=` left behind in a profile or a compose file is how an
1283    /// environment says *not this one*. It used to shadow the access token
1284    /// beside it and then fail as a missing secret, which reads as "you have
1285    /// configured nothing" to someone who has configured the newer variable.
1286    #[test]
1287    fn test_client_from_env_resolves_the_credential_by_precedence() {
1288        assert!(
1289            matches!(credential_from(Some(""), Some("at_from_env")), Some(Credential::AccessToken(_))),
1290            "a blank legacy secret must not shadow the access token beside it"
1291        );
1292        assert!(
1293            matches!(credential_from(Some("   "), Some("at_from_env")), Some(Credential::AccessToken(_))),
1294            "nor must a whitespace-only one"
1295        );
1296        assert!(
1297            matches!(credential_from(Some("sk_from_env"), Some("at_from_env")), Some(Credential::Secret(_))),
1298            "with both set, the longer-standing variable wins"
1299        );
1300        assert!(
1301            matches!(credential_from(Some("sk_from_env"), None), Some(Credential::Secret(_))),
1302            "and it stands alone"
1303        );
1304        assert!(credential_from(None, None).is_none(), "neither configured is a missing secret, not a client");
1305    }
1306}