hot-dev 1.1.3

Official Rust SDK for the Hot Dev API
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
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
//! Resource namespaces mirroring the Hot API v1 resources. This module is a
//! port of hot-python's resources.py.

use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;

use futures_util::StreamExt;
use reqwest::header::{ACCEPT, CONTENT_TYPE};
use reqwest::multipart::{Form, Part};
use reqwest::{Method, Response};
use serde::Serialize;
use serde_json::{json, Value};

use crate::streaming::{
    extract_run_result, iter_stream, wait_for_run_result, EventStream, StreamEventExt,
};
use crate::transport::{data_object, decode_data_response, enc, enc_path, Transport};
use crate::{Error, JsonObject, Result};

/// Optional parameters for [`StreamsResource::subscribe_with_event`].
pub struct SubscribeWithEventOptions {
    /// Scopes the subscription to a project id or slug.
    pub project: Option<String>,
    /// Automatically resubscribe across the API's 5-minute SSE timeout.
    pub reconnect: bool,
    /// Caps reconnection attempts.
    pub max_attempts: u32,
}

impl Default for SubscribeWithEventOptions {
    fn default() -> Self {
        SubscribeWithEventOptions {
            project: None,
            reconnect: true,
            max_attempts: 5,
        }
    }
}

/// Optional parameters for [`StreamsResource::wait_for_run_result`].
pub struct WaitOptions<'a> {
    /// Bounds the wait.
    pub timeout: Duration,
    /// Receives streamed text chunks from the matched run.
    pub on_chunk: Option<&'a mut (dyn FnMut(&str) + Send)>,
}

impl Default for WaitOptions<'_> {
    fn default() -> Self {
        WaitOptions {
            timeout: Duration::from_secs(60),
            on_chunk: None,
        }
    }
}

/// Optional parameters for [`EventsResource::call_hot`].
pub struct CallOptions<'a> {
    /// Bounds the wait for the run result.
    pub timeout: Duration,
    /// Receives streamed text chunks from the run.
    pub on_chunk: Option<&'a mut (dyn FnMut(&str) + Send)>,
}

impl Default for CallOptions<'_> {
    fn default() -> Self {
        CallOptions {
            timeout: Duration::from_secs(60),
            on_chunk: None,
        }
    }
}

/// A build archive to upload.
pub struct BuildUpload {
    /// The build archive content.
    pub content: Vec<u8>,
    /// Names the multipart file part. Defaults to "build".
    pub filename: Option<String>,
    /// The build content hash.
    pub hash: String,
    /// Optionally pins the build id.
    pub build_id: Option<String>,
}

macro_rules! resource {
    ($(#[$doc:meta])* $name:ident) => {
        $(#[$doc])*
        pub struct $name {
            transport: Arc<Transport>,
        }

        impl $name {
            pub(crate) fn new(transport: Arc<Transport>) -> Self {
                Self { transport }
            }
        }
    };
}

resource!(
    /// Publishes and inspects Hot events.
    EventsResource
);
resource!(
    /// Lists and inspects runs.
    RunsResource
);
resource!(
    /// Reads environment info and environment events.
    EnvResource
);
resource!(
    /// Reports organization usage and limits.
    OrgResource
);
resource!(
    /// Subscribes to Hot run streams.
    StreamsResource
);
resource!(
    /// Uploads, downloads, lists, and deletes files.
    FilesResource
);
resource!(
    /// Manages projects.
    ProjectsResource
);
resource!(
    /// Uploads, deploys, and inspects builds.
    BuildsResource
);
resource!(
    /// Manages encrypted project context variables.
    ContextResource
);
resource!(
    /// Manages custom domains.
    DomainsResource
);
resource!(
    /// Creates and revokes scoped sessions.
    SessionsResource
);
resource!(
    /// Creates and revokes scoped service keys.
    ServiceKeysResource
);

impl EventsResource {
    /// Publishes an event and returns the created event data
    /// (event_id, stream_id, ...).
    pub async fn publish(&self, body: impl Serialize) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(
                Method::POST,
                "/events",
                Some(&serde_json::to_value(body)?),
                &[],
            )
            .await?;
        Ok(data_object(envelope))
    }

    /// Publishes a hot:call event for `fn_name` with `args` and waits for the
    /// run result, unwrapping a `{"$ok": ...}` result value.
    pub async fn call_hot(
        &self,
        fn_name: &str,
        args: Vec<Value>,
        opts: CallOptions<'_>,
    ) -> Result<Value> {
        let body = json!({
            "event_type": "hot:call",
            "event_data": { "fn": fn_name, "args": args },
        });
        let Value::Object(body) = body else {
            unreachable!()
        };
        let published = self.publish(body).await?;

        let stream_id = string_field(&published, "stream_id");
        let event_id = string_field(&published, "event_id");
        let run = wait_for_run_result(
            self.transport.clone(),
            &stream_id,
            &event_id,
            opts.timeout,
            opts.on_chunk,
        )
        .await?;
        Ok(extract_run_result(run.get("result").cloned()))
    }

    /// Returns the event list envelope (data + pagination).
    pub async fn list(&self, query: &[(&str, &str)]) -> Result<JsonObject> {
        self.transport
            .request_json(Method::GET, "/events", None, query)
            .await
    }

    /// Returns a single event.
    pub async fn get(&self, event_id: &str) -> Result<JsonObject> {
        let path = format!("/events/{}", enc(event_id));
        let envelope = self
            .transport
            .request_json(Method::GET, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Returns the runs triggered by an event.
    pub async fn get_runs(&self, event_id: &str) -> Result<JsonObject> {
        let path = format!("/events/{}/runs", enc(event_id));
        self.transport
            .request_json(Method::GET, &path, None, &[])
            .await
    }
}

impl RunsResource {
    /// Returns the run list envelope (data + pagination).
    pub async fn list(&self, query: &[(&str, &str)]) -> Result<JsonObject> {
        self.transport
            .request_json(Method::GET, "/runs", None, query)
            .await
    }

    /// Returns aggregate run statistics.
    pub async fn stats(&self) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(Method::GET, "/runs/stats", None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Returns a single run.
    pub async fn get(&self, run_id: &str) -> Result<JsonObject> {
        let path = format!("/runs/{}", enc(run_id));
        let envelope = self
            .transport
            .request_json(Method::GET, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }
}

impl EnvResource {
    /// Returns environment info.
    pub async fn get(&self) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(Method::GET, "/env", None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Streams environment events. Requires API key credentials and a live
    /// API pub/sub backend.
    pub fn subscribe(&self) -> EventStream {
        iter_stream(
            self.transport.clone(),
            Method::GET,
            "/env/subscribe".to_string(),
            None,
            Vec::new(),
        )
    }
}

impl OrgResource {
    /// Returns organization usage and limits.
    pub async fn usage(&self) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(Method::GET, "/org/usage", None, &[])
            .await?;
        Ok(data_object(envelope))
    }
}

impl StreamsResource {
    /// Streams events from an existing run stream.
    pub fn subscribe(&self, stream_id: &str, project: Option<&str>) -> EventStream {
        iter_stream(
            self.transport.clone(),
            Method::GET,
            format!("/streams/{}/subscribe", enc(stream_id)),
            None,
            project_query(project),
        )
    }

    /// Streams events from an existing run stream via POST.
    pub fn subscribe_post(&self, stream_id: &str, project: Option<&str>) -> EventStream {
        iter_stream(
            self.transport.clone(),
            Method::POST,
            format!("/streams/{}/subscribe", enc(stream_id)),
            None,
            project_query(project),
        )
    }

    /// Subscribes to a stream and returns the run object once the run created
    /// by `event_id` reaches run:stop. run:fail and run:cancel become
    /// [`Error::RunFailed`] carrying the run's result message.
    pub async fn wait_for_run_result(
        &self,
        stream_id: &str,
        event_id: &str,
        opts: WaitOptions<'_>,
    ) -> Result<JsonObject> {
        wait_for_run_result(
            self.transport.clone(),
            stream_id,
            event_id,
            opts.timeout,
            opts.on_chunk,
        )
        .await
    }

    /// Atomically subscribes then publishes an event, yielding stream events
    /// until the run completes.
    ///
    /// The Hot API closes SSE subscriptions after 5 minutes of idle time.
    /// While `opts.reconnect` is true (the default), the SDK resubscribes to
    /// the same stream_id and keeps yielding events until a terminal
    /// run:stop/run:fail/run:cancel arrives. Replayed run:start and terminal
    /// events are deduped by run_id; stream:data chunks are not replayed and
    /// may be lost across the disconnect window.
    pub fn subscribe_with_event(
        &self,
        body: impl Serialize,
        opts: SubscribeWithEventOptions,
    ) -> EventStream {
        let body = match serde_json::to_value(body) {
            Ok(body) => body,
            Err(error) => {
                return Box::pin(async_stream::stream! { yield Err(Error::Json(error)) });
            }
        };
        let transport = self.transport.clone();
        let query = project_query(opts.project.as_deref());
        let once = move |transport: Arc<Transport>, query: Vec<(String, String)>| {
            iter_stream(
                transport,
                Method::POST,
                "/streams/subscribe-with-event".to_string(),
                Some(body.clone()),
                query,
            )
        };

        if !opts.reconnect {
            return once(transport, query);
        }

        Box::pin(async_stream::stream! {
            let mut seen_start: HashSet<String> = HashSet::new();
            let mut seen_terminal: HashSet<String> = HashSet::new();
            let mut stream_id: Option<String> = None;
            let mut attempts: u32 = 0;

            loop {
                let mut source = match &stream_id {
                    None => once(transport.clone(), query.clone()),
                    Some(id) => iter_stream(
                        transport.clone(),
                        Method::GET,
                        format!("/streams/{}/subscribe", enc(id)),
                        None,
                        query.clone(),
                    ),
                };

                let mut terminal = false;
                while let Some(item) = source.next().await {
                    let event = match item {
                        Ok(event) => event,
                        Err(error) => {
                            if stream_id.is_none() || attempts >= opts.max_attempts {
                                yield Err(error);
                                return;
                            }
                            break;
                        }
                    };

                    match event.event_type() {
                        "event:published" => {
                            if let Some(published) =
                                event.get("stream_id").and_then(Value::as_str)
                            {
                                stream_id = Some(published.to_string());
                            }
                        }
                        "run:start" => {
                            let run_id = event.run_id().map(str::to_string);
                            if let Some(run_id) = run_id {
                                if !seen_start.insert(run_id) {
                                    continue;
                                }
                            }
                        }
                        "run:stop" | "run:fail" | "run:cancel" => {
                            let run_id = event.run_id().map(str::to_string);
                            if let Some(run_id) = run_id {
                                if !seen_terminal.insert(run_id) {
                                    continue;
                                }
                            }
                            terminal = true;
                        }
                        _ => {}
                    }

                    yield Ok(event);
                }

                if terminal {
                    return;
                }
                if stream_id.is_none() {
                    yield Err(Error::Protocol(
                        "stream ended before event:published was received".to_string(),
                    ));
                    return;
                }

                attempts += 1;
                let delay = Duration::from_millis((250 * u64::from(attempts)).min(2000));
                tokio::time::sleep(delay).await;
            }
        })
    }
}

impl FilesResource {
    /// Returns the file list envelope (data + pagination).
    pub async fn list(&self, query: &[(&str, &str)]) -> Result<JsonObject> {
        self.transport
            .request_json(Method::GET, "/files", None, query)
            .await
    }

    /// Returns a single file's metadata.
    pub async fn get(&self, file_id: &str) -> Result<JsonObject> {
        let path = format!("/files/{}", enc(file_id));
        let envelope = self
            .transport
            .request_json(Method::GET, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Deletes a file.
    pub async fn delete(&self, file_id: &str) -> Result<()> {
        let path = format!("/files/{}", enc(file_id));
        let builder = self.transport.request_builder(Method::DELETE, &path);
        self.transport.execute(builder).await?;
        Ok(())
    }

    /// Returns the raw HTTP response streaming the file content.
    pub async fn download(&self, file_id: &str) -> Result<Response> {
        let path = format!("/files/{}/download", enc(file_id));
        let builder = self.transport.request_builder(Method::GET, &path);
        self.transport.execute(builder).await
    }

    /// Uploads content to a slash-separated file path.
    pub async fn upload(
        &self,
        path: &str,
        content: Vec<u8>,
        content_type: Option<&str>,
    ) -> Result<JsonObject> {
        let request_path = format!("/files/upload/{}", enc_path(path));
        let mut builder = self
            .transport
            .request_builder(Method::PUT, &request_path)
            .header(ACCEPT, "application/json")
            .body(content);
        if let Some(content_type) = content_type {
            builder = builder.header(CONTENT_TYPE, content_type);
        }
        let response = self.transport.execute(builder).await?;
        decode_data_response(response).await
    }

    /// Starts a multipart upload.
    pub async fn initiate_upload(&self, body: impl Serialize) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(
                Method::POST,
                "/files/uploads",
                Some(&serde_json::to_value(body)?),
                &[],
            )
            .await?;
        Ok(data_object(envelope))
    }

    /// Uploads one part of a multipart upload.
    pub async fn upload_part(
        &self,
        upload_id: &str,
        part_number: u32,
        content: Vec<u8>,
    ) -> Result<JsonObject> {
        let path = format!("/files/uploads/{}/{}", enc(upload_id), part_number);
        let builder = self
            .transport
            .request_builder(Method::PUT, &path)
            .header(ACCEPT, "application/json")
            .body(content);
        let response = self.transport.execute(builder).await?;
        decode_data_response(response).await
    }

    /// Finishes a multipart upload.
    pub async fn complete_upload(&self, upload_id: &str) -> Result<JsonObject> {
        let path = format!("/files/uploads/{}/complete", enc(upload_id));
        let envelope = self
            .transport
            .request_json(Method::POST, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Cancels a multipart upload.
    pub async fn abort_upload(&self, upload_id: &str) -> Result<()> {
        let path = format!("/files/uploads/{}", enc(upload_id));
        let builder = self.transport.request_builder(Method::DELETE, &path);
        self.transport.execute(builder).await?;
        Ok(())
    }
}

impl ProjectsResource {
    /// Returns the project list envelope (data + pagination).
    pub async fn list(&self, query: &[(&str, &str)]) -> Result<JsonObject> {
        self.transport
            .request_json(Method::GET, "/projects", None, query)
            .await
    }

    /// Creates a project.
    pub async fn create(&self, body: impl Serialize) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(
                Method::POST,
                "/projects",
                Some(&serde_json::to_value(body)?),
                &[],
            )
            .await?;
        Ok(data_object(envelope))
    }

    /// Returns a project by id or slug.
    pub async fn get(&self, project: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}", enc(project));
        let envelope = self
            .transport
            .request_json(Method::GET, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Patches a project.
    pub async fn update(&self, project: &str, body: impl Serialize) -> Result<JsonObject> {
        let path = format!("/projects/{}", enc(project));
        let envelope = self
            .transport
            .request_json(
                Method::PATCH,
                &path,
                Some(&serde_json::to_value(body)?),
                &[],
            )
            .await?;
        Ok(data_object(envelope))
    }

    /// Deletes a project.
    pub async fn delete(&self, project: &str) -> Result<()> {
        let path = format!("/projects/{}", enc(project));
        let builder = self.transport.request_builder(Method::DELETE, &path);
        self.transport.execute(builder).await?;
        Ok(())
    }

    /// Activates a project.
    pub async fn activate(&self, project: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}/activate", enc(project));
        let envelope = self
            .transport
            .request_json(Method::POST, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Deactivates a project.
    pub async fn deactivate(&self, project: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}/deactivate", enc(project));
        let envelope = self
            .transport
            .request_json(Method::POST, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Returns the project's event handlers.
    pub async fn event_handlers(&self, project: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}/event-handlers", enc(project));
        self.transport
            .request_json(Method::GET, &path, None, &[])
            .await
    }

    /// Returns the project's schedules.
    pub async fn schedules(&self, project: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}/schedules", enc(project));
        self.transport
            .request_json(Method::GET, &path, None, &[])
            .await
    }
}

impl BuildsResource {
    /// Returns the build list envelope across all projects.
    pub async fn list(&self, query: &[(&str, &str)]) -> Result<JsonObject> {
        self.transport
            .request_json(Method::GET, "/builds", None, query)
            .await
    }

    /// Returns the build list envelope for one project.
    pub async fn list_for_project(
        &self,
        project: &str,
        query: &[(&str, &str)],
    ) -> Result<JsonObject> {
        let path = format!("/projects/{}/builds", enc(project));
        self.transport
            .request_json(Method::GET, &path, None, query)
            .await
    }

    /// Returns a single build.
    pub async fn get(&self, project: &str, build_id: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}/builds/{}", enc(project), enc(build_id));
        let envelope = self
            .transport
            .request_json(Method::GET, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Returns the project's deployed build.
    pub async fn deployed(&self, project: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}/builds/deployed", enc(project));
        let envelope = self
            .transport
            .request_json(Method::GET, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Returns the project's live build.
    pub async fn live(&self, project: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}/builds/live", enc(project));
        let envelope = self
            .transport
            .request_json(Method::GET, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Uploads a build archive as multipart form data.
    pub async fn upload(&self, project: &str, upload: BuildUpload) -> Result<JsonObject> {
        let mut form = Form::new().text("hash", upload.hash);
        if let Some(build_id) = upload.build_id {
            form = form.text("build_id", build_id);
        }
        let part = Part::bytes(upload.content)
            .file_name(upload.filename.unwrap_or_else(|| "build".to_string()));
        form = form.part("file", part);

        let path = format!("/projects/{}/builds", enc(project));
        let builder = self
            .transport
            .request_builder(Method::POST, &path)
            .header(ACCEPT, "application/json")
            .multipart(form);
        let response = self.transport.execute(builder).await?;
        decode_data_response(response).await
    }

    /// Returns the raw HTTP response streaming the build archive.
    pub async fn download(&self, project: &str, build_id: &str) -> Result<Response> {
        let path = format!(
            "/projects/{}/builds/{}/download",
            enc(project),
            enc(build_id)
        );
        let builder = self.transport.request_builder(Method::GET, &path);
        self.transport.execute(builder).await
    }

    /// Deploys a build.
    pub async fn deploy(&self, project: &str, build_id: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}/builds/{}/deploy", enc(project), enc(build_id));
        let envelope = self
            .transport
            .request_json(Method::POST, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }
}

impl ContextResource {
    /// Returns the context variable list envelope for a project.
    pub async fn list(&self, project: &str) -> Result<JsonObject> {
        let path = format!("/projects/{}/context", enc(project));
        self.transport
            .request_json(Method::GET, &path, None, &[])
            .await
    }

    /// Creates a context variable.
    pub async fn create(&self, project: &str, body: impl Serialize) -> Result<JsonObject> {
        let path = format!("/projects/{}/context", enc(project));
        let envelope = self
            .transport
            .request_json(Method::POST, &path, Some(&serde_json::to_value(body)?), &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Replaces a context variable.
    pub async fn update(
        &self,
        project: &str,
        key: &str,
        body: impl Serialize,
    ) -> Result<JsonObject> {
        let path = format!("/projects/{}/context/{}", enc(project), enc(key));
        let envelope = self
            .transport
            .request_json(Method::PUT, &path, Some(&serde_json::to_value(body)?), &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Deletes a context variable.
    pub async fn delete(&self, project: &str, key: &str) -> Result<()> {
        let path = format!("/projects/{}/context/{}", enc(project), enc(key));
        let builder = self.transport.request_builder(Method::DELETE, &path);
        self.transport.execute(builder).await?;
        Ok(())
    }
}

impl DomainsResource {
    /// Registers a custom domain.
    pub async fn create(&self, body: impl Serialize) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(
                Method::POST,
                "/domains",
                Some(&serde_json::to_value(body)?),
                &[],
            )
            .await?;
        Ok(data_object(envelope))
    }

    /// Returns the domain list envelope.
    pub async fn list(&self) -> Result<JsonObject> {
        self.transport
            .request_json(Method::GET, "/domains", None, &[])
            .await
    }

    /// Returns a single domain.
    pub async fn get(&self, domain_id: &str) -> Result<JsonObject> {
        let path = format!("/domains/{}", enc(domain_id));
        let envelope = self
            .transport
            .request_json(Method::GET, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Deletes a domain.
    pub async fn delete(&self, domain_id: &str) -> Result<()> {
        let path = format!("/domains/{}", enc(domain_id));
        let builder = self.transport.request_builder(Method::DELETE, &path);
        self.transport.execute(builder).await?;
        Ok(())
    }

    /// Triggers domain verification.
    pub async fn verify(&self, domain_id: &str) -> Result<JsonObject> {
        let path = format!("/domains/{}/verify", enc(domain_id));
        let envelope = self
            .transport
            .request_json(Method::POST, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }
}

impl SessionsResource {
    /// Creates a scoped session.
    pub async fn create(&self, body: impl Serialize) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(
                Method::POST,
                "/sessions",
                Some(&serde_json::to_value(body)?),
                &[],
            )
            .await?;
        Ok(data_object(envelope))
    }

    /// Returns the session list envelope.
    pub async fn list(&self, query: &[(&str, &str)]) -> Result<JsonObject> {
        self.transport
            .request_json(Method::GET, "/sessions", None, query)
            .await
    }

    /// Revokes one session.
    pub async fn revoke(&self, session_id: &str) -> Result<()> {
        let path = format!("/sessions/{}", enc(session_id));
        let builder = self.transport.request_builder(Method::DELETE, &path);
        self.transport.execute(builder).await?;
        Ok(())
    }

    /// Revokes every session.
    pub async fn revoke_all(&self) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(Method::DELETE, "/sessions", None, &[])
            .await?;
        Ok(data_object(envelope))
    }
}

impl ServiceKeysResource {
    /// Creates a scoped service key.
    pub async fn create(&self, body: impl Serialize) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(
                Method::POST,
                "/service-keys",
                Some(&serde_json::to_value(body)?),
                &[],
            )
            .await?;
        Ok(data_object(envelope))
    }

    /// Returns the service key list envelope.
    pub async fn list(&self, query: &[(&str, &str)]) -> Result<JsonObject> {
        self.transport
            .request_json(Method::GET, "/service-keys", None, query)
            .await
    }

    /// Returns a single service key.
    pub async fn get(&self, service_key_id: &str) -> Result<JsonObject> {
        let path = format!("/service-keys/{}", enc(service_key_id));
        let envelope = self
            .transport
            .request_json(Method::GET, &path, None, &[])
            .await?;
        Ok(data_object(envelope))
    }

    /// Patches a service key.
    pub async fn update(&self, service_key_id: &str, body: impl Serialize) -> Result<JsonObject> {
        let path = format!("/service-keys/{}", enc(service_key_id));
        let envelope = self
            .transport
            .request_json(
                Method::PATCH,
                &path,
                Some(&serde_json::to_value(body)?),
                &[],
            )
            .await?;
        Ok(data_object(envelope))
    }

    /// Revokes one service key.
    pub async fn revoke(&self, service_key_id: &str) -> Result<()> {
        let path = format!("/service-keys/{}", enc(service_key_id));
        let builder = self.transport.request_builder(Method::DELETE, &path);
        self.transport.execute(builder).await?;
        Ok(())
    }

    /// Revokes every service key.
    pub async fn revoke_all(&self) -> Result<JsonObject> {
        let envelope = self
            .transport
            .request_json(Method::DELETE, "/service-keys", None, &[])
            .await?;
        Ok(data_object(envelope))
    }
}

fn project_query(project: Option<&str>) -> Vec<(String, String)> {
    match project {
        Some(project) => vec![("project".to_string(), project.to_string())],
        None => Vec::new(),
    }
}

fn string_field(object: &JsonObject, key: &str) -> String {
    object
        .get(key)
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string()
}