Skip to content

Commit

Permalink
refactor(torii-graphql): move away from external url (#2753)
Browse files Browse the repository at this point in the history
* refactor(torii-graphql): move away from external url

* fmt

* better patch

* comment typo
  • Loading branch information
Larkooo authored Dec 3, 2024
1 parent 859c9d9 commit 56c0bf7
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 40 deletions.
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_core::types::{Contract, ContractType, Model};
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 @@ async fn main() -> anyhow::Result<()> {
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 main() -> anyhow::Result<()> {
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;

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 async_graphql_warp::graphql_subscription;
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 @@ use crate::query::data::count_rows;
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);
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 @@ fn graphql_filter(
},
);

// 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)"),
)
});

Expand Down

0 comments on commit 56c0bf7

Please sign in to comment.