fabric-platform 0.1.0

Rust client SDK for the Fabric platform
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
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use serde_json::json;
use std::time::{Duration, Instant};

#[derive(Debug, thiserror::Error)]
pub enum FabricError {
    #[error("HTTP error: {0}")]
    Http(#[from] reqwest::Error),
    #[error("API error ({code}): {message}")]
    Api { code: String, message: String },
    #[error("{0}")]
    Other(String),
}

pub type Result<T> = std::result::Result<T, FabricError>;

pub struct FabricClient {
    client: reqwest::Client,
    base_url: String,
    organization_id: String,
}

impl FabricClient {
    /// Create a new client authenticated with an API key.
    pub fn new(base_url: &str, api_key: &str) -> Result<Self> {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTHORIZATION,
            HeaderValue::from_str(&format!("Bearer {api_key}"))
                .map_err(|e| FabricError::Other(e.to_string()))?,
        );
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

        let client = reqwest::Client::builder()
            .default_headers(headers)
            .build()?;

        Ok(Self {
            client,
            base_url: base_url.trim_end_matches('/').to_string(),
            organization_id: String::new(),
        })
    }

    /// Create a new client authenticated with a principal ID header.
    pub fn with_principal(base_url: &str, principal_id: &str) -> Result<Self> {
        let mut headers = HeaderMap::new();
        headers.insert(
            "X-Principal-Id",
            HeaderValue::from_str(principal_id).map_err(|e| FabricError::Other(e.to_string()))?,
        );
        headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));

        let client = reqwest::Client::builder()
            .default_headers(headers)
            .build()?;

        Ok(Self {
            client,
            base_url: base_url.trim_end_matches('/').to_string(),
            organization_id: String::new(),
        })
    }

    /// Set the organization ID used for scoped requests.
    pub fn set_organization_id(&mut self, org_id: &str) {
        self.organization_id = org_id.to_string();
    }

    // ── Private helpers ──────────────────────────────────────────────

    async fn request<T: serde::de::DeserializeOwned>(
        &self,
        method: reqwest::Method,
        path: &str,
        body: Option<serde_json::Value>,
    ) -> Result<T> {
        let url = format!("{}{path}", self.base_url);
        let mut req = self.client.request(method, &url);
        if let Some(b) = body {
            req = req.json(&b);
        }
        let resp = req.send().await?;
        let status = resp.status();
        let json: serde_json::Value = resp.json().await?;

        if let Some(err) = json.get("error") {
            return Err(FabricError::Api {
                code: status.as_u16().to_string(),
                message: err
                    .as_str()
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| err.to_string()),
            });
        }

        if let Some(data) = json.get("data") {
            serde_json::from_value(data.clone())
                .map_err(|e| FabricError::Other(format!("Failed to deserialize data: {e}")))
        } else {
            serde_json::from_value(json)
                .map_err(|e| FabricError::Other(format!("Failed to deserialize response: {e}")))
        }
    }

    async fn get<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
        self.request(reqwest::Method::GET, path, None).await
    }

    async fn post<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        body: serde_json::Value,
    ) -> Result<T> {
        self.request(reqwest::Method::POST, path, Some(body)).await
    }

    async fn post_empty(&self, path: &str) -> Result<()> {
        let url = format!("{}{path}", self.base_url);
        let resp = self.client.post(&url).send().await?;
        let status = resp.status();
        let json: serde_json::Value = resp.json().await?;

        if let Some(err) = json.get("error") {
            return Err(FabricError::Api {
                code: status.as_u16().to_string(),
                message: err
                    .as_str()
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| err.to_string()),
            });
        }
        Ok(())
    }

    async fn delete_req(&self, path: &str) -> Result<()> {
        let url = format!("{}{path}", self.base_url);
        let resp = self.client.delete(&url).send().await?;
        let status = resp.status();
        let json: serde_json::Value = resp.json().await?;

        if let Some(err) = json.get("error") {
            return Err(FabricError::Api {
                code: status.as_u16().to_string(),
                message: err
                    .as_str()
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| err.to_string()),
            });
        }
        Ok(())
    }

    // ── System ───────────────────────────────────────────────────────

    pub async fn health_check(&self) -> Result<serde_json::Value> {
        self.get("/health").await
    }

    pub async fn system_status(&self) -> Result<serde_json::Value> {
        self.get("/api/v1/system/status").await
    }

    // ── Identity ─────────────────────────────────────────────────────

    pub async fn get_me(&self) -> Result<serde_json::Value> {
        self.get("/api/v1/me").await
    }

    pub async fn get_my_organizations(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/me/organizations").await
    }

    pub async fn get_my_teams(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/me/teams").await
    }

    pub async fn get_my_permissions(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/me/permissions").await
    }

    // ── Organizations ────────────────────────────────────────────────

    pub async fn create_organization(&self, slug: &str, name: &str) -> Result<serde_json::Value> {
        self.post(
            "/api/v1/organizations",
            json!({ "slug": slug, "name": name }),
        )
        .await
    }

    pub async fn list_organizations(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/organizations").await
    }

    pub async fn get_organization(&self, org_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/organizations/{org_id}")).await
    }

    pub async fn list_org_teams(&self, org_id: &str) -> Result<Vec<serde_json::Value>> {
        self.get(&format!("/api/v1/organizations/{org_id}/teams"))
            .await
    }

    pub async fn list_org_members(&self, org_id: &str) -> Result<Vec<serde_json::Value>> {
        self.get(&format!("/api/v1/organizations/{org_id}/members"))
            .await
    }

    // ── Teams ────────────────────────────────────────────────────────

    pub async fn create_team(
        &self,
        org_id: &str,
        slug: &str,
        name: &str,
    ) -> Result<serde_json::Value> {
        self.post(
            &format!("/api/v1/organizations/{org_id}/teams"),
            json!({ "slug": slug, "name": name }),
        )
        .await
    }

    pub async fn get_team(&self, team_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/teams/{team_id}")).await
    }

    // ── Invitations ──────────────────────────────────────────────────

    pub async fn create_invitation(
        &self,
        org_id: &str,
        email: &str,
        role: &str,
    ) -> Result<serde_json::Value> {
        self.post(
            &format!("/api/v1/organizations/{org_id}/invitations"),
            json!({ "email": email, "role": role }),
        )
        .await
    }

    pub async fn accept_invitation(&self, invitation_id: &str) -> Result<()> {
        self.post_empty(&format!("/api/v1/invitations/{invitation_id}/accept"))
            .await
    }

    pub async fn revoke_invitation(&self, invitation_id: &str) -> Result<()> {
        self.delete_req(&format!("/api/v1/invitations/{invitation_id}"))
            .await
    }

    // ── Authorization ────────────────────────────────────────────────

    pub async fn check_permission(&self, action: &str, resource: Option<&str>) -> Result<bool> {
        let mut body = json!({ "action": action });
        if let Some(r) = resource {
            body["resource"] = serde_json::Value::String(r.to_string());
        }
        let resp: serde_json::Value = self.post("/api/v1/authz/check", body).await?;
        Ok(resp
            .get("allowed")
            .and_then(|v| v.as_bool())
            .unwrap_or(false))
    }

    pub async fn check_permissions(
        &self,
        checks: Vec<serde_json::Value>,
    ) -> Result<Vec<serde_json::Value>> {
        self.post("/api/v1/authz/check-batch", json!({ "checks": checks }))
            .await
    }

    // ── API Keys ─────────────────────────────────────────────────────

    pub async fn create_api_key(
        &self,
        name: &str,
        org_id: &str,
        scopes: Option<Vec<&str>>,
    ) -> Result<serde_json::Value> {
        let mut body = json!({ "name": name, "organization_id": org_id });
        if let Some(s) = scopes {
            body["scopes"] = serde_json::Value::from(s);
        }
        self.post("/api/v1/api-keys", body).await
    }

    pub async fn list_api_keys(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/api-keys").await
    }

    pub async fn get_api_key(&self, key_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/api-keys/{key_id}")).await
    }

    pub async fn delete_api_key(&self, key_id: &str) -> Result<()> {
        self.delete_req(&format!("/api/v1/api-keys/{key_id}")).await
    }

    pub async fn disable_api_key(&self, key_id: &str) -> Result<()> {
        self.post_empty(&format!("/api/v1/api-keys/{key_id}/disable"))
            .await
    }

    pub async fn rotate_api_key(&self, key_id: &str) -> Result<serde_json::Value> {
        self.post(&format!("/api/v1/api-keys/{key_id}/rotate"), json!({}))
            .await
    }

    // ── Workflows ────────────────────────────────────────────────────

    pub async fn upsert_workflow(&self, name: &str, body: serde_json::Value) -> Result<String> {
        let mut payload = body;
        payload["name"] = serde_json::Value::String(name.to_string());
        let resp: serde_json::Value = self.post("/api/v1/workflows", payload).await?;
        resp.get("id")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .ok_or_else(|| FabricError::Other("Missing workflow id in response".to_string()))
    }

    pub async fn list_workflows(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/workflows").await
    }

    pub async fn run_workflow(
        &self,
        workflow_id: &str,
        context: serde_json::Value,
    ) -> Result<String> {
        let resp: serde_json::Value = self
            .post(
                &format!("/api/v1/workflows/{workflow_id}/runs"),
                json!({ "context": context }),
            )
            .await?;
        let run_id = resp
            .get("id")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .ok_or_else(|| FabricError::Other("Missing run id in response".to_string()))?;
        self.start_run(&run_id).await?;
        Ok(run_id)
    }

    pub async fn get_run(&self, run_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/runs/{run_id}")).await
    }

    pub async fn start_run(&self, run_id: &str) -> Result<()> {
        self.post_empty(&format!("/api/v1/runs/{run_id}/start"))
            .await
    }

    pub async fn cancel_run(&self, run_id: &str) -> Result<()> {
        self.post_empty(&format!("/api/v1/runs/{run_id}/cancel"))
            .await
    }

    pub async fn wait_for_run(&self, run_id: &str) -> Result<serde_json::Value> {
        let timeout = Duration::from_secs(300);
        let poll_interval = Duration::from_secs(2);
        let start = Instant::now();

        loop {
            let run = self.get_run(run_id).await?;
            if let Some("completed" | "failed" | "cancelled") =
                run.get("status").and_then(|v| v.as_str())
            {
                return Ok(run);
            }
            if start.elapsed() >= timeout {
                return Err(FabricError::Other(format!(
                    "Timed out waiting for run {run_id} after {timeout:?}"
                )));
            }
            tokio::time::sleep(poll_interval).await;
        }
    }

    pub async fn list_runs(&self, workflow_id: &str) -> Result<Vec<serde_json::Value>> {
        self.get(&format!("/api/v1/workflows/{workflow_id}/runs"))
            .await
    }

    pub async fn run_log(&self, run_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/runs/{run_id}/log")).await
    }

    // ── Face Swap & Motion Transfer ─────────────────────────────────

    /// Run the `video/face-swap` workflow.
    ///
    /// Swaps a persona face onto a source image/video. Provide either
    /// `target_url` (direct face URL) or `persona_gallery_id` (to pull
    /// from an org gallery).
    pub async fn face_swap(
        &self,
        source_url: &str,
        target_url: Option<&str>,
        persona_gallery_id: Option<&str>,
    ) -> Result<serde_json::Value> {
        let mut context = json!({ "source_url": source_url });
        if let Some(url) = target_url {
            context["target_url"] = serde_json::Value::String(url.to_string());
        }
        if let Some(gid) = persona_gallery_id {
            context["persona_gallery_id"] = serde_json::Value::String(gid.to_string());
        }
        if !self.organization_id.is_empty() {
            context["organization_id"] = serde_json::Value::String(self.organization_id.clone());
        }
        let run_id = self.run_workflow("video/face-swap", context).await?;
        self.wait_for_run(&run_id).await
    }

    /// Run the `video/motion-transfer` workflow.
    ///
    /// Animates a persona image using a reference video's motion (dance,
    /// gestures, expressions).
    pub async fn motion_transfer(
        &self,
        driving_video_url: &str,
        source_image_url: Option<&str>,
        persona_gallery_id: Option<&str>,
        motion_model: Option<&str>,
    ) -> Result<serde_json::Value> {
        let mut context = json!({ "driving_video_url": driving_video_url });
        if let Some(url) = source_image_url {
            context["source_image_url"] = serde_json::Value::String(url.to_string());
        }
        if let Some(gid) = persona_gallery_id {
            context["persona_gallery_id"] = serde_json::Value::String(gid.to_string());
        }
        if let Some(model) = motion_model {
            context["motion_model"] = serde_json::Value::String(model.to_string());
        }
        if !self.organization_id.is_empty() {
            context["organization_id"] = serde_json::Value::String(self.organization_id.clone());
        }
        let run_id = self.run_workflow("video/motion-transfer", context).await?;
        self.wait_for_run(&run_id).await
    }

    // ── Jobs ─────────────────────────────────────────────────────────

    pub async fn create_job(&self, body: serde_json::Value) -> Result<serde_json::Value> {
        self.post("/api/v1/jobs", body).await
    }

    pub async fn get_job(&self, job_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/jobs/{job_id}")).await
    }

    pub async fn list_jobs(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/jobs").await
    }

    pub async fn get_job_usage(&self, job_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/jobs/{job_id}/usage")).await
    }

    // ── Providers ────────────────────────────────────────────────────

    pub async fn list_providers(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/providers").await
    }

    pub async fn execute_provider(&self, body: serde_json::Value) -> Result<serde_json::Value> {
        self.post("/api/v1/providers/execute", body).await
    }

    pub async fn estimate_cost(&self, body: serde_json::Value) -> Result<serde_json::Value> {
        self.post("/api/v1/providers/estimate", body).await
    }

    // ── Nodes ────────────────────────────────────────────────────────

    pub async fn list_nodes(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/nodes").await
    }

    pub async fn get_node(&self, node_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/nodes/{node_id}")).await
    }

    // ── Usage & Audit ────────────────────────────────────────────────

    pub async fn get_org_usage(&self, org_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/organizations/{org_id}/usage"))
            .await
    }

    pub async fn get_org_usage_records(&self, org_id: &str) -> Result<Vec<serde_json::Value>> {
        self.get(&format!("/api/v1/organizations/{org_id}/usage/records"))
            .await
    }

    pub async fn get_org_usage_daily(&self, org_id: &str) -> Result<Vec<serde_json::Value>> {
        self.get(&format!("/api/v1/organizations/{org_id}/usage/daily"))
            .await
    }

    pub async fn get_org_audit_logs(&self, org_id: &str) -> Result<Vec<serde_json::Value>> {
        self.get(&format!("/api/v1/organizations/{org_id}/audit-logs"))
            .await
    }

    pub async fn get_audit_logs(&self) -> Result<Vec<serde_json::Value>> {
        self.get("/api/v1/audit-logs").await
    }

    // ── Webhooks ─────────────────────────────────────────────────────

    pub async fn create_webhook(
        &self,
        org_id: &str,
        url: &str,
        events: Vec<&str>,
        secret: Option<&str>,
    ) -> Result<serde_json::Value> {
        let mut body = json!({
            "url": url,
            "events": events,
        });
        if let Some(s) = secret {
            body["secret"] = serde_json::Value::String(s.to_string());
        }
        self.post(&format!("/api/v1/organizations/{org_id}/webhooks"), body)
            .await
    }

    pub async fn list_webhooks(&self, org_id: &str) -> Result<Vec<serde_json::Value>> {
        self.get(&format!("/api/v1/organizations/{org_id}/webhooks"))
            .await
    }

    pub async fn get_webhook(&self, webhook_id: &str) -> Result<serde_json::Value> {
        self.get(&format!("/api/v1/webhooks/{webhook_id}")).await
    }

    pub async fn delete_webhook(&self, webhook_id: &str) -> Result<()> {
        self.delete_req(&format!("/api/v1/webhooks/{webhook_id}"))
            .await
    }

    // ── Secrets ──────────────────────────────────────────────────────

    pub async fn set_secret(&self, name: &str, value: &str) -> Result<()> {
        let _: serde_json::Value = self
            .post("/api/v1/secrets", json!({ "name": name, "value": value }))
            .await?;
        Ok(())
    }

    pub async fn list_secrets(&self) -> Result<Vec<String>> {
        self.get("/api/v1/secrets").await
    }

    pub async fn delete_secret(&self, name: &str) -> Result<()> {
        self.delete_req(&format!("/api/v1/secrets/{name}")).await
    }

    // ── Schedules ────────────────────────────────────────────────────

    pub async fn create_schedule(
        &self,
        workflow_id: &str,
        cron: &str,
        context: Option<serde_json::Value>,
    ) -> Result<serde_json::Value> {
        let mut body = json!({ "cron": cron });
        if let Some(ctx) = context {
            body["context"] = ctx;
        }
        self.post(&format!("/api/v1/workflows/{workflow_id}/schedules"), body)
            .await
    }

    pub async fn list_schedules(&self, workflow_id: &str) -> Result<Vec<serde_json::Value>> {
        self.get(&format!("/api/v1/workflows/{workflow_id}/schedules"))
            .await
    }

    pub async fn delete_schedule(&self, schedule_id: &str) -> Result<()> {
        self.delete_req(&format!("/api/v1/schedules/{schedule_id}"))
            .await
    }
}