inferadb 0.1.5

Official Rust SDK for InferaDB
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
//! Organization management for the control plane.

use serde::{Deserialize, Serialize};

use crate::client::Client;
use crate::control::audit::AuditLogsClient;
use crate::control::members::{InvitationsClient, MembersClient};
use crate::control::teams::TeamsClient;
use crate::control::vaults::VaultsClient;
use crate::control::{Page, SortOrder};
use crate::Error;

/// Client for organization-level control plane operations.
///
/// Access via `client.organization("org_id")`.
///
/// ## Example
///
/// ```rust,ignore
/// let org = client.organization("org_abc123");
///
/// // Access vault management
/// let vaults = org.vaults().list().await?;
///
/// // Get organization details
/// let info = org.get().await?;
/// ```
#[derive(Clone)]
pub struct OrganizationControlClient {
    client: Client,
    organization_id: String,
}

impl OrganizationControlClient {
    /// Creates a new organization control client.
    pub(crate) fn new(client: Client, organization_id: impl Into<String>) -> Self {
        Self {
            client,
            organization_id: organization_id.into(),
        }
    }

    /// Returns the organization ID.
    pub fn organization_id(&self) -> &str {
        &self.organization_id
    }

    /// Returns a client for vault management.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let vaults = org.vaults();
    ///
    /// // List all vaults
    /// let list = vaults.list().await?;
    ///
    /// // Create a new vault
    /// let vault = vaults.create(CreateVaultRequest {
    ///     name: "My Vault".into(),
    ///     ..Default::default()
    /// }).await?;
    /// ```
    pub fn vaults(&self) -> VaultsClient {
        VaultsClient::new(self.client.clone(), self.organization_id.clone())
    }

    /// Returns a client for member management.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let members = org.members();
    ///
    /// // List all members
    /// let list = members.list().await?;
    ///
    /// // Invite a new member
    /// members.invite(InviteMemberRequest::new("alice@example.com", OrgRole::Member)).await?;
    /// ```
    pub fn members(&self) -> MembersClient {
        MembersClient::new(self.client.clone(), self.organization_id.clone())
    }

    /// Returns a client for team management.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let teams = org.teams();
    ///
    /// // List all teams
    /// let list = teams.list().await?;
    ///
    /// // Create a new team
    /// let team = teams.create(CreateTeamRequest::new("Engineering")).await?;
    /// ```
    pub fn teams(&self) -> TeamsClient {
        TeamsClient::new(self.client.clone(), self.organization_id.clone())
    }

    /// Returns a client for invitation management.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let invitations = org.invitations();
    ///
    /// // List pending invitations
    /// let pending = invitations.list().await?;
    ///
    /// // Resend an invitation
    /// invitations.resend("inv_abc123").await?;
    /// ```
    pub fn invitations(&self) -> InvitationsClient {
        InvitationsClient::new(self.client.clone(), self.organization_id.clone())
    }

    /// Returns a client for audit log queries.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let audit = org.audit();
    ///
    /// // List recent events
    /// let events = audit.list().await?;
    ///
    /// // Filter by actor
    /// let user_events = audit.list().actor("user_abc123").await?;
    /// ```
    pub fn audit(&self) -> AuditLogsClient {
        AuditLogsClient::new(self.client.clone(), self.organization_id.clone())
    }

    /// Gets the organization details.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let info = org.get().await?;
    /// println!("Organization: {}", info.name);
    /// ```
    #[cfg(feature = "rest")]
    pub async fn get(&self) -> Result<OrganizationInfo, Error> {
        let path = format!("/control/v1/organizations/{}", self.organization_id);
        self.client.inner().control_get(&path).await
    }

    /// Gets the organization details.
    #[cfg(not(feature = "rest"))]
    pub async fn get(&self) -> Result<OrganizationInfo, Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }

    /// Updates the organization.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let updated = org.update(UpdateOrganizationRequest {
    ///     display_name: Some("New Display Name".into()),
    ///     ..Default::default()
    /// }).await?;
    /// ```
    #[cfg(feature = "rest")]
    pub async fn update(
        &self,
        request: UpdateOrganizationRequest,
    ) -> Result<OrganizationInfo, Error> {
        let path = format!("/control/v1/organizations/{}", self.organization_id);
        self.client.inner().control_patch(&path, &request).await
    }

    /// Updates the organization.
    #[cfg(not(feature = "rest"))]
    pub async fn update(
        &self,
        _request: UpdateOrganizationRequest,
    ) -> Result<OrganizationInfo, Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }

    /// Deletes the organization.
    ///
    /// **Warning**: This is a destructive operation that cannot be undone.
    /// All vaults and data within the organization will be permanently deleted.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// // Requires confirmation
    /// org.delete().confirm("DELETE org_abc123").await?;
    /// ```
    pub fn delete(&self) -> DeleteOrganizationRequest {
        DeleteOrganizationRequest {
            client: self.clone(),
            confirmation: None,
        }
    }
}

impl std::fmt::Debug for OrganizationControlClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OrganizationControlClient")
            .field("organization_id", &self.organization_id)
            .finish_non_exhaustive()
    }
}

/// Client for listing and creating organizations.
///
/// Access via `client.organizations()`.
#[derive(Clone)]
pub struct OrganizationsClient {
    client: Client,
}

impl OrganizationsClient {
    /// Creates a new organizations client.
    pub(crate) fn new(client: Client) -> Self {
        Self { client }
    }

    /// Lists all organizations the current user has access to.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let orgs = client.organizations().list().await?;
    /// for org in orgs.items {
    ///     println!("{}: {}", org.id, org.name);
    /// }
    /// ```
    pub fn list(&self) -> ListOrganizationsRequest {
        ListOrganizationsRequest {
            client: self.client.clone(),
            limit: None,
            cursor: None,
            sort: None,
        }
    }

    /// Creates a new organization.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let org = client.organizations().create(CreateOrganizationRequest {
    ///     name: "my-org".into(),
    ///     display_name: Some("My Organization".into()),
    /// }).await?;
    /// ```
    #[cfg(feature = "rest")]
    pub async fn create(
        &self,
        request: CreateOrganizationRequest,
    ) -> Result<OrganizationInfo, Error> {
        self.client
            .inner()
            .control_post("/control/v1/organizations", &request)
            .await
    }

    /// Creates a new organization.
    #[cfg(not(feature = "rest"))]
    pub async fn create(
        &self,
        _request: CreateOrganizationRequest,
    ) -> Result<OrganizationInfo, Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }
}

impl std::fmt::Debug for OrganizationsClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OrganizationsClient")
            .finish_non_exhaustive()
    }
}

/// Information about an organization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrganizationInfo {
    /// The organization ID (e.g., "org_abc123").
    pub id: String,
    /// The organization name (URL-safe slug).
    pub name: String,
    /// Human-readable display name.
    pub display_name: Option<String>,
    /// When the organization was created.
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When the organization was last updated.
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

/// Request to create a new organization.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CreateOrganizationRequest {
    /// The organization name (URL-safe slug).
    pub name: String,
    /// Human-readable display name.
    pub display_name: Option<String>,
}

impl CreateOrganizationRequest {
    /// Creates a new request with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            display_name: None,
        }
    }

    /// Sets the display name.
    #[must_use]
    pub fn with_display_name(mut self, display_name: impl Into<String>) -> Self {
        self.display_name = Some(display_name.into());
        self
    }
}

/// Request to update an organization.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateOrganizationRequest {
    /// New display name.
    pub display_name: Option<String>,
}

impl UpdateOrganizationRequest {
    /// Creates a new empty update request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the display name.
    #[must_use]
    pub fn with_display_name(mut self, display_name: impl Into<String>) -> Self {
        self.display_name = Some(display_name.into());
        self
    }
}

/// Request to list organizations.
pub struct ListOrganizationsRequest {
    client: Client,
    limit: Option<usize>,
    cursor: Option<String>,
    sort: Option<SortOrder>,
}

impl ListOrganizationsRequest {
    /// Sets the maximum number of results to return.
    #[must_use]
    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Sets the pagination cursor.
    #[must_use]
    pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
        self.cursor = Some(cursor.into());
        self
    }

    /// Sets the sort order.
    #[must_use]
    pub fn sort(mut self, order: SortOrder) -> Self {
        self.sort = Some(order);
        self
    }

    #[cfg(feature = "rest")]
    async fn execute(self) -> Result<Page<OrganizationInfo>, Error> {
        // Build query string
        let mut path = "/control/v1/organizations".to_string();
        let mut query_parts = Vec::new();

        if let Some(limit) = self.limit {
            query_parts.push(format!("limit={}", limit));
        }
        if let Some(cursor) = &self.cursor {
            query_parts.push(format!("cursor={}", urlencoding::encode(cursor)));
        }
        if let Some(sort) = &self.sort {
            query_parts.push(format!("sort={}", sort.as_str()));
        }

        if !query_parts.is_empty() {
            path.push('?');
            path.push_str(&query_parts.join("&"));
        }

        self.client.inner().control_get(&path).await
    }

    #[cfg(not(feature = "rest"))]
    async fn execute(self) -> Result<Page<OrganizationInfo>, Error> {
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }
}

impl std::future::IntoFuture for ListOrganizationsRequest {
    type Output = Result<Page<OrganizationInfo>, Error>;
    type IntoFuture = std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.execute())
    }
}

/// Request to delete an organization.
pub struct DeleteOrganizationRequest {
    client: OrganizationControlClient,
    confirmation: Option<String>,
}

impl DeleteOrganizationRequest {
    /// Confirms the deletion with the organization ID.
    ///
    /// You must pass `"DELETE {org_id}"` to confirm deletion.
    #[must_use]
    pub fn confirm(mut self, confirmation: impl Into<String>) -> Self {
        self.confirmation = Some(confirmation.into());
        self
    }

    #[cfg(feature = "rest")]
    async fn execute(self) -> Result<(), Error> {
        let expected = format!("DELETE {}", self.client.organization_id);
        match &self.confirmation {
            Some(c) if c == &expected => {
                let path = format!("/control/v1/organizations/{}", self.client.organization_id);
                self.client.client.inner().control_delete(&path).await
            }
            Some(c) => Err(Error::invalid_argument(format!(
                "Invalid confirmation. Expected '{}', got '{}'",
                expected, c
            ))),
            None => Err(Error::invalid_argument(
                "Deletion requires confirmation. Call .confirm(\"DELETE org_id\") first",
            )),
        }
    }

    #[cfg(not(feature = "rest"))]
    async fn execute(self) -> Result<(), Error> {
        let _ = self.confirmation;
        Err(Error::configuration(
            "REST feature is required for control API",
        ))
    }
}

impl std::future::IntoFuture for DeleteOrganizationRequest {
    type Output = Result<(), Error>;
    type IntoFuture = std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.execute())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::BearerCredentialsConfig;
    use crate::transport::mock::MockTransport;
    use std::sync::Arc;

    async fn create_test_client() -> Client {
        let mock_transport = Arc::new(MockTransport::new());
        Client::builder()
            .url("https://api.example.com")
            .credentials(BearerCredentialsConfig::new("test"))
            .build_with_transport(mock_transport)
            .await
            .unwrap()
    }

    #[test]
    fn test_create_organization_request() {
        let req = CreateOrganizationRequest::new("my-org").with_display_name("My Organization");

        assert_eq!(req.name, "my-org");
        assert_eq!(req.display_name, Some("My Organization".to_string()));
    }

    #[test]
    fn test_update_organization_request() {
        let req = UpdateOrganizationRequest::new().with_display_name("New Name");

        assert_eq!(req.display_name, Some("New Name".to_string()));
    }

    #[test]
    fn test_delete_organization_confirmation_validation() {
        // Test that confirmation validation logic works correctly
        // This doesn't require a server - it's pure string matching
        let org_id = "org_test";
        let expected = format!("DELETE {}", org_id);
        assert_eq!(expected, "DELETE org_test");
        assert_ne!("DELETE wrong_org", expected);
    }

    #[tokio::test]
    async fn test_organization_control_client_accessors() {
        let client = create_test_client().await;
        let org = OrganizationControlClient::new(client, "org_test");
        assert_eq!(org.organization_id(), "org_test");
    }

    #[tokio::test]
    async fn test_organization_control_client_debug() {
        let client = create_test_client().await;
        let org = OrganizationControlClient::new(client, "org_test");
        let debug = format!("{:?}", org);
        assert!(debug.contains("OrganizationControlClient"));
        assert!(debug.contains("org_test"));
    }

    #[tokio::test]
    async fn test_organizations_client_debug() {
        let client = create_test_client().await;
        let orgs = OrganizationsClient::new(client);
        let debug = format!("{:?}", orgs);
        assert!(debug.contains("OrganizationsClient"));
    }

    #[tokio::test]
    async fn test_organization_sub_clients() {
        let client = create_test_client().await;
        let org = OrganizationControlClient::new(client, "org_test");

        // Test that sub-clients can be created (coverage for accessor methods)
        let _vaults = org.vaults();
        let _members = org.members();
        let _teams = org.teams();
        let _invitations = org.invitations();
        let _audit_logs = org.audit();
    }

    #[tokio::test]
    async fn test_list_organizations_request_builders() {
        let client = create_test_client().await;
        let orgs = OrganizationsClient::new(client);

        // Test all builder methods
        let _request = orgs
            .list()
            .limit(50)
            .cursor("cursor_xyz")
            .sort(SortOrder::Descending);

        // Just verify the builder compiles and returns a request
    }

    #[tokio::test]
    async fn test_delete_organization_request_builder() {
        let client = create_test_client().await;
        let org = OrganizationControlClient::new(client, "org_test");

        // Test delete with confirmation builder
        let _request = org.delete().confirm("DELETE org_test");
    }
}

#[cfg(all(test, feature = "rest"))]
mod wiremock_tests {
    use super::*;
    use crate::auth::BearerCredentialsConfig;
    use crate::Client;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    async fn create_mock_client(server: &MockServer) -> Client {
        Client::builder()
            .url(server.uri())
            .insecure()
            .credentials(BearerCredentialsConfig::new("test_token"))
            .build()
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn test_list_organizations() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/control/v1/organizations"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "items": [
                    {
                        "id": "org_123",
                        "name": "my-org",
                        "display_name": "My Organization",
                        "created_at": "2024-01-01T00:00:00Z",
                        "updated_at": "2024-01-02T00:00:00Z"
                    }
                ],
                "page_info": {
                    "has_next": false,
                    "next_cursor": null,
                    "total_count": 1
                }
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let orgs = OrganizationsClient::new(client);
        let result = orgs.list().await;

        assert!(result.is_ok());
        let page = result.unwrap();
        assert_eq!(page.items.len(), 1);
        assert_eq!(page.items[0].name, "my-org");
    }

    #[tokio::test]
    async fn test_list_organizations_with_filters() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/control/v1/organizations"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "items": [],
                "page_info": {
                    "has_next": false,
                    "next_cursor": null,
                    "total_count": 0
                }
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let orgs = OrganizationsClient::new(client);
        let result = orgs
            .list()
            .limit(10)
            .cursor("cursor_abc")
            .sort(SortOrder::Descending)
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_create_organization() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/control/v1/organizations"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "org_new",
                "name": "new-org",
                "display_name": "New Organization",
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-01T00:00:00Z"
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let orgs = OrganizationsClient::new(client);
        let request =
            CreateOrganizationRequest::new("new-org").with_display_name("New Organization");
        let result = orgs.create(request).await;

        assert!(result.is_ok());
        let org = result.unwrap();
        assert_eq!(org.name, "new-org");
    }

    #[tokio::test]
    async fn test_get_organization() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/control/v1/organizations/org_abc"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "org_abc",
                "name": "test-org",
                "display_name": "Test Organization",
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-02T00:00:00Z"
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let org = OrganizationControlClient::new(client, "org_abc");
        let result = org.get().await;

        assert!(result.is_ok());
        let info = result.unwrap();
        assert_eq!(info.id, "org_abc");
    }

    #[tokio::test]
    async fn test_update_organization() {
        let server = MockServer::start().await;

        Mock::given(method("PATCH"))
            .and(path("/control/v1/organizations/org_abc"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "org_abc",
                "name": "test-org",
                "display_name": "Updated Organization",
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-03T00:00:00Z"
            })))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let org = OrganizationControlClient::new(client, "org_abc");
        let request =
            UpdateOrganizationRequest::default().with_display_name("Updated Organization");
        let result = org.update(request).await;

        assert!(result.is_ok());
        let info = result.unwrap();
        assert_eq!(info.display_name, Some("Updated Organization".to_string()));
    }

    #[tokio::test]
    async fn test_delete_organization() {
        let server = MockServer::start().await;

        Mock::given(method("DELETE"))
            .and(path("/control/v1/organizations/org_abc"))
            .respond_with(ResponseTemplate::new(204))
            .mount(&server)
            .await;

        let client = create_mock_client(&server).await;
        let org = OrganizationControlClient::new(client, "org_abc");
        let result = org.delete().confirm("DELETE org_abc").await;

        assert!(result.is_ok());
    }
}