fundaia 0.7.2

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

use anyhow::{anyhow, bail, Context, Result};
use futures_util::StreamExt;
use reqwest::{Method, StatusCode};
use serde::de::DeserializeOwned;
use serde::Serialize;

use super::models::*;
use crate::config::normalise_url;

/// Every call this tool makes, in one place.
///
/// Thin on purpose: it owns the base address, the bearer header and the shape
/// of a failure, and knows nothing about what any of it means. The commands
/// hold the meaning, the renderer holds the appearance, and this holds the
/// wire — which is what lets a command be read without a browser tab open on
/// the API.
/// Cloning one is cheap: `reqwest::Client` is a handle onto a shared pool, so a
/// clone shares the connections rather than opening a second set.
#[derive(Clone)]
pub struct ApiClient {
    base: String,
    http: reqwest::Client,
    /// The one for event streams. See `new` for why it cannot be the same one.
    streaming: reqwest::Client,
    token: Option<String>,
}

/// A server error, as much of it as is worth showing.
#[derive(Debug)]
pub struct ApiError {
    pub status: StatusCode,
    pub code: String,
    pub message: String,
}

impl std::fmt::Display for ApiError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(formatter, "{} ({})", self.message, self.status.as_u16())
    }
}

impl std::error::Error for ApiError {}

#[derive(serde::Deserialize)]
struct ErrorBody {
    #[serde(default)]
    error: Option<String>,
    #[serde(default)]
    message: Option<String>,
}

impl ApiClient {
    pub fn new(base: &str, token: Option<String>) -> Result<Self> {
        let http = reqwest::Client::builder()
            // Long enough for a cold start behind the gateway, short enough
            // that a wedged connection does not hang a terminal for ever.
            .timeout(Duration::from_secs(60))
            .user_agent(concat!("fundaia/", env!("CARGO_PKG_VERSION")))
            .build()
            .context("could not build the HTTP client")?;

        /*
         * A second client, because `timeout` above is the whole request.
         *
         * It covers reading the body too, which is right for a JSON answer and
         * wrong for a stream: a build that prints for more than a minute had
         * its log cut off mid-line, and `watch` — which is silent by design
         * until something happens — died after exactly sixty seconds every
         * time. What a stream needs is a limit on *silence*, and the server
         * sends a keep-alive comment every twenty seconds, so a read that
         * blocks far longer than that is a connection nobody is on the other
         * end of.
         */
        let streaming = reqwest::Client::builder()
            .read_timeout(Duration::from_secs(90))
            .user_agent(concat!("fundaia/", env!("CARGO_PKG_VERSION")))
            .build()
            .context("could not build the streaming HTTP client")?;

        Ok(Self {
            base: normalise_url(base),
            http,
            streaming,
            token,
        })
    }

    pub fn base(&self) -> &str {
        &self.base
    }

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

    pub async fn post<T: DeserializeOwned, B: Serialize>(&self, path: &str, body: &B) -> Result<T> {
        self.send(Method::POST, path, Some(body)).await
    }

    pub async fn put<T: DeserializeOwned, B: Serialize>(&self, path: &str, body: &B) -> Result<T> {
        self.send(Method::PUT, path, Some(body)).await
    }

    /// PATCH answers with a small body every caller here ignores.
    pub async fn patch<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
        let response = self.request(Method::PATCH, path, Some(body)).send().await?;
        Self::check(response).await?;
        Ok(())
    }

    /// For the DELETEs that answer with something worth reading — how many
    /// references a disconnection removed, and nothing else so far.
    pub async fn delete_for<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        self.send(Method::DELETE, path, None::<&()>).await
    }

    /// For the endpoints that answer 204, where decoding a body would fail.
    pub async fn delete(&self, path: &str) -> Result<()> {
        let response = self
            .request(Method::DELETE, path, None::<&()>)
            .send()
            .await?;
        Self::check(response).await?;
        Ok(())
    }

    async fn send<T: DeserializeOwned, B: Serialize>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
    ) -> Result<T> {
        let response = self.request(method, path, body).send().await?;
        let text = Self::check(response).await?;

        // An empty body decoded as `T` fails with a message about the input
        // being empty, which sends the reader looking in the wrong place.
        if text.trim().is_empty() {
            bail!("the server answered {path} with nothing at all");
        }

        serde_json::from_str(&text)
            .with_context(|| format!("could not read the answer from {path}"))
    }

    fn request<B: Serialize>(
        &self,
        method: Method,
        path: &str,
        body: Option<&B>,
    ) -> reqwest::RequestBuilder {
        self.request_with(&self.http, method, path, body)
    }

    /// The same request, on the client that tolerates a long quiet body.
    fn streaming_request(&self, path: &str) -> reqwest::RequestBuilder {
        self.request_with(&self.streaming, Method::GET, path, None::<&()>)
            .header("accept", "text/event-stream")
    }

    fn request_with<B: Serialize>(
        &self,
        client: &reqwest::Client,
        method: Method,
        path: &str,
        body: Option<&B>,
    ) -> reqwest::RequestBuilder {
        let mut builder = client.request(method, format!("{}{path}", self.base));

        if let Some(token) = &self.token {
            builder = builder.bearer_auth(token);
        }
        if let Some(body) = body {
            builder = builder.json(body);
        }

        builder
    }

    /// Turns a non-2xx into an `ApiError` carrying the server's own words.
    async fn check(response: reqwest::Response) -> Result<String> {
        let status = response.status();
        let text = response.text().await.unwrap_or_default();

        if status.is_success() {
            return Ok(text);
        }

        let body: ErrorBody = serde_json::from_str(&text).unwrap_or(ErrorBody {
            error: None,
            message: None,
        });

        let message = body.message.unwrap_or_else(|| match status {
            StatusCode::UNAUTHORIZED => "not signed in — run `fundaia login`".to_owned(),
            StatusCode::NOT_FOUND => "there is nothing there".to_owned(),
            _ => status
                .canonical_reason()
                .unwrap_or("the request failed")
                .to_owned(),
        });

        Err(ApiError {
            status,
            code: body.error.unwrap_or_else(|| "unknown_error".to_owned()),
            message,
        }
        .into())
    }

    // ---------------------------------------------------------------- reads

    pub async fn projects(&self) -> Result<Vec<Project>> {
        Ok(self
            .get::<ProjectsPage>("/api/infra/projects")
            .await?
            .projects)
    }

    /// Finds a project by id, slug or name, in that order of specificity.
    ///
    /// A CLI is typed at, so it has to accept the thing a person can see on a
    /// screen. Ambiguity is an error rather than a guess: two projects whose
    /// names differ only in case is unlikely, and picking one silently is the
    /// kind of helpfulness that deploys to the wrong place.
    pub async fn find_project(&self, reference: &str) -> Result<Project> {
        let projects = self.projects().await?;
        let needle = reference.to_lowercase();

        let matched: Vec<Project> = projects
            .into_iter()
            .filter(|project| {
                project.id == reference
                    || project.slug.to_lowercase() == needle
                    || project.name.to_lowercase() == needle
            })
            .collect();

        match matched.len() {
            0 => Err(anyhow!("there is no project called `{reference}`")),
            1 => Ok(matched.into_iter().next().expect("length checked")),
            other => Err(anyhow!(
                "`{reference}` matches {other} projects — use the id"
            )),
        }
    }

    pub async fn services(&self, project_id: &str) -> Result<ServicesPage> {
        self.get(&format!("/api/infra/projects/{project_id}/services"))
            .await
    }

    /// The same lookup for a service, within one project.
    pub async fn find_service(&self, project_id: &str, reference: &str) -> Result<Service> {
        let page = self.services(project_id).await?;
        let needle = reference.to_lowercase();

        let matched: Vec<Service> = page
            .services
            .into_iter()
            .filter(|service| {
                service.id == reference
                    || service.slug.to_lowercase() == needle
                    || service.name.to_lowercase() == needle
            })
            .collect();

        match matched.len() {
            0 => Err(anyhow!("this project has no service called `{reference}`")),
            1 => Ok(matched.into_iter().next().expect("length checked")),
            other => Err(anyhow!(
                "`{reference}` matches {other} services — use the id"
            )),
        }
    }

    pub async fn service_detail(&self, service_environment_id: &str) -> Result<ServiceDetail> {
        self.get(&format!("/api/infra/services/{service_environment_id}"))
            .await
    }

    pub async fn deployments(&self, service_environment_id: &str) -> Result<Vec<Deployment>> {
        Ok(self
            .get::<DeploymentsPage>(&format!(
                "/api/infra/services/{service_environment_id}/deployments"
            ))
            .await?
            .deployments)
    }

    pub async fn deployment(&self, deployment_id: &str) -> Result<DeploymentDetail> {
        self.get(&format!("/api/infra/deployments/{deployment_id}"))
            .await
    }

    pub async fn variables(&self, service_environment_id: &str) -> Result<Vec<Variable>> {
        Ok(self
            .get::<VariablesPage>(&format!(
                "/api/infra/services/{service_environment_id}/variables"
            ))
            .await?
            .variables)
    }

    pub async fn domains(&self, service_environment_id: &str) -> Result<Vec<Domain>> {
        Ok(self
            .get::<DomainsPage>(&format!(
                "/api/infra/services/{service_environment_id}/domains"
            ))
            .await?
            .domains)
    }

    pub async fn usage(
        &self,
        service_environment_id: &str,
        minutes: u32,
    ) -> Result<Vec<UsageSample>> {
        Ok(self
            .get::<UsagePage>(&format!(
                "/api/infra/services/{service_environment_id}/usage?minutes={minutes}"
            ))
            .await?
            .samples)
    }

    pub async fn templates(&self) -> Result<Vec<Template>> {
        Ok(self
            .get::<TemplatesPage>("/api/infra/templates")
            .await?
            .templates)
    }

    pub async fn candidates(
        &self,
        service_environment_id: &str,
    ) -> Result<Vec<ConnectionCandidate>> {
        Ok(self
            .get::<ConnectionCandidates>(&format!(
                "/api/infra/services/{service_environment_id}/connections"
            ))
            .await?
            .candidates)
    }

    pub async fn whoami(&self) -> Result<Option<PrincipalIdentity>> {
        Ok(self.get::<Principal>("/api/auth/session").await?.principal)
    }

    pub async fn version(&self) -> Result<ServerVersion> {
        self.get("/api/version").await
    }

    // --------------------------------------------------------------- writes

    pub async fn deploy(&self, service_environment_id: &str) -> Result<Deployment> {
        Ok(self
            .post::<DeploymentAccepted, _>(
                &format!("/api/infra/services/{service_environment_id}/deploy"),
                &serde_json::json!({}),
            )
            .await?
            .deployment)
    }

    pub async fn restart(&self, service_environment_id: &str) -> Result<Deployment> {
        Ok(self
            .post::<DeploymentAccepted, _>(
                &format!("/api/infra/services/{service_environment_id}/restart"),
                &serde_json::json!({}),
            )
            .await?
            .deployment)
    }

    pub async fn stop(&self, service_environment_id: &str) -> Result<()> {
        let response = self
            .request(
                Method::POST,
                &format!("/api/infra/services/{service_environment_id}/stop"),
                Some(&serde_json::json!({})),
            )
            .send()
            .await?;
        Self::check(response).await?;
        Ok(())
    }

    pub async fn rollback(&self, deployment_id: &str) -> Result<Deployment> {
        Ok(self
            .post::<DeploymentAccepted, _>(
                &format!("/api/infra/deployments/{deployment_id}/rollback"),
                &serde_json::json!({}),
            )
            .await?
            .deployment)
    }

    pub async fn set_variable(
        &self,
        service_environment_id: &str,
        key: &str,
        value: &str,
        secret: bool,
        sealed: bool,
    ) -> Result<()> {
        let _: serde_json::Value = self
            .put(
                &format!("/api/infra/services/{service_environment_id}/variables"),
                &serde_json::json!({
                    "key": key,
                    "value": value,
                    "secret": secret,
                    "sealed": sealed,
                }),
            )
            .await?;
        Ok(())
    }

    pub async fn backups(&self, service_environment_id: &str) -> Result<BackupsPage> {
        self.get(&format!(
            "/api/infra/services/{service_environment_id}/backups"
        ))
        .await
    }

    /// Takes a copy and waits for it: the server does not answer until it is on disk.
    pub async fn take_backup(&self, service_environment_id: &str) -> Result<Backup> {
        Ok(self
            .post::<BackupTaken, _>(
                &format!("/api/infra/services/{service_environment_id}/backups"),
                &serde_json::json!({}),
            )
            .await?
            .backup)
    }

    pub async fn schedule_backups(
        &self,
        service_environment_id: &str,
        schedules: &[String],
    ) -> Result<Vec<String>> {
        Ok(self
            .put::<BackupSchedules, _>(
                &format!("/api/infra/services/{service_environment_id}/backups/schedule"),
                &serde_json::json!({ "schedules": schedules }),
            )
            .await?
            .schedules)
    }

    /// Overwrites the volume. The server takes a safety copy first.
    pub async fn restore_backup(&self, backup_id: &str) -> Result<Backup> {
        Ok(self
            .post::<BackupTaken, _>(
                &format!("/api/infra/backups/{backup_id}/restore"),
                &serde_json::json!({}),
            )
            .await?
            .backup)
    }

    pub async fn lock_backup(&self, backup_id: &str, locked: bool) -> Result<Backup> {
        Ok(self
            .put::<BackupTaken, _>(
                &format!("/api/infra/backups/{backup_id}/lock"),
                &serde_json::json!({ "locked": locked }),
            )
            .await?
            .backup)
    }

    pub async fn delete_backup(&self, backup_id: &str) -> Result<()> {
        self.delete(&format!("/api/infra/backups/{backup_id}"))
            .await
    }

    /// Seals a variable. One way: the server refuses every read and write after.
    pub async fn seal_variable(&self, variable_id: &str) -> Result<()> {
        let _: serde_json::Value = self
            .post(
                &format!("/api/infra/variables/{variable_id}/seal"),
                &serde_json::json!({}),
            )
            .await?;
        Ok(())
    }

    pub async fn remove_variable(&self, variable_id: &str) -> Result<()> {
        self.delete(&format!("/api/infra/variables/{variable_id}"))
            .await
    }

    pub async fn reveal_variable(&self, variable_id: &str) -> Result<String> {
        Ok(self
            .post::<RevealedVariable, _>(
                &format!("/api/infra/variables/{variable_id}/reveal"),
                &serde_json::json!({}),
            )
            .await?
            .value)
    }

    pub async fn connect(&self, consumer_id: &str, provider_id: &str) -> Result<Connection> {
        Ok(self
            .post::<ConnectionMade, _>(
                &format!("/api/infra/services/{consumer_id}/connections"),
                &serde_json::json!({ "providerId": provider_id }),
            )
            .await?
            .connection)
    }

    pub async fn add_domain(
        &self,
        service_environment_id: &str,
        host: Option<&str>,
    ) -> Result<Domain> {
        #[derive(serde::Deserialize)]
        struct Added {
            domain: Domain,
        }

        let body = match host {
            Some(host) => serde_json::json!({ "host": host }),
            None => serde_json::json!({}),
        };

        Ok(self
            .post::<Added, _>(
                &format!("/api/infra/services/{service_environment_id}/domains"),
                &body,
            )
            .await?
            .domain)
    }

    pub async fn remove_domain(&self, domain_id: &str) -> Result<()> {
        self.delete(&format!("/api/infra/domains/{domain_id}"))
            .await
    }

    pub async fn create_service(&self, project_id: &str, draft: &NewService) -> Result<String> {
        #[derive(serde::Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Created {
            service_id: String,
        }

        Ok(self
            .post::<Created, _>(&format!("/api/infra/projects/{project_id}/services"), draft)
            .await?
            .service_id)
    }

    // ------------------------------------------------- settings & capacity

    pub async fn capacity(&self) -> Result<Capacity> {
        self.get("/api/infra/capacity").await
    }

    /// Changes only the fields that were given; the rest are left alone.
    pub async fn update_settings(
        &self,
        service_environment_id: &str,
        patch: &SettingsPatch,
    ) -> Result<()> {
        self.patch(
            &format!("/api/infra/services/{service_environment_id}"),
            patch,
        )
        .await
    }

    /// Turns bucket encryption on or off, and reports what it moved.
    pub async fn set_encryption(
        &self,
        service_environment_id: &str,
        enabled: bool,
    ) -> Result<EncryptionOutcome> {
        self.put(
            &format!("/api/infra/services/{service_environment_id}/encryption"),
            &serde_json::json!({ "enabled": enabled }),
        )
        .await
    }

    /// Publishes a service on the internet, or takes it off.
    ///
    /// Off removes its hostnames; the project network is untouched, because
    /// that part was never optional.
    pub async fn set_public_access(
        &self,
        service_environment_id: &str,
        public_access: bool,
    ) -> Result<ExposureOutcome> {
        self.put(
            &format!("/api/infra/services/{service_environment_id}/public-access"),
            &serde_json::json!({ "publicAccess": public_access }),
        )
        .await
    }

    pub async fn delete_service(&self, service_id: &str) -> Result<()> {
        self.delete(&format!("/api/infra/services/{service_id}"))
            .await
    }

    // -------------------------------------------------------------- projects

    /// With no workspace named, the server puts it in the caller's own.
    pub async fn create_project(
        &self,
        name: &str,
        description: Option<&str>,
        workspace_id: Option<&str>,
    ) -> Result<Project> {
        let mut body = serde_json::Map::new();
        body.insert("name".into(), name.into());
        if let Some(description) = description {
            body.insert("description".into(), description.into());
        }
        if let Some(workspace_id) = workspace_id {
            body.insert("workspaceId".into(), workspace_id.into());
        }

        Ok(self
            .post::<ProjectCreated, _>("/api/infra/projects", &serde_json::Value::Object(body))
            .await?
            .project)
    }

    /// An absent field keeps what the project already has, which is why the
    /// description is optional rather than emptied by omission.
    pub async fn rename_project(
        &self,
        project_id: &str,
        name: Option<&str>,
        description: Option<&str>,
    ) -> Result<()> {
        let mut body = serde_json::Map::new();
        if let Some(name) = name {
            body.insert("name".into(), name.into());
        }
        if let Some(description) = description {
            body.insert("description".into(), description.into());
        }

        self.patch(
            &format!("/api/infra/projects/{project_id}"),
            &serde_json::Value::Object(body),
        )
        .await
    }

    pub async fn archive_project(&self, project_id: &str) -> Result<()> {
        self.delete(&format!("/api/infra/projects/{project_id}"))
            .await
    }

    pub async fn move_project(&self, project_id: &str, workspace_id: &str) -> Result<()> {
        self.patch(
            &format!("/api/infra/projects/{project_id}/workspace"),
            &serde_json::json!({ "workspaceId": workspace_id }),
        )
        .await
    }

    /// Undoes a connection, which means deleting the variable references that
    /// were the whole of it. The count is what to report.
    pub async fn disconnect(&self, consumer_id: &str, provider_id: &str) -> Result<u32> {
        Ok(self
            .delete_for::<Disconnected>(&format!(
                "/api/infra/services/{consumer_id}/connections/{provider_id}"
            ))
            .await?
            .removed)
    }

    // --------------------------------------------------------------- volumes

    pub async fn volumes(&self, service_environment_id: &str) -> Result<Vec<Volume>> {
        Ok(self
            .get::<VolumesPage>(&format!(
                "/api/infra/services/{service_environment_id}/volumes"
            ))
            .await?
            .volumes)
    }

    pub async fn attach_volume(
        &self,
        service_environment_id: &str,
        mount_path: &str,
    ) -> Result<Volume> {
        Ok(self
            .post::<VolumeAttached, _>(
                &format!("/api/infra/services/{service_environment_id}/volumes"),
                &serde_json::json!({ "mountPath": mount_path }),
            )
            .await?
            .volume)
    }

    pub async fn detach_volume(&self, volume_id: &str) -> Result<()> {
        self.delete(&format!("/api/infra/volumes/{volume_id}"))
            .await
    }

    // ---------------------------------------------------------------- builds

    pub async fn recipe(&self, service_environment_id: &str) -> Result<Recipe> {
        self.get(&format!(
            "/api/infra/services/{service_environment_id}/recipe"
        ))
        .await
    }

    /// Once edited, never regenerated: what shipped is always what was on
    /// screen. The server says so by answering `edited`.
    pub async fn edit_recipe(
        &self,
        service_environment_id: &str,
        containerfile: &str,
    ) -> Result<String> {
        Ok(self
            .put::<EditedRecipe, _>(
                &format!("/api/infra/services/{service_environment_id}/recipe"),
                &serde_json::json!({ "containerfile": containerfile }),
            )
            .await?
            .source)
    }

    /// One request for the whole file: fifty keys set one at a time is fifty
    /// audit entries and fifty chances to stop halfway.
    pub async fn import_variables(
        &self,
        service_environment_id: &str,
        variables: &[VariableDraft],
    ) -> Result<u32> {
        let imported: ImportedVariables = self
            .post(
                &format!("/api/infra/services/{service_environment_id}/variables/import"),
                &serde_json::json!({ "variables": variables }),
            )
            .await?;

        // A server that does not count them back is not a failure; what was
        // asked for is what to report.
        Ok(match imported.imported {
            0 => variables.len() as u32,
            counted => counted,
        })
    }

    // ----------------------------------------------------------- workspaces

    pub async fn workspaces(&self) -> Result<Vec<Workspace>> {
        Ok(self
            .get::<WorkspacesPage>("/api/infra/workspaces")
            .await?
            .workspaces)
    }

    /// The same id-or-slug-or-name lookup projects get, for the same reason.
    ///
    /// With no reference it answers the first one, which is the workspace
    /// somebody created rather than one they were invited into — the same
    /// default the server applies when a request does not name one.
    pub async fn find_workspace(&self, reference: Option<&str>) -> Result<Workspace> {
        let workspaces = self.workspaces().await?;

        let Some(reference) = reference else {
            return workspaces
                .into_iter()
                .next()
                .ok_or_else(|| anyhow!("this account is in no workspace"));
        };

        let needle = reference.to_lowercase();
        let matched: Vec<Workspace> = workspaces
            .into_iter()
            .filter(|workspace| {
                workspace.id == reference
                    || workspace.slug.to_lowercase() == needle
                    || workspace.name.to_lowercase() == needle
            })
            .collect();

        match matched.len() {
            0 => Err(anyhow!("there is no workspace called `{reference}`")),
            1 => Ok(matched.into_iter().next().expect("length checked")),
            other => Err(anyhow!(
                "`{reference}` matches {other} workspaces — use the id"
            )),
        }
    }

    pub async fn members(&self, workspace_id: &str) -> Result<Vec<Member>> {
        Ok(self
            .get::<MembersPage>(&format!("/api/infra/workspaces/{workspace_id}/members"))
            .await?
            .members)
    }

    pub async fn invitations(&self, workspace_id: &str) -> Result<Vec<Invitation>> {
        Ok(self
            .get::<InvitationsPage>(&format!("/api/infra/workspaces/{workspace_id}/invitations"))
            .await?
            .invitations)
    }

    pub async fn invite(
        &self,
        workspace_id: &str,
        email: &str,
        role: &str,
    ) -> Result<SentInvitation> {
        self.post(
            &format!("/api/infra/workspaces/{workspace_id}/invitations"),
            &NewInvitation {
                email: email.to_string(),
                role: role.to_string(),
            },
        )
        .await
    }

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

    pub async fn remove_member(&self, workspace_id: &str, user_id: &str) -> Result<()> {
        self.delete(&format!(
            "/api/infra/workspaces/{workspace_id}/members/{user_id}"
        ))
        .await
    }

    // ------------------------------------------------------------ streaming

    /// Replays and then follows a deployment's log.
    ///
    /// Server-sent events parsed by hand rather than through a crate: the whole
    /// format this needs is `event:`, `data:` and a blank line, and a
    /// dependency for forty lines of splitting is a dependency to update.
    pub async fn stream_log<F>(&self, deployment_id: &str, after: u64, mut on_line: F) -> Result<()>
    where
        F: FnMut(LogLine),
    {
        let response = self
            .streaming_request(&format!(
                "/api/infra/deployments/{deployment_id}/log/stream?after={after}"
            ))
            .send()
            .await?;

        if !response.status().is_success() {
            Self::check(response).await?;
            return Ok(());
        }

        let mut stream = response.bytes_stream();
        let mut buffer = String::new();

        while let Some(chunk) = stream.next().await {
            buffer.push_str(&String::from_utf8_lossy(&chunk?));

            // Events are separated by a blank line; anything after the last one
            // is a partial event and stays in the buffer for the next chunk.
            while let Some(boundary) = buffer.find("\n\n") {
                let event: String = buffer.drain(..boundary + 2).collect();
                if let Some(line) = parse_log_event(&event) {
                    on_line(line);
                }
                if event.contains("event: end") {
                    return Ok(());
                }
            }
        }

        Ok(())
    }

    /// Everything the platform is doing, until Ctrl-C.
    ///
    /// The same stream the web interface holds open, filtered by the same guard:
    /// what arrives here is what this token's owner is allowed to see, decided
    /// on the server. It never ends on its own — there is no `event: end` on a
    /// firehose — so the loop runs until the process is stopped or the socket
    /// drops.
    pub async fn stream_events<F>(&self, mut on_event: F) -> Result<()>
    where
        F: FnMut(InfraEvent),
    {
        let response = self.streaming_request("/api/infra/stream").send().await?;

        if !response.status().is_success() {
            Self::check(response).await?;
            return Ok(());
        }

        let mut stream = response.bytes_stream();
        let mut buffer = String::new();

        while let Some(chunk) = stream.next().await {
            buffer.push_str(&String::from_utf8_lossy(&chunk?));

            while let Some(boundary) = buffer.find("\n\n") {
                let event: String = buffer.drain(..boundary + 2).collect();
                // `ready` carries the connection id, which is presence's
                // business and a terminal has no field to focus.
                if event.contains("event: infra") {
                    if let Some(parsed) = parse_infra_event(&event) {
                        on_event(parsed);
                    }
                }
            }
        }

        Ok(())
    }

    /// One page of log history, for the non-following case.
    pub async fn read_log(&self, deployment_id: &str, after: u64) -> Result<Vec<LogLine>> {
        Ok(self
            .get::<LogPage>(&format!(
                "/api/infra/deployments/{deployment_id}/log?after={after}"
            ))
            .await?
            .lines)
    }
}

/// The `data:` payload of one event, when it is a log line.
fn parse_log_event(event: &str) -> Option<LogLine> {
    serde_json::from_str::<LogLine>(&payload_of(event)?).ok()
}

/// The same, for the firehose the whole platform publishes onto.
fn parse_infra_event(event: &str) -> Option<InfraEvent> {
    serde_json::from_str::<InfraEvent>(&payload_of(event)?).ok()
}

/// The `data:` lines of one event, rejoined.
///
/// Several because a payload containing a newline is split across them on the
/// way out, and reading only the first would truncate it silently.
fn payload_of(event: &str) -> Option<String> {
    let payload: String = event
        .lines()
        .filter_map(|line| line.strip_prefix("data:"))
        .map(str::trim_start)
        .collect::<Vec<_>>()
        .join("\n");

    if payload.is_empty() {
        None
    } else {
        Some(payload)
    }
}

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

    #[test]
    fn it_should_read_a_log_line_out_of_an_event() {
        let event = "id: 4\nevent: infra\ndata: {\"sequence\":4,\"stream\":\"build\",\"level\":\"info\",\"message\":\"hello\"}\n\n";
        assert_eq!(parse_log_event(event).unwrap().message, "hello");
    }

    #[test]
    fn it_should_ignore_an_event_with_no_data() {
        assert!(parse_log_event("event: end\n\n").is_none());
    }

    #[test]
    fn it_should_read_a_deployment_out_of_an_infra_event() {
        let event = "event: infra\ndata: {\"kind\":\"deployment-status\",\"projectId\":\"prj_1\",\"status\":\"queued\",\"trigger\":\"git-push\",\"serviceName\":\"api\"}\n\n";
        assert_eq!(
            parse_infra_event(event).unwrap().service_name.unwrap(),
            "api"
        );
    }

    /// A client that refused what it does not draw would stop working the day
    /// the server learns to publish a seventh kind.
    #[test]
    fn it_should_read_an_event_whose_kind_it_has_never_heard_of() {
        let event = "event: infra\ndata: {\"kind\":\"something-new\",\"projectId\":\"prj_1\"}\n\n";
        assert_eq!(parse_infra_event(event).unwrap().kind, "something-new");
    }

    #[test]
    fn it_should_ignore_an_event_whose_data_is_not_a_log_line() {
        assert!(parse_log_event("data: {\"kind\":\"usage\"}\n\n").is_none());
    }

    #[test]
    fn it_should_join_a_payload_split_across_several_data_lines() {
        let event = "data: {\"sequence\":1,\"message\":\n data: \"split\"}\n\n";
        // Malformed on purpose: the point is that it does not panic.
        let _ = parse_log_event(event);
    }
}