stackmachine 0.1.0

Async Rust SDK for StackMachine.
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
//! Resource methods use snake_case Rust names and schema-derived input structs.
use crate::{
    Error, Page, Pagination, Result, StackMachine, inputs::*, models::*, operations as gql,
};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Value, json};

macro_rules! resources {
    ($($name:ident),+ $(,)?) => {$(
        #[derive(Clone, Copy)]
        pub struct $name<'a> { client: &'a StackMachine }
    )+};
}

resources!(
    Apps, Domains, Volumes, Databases, Cache, CronJobs, Git, Versions, Logs, Ssh, SshUsers,
    SshKeys, Dns, DnsDomains, DnsRecords, Emails, Packages, Usage
);

macro_rules! accessors {
    ($($method:ident: $resource:ident),+ $(,)?) => {$(
        pub fn $method(&self) -> $resource<'_> { $resource { client: self } }
    )+};
}

impl StackMachine {
    accessors!(apps: Apps, dns: Dns, emails: Emails, packages: Packages, usage: Usage);
}

macro_rules! children {
    ($($method:ident: $resource:ident),+ $(,)?) => {$(
        pub fn $method(&self) -> $resource<'a> { $resource { client: self.client } }
    )+};
}

macro_rules! mutations {
    ($($method:ident($input:ty) -> $output:ty = $query:ident, $pointer:literal);+ $(;)?) => {$(
        pub async fn $method(&self, input: &$input) -> Result<$output> {
            self.client.mutation(gql::$query, input, $pointer).await
        }
    )+};
}

#[derive(Clone, Debug)]
pub struct AppsListParams {
    pub owner_id: Option<String>,
    pub sort_by: DeployAppsSortBy,
    pub pagination: Pagination,
}

impl Default for AppsListParams {
    fn default() -> Self {
        Self {
            owner_id: None,
            sort_by: DeployAppsSortBy::Newest,
            pagination: Pagination::default(),
        }
    }
}

impl<'a> Apps<'a> {
    children!(domains: Domains, volumes: Volumes, databases: Databases, cache: Cache,
        cronjobs: CronJobs, git: Git, versions: Versions, logs: Logs, ssh: Ssh);

    pub async fn list(&self, params: AppsListParams) -> Result<Page<App>> {
        self.client
            .page(
                gql::LIST_APPS_QUERY,
                params
                    .pagination
                    .variables(json!({"ownerId": params.owner_id, "sortBy": params.sort_by}))?,
                "/getDeployApps",
            )
            .await
    }

    pub async fn retrieve(&self, id: &str) -> Result<App> {
        let mut apps = nodes(self.client, gql::GET_APPS_BY_IDS_QUERY, &[id], "DeployApp").await?;
        apps.pop()
            .flatten()
            .ok_or_else(|| Error::missing("app", id))
    }

    pub async fn retrieve_many(&self, ids: &[impl AsRef<str>]) -> Result<Vec<Option<App>>> {
        nodes(self.client, gql::GET_APPS_BY_IDS_QUERY, ids, "DeployApp").await
    }

    pub async fn retrieve_by_name(&self, name: &str, owner: Option<&str>) -> Result<App> {
        self.client
            .read(
                gql::GET_APP_BY_NAME_QUERY,
                json!({"name": name, "owner": owner}),
                "/app",
            )
            .await
    }

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client
            .delete(gql::DELETE_APP_MUTATION, json!({"id": id}), "deleteApp")
            .await
    }
}

impl Domains<'_> {
    pub async fn list(&self, app_id: &str, pagination: Pagination) -> Result<Page<AppDomain>> {
        self.client
            .page(
                gql::LIST_APP_DOMAINS_QUERY,
                pagination.variables(json!({"appId": app_id, "sortBy": "NEWEST"}))?,
                "/node/domains",
            )
            .await
    }

    pub async fn retrieve(&self, id: &str) -> Result<AppDomain> {
        nodes(self.client, gql::GET_APP_ALIASES_QUERY, &[id], "AppAlias")
            .await?
            .pop()
            .flatten()
            .ok_or_else(|| Error::missing("app domain", id))
    }

    pub async fn retrieve_many(&self, ids: &[impl AsRef<str>]) -> Result<Vec<Option<AppDomain>>> {
        nodes(self.client, gql::GET_APP_ALIASES_QUERY, ids, "AppAlias").await
    }

    mutations!(create(UpsertAppDomainInput) -> Vec<AppDomain> = UPSERT_APP_DOMAIN_MUTATION, "/upsertAppDomain/domains");

    pub async fn verify(&self, id: &str) -> Result<bool> {
        self.client
            .mutation(
                gql::VERIFY_APP_DOMAIN_MUTATION,
                json!({"domainId": id}),
                "/verifyAppDomain/verified",
            )
            .await
    }

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client
            .delete(
                gql::DELETE_APP_DOMAIN_MUTATION,
                json!({"id": id}),
                "deleteAppDomain",
            )
            .await
    }
}

impl Volumes<'_> {
    pub async fn list(&self, app_id: &str, pagination: Pagination) -> Result<Page<AppVolume>> {
        self.client
            .page(
                gql::LIST_APP_VOLUMES_QUERY,
                pagination.variables(json!({"appId": app_id}))?,
                "/node/volumes",
            )
            .await
    }

    mutations!(
        create(CreateAppVolumeInput) -> AppVolume = CREATE_APP_VOLUME_MUTATION, "/createAppVolume/volume";
        update(UpdateVolumeInput) -> AppVolume = UPDATE_VOLUME_MUTATION, "/updateVolume/volume"
    );

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client
            .delete(
                gql::DELETE_APP_VOLUME_MUTATION,
                json!({"id": id}),
                "deleteAppVolume",
            )
            .await
    }
}

impl Databases<'_> {
    pub async fn list(&self, app_id: &str, pagination: Pagination) -> Result<Page<AppDatabase>> {
        self.client
            .page(
                gql::LIST_APP_DATABASES_QUERY,
                pagination.variables(json!({"appId": app_id}))?,
                "/node/databases",
            )
            .await
    }

    mutations!(
        create(CreateAppDBInput) -> DatabaseCredentials = CREATE_APP_DATABASE_MUTATION, "/createAppDb";
        create_and_link(CreateAppDatabaseInput) -> DatabaseCredentials = CREATE_DATABASE_AND_LINK_TO_APP_MUTATION, "/createDatabaseAndLinkToApp"
    );

    pub async fn rotate_credentials(&self, id: &str) -> Result<DatabaseCredentials> {
        self.client
            .mutation(
                gql::ROTATE_APP_DATABASE_CREDENTIALS_MUTATION,
                json!({"id": id}),
                "/rotateCredentialsForAppDb",
            )
            .await
    }

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client
            .delete(
                gql::DELETE_APP_DATABASE_MUTATION,
                json!({"id": id}),
                "deleteAppDb",
            )
            .await
    }
}

impl Cache<'_> {
    pub async fn retrieve(&self, app_id: &str) -> Result<AppCache> {
        self.client
            .read(gql::GET_APP_CACHE_QUERY, json!({"id": app_id}), "/node")
            .await
    }

    pub async fn update(&self, app_id: &str, enabled: bool) -> Result<()> {
        success(
            self.client,
            gql::CONFIGURE_APP_CDN_CACHE_MUTATION,
            json!({"app": app_id, "config": {"enabled": enabled}}),
            "/configureAppCdnCache/success",
        )
        .await
    }

    pub async fn purge(&self, app_id: &str) -> Result<()> {
        success(
            self.client,
            gql::PURGE_APP_CDN_CACHE_MUTATION,
            json!({"app": app_id}),
            "/purgeAppCdnCache/success",
        )
        .await
    }
}

#[derive(Clone, Debug)]
pub struct CronJobsListParams {
    pub filter: Option<CronJobFilter>,
    pub order_by: CronJobOrderBy,
    pub direction: CronJobSortDirection,
    pub pagination: Pagination,
}

impl Default for CronJobsListParams {
    fn default() -> Self {
        Self {
            filter: None,
            order_by: CronJobOrderBy::Id,
            direction: CronJobSortDirection::Desc,
            pagination: Pagination::default(),
        }
    }
}

impl CronJobs<'_> {
    pub async fn list(&self, app_id: &str, params: CronJobsListParams) -> Result<Page<CronJob>> {
        self.client
            .page(
                gql::LIST_APP_CRON_JOBS_QUERY,
                params
                    .pagination
                    .variables(json!({"appId": app_id, "filter": params.filter,
                        "orderBy": params.order_by, "direction": params.direction}))?,
                "/node/cronJobs",
            )
            .await
    }

    pub async fn retrieve(&self, id: &str) -> Result<CronJob> {
        nodes(
            self.client,
            gql::GET_CRON_JOBS_BY_IDS_QUERY,
            &[id],
            "CronJob",
        )
        .await?
        .pop()
        .flatten()
        .ok_or_else(|| Error::missing("cron job", id))
    }

    pub async fn retrieve_many(&self, ids: &[impl AsRef<str>]) -> Result<Vec<Option<CronJob>>> {
        nodes(self.client, gql::GET_CRON_JOBS_BY_IDS_QUERY, ids, "CronJob").await
    }

    pub async fn create(&self, input: &CreateCronJobInput) -> Result<CronJob> {
        if input.execute.is_some() == input.fetch.is_some() {
            return Err(Error::Validation(
                "exactly one of execute or fetch must be provided".into(),
            ));
        }
        self.client
            .mutation(
                gql::CREATE_CRON_JOB_MUTATION,
                input,
                "/createCronJob/cronJob",
            )
            .await
    }

    pub async fn update(&self, input: &UpdateCronJobInput) -> Result<CronJob> {
        if input.execute.is_some() && input.fetch.is_some() {
            return Err(Error::Validation(
                "execute and fetch cannot both be provided".into(),
            ));
        }
        self.client
            .mutation(
                gql::UPDATE_CRON_JOB_MUTATION,
                input,
                "/updateCronJob/cronJob",
            )
            .await
    }

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client
            .delete(
                gql::DELETE_CRON_JOB_MUTATION,
                json!({"cronJobId": id}),
                "deleteCronJob",
            )
            .await
    }
}

impl Git<'_> {
    pub async fn retrieve(&self, app_id: &str) -> Result<Option<GitConnection>> {
        let data: Value = self
            .client
            .graphql(gql::GET_APP_GIT_CONNECTION_QUERY, json!({"id": app_id}))
            .await?;
        let node = data
            .get("node")
            .filter(|node| node.get("__typename").and_then(Value::as_str) == Some("DeployApp"))
            .ok_or_else(|| Error::missing("app", app_id))?;
        node.get("githubRepoConnection")
            .filter(|value| !value.is_null())
            .map(|value| serde_json::from_value(value.clone()).map_err(Error::from))
            .transpose()
    }

    mutations!(
        connect(ConnectGithubRepoToAppInput) -> GitConnection = CONNECT_GITHUB_REPO_TO_APP_MUTATION, "/connectGithubRepoToApp/githubRepoConnection";
        update(UpdateGithubRepoAppConnectionInput) -> GitConnection = UPDATE_GITHUB_REPO_CONNECTION_MUTATION, "/updateGithubRepoConnection/githubRepoConnection"
    );

    pub async fn delete(&self, app_id: &str) -> Result<()> {
        self.client
            .delete(
                gql::DISCONNECT_GITHUB_REPO_FROM_APP_MUTATION,
                json!({"appId": app_id}),
                "disconnectGithubRepoFromApp",
            )
            .await
    }
}

#[derive(Clone, Debug, Default)]
pub struct VersionsListParams {
    pub created_after: Option<String>,
    pub sort_by: Option<DeployAppVersionsSortBy>,
    pub pagination: Pagination,
}

impl Versions<'_> {
    pub async fn list(&self, app_id: &str, params: VersionsListParams) -> Result<Page<AppVersion>> {
        self.client.page(gql::LIST_APP_VERSIONS_QUERY, params.pagination.variables(
            json!({"appId": app_id, "createdAfter": params.created_after, "sortBy": params.sort_by}))?, "/node/versions").await
    }
}

#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LogsListParams {
    pub since: Option<String>,
    pub until: Option<String>,
    pub instance_id: Option<String>,
    pub request_id: Option<String>,
    pub streams: Option<Vec<LogStream>>,
    pub text_search: Option<String>,
    #[serde(skip)]
    pub pagination: Pagination,
}

impl Logs<'_> {
    /// Logs belong to an app version; pass a version ID, not an app ID.
    pub async fn list(&self, version_id: &str, params: LogsListParams) -> Result<Page<Log>> {
        let mut variables = serde_json::to_value(&params)?;
        variables["appId"] = json!(version_id);
        self.client
            .page(
                gql::GET_APP_LOGS_QUERY,
                params.pagination.variables(variables)?,
                "/node/logs",
            )
            .await
    }
}

impl<'a> Ssh<'a> {
    children!(users: SshUsers);

    pub async fn retrieve(&self, app_id: &str) -> Result<SshServer> {
        self.client
            .read(
                gql::GET_APP_SSH_SERVER_QUERY,
                json!({"id": app_id}),
                "/node/sshServer",
            )
            .await
    }

    mutations!(
        update(ToggleSshServerInput) -> SshServer = TOGGLE_SSH_SERVER_MUTATION, "/toggleSshServer/sshServer";
        generate_token(GenerateSshTokenInput) -> String = GENERATE_SSH_TOKEN_MUTATION, "/generateSshToken/token"
    );
}

impl<'a> SshUsers<'a> {
    children!(authorized_keys: SshKeys);

    pub async fn list(&self, app_id: &str, pagination: Pagination) -> Result<Page<SshUser>> {
        self.client
            .page(
                gql::GET_APP_SSH_USERS_QUERY,
                pagination.variables(json!({"id": app_id}))?,
                "/node/sshServer/users",
            )
            .await
    }

    pub async fn retrieve(&self, id: &str) -> Result<SshUser> {
        nodes(
            self.client,
            gql::GET_SSH_USERS_BY_IDS_QUERY,
            &[id],
            "SshUser",
        )
        .await?
        .pop()
        .flatten()
        .ok_or_else(|| Error::missing("SSH user", id))
    }

    pub async fn retrieve_many(&self, ids: &[impl AsRef<str>]) -> Result<Vec<Option<SshUser>>> {
        nodes(self.client, gql::GET_SSH_USERS_BY_IDS_QUERY, ids, "SshUser").await
    }

    mutations!(update(EditSshUserInput) -> SshUser = EDIT_SSH_USER_MUTATION, "/editSshUser/sshUser");

    pub async fn reveal_password(&self, id: &str) -> Result<SshPassword> {
        self.client
            .mutation(
                gql::REVEAL_SSH_USER_PASSWORD_MUTATION,
                json!({"sshUserId": id}),
                "/revealSshUserPassword",
            )
            .await
    }

    pub async fn rotate_password(&self, id: &str) -> Result<SshPassword> {
        self.client
            .mutation(
                gql::ROTATE_SSH_USER_PASSWORD_MUTATION,
                json!({"sshUserId": id}),
                "/rotateSshUserPassword",
            )
            .await
    }
}

impl SshKeys<'_> {
    pub async fn list(
        &self,
        ssh_user_id: &str,
        pagination: Pagination,
    ) -> Result<Page<SshAuthorizedKey>> {
        self.client
            .page(
                gql::GET_SSH_AUTHORIZED_KEYS_QUERY,
                pagination.variables(json!({"id": ssh_user_id}))?,
                "/node/authorizedKeys",
            )
            .await
    }

    mutations!(create(AddSshAuthorizedKeyInput) -> SshAuthorizedKey = ADD_SSH_AUTHORIZED_KEY_MUTATION, "/addSshAuthorizedKey/authorizedKey");

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client
            .delete(
                gql::DELETE_SSH_AUTHORIZED_KEY_BY_ID_MUTATION,
                json!({"id": id}),
                "deleteSshAuthorizedKeyById",
            )
            .await
    }
}

impl<'a> Dns<'a> {
    children!(domains: DnsDomains, records: DnsRecords);
}

impl DnsDomains<'_> {
    pub async fn list(
        &self,
        owner_id: Option<&str>,
        pagination: Pagination,
    ) -> Result<Page<DnsDomain>> {
        self.client
            .page(
                gql::LIST_DNS_DOMAINS_QUERY,
                pagination.variables(json!({"owner": owner_id}))?,
                "/getAllDomains",
            )
            .await
    }

    pub async fn retrieve(&self, id: &str) -> Result<DnsDomain> {
        nodes(self.client, gql::GET_DNS_DOMAINS_QUERY, &[id], "DNSDomain")
            .await?
            .pop()
            .flatten()
            .ok_or_else(|| Error::missing("DNS domain", id))
    }

    pub async fn retrieve_many(&self, ids: &[impl AsRef<str>]) -> Result<Vec<Option<DnsDomain>>> {
        nodes(self.client, gql::GET_DNS_DOMAINS_QUERY, ids, "DNSDomain").await
    }

    pub async fn retrieve_by_name(&self, name: &str) -> Result<DnsDomain> {
        self.client
            .read(
                gql::GET_DNS_DOMAIN_BY_NAME_QUERY,
                json!({"name": name}),
                "/getDomain",
            )
            .await
    }

    mutations!(
        create(RegisterDomainInput) -> DnsDomain = REGISTER_DNS_DOMAIN_MUTATION, "/registerDomain/domain";
        import_zone_file(UpsertDomainFromZoneFileInput) -> DnsDomain = UPSERT_DNS_DOMAIN_FROM_ZONE_FILE_MUTATION, "/upsertDomainFromZoneFile/domain"
    );

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client
            .delete(
                gql::DELETE_DNS_DOMAIN_MUTATION,
                json!({"domainId": id}),
                "deleteDomain",
            )
            .await
    }
}

impl DnsRecords<'_> {
    pub async fn list(&self, domain_id: &str, pagination: Pagination) -> Result<Page<DnsRecord>> {
        self.client
            .page(
                gql::LIST_DNS_RECORDS_CONNECTION_QUERY,
                pagination.variables(json!({"domainId": domain_id}))?,
                "/node/recordsConnection",
            )
            .await
    }

    pub async fn retrieve(&self, id: &str) -> Result<DnsRecord> {
        let data: Value = self
            .client
            .graphql(gql::GET_DNS_RECORDS_QUERY, json!({"ids": [id]}))
            .await?;
        let node = data
            .pointer("/nodes/0")
            .filter(|node| node.get("domain").is_some())
            .ok_or_else(|| Error::missing("DNS record", id))?;
        Ok(serde_json::from_value(node.clone())?)
    }

    mutations!(
        create(UpsertDNSRecordInput) -> DnsRecord = UPSERT_DNS_RECORD_MUTATION, "/upsertDNSRecord/record";
        update(UpsertDNSRecordInput) -> DnsRecord = UPSERT_DNS_RECORD_MUTATION, "/upsertDNSRecord/record";
        update_many(UpdateDNSRecordsInput) -> Vec<DnsRecord> = UPDATE_DNS_RECORDS_MUTATION, "/updateDNSRecords/records"
    );

    pub async fn delete(&self, id: &str) -> Result<()> {
        self.client
            .delete(
                gql::DELETE_DNS_RECORD_MUTATION,
                json!({"recordId": id}),
                "deleteDNSRecord",
            )
            .await
    }
}

impl Emails<'_> {
    pub async fn sent(
        &self,
        app_or_owner_id: &str,
        pagination: Pagination,
    ) -> Result<Page<EmailMessage>> {
        self.client
            .page(
                gql::LIST_SENT_EMAILS_QUERY,
                pagination.variables(json!({"id": app_or_owner_id}))?,
                "/node/emails",
            )
            .await
    }

    pub async fn received(
        &self,
        app_or_owner_id: &str,
        pagination: Pagination,
    ) -> Result<Page<EmailMessage>> {
        self.client
            .page(
                gql::LIST_RECEIVED_EMAILS_QUERY,
                pagination.variables(json!({"id": app_or_owner_id}))?,
                "/node/emails",
            )
            .await
    }

    /// Send text or HTML email. Binary MIME uploads require multipart transport,
    /// which is not part of this client's HTTP JSON interface.
    pub async fn send(&self, input: &SendAppEmailInput) -> Result<EmailMessage> {
        if input.raw_message.is_some() {
            return Err(Error::Validation(
                "raw_message uploads are not supported; use text_body or html_body".into(),
            ));
        }
        self.client
            .mutation(gql::SEND_APP_EMAIL_MUTATION, input, "/sendAppEmail/message")
            .await
    }
}

impl Packages<'_> {
    pub async fn search(
        &self,
        query: &str,
        filter: Option<&PackagesFilter>,
        pagination: Pagination,
    ) -> Result<Page<PackageVersion>> {
        self.client
            .page(
                gql::SEARCH_PACKAGES_QUERY,
                pagination.variables(json!({"query": query, "packages": filter}))?,
                "/search",
            )
            .await
    }
}

#[derive(Clone, Copy, Debug)]
pub enum UsageScope<'a> {
    Viewer,
    App(&'a str),
    Owner(&'a str),
}

impl Usage<'_> {
    pub async fn metrics(
        &self,
        scope: UsageScope<'_>,
        start: &str,
        end: &str,
        grouped_by: MetricGrouping,
    ) -> Result<UsageMetrics> {
        let mut variables = json!({"start": start, "end": end, "groupedBy": grouped_by});
        let (query, pointer) = match scope {
            UsageScope::Viewer => (gql::USAGE_VIEWER_METRICS_QUERY, "/viewer/groupedMetrics"),
            UsageScope::App(id) => {
                variables["appId"] = json!(id);
                (gql::USAGE_APP_METRICS_QUERY, "/node/groupedMetrics")
            }
            UsageScope::Owner(owner) => {
                variables["owner"] = json!(owner);
                (gql::USAGE_OWNER_METRICS_QUERY, "/owner/groupedMetrics")
            }
        };
        self.client.read(query, variables, pointer).await
    }
}

async fn nodes<T: DeserializeOwned>(
    client: &StackMachine,
    query: &str,
    ids: &[impl AsRef<str>],
    typename: &str,
) -> Result<Vec<Option<T>>> {
    if ids.is_empty() {
        return Ok(Vec::new());
    }
    let ids: Vec<&str> = ids.iter().map(AsRef::as_ref).collect();
    let data: Value = client.graphql(query, json!({"ids": ids})).await?;
    let nodes = data
        .get("nodes")
        .and_then(Value::as_array)
        .ok_or_else(|| Error::InvalidResponse("response is missing nodes".into()))?;
    ids.iter()
        .enumerate()
        .map(|(index, _)| {
            nodes
                .get(index)
                .filter(|node| node.get("__typename").and_then(Value::as_str) == Some(typename))
                .map(|node| serde_json::from_value(node.clone()).map_err(Error::from))
                .transpose()
        })
        .collect()
}

async fn success(
    client: &StackMachine,
    query: &str,
    variables: Value,
    pointer: &str,
) -> Result<()> {
    if client.read::<bool>(query, variables, pointer).await? {
        Ok(())
    } else {
        Err(Error::InvalidResponse(format!("{pointer} returned false")))
    }
}