Skip to content

Commit

Permalink
CLI: dedup some code (#29)
Browse files Browse the repository at this point in the history
* simplify is_address

* cli: dedup some code
  • Loading branch information
Centril authored Jun 30, 2023
1 parent 2621de2 commit 6e415e3
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 139 deletions.
21 changes: 4 additions & 17 deletions crates/cli/src/subcommands/call.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use crate::config::Config;
use crate::util::get_auth_header;
use crate::util::spacetime_dns;
use crate::util::{database_address, get_auth_header_only};
use anyhow::Error;
use clap::Arg;
use clap::ArgAction;
use clap::ArgMatches;
use spacetimedb_lib::name::{is_address, DnsLookupResponse};
use clap::{Arg, ArgAction, ArgMatches};

pub fn cli() -> clap::Command {
clap::Command::new("call")
Expand Down Expand Up @@ -51,16 +47,7 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), Error> {
let as_identity = args.get_one::<String>("as_identity");
let anon_identity = args.get_flag("anon_identity");

let address = if is_address(database.as_str()) {
database.clone()
} else {
match spacetime_dns(&config, database).await? {
DnsLookupResponse::Success { domain: _, address } => address,
DnsLookupResponse::Failure { domain } => {
return Err(anyhow::anyhow!("The dns resolution of {} failed.", domain));
}
}
};
let address = database_address(&config, database).await?;

let client = reqwest::Client::new();
let mut builder = client.post(format!(
Expand All @@ -69,7 +56,7 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), Error> {
address,
reducer_name
));
if let Some((auth_header, _)) = get_auth_header(&mut config, anon_identity, as_identity.map(|x| x.as_str())).await {
if let Some(auth_header) = get_auth_header_only(&mut config, anon_identity, as_identity).await {
builder = builder.header("Authorization", auth_header);
}

Expand Down
25 changes: 5 additions & 20 deletions crates/cli/src/subcommands/delete.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
use crate::config::Config;
use crate::util::get_auth_header;
use crate::util::spacetime_dns;
use clap::Arg;

use clap::ArgMatches;
use spacetimedb_lib::name::{is_address, DnsLookupResponse};
use crate::util::{database_address, get_auth_header_only};
use clap::{Arg, ArgMatches};

pub fn cli() -> clap::Command {
clap::Command::new("delete")
Expand All @@ -26,22 +22,11 @@ pub fn cli() -> clap::Command {

pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
let database = args.get_one::<String>("database").unwrap();

let identity_or_name = args.get_one::<String>("identity");
let auth_header = get_auth_header(&mut config, false, identity_or_name.map(|x| x.as_str()))
.await
.map(|x| x.0);

let address = if is_address(database.as_str()) {
database.clone()
} else {
match spacetime_dns(&config, database).await? {
DnsLookupResponse::Success { domain: _, address } => address,
DnsLookupResponse::Failure { domain } => {
return Err(anyhow::anyhow!("The dns resolution of {} failed.", domain));
}
}
};
let auth_header = get_auth_header_only(&mut config, false, identity_or_name).await;

let address = database_address(&config, database).await?;

let client = reqwest::Client::new();
let mut builder = client.post(format!("{}/database/delete/{}", config.get_host_url(), address));
Expand Down
22 changes: 4 additions & 18 deletions crates/cli/src/subcommands/describe.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use crate::config::Config;
use crate::util::{get_auth_header, spacetime_dns};
use clap::Arg;
use clap::ArgAction::SetTrue;
use clap::ArgMatches;
use spacetimedb_lib::name::{is_address, DnsLookupResponse};
use crate::util::{database_address, get_auth_header_only};
use clap::{Arg, ArgAction::SetTrue, ArgMatches};

pub fn cli() -> clap::Command {
clap::Command::new("describe")
Expand Down Expand Up @@ -53,20 +50,9 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E
let as_identity = args.get_one::<String>("as_identity");
let anon_identity = args.get_flag("anon_identity");

let auth_header = get_auth_header(&mut config, anon_identity, as_identity.map(|x| x.as_str()))
.await
.map(|x| x.0);
let auth_header = get_auth_header_only(&mut config, anon_identity, as_identity).await;

let address = if is_address(database.as_str()) {
database.clone()
} else {
match spacetime_dns(&config, database).await? {
DnsLookupResponse::Success { domain: _, address } => address,
DnsLookupResponse::Failure { domain } => {
return Err(anyhow::anyhow!("The dns resolution of {} failed.", domain));
}
}
};
let address = database_address(&config, database).await?;

let res = match entity_name {
None => {
Expand Down
6 changes: 2 additions & 4 deletions crates/cli/src/subcommands/dns.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::config::Config;
use crate::util::{get_auth_header, spacetime_dns, spacetime_register_tld, spacetime_reverse_dns};
use crate::util::{get_auth_header_only, spacetime_dns, spacetime_register_tld, spacetime_reverse_dns};
use clap::ArgMatches;
use clap::{Arg, Command};
use reqwest::Url;
Expand Down Expand Up @@ -113,9 +113,7 @@ pub async fn exec_set_name(mut config: Config, args: &ArgMatches) -> Result<(),
let domain = args.get_one::<String>("domain").unwrap();
let address = args.get_one::<String>("address").unwrap();
let identity = args.get_one::<String>("identity");
let (auth_header, _) = get_auth_header(&mut config, false, identity.map(|x| x.as_str()))
.await
.unwrap();
let auth_header = get_auth_header_only(&mut config, false, identity).await.unwrap();

let query_params = vec![
("domain", domain.clone()),
Expand Down
18 changes: 3 additions & 15 deletions crates/cli/src/subcommands/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ use std::borrow::Cow;
use std::io::{self, Write};

use crate::config::Config;
use crate::util::get_auth_header;
use crate::util::spacetime_dns;
use clap::ArgMatches;
use clap::{Arg, ArgAction};
use crate::util::{database_address, get_auth_header};
use clap::{Arg, ArgAction, ArgMatches};
use futures::{AsyncBufReadExt, TryStreamExt};
use is_terminal::IsTerminal;
use spacetimedb_lib::name::{is_address, DnsLookupResponse};
use termcolor::{Color, ColorSpec, WriteColor};

pub fn cli() -> clap::Command {
Expand Down Expand Up @@ -92,16 +89,7 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E
.await
.map(|x| x.0);

let address = if is_address(database.as_str()) {
database.clone()
} else {
match spacetime_dns(&config, database).await? {
DnsLookupResponse::Success { domain: _, address } => address,
DnsLookupResponse::Failure { domain } => {
return Err(anyhow::anyhow!("The dns resolution of {} failed.", domain));
}
}
};
let address = database_address(&config, database).await?;

// TODO: num_lines should default to like 10 if follow is specified?
let query_parms = LogsParams { num_lines, follow };
Expand Down
37 changes: 7 additions & 30 deletions crates/cli/src/subcommands/sql.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
use crate::api::{from_json_seed, ClientApi, Connection, StmtResultJson};
use anyhow::Context;
use clap::Arg;
use clap::ArgAction;
use clap::ArgMatches;
use clap::{Arg, ArgAction, ArgMatches};
use reqwest::RequestBuilder;
use spacetimedb_lib::de::serde::SeedWrapper;
use spacetimedb_lib::name::{is_address, DnsLookupResponse};
use spacetimedb_lib::sats::satn;
use spacetimedb_lib::sats::Typespace;
use spacetimedb_lib::sats::{satn, Typespace};
use tabled::builder::Builder;
use tabled::Style;

use crate::config::Config;
use crate::util::get_auth_header;
use crate::util::spacetime_dns;
use crate::util::{database_address, get_auth_header_only};

pub fn cli() -> clap::Command {
clap::Command::new("sql")
Expand Down Expand Up @@ -48,33 +43,15 @@ pub fn cli() -> clap::Command {

pub(crate) async fn parse_req(mut config: Config, args: &ArgMatches) -> Result<Connection, anyhow::Error> {
let database = args.get_one::<String>("database").unwrap();

let as_identity = args.get_one::<String>("as_identity");
let anon_identity = args.get_flag("anon_identity");

let auth_header = get_auth_header(&mut config, anon_identity, as_identity.map(|x| x.as_str()))
.await
.map(|x| x.0);

let address = if is_address(database.as_str()) {
database.clone()
} else {
match spacetime_dns(&config, database).await? {
DnsLookupResponse::Success { domain: _, address } => address,
DnsLookupResponse::Failure { domain } => {
return Err(anyhow::anyhow!("The dns resolution of {} failed.", domain));
}
}
};

let con = Connection {
Ok(Connection {
host: config.get_host_url(),
address,
auth_header: get_auth_header_only(&mut config, anon_identity, as_identity).await,
address: database_address(&config, database).await?,
database: database.to_string(),
auth_header,
};

Ok(con)
})
}

pub(crate) async fn run_sql(builder: RequestBuilder, sql: &str) -> Result<(), anyhow::Error> {
Expand Down
28 changes: 4 additions & 24 deletions crates/cli/src/subcommands/tracelog.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
use crate::config::Config;
use crate::util::spacetime_dns;
use clap::Arg;
use clap::ArgMatches;
use crate::util::database_address;
use clap::{Arg, ArgMatches};
use reqwest::StatusCode;
use spacetimedb_lib::name::{is_address, DnsLookupResponse};
use std::path::Path;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
Expand Down Expand Up @@ -72,16 +70,7 @@ pub async fn exec_replay(config: Config, args: &ArgMatches) -> Result<(), anyhow

pub async fn exec_stop(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
let database = args.get_one::<String>("database").unwrap();
let address = if is_address(database.as_str()) {
database.clone()
} else {
match spacetime_dns(&config, database).await? {
DnsLookupResponse::Success { domain: _, address } => address,
DnsLookupResponse::Failure { domain } => {
return Err(anyhow::anyhow!("The dns resolution of {} failed.", domain));
}
}
};
let address = database_address(&config, database).await?;

let client = reqwest::Client::new();
let res = client
Expand All @@ -105,16 +94,7 @@ pub async fn exec_stop(config: Config, args: &ArgMatches) -> Result<(), anyhow::

pub async fn exec_get(config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
let database = args.get_one::<String>("database").unwrap();
let address = if is_address(database.as_str()) {
database.clone()
} else {
match spacetime_dns(&config, database).await? {
DnsLookupResponse::Success { domain: _, address } => address,
DnsLookupResponse::Failure { domain } => {
return Err(anyhow::anyhow!("The dns resolution of {} failed.", domain));
}
}
};
let address = database_address(&config, database).await?;

let client = reqwest::Client::new();
let res = client
Expand Down
30 changes: 25 additions & 5 deletions crates/cli/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use clap::{
};

use serde::Deserialize;
use spacetimedb_lib::name::{DnsLookupResponse, RegisterTldResult, ReverseDNSResponse};
use spacetimedb_lib::name::{is_address, DnsLookupResponse, RegisterTldResult, ReverseDNSResponse};
use spacetimedb_lib::Identity;

use crate::config::{Config, IdentityConfig};
Expand Down Expand Up @@ -42,6 +42,17 @@ pub fn match_subcommand_or_exit(command: Command) -> (String, ArgMatches) {
(cmd.to_string(), subcommand_args.clone())
}

/// Determine the address of the `database`.
pub async fn database_address(config: &Config, database: &str) -> Result<String, anyhow::Error> {
if is_address(database) {
return Ok(database.to_string());
}
match spacetime_dns(config, database).await? {
DnsLookupResponse::Success { domain: _, address } => Ok(address),
DnsLookupResponse::Failure { domain } => Err(anyhow::anyhow!("The dns resolution of `{}` failed.", domain)),
}
}

/// Converts a name to a database address.
pub async fn spacetime_dns(config: &Config, domain: &str) -> Result<DnsLookupResponse, anyhow::Error> {
let client = reqwest::Client::new();
Expand All @@ -59,9 +70,7 @@ pub async fn spacetime_register_tld(
tld: &str,
identity: Option<&String>,
) -> Result<RegisterTldResult, anyhow::Error> {
let (auth_header, _) = get_auth_header(config, false, identity.map(|x| x.as_str()))
.await
.unwrap();
let auth_header = get_auth_header_only(config, false, identity).await.unwrap();

// TODO(jdetter): Fix URL encoding on specifying this domain
let builder = reqwest::Client::new()
Expand Down Expand Up @@ -170,6 +179,17 @@ pub async fn select_identity_config(
}
}

/// See [`get_auth_header`].
pub async fn get_auth_header_only(
config: &mut Config,
anon_identity: bool,
identity_or_name: Option<&String>,
) -> Option<String> {
get_auth_header(config, anon_identity, identity_or_name.map(|x| x.as_str()))
.await
.map(|(ah, _)| ah)
}

/// Gets the `auth_header` for a request to the server depending on how you want
/// to identify yourself. If you specify `anon_identity = true` then no
/// `auth_header` is returned. If you specify an identity this function will try
Expand All @@ -181,7 +201,7 @@ pub async fn select_identity_config(
/// # Arguments
/// * `config` - The config file reference
/// * `anon_identity` - Whether or not to just use an anonymous identity (no identity)
/// * `identity` - The identity to try to lookup, which is typically provided from the command line
/// * `identity_or_name` - The identity to try to lookup, which is typically provided from the command line
pub async fn get_auth_header(
config: &mut Config,
anon_identity: bool,
Expand Down
10 changes: 4 additions & 6 deletions crates/lib/src/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,13 +366,11 @@ pub struct ReverseDNSResponse {
pub names: Vec<DomainName>,
}

/// Returns whether a hex string is a valid address. Any string that is a valid address is
/// an invalid database name
/// Returns whether a hex string is a valid address.
///
/// Any string that is a valid address is an invalid database name.
pub fn is_address(hex: &str) -> bool {
match hex::decode(hex) {
Ok(value) => value.len() == 16,
Err(_) => false,
}
hex::decode(hex).map_or(false, |value| value.len() == 16)
}

#[derive(thiserror::Error, Debug)]
Expand Down

0 comments on commit 6e415e3

Please sign in to comment.