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
pub mod global_id;
pub mod gql;
pub mod stream;

use std::{collections::HashSet, time::Duration};

use anyhow::Context;
use cynic::{http::CynicReqwestError, GraphQlResponse, MutationBuilder, Operation, QueryBuilder};
use futures::StreamExt;
use time::OffsetDateTime;
use tracing::Instrument;
use url::Url;
use wasmer_deploy_schema::schema::{DeploymentV1, NetworkTokenV1, WebcPackageIdentifierV1};

use crate::backend::gql::Log;

use self::gql::{
    CreateNamespaceVars, DeployApp, DeployAppConnection, DeployAppVersion,
    DeployAppVersionConnection, GetDeployAppAndVersion, GetDeployAppVersionsVars,
    GetNamespaceAppsVars, PackageVersionConnection, PublishDeployAppVars,
};

const ENDPOINT_DEV: &str = "https://registry.wapm.dev/graphql";
const ENDPOINT_PROD: &str = "https://registry.wapm.io/graphql";

pub fn endpoint_dev() -> Url {
    Url::parse(ENDPOINT_DEV).unwrap()
}

pub fn endpoint_prod() -> Url {
    Url::parse(ENDPOINT_PROD).unwrap()
}

#[derive(Clone, Debug)]
pub struct BackendClient {
    auth_token: Option<String>,
    graphql_endpoint: Url,

    client: reqwest::Client,
    #[allow(unused)]
    extra_debugging: bool,
}

impl BackendClient {
    pub fn with_client(client: reqwest::Client, graphql_endpoint: Url) -> Self {
        Self {
            client,
            auth_token: None,
            graphql_endpoint,
            extra_debugging: false,
        }
    }

    pub fn graphql_endpoint(&self) -> &Url {
        &self.graphql_endpoint
    }

    pub fn auth_token(&self) -> Option<&str> {
        self.auth_token.as_deref()
    }

    pub fn new(graphql_endpoint: Url) -> Self {
        Self {
            client: reqwest::Client::new(),
            auth_token: None,
            graphql_endpoint,
            extra_debugging: false,
        }
    }

    pub fn with_auth_token(mut self, auth_token: String) -> Self {
        self.auth_token = Some(auth_token);
        self
    }

    pub async fn run_graphql_raw<ResponseData, Vars>(
        &self,
        operation: Operation<ResponseData, Vars>,
    ) -> Result<cynic::GraphQlResponse<ResponseData>, anyhow::Error>
    where
        Vars: serde::Serialize + std::fmt::Debug,
        ResponseData: serde::de::DeserializeOwned + std::fmt::Debug + 'static,
    {
        let req = self.client.post(self.graphql_endpoint.as_str());
        let b = if let Some(token) = &self.auth_token {
            req.bearer_auth(token)
        } else {
            req
        };

        if self.extra_debugging {
            tracing::trace!(
                query=%operation.query,
                vars=?operation.variables,
                "running GraphQL query"
            );
        }
        let query = operation.query.clone();

        let res = b.json(&operation).send().await;

        let res = match res {
            Ok(response) => {
                let status = response.status();
                if !status.is_success() {
                    let body_string = match response.text().await {
                        Ok(b) => b,
                        Err(err) => {
                            tracing::error!("could not load response body: {err}");
                            "<could not retrieve body>".to_string()
                        }
                    };

                    match serde_json::from_str::<GraphQlResponse<ResponseData>>(&body_string) {
                        Ok(response) => Ok(response),
                        Err(_) => Err(CynicReqwestError::ErrorResponse(status, body_string)),
                    }
                } else {
                    let body = response.bytes().await?;

                    let jd = &mut serde_json::Deserializer::from_slice(&body);
                    let data: Result<GraphQlResponse<ResponseData>, _> =
                        serde_path_to_error::deserialize(jd).map_err(|err| {
                            let body_txt = String::from_utf8_lossy(&body);
                            CynicReqwestError::ErrorResponse(
                                reqwest::StatusCode::INTERNAL_SERVER_ERROR,
                                format!("Could not decode JSON response: {err} -- '{body_txt}'"),
                            )
                        });

                    data
                }
            }
            Err(e) => Err(CynicReqwestError::ReqwestError(e)),
        };
        let res = res?;

        if let Some(errors) = &res.errors {
            if !errors.is_empty() {
                tracing::warn!(
                    ?errors,
                    data=?res.data,
                    %query,
                    endpoint=%self.graphql_endpoint,
                    "GraphQL query succeeded, but returned errors",
                );
            }
        }

        Ok(res)
    }

    pub async fn run_graphql<ResponseData, Vars>(
        &self,
        operation: Operation<ResponseData, Vars>,
    ) -> Result<ResponseData, anyhow::Error>
    where
        Vars: serde::Serialize + std::fmt::Debug,
        ResponseData: serde::de::DeserializeOwned + std::fmt::Debug + 'static,
    {
        let res = self.run_graphql_raw(operation).await?;

        if let Some(data) = res.data {
            Ok(data)
        } else if let Some(errs) = res.errors {
            let errs = GraphQLApiFailure { errors: errs };
            Err(errs).context("GraphQL query failed")
        } else {
            Err(anyhow::anyhow!("Query did not return any data"))
        }
    }

    /// Run a GraphQL query, but fail (return an Error) if any error is returned
    /// in the response.
    pub async fn run_graphql_strict<ResponseData, Vars>(
        &self,
        operation: Operation<ResponseData, Vars>,
    ) -> Result<ResponseData, anyhow::Error>
    where
        Vars: serde::Serialize + std::fmt::Debug,
        ResponseData: serde::de::DeserializeOwned + std::fmt::Debug + 'static,
    {
        let res = self.run_graphql_raw(operation).await?;

        if let Some(errs) = res.errors {
            if !errs.is_empty() {
                let errs = GraphQLApiFailure { errors: errs };
                return Err(errs).context("GraphQL query failed");
            }
        }

        if let Some(data) = res.data {
            Ok(data)
        } else {
            Err(anyhow::anyhow!("Query did not return any data"))
        }
    }
}

#[derive(Debug)]
pub struct GraphQLApiFailure {
    pub errors: Vec<cynic::GraphQlError>,
}

impl GraphQLApiFailure {
    pub fn from_errors(
        msg: impl Into<String>,
        errors: Option<Vec<cynic::GraphQlError>>,
    ) -> anyhow::Error {
        let msg = msg.into();
        if let Some(errs) = errors {
            if !errs.is_empty() {
                let err = GraphQLApiFailure { errors: errs };
                return anyhow::Error::new(err).context(msg);
            }
        }
        anyhow::anyhow!("{msg} - query did not return any data")
    }
}

impl std::fmt::Display for GraphQLApiFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let errs = self
            .errors
            .iter()
            .map(|err| err.to_string())
            .collect::<Vec<_>>()
            .join(", ");
        write!(f, "GraphQL API failure: {}", errs)
    }
}

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

/// Load a webc package from the registry.
pub async fn fetch_webc_package(
    client: &BackendClient,
    ident: &WebcPackageIdentifierV1,
    default_registry: &Url,
) -> Result<webc::compat::Container, anyhow::Error> {
    let url = ident.build_download_url_with_default_registry(default_registry);
    let data = client
        .client
        .get(url)
        .header(reqwest::header::ACCEPT, "application/webc")
        .send()
        .await?
        .error_for_status()?
        .bytes()
        .await?;

    webc::compat::Container::from_bytes(data).context("failed to parse webc package")
}

/// Get the currently logged in used, together with all accessible namespaces.
///
/// You can optionally filter the namespaces by the user role.
pub async fn current_user_with_namespaces(
    client: &BackendClient,
    namespace_role: Option<gql::GrapheneRole>,
) -> Result<gql::UserWithNamespaces, anyhow::Error> {
    client
        .run_graphql(gql::GetCurrentUser::build(gql::GetCurrentUserVars {
            namespace_role,
        }))
        .await?
        .viewer
        .context("not logged in")
}

pub async fn get_app(
    client: &BackendClient,
    owner: String,
    name: String,
) -> Result<Option<gql::DeployApp>, anyhow::Error> {
    client
        .run_graphql(gql::GetDeployApp::build(gql::GetDeployAppVars {
            name,
            owner,
        }))
        .await
        .map(|x| x.get_deploy_app)
}

pub async fn get_app_by_alias(
    client: &BackendClient,
    alias: String,
) -> Result<Option<gql::DeployApp>, anyhow::Error> {
    client
        .run_graphql(gql::GetDeployAppByAlias::build(
            gql::GetDeployAppByAliasVars { alias },
        ))
        .await
        .map(|x| x.get_app_by_global_alias)
}

pub async fn get_app_version(
    client: &BackendClient,
    owner: String,
    name: String,
    version: String,
) -> Result<Option<gql::DeployAppVersion>, anyhow::Error> {
    client
        .run_graphql(gql::GetDeployAppVersion::build(
            gql::GetDeployAppVersionVars {
                name,
                owner,
                version,
            },
        ))
        .await
        .map(|x| x.get_deploy_app_version)
}

/// Retrieve a deploy app together with a specific version.
pub async fn get_app_with_version(
    client: &BackendClient,
    owner: String,
    name: String,
    version: String,
) -> Result<GetDeployAppAndVersion, anyhow::Error> {
    client
        .run_graphql(gql::GetDeployAppAndVersion::build(
            gql::GetDeployAppAndVersionVars {
                name,
                owner,
                version,
            },
        ))
        .await
}

pub async fn get_app_and_package_by_name(
    client: &BackendClient,
    vars: gql::GetPackageAndAppVars,
) -> Result<(Option<gql::Package>, Option<gql::DeployApp>), anyhow::Error> {
    let res = client
        .run_graphql(gql::GetPackageAndApp::build(vars))
        .await?;
    Ok((res.get_package, res.get_deploy_app))
}

pub async fn get_deploy_apps(
    client: &BackendClient,
    vars: gql::GetDeployAppsVars,
) -> Result<DeployAppConnection, anyhow::Error> {
    let res = client.run_graphql(gql::GetDeployApps::build(vars)).await?;
    res.get_deploy_apps.context("no apps returned")
}

pub fn get_deploy_apps_stream(
    client: &BackendClient,
    vars: gql::GetDeployAppsVars,
) -> impl futures::Stream<Item = Result<Vec<DeployApp>, anyhow::Error>> + '_ {
    futures::stream::try_unfold(
        Some(vars),
        move |vars: Option<gql::GetDeployAppsVars>| async move {
            let vars = match vars {
                Some(vars) => vars,
                None => return Ok(None),
            };

            let page = get_deploy_apps(client, vars.clone()).await?;

            let end_cursor = page.page_info.end_cursor;

            let items = page
                .edges
                .into_iter()
                .filter_map(|x| x.and_then(|x| x.node))
                .collect::<Vec<_>>();

            let new_vars = end_cursor.map(|c| gql::GetDeployAppsVars {
                after: Some(c),
                ..vars
            });

            Ok(Some((items, new_vars)))
        },
    )
}

pub async fn get_deploy_app_versions(
    client: &BackendClient,
    vars: GetDeployAppVersionsVars,
) -> Result<DeployAppVersionConnection, anyhow::Error> {
    let res = client
        .run_graphql_strict(gql::GetDeployAppVersions::build(vars))
        .await?;
    let versions = res.get_deploy_app.context("app not found")?.versions;
    Ok(versions)
}

pub async fn get_app_by_id(
    client: &BackendClient,
    app_id: String,
) -> Result<DeployApp, anyhow::Error> {
    client
        .run_graphql(gql::GetDeployAppById::build(gql::GetDeployAppByIdVars {
            app_id: app_id.into(),
        }))
        .await?
        .app
        .context("app not found")?
        .into_deploy_app()
        .context("app conversion failed")
}

pub async fn get_node(
    client: &BackendClient,
    id: String,
) -> Result<Option<gql::Node>, anyhow::Error> {
    client
        .run_graphql(gql::GetNode::build(gql::GetNodeVars { id: id.into() }))
        .await
        .map(|x| x.node)
}

pub async fn get_app_with_version_by_id(
    client: &BackendClient,
    app_id: String,
    version_id: String,
) -> Result<(DeployApp, DeployAppVersion), anyhow::Error> {
    let res = client
        .run_graphql(gql::GetDeployAppAndVersionById::build(
            gql::GetDeployAppAndVersionByIdVars {
                app_id: app_id.into(),
                version_id: version_id.into(),
            },
        ))
        .await?;

    let app = res
        .app
        .context("app not found")?
        .into_deploy_app()
        .context("app conversion failed")?;
    let version = res
        .version
        .context("version not found")?
        .into_deploy_app_version()
        .context("version conversion failed")?;

    Ok((app, version))
}

pub async fn get_app_version_by_id(
    client: &BackendClient,
    version_id: String,
) -> Result<DeployAppVersion, anyhow::Error> {
    client
        .run_graphql(gql::GetDeployAppVersionById::build(
            gql::GetDeployAppVersionByIdVars {
                version_id: version_id.into(),
            },
        ))
        .await?
        .version
        .context("app not found")?
        .into_deploy_app_version()
        .context("app version conversion failed")
}

pub async fn get_app_version_by_id_with_app(
    client: &BackendClient,
    version_id: String,
) -> Result<(DeployApp, DeployAppVersion), anyhow::Error> {
    let version = client
        .run_graphql(gql::GetDeployAppVersionById::build(
            gql::GetDeployAppVersionByIdVars {
                version_id: version_id.into(),
            },
        ))
        .await?
        .version
        .context("app not found")?
        .into_deploy_app_version()
        .context("app version conversion failed")?;

    let app_id = version
        .app
        .as_ref()
        .context("could not load app for version")?
        .id
        .clone();

    let app = get_app_by_id(client, app_id.into_inner()).await?;

    Ok((app, version))
}

pub async fn user_apps(client: &BackendClient) -> Result<Vec<gql::DeployApp>, anyhow::Error> {
    let user = client
        .run_graphql(gql::GetCurrentUserWithApps::build(()))
        .await?
        .viewer
        .context("not logged in")?;

    let apps = user
        .apps
        .edges
        .into_iter()
        .flatten()
        .filter_map(|x| x.node)
        .collect();

    Ok(apps)
}

pub async fn user_accessible_apps(
    client: &BackendClient,
) -> Result<Vec<gql::DeployApp>, anyhow::Error> {
    let mut apps = Vec::new();

    // Get user apps.

    let user_apps = user_apps(client).await?;

    apps.extend(user_apps);

    // Get all aps in user-accessible namespaces.
    let namespace_res = client
        .run_graphql(gql::GetCurrentUser::build(gql::GetCurrentUserVars {
            namespace_role: None,
        }))
        .await?;
    let active_user = namespace_res.viewer.context("not logged in")?;
    let namespace_names = active_user
        .namespaces
        .edges
        .iter()
        .filter_map(|edge| edge.as_ref())
        .filter_map(|edge| edge.node.as_ref())
        .map(|node| node.name.clone())
        .collect::<Vec<_>>();

    for namespace in namespace_names {
        let out = client
            .run_graphql(gql::GetNamespaceApps::build(GetNamespaceAppsVars {
                name: namespace.to_string(),
            }))
            .await?;

        if let Some(ns) = out.get_namespace {
            let ns_apps = ns.apps.edges.into_iter().flatten().filter_map(|x| x.node);
            apps.extend(ns_apps);
        }
    }
    Ok(apps)
}

pub async fn namespace_apps(
    client: &BackendClient,
    namespace: &str,
) -> Result<Vec<gql::DeployApp>, anyhow::Error> {
    let res = client
        .run_graphql(gql::GetNamespaceApps::build(GetNamespaceAppsVars {
            name: namespace.to_string(),
        }))
        .await?;

    let ns = res
        .get_namespace
        .with_context(|| format!("failed to get namespace '{}'", namespace))?;

    let apps = ns
        .apps
        .edges
        .into_iter()
        .flatten()
        .filter_map(|x| x.node)
        .collect();

    Ok(apps)
}

pub async fn publish_deploy_app(
    client: &BackendClient,
    vars: PublishDeployAppVars,
) -> Result<DeployAppVersion, anyhow::Error> {
    let res = client
        .run_graphql_raw(gql::PublishDeployApp::build(vars))
        .await?;

    if let Some(app) = res
        .data
        .and_then(|d| d.publish_deploy_app)
        .map(|d| d.deploy_app_version)
    {
        Ok(app)
    } else {
        Err(GraphQLApiFailure::from_errors(
            "could not publish app",
            res.errors,
        ))
    }
}

/// Get all namespaces accessible by the current user.
pub async fn user_namespaces(client: &BackendClient) -> Result<Vec<gql::Namespace>, anyhow::Error> {
    let user = client
        .run_graphql(gql::GetCurrentUser::build(gql::GetCurrentUserVars {
            namespace_role: None,
        }))
        .await?
        .viewer
        .context("not logged in")?;

    let ns = user
        .namespaces
        .edges
        .into_iter()
        .flatten()
        // .filter_map(|x| x)
        .filter_map(|x| x.node)
        .collect();

    Ok(ns)
}

pub async fn get_namespace(
    client: &BackendClient,
    name: String,
) -> Result<Option<gql::Namespace>, anyhow::Error> {
    client
        .run_graphql(gql::GetNamespace::build(gql::GetNamespaceVars { name }))
        .await
        .map(|x| x.get_namespace)
}

pub async fn create_namespace(
    client: &BackendClient,
    vars: CreateNamespaceVars,
) -> Result<gql::Namespace, anyhow::Error> {
    client
        .run_graphql(gql::CreateNamespace::build(vars))
        .await?
        .create_namespace
        .map(|x| x.namespace)
        .context("no namespace returned")
}

pub async fn get_package(
    client: &BackendClient,
    name: String,
) -> Result<Option<gql::Package>, anyhow::Error> {
    client
        .run_graphql_strict(gql::GetPackage::build(gql::GetPackageVars { name }))
        .await
        .map(|x| x.get_package)
}

pub async fn get_package_version(
    client: &BackendClient,
    name: String,
    version: String,
) -> Result<Option<gql::PackageVersionWithPackage>, anyhow::Error> {
    client
        .run_graphql_strict(gql::GetPackageVersion::build(gql::GetPackageVersionVars {
            name,
            version,
        }))
        .await
        .map(|x| x.get_package_version)
}

pub async fn get_package_versions(
    client: &BackendClient,
    vars: gql::AllPackageVersionsVars,
) -> Result<PackageVersionConnection, anyhow::Error> {
    let res = client
        .run_graphql(gql::GetAllPackageVersions::build(vars))
        .await?;
    Ok(res.all_package_versions)
}

pub fn get_package_versions_stream(
    client: &BackendClient,
    vars: gql::AllPackageVersionsVars,
) -> impl futures::Stream<Item = Result<Vec<gql::PackageVersionWithPackage>, anyhow::Error>> + '_ {
    futures::stream::try_unfold(
        Some(vars),
        move |vars: Option<gql::AllPackageVersionsVars>| async move {
            let vars = match vars {
                Some(vars) => vars,
                None => return Ok(None),
            };

            let page = get_package_versions(client, vars.clone()).await?;

            let end_cursor = page.page_info.end_cursor;

            let items = page
                .edges
                .into_iter()
                .filter_map(|x| x.and_then(|x| x.node))
                .collect::<Vec<_>>();

            let new_vars = end_cursor.map(|cursor| gql::AllPackageVersionsVars {
                after: Some(cursor),
                ..vars
            });

            Ok(Some((items, new_vars)))
        },
    )
}

pub async fn generate_deploy_token_raw(
    client: &BackendClient,
    app_version_id: String,
) -> Result<String, anyhow::Error> {
    let res = client
        .run_graphql(gql::GenerateDeployToken::build(
            gql::GenerateDeployTokenVars { app_version_id },
        ))
        .await?;

    res.generate_deploy_token
        .map(|x| x.token)
        .context("no token returned")
}

#[derive(Debug, PartialEq)]
pub enum GenerateTokenBy {
    Id(NetworkTokenV1),
}

#[derive(Debug, PartialEq)]
pub enum TokenKind {
    SSH,
    Network(GenerateTokenBy),
    Other(Box<DeploymentV1>),
}

pub async fn generate_deploy_config_token_raw(
    client: &BackendClient,
    token_kind: TokenKind,
) -> Result<String, anyhow::Error> {
    let res = client
        .run_graphql(gql::GenerateDeployConfigToken::build(
            gql::GenerateDeployConfigTokenVars {
                input: match token_kind {
                    TokenKind::SSH => "{}".to_string(),
                    TokenKind::Network(by) => match by {
                        GenerateTokenBy::Id(token) => serde_json::to_string(&token)?,
                    },
                    TokenKind::Other(deploy) => serde_json::to_string(&deploy)?,
                },
            },
        ))
        .await?;

    res.generate_deploy_config_token
        .map(|x| x.token)
        .context("no token returned")
}

/// Get pages of logs associated with an application that lie within the
/// specified date range.
// NOTE: this is not public due to severe usability issues.
// The stream can loop forever due to re-fetching the same logs over and over.
#[tracing::instrument(skip_all, level = "debug")]
#[allow(clippy::let_with_type_underscore)]
fn get_app_logs(
    client: &BackendClient,
    name: String,
    owner: String,
    tag: Option<String>,
    start: OffsetDateTime,
    end: Option<OffsetDateTime>,
) -> impl futures::Stream<Item = Result<Vec<Log>, anyhow::Error>> + '_ {
    // Note: the backend will limit responses to a certain number of log
    // messages, so we use try_unfold() to keep calling it until we stop getting
    // new log messages.
    let span = tracing::Span::current();

    futures::stream::try_unfold(start, move |start| {
        let variables = gql::GetDeployAppLogsVars {
            name: name.clone(),
            owner: owner.clone(),
            version: tag.clone(),
            // TODO: increase pagination size
            // See https://github.com/wasmerio/deploy/issues/460
            // first: Some(500),
            first: Some(10),
            starting_from: unix_timestamp(start),
            until: end.map(unix_timestamp),
        };

        let fut = async move {
            let deploy_app_version = client
                .run_graphql(gql::GetDeployAppLogs::build(variables))
                .await?
                .get_deploy_app_version
                .context("unknown package version")?;

            let page: Vec<_> = deploy_app_version
                .logs
                .edges
                .into_iter()
                .flatten()
                .filter_map(|edge| edge.node)
                .collect();

            if page.is_empty() {
                Ok(None)
            } else {
                let last_message = page.last().expect("The page is non-empty");
                let timestamp = last_message.timestamp;
                // NOTE: adding 1 microsecond to the timestamp to avoid fetching
                // the last message again.
                let timestamp = OffsetDateTime::from_unix_timestamp_nanos(timestamp as i128)
                    .with_context(|| {
                        format!("Unable to interpret {timestamp} as a unix timestamp")
                    })?;

                // FIXME: We need a better way to tell the backend "give me the
                // next set of logs". Adding 1 nanosecond could theoretically
                // mean we miss messages if multiple log messages arrived at
                // the same nanosecond and the page ended midway.

                let next_timestamp = timestamp + Duration::from_nanos(1_000);

                Ok(Some((page, next_timestamp)))
            }
        };

        fut.instrument(span.clone())
    })
}

/// Get pages of logs associated with an application that lie within the
/// specified date range.
///
/// In contrast to [`get_app_logs`], this function collects the stream into a
/// final vector.
#[tracing::instrument(skip_all, level = "debug")]
#[allow(clippy::let_with_type_underscore)]
pub async fn get_app_logs_paginated(
    client: &BackendClient,
    name: String,
    owner: String,
    tag: Option<String>,
    start: OffsetDateTime,
    end: Option<OffsetDateTime>,
    max_lines: usize,
) -> Result<Vec<Log>, anyhow::Error> {
    let mut logs = Vec::new();

    let stream = get_app_logs(client, name, owner, tag, start, end);
    futures::pin_mut!(stream);

    let mut hasher = HashSet::new();

    while let Some(res) = stream.next().await {
        let mut page = res?;

        // Prevent duplicates.
        // TODO: don't clone the message, just hash it.
        page.retain(|log| hasher.insert((log.message.clone(), log.timestamp.round() as i128)));

        if page.is_empty() {
            break;
        }
        logs.extend(page);
        if logs.len() >= max_lines {
            break;
        }
    }

    Ok(logs)
}

/// Convert a [`OffsetDateTime`] to a unix timestamp that the WAPM backend
/// understands.
fn unix_timestamp(ts: OffsetDateTime) -> f64 {
    let nanos_per_second = 1_000_000_000;
    let timestamp = ts.unix_timestamp_nanos();
    let nanos = timestamp % nanos_per_second;
    let secs = timestamp / nanos_per_second;

    (secs as f64) + (nanos as f64 / nanos_per_second as f64)
}