fix(wasmer-api): Resolve compilation issues when targeting wasm32

This commit is contained in:
Edoardo Marangoni
2024-07-03 18:41:33 +02:00
parent 65e92370cd
commit 144131f873
6 changed files with 135 additions and 27 deletions

View File

@ -13,6 +13,8 @@ repository.workspace = true
rust-version.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
derive-wasm-bindgen = ["dep:serde-wasm-bindgen"]
[dependencies]
# Wasmer dependencies.
@ -34,6 +36,13 @@ pin-project-lite = "0.2.10"
serde_path_to_error = "0.1.14"
harsh = "0.2.2"
reqwest = { version = "0.11.13", default-features = false, features = ["json"] }
merge-streams = "0.1.2"
wasm-bindgen = "0.2.92"
serde-wasm-bindgen = { version = "0.6", optional = true }
[target.'cfg(target_family = "wasm")'.dependencies.getrandom]
version = "0.2.14"
features = ["js"]
[dev-dependencies]
base64 = "0.13.1"

View File

@ -193,7 +193,6 @@ type Namespace implements Node & PackageOwner & Owner {
name: String!
displayName: String
description: String!
avatar: String!
avatarUpdatedAt: DateTime
twitterHandle: String
githubHandle: String
@ -205,6 +204,7 @@ type Namespace implements Node & PackageOwner & Owner {
userSet(offset: Int, before: String, after: String, first: Int, last: Int): UserConnection!
globalName: String!
globalId: ID!
avatar: String!
packages(offset: Int, before: String, after: String, first: Int, last: Int): PackageConnection!
apps(sortBy: DeployAppsSortBy, offset: Int, before: String, after: String, first: Int, last: Int): DeployAppConnection!
packageVersions(offset: Int, before: String, after: String, first: Int, last: Int): PackageVersionConnection!
@ -939,6 +939,8 @@ type BindingsGeneratorEdge {
type BindingsGenerator implements Node {
"""The ID of the object"""
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
packageVersion: PackageVersion!
active: Boolean!
commandName: String!
@ -1235,11 +1237,13 @@ type AppTemplate implements Node {
updatedAt: DateTime!
readme: String!
useCases: JSONString!
framework: String!
language: String!
repoLicense: String!
usingPackage: Package
defaultImage: String
framework: String!
templateFramework: TemplateFramework
language: String!
templateLanguage: TemplateLanguage
}
type AppTemplateCategory implements Node {
@ -1253,6 +1257,24 @@ type AppTemplateCategory implements Node {
appTemplates(offset: Int, before: String, after: String, first: Int, last: Int): AppTemplateConnection!
}
type TemplateFramework implements Node {
"""The ID of the object"""
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
name: String!
slug: String!
}
type TemplateLanguage implements Node {
"""The ID of the object"""
id: ID!
createdAt: DateTime!
updatedAt: DateTime!
name: String!
slug: String!
}
type Collection {
slug: String!
displayName: String!
@ -1540,14 +1562,14 @@ type DNSDomainEdge {
}
type DNSDomain implements Node {
createdAt: DateTime!
updatedAt: DateTime!
deletedAt: DateTime
name: String!
"""This zone will be accessible at /dns/{slug}/."""
slug: String!
zoneFile: String!
createdAt: DateTime!
updatedAt: DateTime!
deletedAt: DateTime
"""The ID of the object"""
id: ID!
@ -2258,7 +2280,9 @@ type Query {
getAppByGlobalAlias(alias: String!): DeployApp
getDeployApps(sortBy: DeployAppsSortBy, updatedAfter: DateTime, offset: Int, before: String, after: String, first: Int, last: Int): DeployAppConnection!
getAppVersions(sortBy: DeployAppVersionsSortBy, updatedAfter: DateTime, offset: Int, before: String, after: String, first: Int, last: Int): DeployAppVersionConnection!
getAppTemplates(categorySlug: String, sortBy: AppTemplatesSortBy, offset: Int, before: String, after: String, first: Int, last: Int): AppTemplateConnection
getTemplateFrameworks(offset: Int, before: String, after: String, first: Int, last: Int): TemplateFrameworkConnection
getTemplateLanguages(offset: Int, before: String, after: String, first: Int, last: Int): TemplateLanguageConnection
getAppTemplates(categorySlug: String, frameworkSlug: String, languageSlug: String, sortBy: AppTemplatesSortBy, offset: Int, before: String, after: String, first: Int, last: Int): AppTemplateConnection
getAppTemplate(slug: String!): AppTemplate
getAppTemplateCategories(offset: Int, before: String, after: String, first: Int, last: Int): AppTemplateCategoryConnection
viewer: User
@ -2357,6 +2381,46 @@ enum DNSRecordsSortBy {
OLDEST
}
type TemplateFrameworkConnection {
"""Pagination data for this connection."""
pageInfo: PageInfo!
"""Contains the nodes in this connection."""
edges: [TemplateFrameworkEdge]!
"""Total number of items in the connection."""
totalCount: Int
}
"""A Relay edge containing a `TemplateFramework` and its cursor."""
type TemplateFrameworkEdge {
"""The item at the end of the edge"""
node: TemplateFramework
"""A cursor for use in pagination"""
cursor: String!
}
type TemplateLanguageConnection {
"""Pagination data for this connection."""
pageInfo: PageInfo!
"""Contains the nodes in this connection."""
edges: [TemplateLanguageEdge]!
"""Total number of items in the connection."""
totalCount: Int
}
"""A Relay edge containing a `TemplateLanguage` and its cursor."""
type TemplateLanguageEdge {
"""The item at the end of the edge"""
node: TemplateLanguage
"""A cursor for use in pagination"""
cursor: String!
}
enum AppTemplatesSortBy {
NEWEST
OLDEST

View File

@ -1,11 +1,11 @@
#[cfg(not(target_family = "wasm"))]
use std::time::Duration;
use crate::GraphQLApiFailure;
use anyhow::{bail, Context as _};
use cynic::{http::CynicReqwestError, GraphQlResponse, Operation};
use url::Url;
use crate::GraphQLApiFailure;
/// API client for the Wasmer API.
///
/// Use the queries in [`crate::queries`] to interact with the API.
@ -53,11 +53,18 @@ impl WasmerClient {
}
pub fn new(graphql_endpoint: Url, user_agent: &str) -> Result<Self, anyhow::Error> {
#[cfg(target_family = "wasm")]
let client = reqwest::Client::builder()
.build()
.context("could not construct http client")?;
#[cfg(not(target_family = "wasm"))]
let client = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(90))
.build()
.context("could not construct http client")?;
Self::new_with_client(client, graphql_endpoint, user_agent)
}

View File

@ -1,9 +1,10 @@
use std::{collections::HashSet, pin::Pin, time::Duration};
use std::{collections::HashSet, time::Duration};
use anyhow::{bail, Context};
use cynic::{MutationBuilder, QueryBuilder};
use edge_schema::schema::NetworkTokenV1;
use futures::{Stream, StreamExt};
use futures::StreamExt;
use merge_streams::MergeStreams;
use time::OffsetDateTime;
use tracing::Instrument;
use url::Url;
@ -606,8 +607,7 @@ pub async fn user_accessible_apps(
impl futures::Stream<Item = Result<Vec<types::DeployApp>, anyhow::Error>> + '_,
anyhow::Error,
> {
let apps: Pin<Box<dyn Stream<Item = Result<Vec<DeployApp>, anyhow::Error>> + Send + Sync>> =
Box::pin(user_apps(client).await);
let user_apps = user_apps(client).await;
// Get all aps in user-accessible namespaces.
let namespace_res = client
@ -627,17 +627,13 @@ pub async fn user_accessible_apps(
.map(|node| node.name.clone())
.collect::<Vec<_>>();
let mut all_apps = vec![apps];
let mut ns_apps = vec![];
for ns in namespace_names {
let apps: Pin<Box<dyn Stream<Item = Result<Vec<DeployApp>, anyhow::Error>> + Send + Sync>> =
Box::pin(namespace_apps(client, ns).await);
all_apps.push(apps);
let apps = namespace_apps(client, ns).await;
ns_apps.push(apps);
}
let apps = futures::stream::select_all(all_apps);
Ok(apps)
Ok((user_apps, ns_apps.merge()).merge())
}
/// Get apps for a specific namespace.
@ -998,11 +994,18 @@ fn get_app_logs(
if page.is_empty() {
if watch {
/*
TODO: the resolution of watch should be configurable
TODO: should this be async?
*/
/*
* [TODO]: The resolution here should be configurable.
*/
// No tokio::time::sleep on wasm32 as of now.
// Probably not ideal?
#[cfg(target_family = "wasm32")]
std::thread::sleep(Duration::from_secs(1));
#[cfg(not(target_family = "wasm32"))]
tokio::time::sleep(Duration::from_secs(1)).await;
continue;
}

View File

@ -58,7 +58,7 @@ mod queries {
pub viewer: Option<UserWithNamespaces>,
}
#[derive(cynic::QueryFragment, Debug)]
#[derive(cynic::QueryFragment, Debug, serde::Serialize)]
pub struct User {
pub id: cynic::Id,
pub username: String,