spacetimedb_cli/subcommands/
publish.rs

1use clap::Arg;
2use clap::ArgAction::{Set, SetTrue};
3use clap::ArgMatches;
4use reqwest::{StatusCode, Url};
5use spacetimedb_client_api_messages::name::PublishOp;
6use spacetimedb_client_api_messages::name::{is_identity, parse_database_name, PublishResult};
7use std::fs;
8use std::path::PathBuf;
9
10use crate::config::Config;
11use crate::util::{add_auth_header_opt, get_auth_header, ResponseExt};
12use crate::util::{decode_identity, unauth_error_context, y_or_n};
13use crate::{build, common_args};
14
15pub fn cli() -> clap::Command {
16    clap::Command::new("publish")
17        .about("Create and update a SpacetimeDB database")
18        .arg(
19            Arg::new("clear_database")
20                .long("delete-data")
21                .short('c')
22                .action(SetTrue)
23                .requires("name|identity")
24                .help("When publishing to an existing database identity, first DESTROY all data associated with the module"),
25        )
26        .arg(
27            Arg::new("build_options")
28                .long("build-options")
29                .alias("build-opts")
30                .action(Set)
31                .default_value("")
32                .help("Options to pass to the build command, for example --build-options='--lint-dir='")
33        )
34        .arg(
35            Arg::new("project_path")
36                .value_parser(clap::value_parser!(PathBuf))
37                .default_value(".")
38                .long("project-path")
39                .short('p')
40                .help("The system path (absolute or relative) to the module project")
41        )
42        .arg(
43            Arg::new("wasm_file")
44                .value_parser(clap::value_parser!(PathBuf))
45                .long("bin-path")
46                .short('b')
47                .conflicts_with("project_path")
48                .conflicts_with("build_options")
49                .help("The system path (absolute or relative) to the compiled wasm binary we should publish, instead of building the project."),
50        )
51        .arg(
52            common_args::anonymous()
53        )
54        .arg(
55            Arg::new("name|identity")
56                .help("A valid domain or identity for this database")
57                .long_help(
58"A valid domain or identity for this database.
59
60Database names must match the regex `/^[a-z0-9]+(-[a-z0-9]+)*$/`,
61i.e. only lowercase ASCII letters and numbers, separated by dashes."),
62        )
63        .arg(common_args::server()
64                .help("The nickname, domain name or URL of the server to host the database."),
65        )
66        .arg(
67            common_args::yes()
68        )
69        .after_help("Run `spacetime help publish` for more detailed information.")
70}
71
72pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::Error> {
73    let server = args.get_one::<String>("server").map(|s| s.as_str());
74    let name_or_identity = args.get_one::<String>("name|identity");
75    let path_to_project = args.get_one::<PathBuf>("project_path").unwrap();
76    let clear_database = args.get_flag("clear_database");
77    let force = args.get_flag("force");
78    let anon_identity = args.get_flag("anon_identity");
79    let wasm_file = args.get_one::<PathBuf>("wasm_file");
80    let database_host = config.get_host_url(server)?;
81    let build_options = args.get_one::<String>("build_options").unwrap();
82
83    // If the user didn't specify an identity and we didn't specify an anonymous identity, then
84    // we want to use the default identity
85    // TODO(jdetter): We should maybe have some sort of user prompt here for them to be able to
86    //  easily create a new identity with an email
87    let auth_header = get_auth_header(&mut config, anon_identity, server, !force).await?;
88
89    let client = reqwest::Client::new();
90
91    // If a domain or identity was provided, we should locally make sure it looks correct and
92    let mut builder = if let Some(name_or_identity) = name_or_identity {
93        if !is_identity(name_or_identity) {
94            parse_database_name(name_or_identity)?;
95        }
96        let encode_set = const { &percent_encoding::NON_ALPHANUMERIC.remove(b'_').remove(b'-') };
97        let domain = percent_encoding::percent_encode(name_or_identity.as_bytes(), encode_set);
98        client.put(format!("{database_host}/v1/database/{domain}"))
99    } else {
100        client.post(format!("{database_host}/v1/database"))
101    };
102
103    if !path_to_project.exists() {
104        return Err(anyhow::anyhow!(
105            "Project path does not exist: {}",
106            path_to_project.display()
107        ));
108    }
109
110    let path_to_wasm = if let Some(path) = wasm_file {
111        println!("Skipping build. Instead we are publishing {}", path.display());
112        path.clone()
113    } else {
114        build::exec_with_argstring(config.clone(), path_to_project, build_options).await?
115    };
116    let program_bytes = fs::read(path_to_wasm)?;
117
118    let server_address = {
119        let url = Url::parse(&database_host)?;
120        url.host_str().unwrap_or("<default>").to_string()
121    };
122    if server_address != "localhost" && server_address != "127.0.0.1" {
123        println!("You are about to publish to a non-local server: {}", server_address);
124        if !y_or_n(force, "Are you sure you want to proceed?")? {
125            println!("Aborting");
126            return Ok(());
127        }
128    }
129
130    println!(
131        "Uploading to {} => {}",
132        server.unwrap_or(config.default_server_name().unwrap_or("<default>")),
133        database_host
134    );
135
136    if clear_database {
137        // Note: `name_or_identity` should be set, because it is `required` in the CLI arg config.
138        println!(
139            "This will DESTROY the current {} module, and ALL corresponding data.",
140            name_or_identity.unwrap()
141        );
142        if !y_or_n(
143            force,
144            format!(
145                "Are you sure you want to proceed? [deleting {}]",
146                name_or_identity.unwrap()
147            )
148            .as_str(),
149        )? {
150            println!("Aborting");
151            return Ok(());
152        }
153        builder = builder.query(&[("clear", true)]);
154    }
155
156    println!("Publishing module...");
157
158    builder = add_auth_header_opt(builder, &auth_header);
159
160    let res = builder.body(program_bytes).send().await?;
161    if res.status() == StatusCode::UNAUTHORIZED && !anon_identity {
162        // If we're not in the `anon_identity` case, then we have already forced the user to log in above (using `get_auth_header`), so this should be safe to unwrap.
163        let token = config.spacetimedb_token().unwrap();
164        let identity = decode_identity(token)?;
165        let err = res.text().await?;
166        return unauth_error_context(
167            Err(anyhow::anyhow!(err)),
168            &identity,
169            config.server_nick_or_host(server)?,
170        );
171    }
172
173    let response: PublishResult = res.json_or_error().await?;
174    match response {
175        PublishResult::Success {
176            domain,
177            database_identity,
178            op,
179        } => {
180            let op = match op {
181                PublishOp::Created => "Created new",
182                PublishOp::Updated => "Updated",
183            };
184            if let Some(domain) = domain {
185                println!("{} database with name: {}, identity: {}", op, domain, database_identity);
186            } else {
187                println!("{} database with identity: {}", op, database_identity);
188            }
189        }
190        PublishResult::PermissionDenied { name } => {
191            if anon_identity {
192                anyhow::bail!("You need to be logged in as the owner of {name} to publish to {name}",);
193            }
194            // If we're not in the `anon_identity` case, then we have already forced the user to log in above (using `get_auth_header`), so this should be safe to unwrap.
195            let token = config.spacetimedb_token().unwrap();
196            let identity = decode_identity(token)?;
197            //TODO(jdetter): Have a nice name generator here, instead of using some abstract characters
198            // we should perhaps generate fun names like 'green-fire-dragon' instead
199            let suggested_tld: String = identity.chars().take(12).collect();
200            return Err(anyhow::anyhow!(
201                "The database {name} is not registered to the identity you provided.\n\
202                We suggest you push to either a domain owned by you, or a new domain like:\n\
203                \tspacetime publish {suggested_tld}\n",
204            ));
205        }
206    }
207
208    Ok(())
209}