Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(torii-graphql): move away from external url #2753

Merged
merged 4 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions bin/torii/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
use torii_server::proxy::Proxy;
use tracing::{error, info};
use tracing_subscriber::{fmt, EnvFilter};
use url::{form_urlencoded, Url};
use url::form_urlencoded;

pub(crate) const LOG_TARGET: &str = "torii::cli";

Expand Down Expand Up @@ -220,7 +220,6 @@
let graphql_server = spawn_rebuilding_graphql_server(
shutdown_tx.clone(),
readonly_pool.into(),
args.external_url,
proxy_server.clone(),
);

Expand Down Expand Up @@ -273,15 +272,13 @@
async fn spawn_rebuilding_graphql_server(
shutdown_tx: Sender<()>,
pool: Arc<SqlitePool>,
external_url: Option<Url>,
proxy_server: Arc<Proxy>,
) {
let mut broker = SimpleBroker::<Model>::subscribe();

loop {
let shutdown_rx = shutdown_tx.subscribe();
let (new_addr, new_server) =
torii_graphql::server::new(shutdown_rx, &pool, external_url.clone()).await;
let (new_addr, new_server) = torii_graphql::server::new(shutdown_rx, &pool).await;

Check warning on line 281 in bin/torii/src/main.rs

View check run for this annotation

Codecov / codecov/patch

bin/torii/src/main.rs#L281

Added line #L281 was not covered by tests

tokio::spawn(new_server);

Expand Down
10 changes: 0 additions & 10 deletions crates/torii/cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,6 @@ pub struct ToriiArgs {
)]
pub db_dir: Option<PathBuf>,

/// The external url of the server, used for configuring the GraphQL Playground in a hosted
/// environment
#[arg(long, value_parser = parse_url, help = "The external url of the server, used for configuring the GraphQL Playground in a hosted environment.")]
pub external_url: Option<Url>,

/// Open World Explorer on the browser.
#[arg(long, help = "Open World Explorer on the browser.")]
pub explorer: bool,
Expand Down Expand Up @@ -97,10 +92,6 @@ impl ToriiArgs {
self.db_dir = config.db_dir;
}

if self.external_url.is_none() {
self.external_url = config.external_url;
}

// Currently the comparison it's only at the top level.
// Need to make it more granular.

Expand Down Expand Up @@ -164,7 +155,6 @@ impl TryFrom<ToriiArgs> for ToriiArgsConfig {
config.rpc =
if args.rpc == Url::parse(DEFAULT_RPC_URL).unwrap() { None } else { Some(args.rpc) };
config.db_dir = args.db_dir;
config.external_url = args.external_url;
config.explorer = Some(args.explorer);

// Only include the following options if they are not the default.
Expand Down
30 changes: 5 additions & 25 deletions crates/torii/graphql/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use serde_json::json;
use sqlx::{Pool, Sqlite};
use tokio::sync::broadcast::Receiver;
use url::Url;
use warp::{Filter, Rejection, Reply};

use super::schema::build_schema;
Expand All @@ -18,21 +17,19 @@
pub async fn new(
mut shutdown_rx: Receiver<()>,
pool: &Pool<Sqlite>,
external_url: Option<Url>,
) -> (SocketAddr, impl Future<Output = ()> + 'static) {
let schema = build_schema(pool).await.unwrap();
let mut conn = pool.acquire().await.unwrap();
let num_models = count_rows(&mut conn, MODEL_TABLE, &None, &None).await.unwrap();

let routes = graphql_filter(schema, external_url, num_models == 0);
let routes = graphql_filter(schema, num_models == 0);

Check warning on line 25 in crates/torii/graphql/src/server.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/server.rs#L25

Added line #L25 was not covered by tests
warp::serve(routes).bind_with_graceful_shutdown(([127, 0, 0, 1], 0), async move {
shutdown_rx.recv().await.ok();
})
}

fn graphql_filter(
schema: Schema,
external_url: Option<Url>,
is_empty: bool,
) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
let graphql_post = async_graphql_warp::graphql(schema.clone()).and_then(
Expand All @@ -48,30 +45,13 @@
},
);

// If an external URL is provided, we are expecting the GraphQL endpoint to be given.
// Hence, we don't have to append "/graphql" to the URL.
let (graphql_endpoint, subscription_endpoint) = if let Some(external_url) = external_url {
let graphql_url = external_url;
let mut websocket_url = graphql_url.clone();
websocket_url.set_path(&format!("{}/ws", websocket_url.path()));
let _ = websocket_url.set_scheme(match websocket_url.scheme() {
"https" => "wss",
"http" => "ws",
_ => panic!("Invalid URL scheme - must be http or https"),
});
(graphql_url.to_string(), websocket_url.to_string())
} else {
// Otherwise, we are running the GraphQL server locally and we need to
// append "/graphql" to the URL.
("graphql".to_string(), "graphql/ws".to_string())
};

let playground_filter = warp::path("graphql").map(move || {
warp::reply::html(
GraphiQLSource::build()
.endpoint(&graphql_endpoint)
.subscription_endpoint(&subscription_endpoint)
.finish(),
.subscription_endpoint("/ws")
// we patch the generated source to use the current URL instead of the origin
// for hosted services like SLOT
.finish().replace("new URL(endpoint, window.location.origin);", "new URL(window.location.href.trimEnd('/') + endpoint)"),

Check warning on line 54 in crates/torii/graphql/src/server.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/graphql/src/server.rs#L51-L54

Added lines #L51 - L54 were not covered by tests
)
});

Expand Down
Loading