openapp-sdk-core 1.0.1

Core of the OpenApp SDK: HTTP transport, auth, retries, telemetry, and per-resource sub-clients reused by every language SDK.
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
//! The top-level [`Client`] and its builder.
//!
//! A `Client` is the user-facing entry point: it owns the transport engine and hands
//! out per-tag sub-clients (orgs, devices, entities, …) on demand.

use std::{
    sync::{Arc, Once},
    time::Duration,
};

use reqwest_middleware::ClientBuilder as MiddlewareBuilder;
use reqwest_retry::{RetryTransientMiddleware, policies::ExponentialBackoff};
use url::Url;

use crate::{
    auth::{SharedTokenProvider, StaticApiKey},
    error::SdkError,
    interceptor::{Interceptor, SharedInterceptor, TracingInterceptor},
    resources,
    retry::RetryPolicy,
    transport::Transport,
};

static RUSTLS_PROVIDER_INIT: Once = Once::new();

fn ensure_rustls_provider() {
    RUSTLS_PROVIDER_INIT.call_once(|| {
        // Safe to ignore if another provider is already installed globally.
        let _ = rustls::crypto::ring::default_provider().install_default();
    });
}

/// User-visible client configuration snapshot (read-only after [`ClientBuilder::build`]).
#[derive(Debug, Clone)]
pub struct ClientConfig {
    pub base_url: Url,
    pub user_agent: String,
    pub default_timeout: Duration,
    pub retry: RetryPolicy,
    pub default_org: Option<String>,
}

/// Fluent builder for [`Client`]. Use [`Client::builder`] to construct one.
#[derive(Debug)]
pub struct ClientBuilder {
    token_provider: Option<SharedTokenProvider>,
    base_url: Option<Url>,
    user_agent: Option<String>,
    default_timeout: Duration,
    retry: RetryPolicy,
    interceptors: Vec<SharedInterceptor>,
    underlying: Option<reqwest::Client>,
    org: Option<String>,
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self {
            token_provider: None,
            base_url: None,
            user_agent: None,
            default_timeout: Duration::from_secs(30),
            retry: RetryPolicy::default(),
            interceptors: vec![Arc::new(TracingInterceptor) as SharedInterceptor],
            underlying: None,
            org: None,
        }
    }
}

impl ClientBuilder {
    /// Authenticate with a static `OpenApp` API key. The API root (`{origin}/api/v1`) is
    /// derived from the origin embedded in the token unless overridden via
    /// [`ClientBuilder::base_url`].
    #[must_use]
    pub fn api_key(mut self, token: impl Into<String>) -> Self {
        match StaticApiKey::from_raw(token) {
            Ok(provider) => {
                if self.base_url.is_none() {
                    self.base_url = Some(provider.api_key().api_base_url());
                }
                self.token_provider = Some(Arc::new(provider));
            }
            Err(err) => {
                // Defer the error to `.build()` so the fluent builder keeps composing.
                self.token_provider = Some(Arc::new(FailingProvider(err.to_string())));
            }
        }
        self
    }

    /// Use a custom [`TokenProvider`](crate::auth::TokenProvider).
    #[must_use]
    pub fn token_provider(mut self, provider: SharedTokenProvider) -> Self {
        self.token_provider = Some(provider);
        self
    }

    /// Override the API root every request path is resolved against (for example
    /// `https://openapp.house/api/v1`, including the `/api/v1` prefix). Rarely needed —
    /// [`ClientBuilder::api_key`] derives it from the token's origin.
    pub fn base_url(mut self, url: impl AsRef<str>) -> Result<Self, SdkError> {
        let parsed = Url::parse(url.as_ref())
            .map_err(|e| SdkError::Config(format!("invalid base_url: {e}")))?;
        self.base_url = Some(parsed);
        Ok(self)
    }

    /// Set the `User-Agent` header. Defaults to `"openapp-sdk/<version>"`.
    #[must_use]
    pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
        self.user_agent = Some(ua.into());
        self
    }

    /// Set the default per-request timeout.
    #[must_use]
    pub fn default_timeout(mut self, timeout: Duration) -> Self {
        self.default_timeout = timeout;
        self
    }

    /// Override the default retry policy.
    #[must_use]
    pub fn retry_policy(mut self, policy: RetryPolicy) -> Self {
        self.retry = policy;
        self
    }

    /// Set the default organization context (`X-Org` header) for every request.
    #[must_use]
    pub fn org(mut self, org: impl Into<String>) -> Self {
        self.org = Some(org.into());
        self
    }

    /// Add an [`Interceptor`]. Interceptors run in insertion order.
    #[must_use]
    pub fn interceptor(mut self, interceptor: impl Interceptor + 'static) -> Self {
        self.interceptors.push(Arc::new(interceptor));
        self
    }

    /// Supply a pre-built `reqwest::Client` (e.g. with a custom TLS root bundle).
    #[must_use]
    pub fn reqwest_client(mut self, client: reqwest::Client) -> Self {
        self.underlying = Some(client);
        self
    }

    /// Finalize the builder into a [`Client`].
    ///
    /// # Errors
    ///
    /// Returns [`SdkError::Config`] when no authentication or base URL has been
    /// configured, or when a token-provider error has been deferred from
    /// [`ClientBuilder::api_key`].
    ///
    /// # Panics
    ///
    /// Panics if the default [`reqwest::Client`] cannot be built. In practice this
    /// only happens if the host is missing TLS roots, which is treated as a
    /// programmer error rather than a recoverable condition.
    pub fn build(self) -> Result<Client, SdkError> {
        ensure_rustls_provider();

        let tokens = self
            .token_provider
            .ok_or_else(|| SdkError::Config("no authentication configured".into()))?;
        let base_url = self
            .base_url
            .ok_or_else(|| SdkError::Config("no base URL configured".into()))?;

        let user_agent = self.user_agent.unwrap_or_else(|| {
            format!(
                "{}/{}",
                openapp_sdk_common::SDK_NAME,
                openapp_sdk_common::SDK_VERSION
            )
        });

        let underlying = self.underlying.unwrap_or_else(|| {
            reqwest::Client::builder()
                .user_agent(user_agent.clone())
                .pool_idle_timeout(Some(Duration::from_secs(90)))
                .build()
                .expect("reqwest::Client defaults must build")
        });

        let backoff = ExponentialBackoff::builder()
            .retry_bounds(self.retry.initial_backoff, self.retry.max_backoff)
            .base(2)
            .build_with_max_retries(self.retry.max_retries);

        let client = MiddlewareBuilder::new(underlying)
            .with(RetryTransientMiddleware::new_with_policy(backoff))
            .build();

        let config = ClientConfig {
            base_url: base_url.clone(),
            user_agent: user_agent.clone(),
            default_timeout: self.default_timeout,
            retry: self.retry,
            default_org: self.org.clone(),
        };

        let transport = Transport::new(
            client,
            base_url,
            user_agent,
            tokens,
            self.interceptors,
            self.default_timeout,
            self.org,
        );

        Ok(Client {
            transport: Arc::new(transport),
            config,
        })
    }
}

/// Fails every token request with the deferred parse error captured at build time.
#[derive(Debug)]
struct FailingProvider(String);

#[async_trait::async_trait]
impl crate::auth::TokenProvider for FailingProvider {
    async fn token(&self) -> Result<crate::auth::AuthToken, SdkError> {
        Err(SdkError::Auth(self.0.clone()))
    }
}

/// High-level SDK client. Cheap to clone — all heavy state sits behind an `Arc`.
#[derive(Debug, Clone)]
pub struct Client {
    transport: Arc<Transport>,
    config: ClientConfig,
}

impl Client {
    /// Start a [`ClientBuilder`].
    #[must_use]
    pub fn builder() -> ClientBuilder {
        ClientBuilder::default()
    }

    /// Snapshot of the effective configuration.
    #[must_use]
    pub fn config(&self) -> &ClientConfig {
        &self.config
    }

    /// Transport engine — exposed for advanced callers (the `PyO3` bridge, tests).
    #[must_use]
    pub fn transport(&self) -> Arc<Transport> {
        self.transport.clone()
    }

    /// Return a client scoped to a different organization (`X-Org` header).
    #[must_use]
    pub fn with_org(&self, org: impl Into<String>) -> Client {
        let org = org.into();
        let transport = Arc::new(self.transport.with_default_org(org.clone()));
        Client {
            transport,
            config: ClientConfig {
                default_org: Some(org),
                ..self.config.clone()
            },
        }
    }

    // -- Per-tag sub-clients -------------------------------------------------

    #[must_use]
    pub fn api_keys(&self) -> resources::ApiKeysClient {
        resources::ApiKeysClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn agents(&self) -> resources::AgentsClient {
        resources::AgentsClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn users(&self) -> resources::UsersClient {
        resources::UsersClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn orgs(&self) -> resources::OrgsClient {
        resources::OrgsClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn devices(&self) -> resources::DevicesClient {
        resources::DevicesClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn billing(&self) -> resources::BillingClient {
        resources::BillingClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn entities(&self) -> resources::EntitiesClient {
        resources::EntitiesClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn integrations(&self) -> resources::IntegrationsClient {
        resources::IntegrationsClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn zones(&self) -> resources::ZonesClient {
        resources::ZonesClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn lan_agent(&self) -> resources::LanAgentClient {
        resources::LanAgentClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn scripting(&self) -> resources::ScriptingClient {
        resources::ScriptingClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn directory_listing_members(&self) -> resources::DirectoryListingMembersClient {
        resources::DirectoryListingMembersClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn public_access(&self) -> resources::PublicAccessClient {
        resources::PublicAccessClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn auth(&self) -> resources::AuthClient {
        resources::AuthClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn me(&self) -> resources::MeClient {
        resources::MeClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn eula(&self) -> resources::EulaClient {
        resources::EulaClient::new(self.transport.clone())
    }

    #[must_use]
    pub fn status(&self) -> resources::StatusClient {
        resources::StatusClient::new(self.transport.clone())
    }
}

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

    #[test]
    fn build_requires_auth() {
        let err = Client::builder().build().unwrap_err();
        assert!(matches!(err, SdkError::Config(_)));
    }

    #[test]
    fn api_key_derives_versioned_api_root_from_origin() {
        let client = Client::builder()
            .api_key("https://openapp.house_openapp_SECRET")
            .build()
            .unwrap();
        assert_eq!(
            client.config().base_url.as_str(),
            "https://openapp.house/api/v1"
        );
    }

    #[test]
    fn explicit_base_url_overrides_derived_root() {
        let client = Client::builder()
            .base_url("http://localhost:4455/api/v1")
            .unwrap()
            .api_key("http://oathkeeper:4455_openapp_SECRET")
            .build()
            .unwrap();
        assert_eq!(
            client.config().base_url.as_str(),
            "http://localhost:4455/api/v1"
        );
    }

    #[test]
    fn org_sets_default_org_on_config() {
        let client = Client::builder()
            .api_key("https://openapp.house_openapp_SECRET")
            .org("01HORG00000000000000000000")
            .build()
            .unwrap();
        assert_eq!(
            client.config().default_org.as_deref(),
            Some("01HORG00000000000000000000")
        );
        assert_eq!(
            client.transport().default_org(),
            Some("01HORG00000000000000000000")
        );
    }

    #[test]
    fn with_org_returns_scoped_client() {
        let client = Client::builder()
            .api_key("https://openapp.house_openapp_SECRET")
            .build()
            .unwrap();
        let scoped = client.with_org("01HORG00000000000000000001");
        assert_eq!(
            scoped.config().default_org.as_deref(),
            Some("01HORG00000000000000000001")
        );
        assert!(client.config().default_org.is_none());
    }

    #[test]
    fn deferred_token_error_surfaces_at_request_time() {
        // Malformed token: no separator. `build()` still succeeds; the error surfaces
        // when the first request asks the provider for a token.
        let client = Client::builder()
            .api_key("not a token")
            .base_url("https://openapp.house/api/v1")
            .unwrap()
            .build()
            .unwrap();
        let _ = client; // the error path is exercised by transport tests
    }
}