Skip to content
Draft
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
c85193f
client-api: Create `clear_database` control state method + handle parent
kim Oct 2, 2025
a06c7ca
cli: Add parent support to publish command
kim Oct 2, 2025
5f0abe5
Merge remote-tracking branch 'origin/master' into kim/teams
kim Oct 2, 2025
767a0f9
client-api: Make `DeleteDatabaseParams` field(s) public
kim Oct 7, 2025
1db2a4b
cli: Handle delete confirmation
kim Oct 7, 2025
f86a5d9
Move publish handler back into mono-module
kim Oct 9, 2025
84510e7
Merge remote-tracking branch 'origin/master' into kim/teams
kim Oct 9, 2025
8250080
Move shared types to client-api-messages and render database tree using
kim Oct 10, 2025
faba135
Fix token serialization
kim Oct 10, 2025
59584ae
Add DatabaseTree iterator
kim Oct 10, 2025
f1d6afe
Add simple smoketest
kim Oct 10, 2025
2ae00a7
Merge remote-tracking branch 'origin/master' into kim/teams
kim Oct 10, 2025
7c51072
Regen CLI docs
kim Oct 10, 2025
ca3d1a8
fixup! Regen CLI docs
kim Oct 10, 2025
61f72ee
Debug and fix database names smoke test
kim Oct 13, 2025
0a0966c
smoketests + big arse changes to make clear database + sql work
kim Oct 21, 2025
00977ff
Force an AuthCtx down subscriptions
kim Oct 22, 2025
d869df6
Funnel AuthCtx to one-off queries
kim Oct 22, 2025
a5da347
Make identity routes customizable, like database routes
kim Oct 22, 2025
1e43a75
Merge remote-tracking branch 'origin/master' into kim/teams
kim Oct 23, 2025
fdb5b49
Fix legacy SQL permissions
kim Oct 23, 2025
450ac67
Disable assertion that would require knowledge about the edition
kim Oct 23, 2025
e28f069
Merge remote-tracking branch 'origin/master' into kim/teams
kim Oct 24, 2025
9b8e564
Docs around SQL permissions
kim Oct 24, 2025
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
100 changes: 94 additions & 6 deletions crates/cli/src/subcommands/delete.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
use std::collections::{BTreeMap, BTreeSet};
use std::io;

use crate::common_args;
use crate::config::Config;
use crate::util::{add_auth_header_opt, database_identity, get_auth_header};
use crate::util::{add_auth_header_opt, database_identity, get_auth_header, y_or_n, AuthHeader};
use clap::{Arg, ArgMatches};
use http::StatusCode;
use reqwest::Response;
use spacetimedb_lib::{Hash, Identity};

pub fn cli() -> clap::Command {
clap::Command::new("delete")
Expand All @@ -22,11 +28,93 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E
let force = args.get_flag("force");

let identity = database_identity(&config, database, server).await?;

let builder = reqwest::Client::new().delete(format!("{}/v1/database/{}", config.get_host_url(server)?, identity));
let host_url = config.get_host_url(server)?;
let request_path = format!("{host_url}/v1/database/{identity}");
let auth_header = get_auth_header(&mut config, false, server, !force).await?;
let builder = add_auth_header_opt(builder, &auth_header);
builder.send().await?.error_for_status()?;
let client = reqwest::Client::new();

let response = send_request(&client, &request_path, &auth_header, None).await?;
match response.status() {
StatusCode::PRECONDITION_REQUIRED => {
let confirm = response.json::<ConfirmationResponse>().await?;
println!("WARNING: Deleting the database {identity} will also delete its children:");
confirm.print_database_tree_info(io::stdout())?;
if y_or_n(force, "Do you want to proceed deleting above databases?")? {
send_request(&client, &request_path, &auth_header, Some(confirm.token))
.await?
.error_for_status()?;
} else {
println!("Aborting");
}

Ok(())
}
StatusCode::OK => Ok(()),
_ => response.error_for_status().map(drop).map_err(Into::into),
}
}

async fn send_request(
client: &reqwest::Client,
request_path: &str,
auth: &AuthHeader,
confirmation_token: Option<Hash>,
) -> Result<Response, reqwest::Error> {
let mut builder = client.delete(request_path);
builder = add_auth_header_opt(builder, auth);
if let Some(token) = confirmation_token {
builder = builder.query(&[("token", token.to_string())]);
}
builder.send().await
}

#[derive(serde::Deserialize)]
struct ConfirmationResponse {
database_tree: DatabaseTreeInfo,
token: Hash,
}

impl ConfirmationResponse {
pub fn print_database_tree_info(&self, mut out: impl io::Write) -> anyhow::Result<()> {
let fmt_names = |names: &BTreeSet<String>| match names.len() {
0 => <_>::default(),
1 => format!(": {}", names.first().unwrap()),
_ => format!(": {names:?}"),
};

let tree_info = &self.database_tree;

write!(out, "{}{}", tree_info.root.identity, fmt_names(&tree_info.root.names))?;
for (identity, info) in &tree_info.children {
let names = fmt_names(&info.names);
let parent = info
.parent
.map(|parent| format!(" (parent: {parent})"))
.unwrap_or_default();

write!(out, "{identity}{parent}{names}")?;
}

Ok(())
}
}

// TODO: Should below types be in client-api?

#[derive(serde::Deserialize)]
pub struct DatabaseTreeInfo {
root: RootDatabase,
children: BTreeMap<Identity, DatabaseInfo>,
}

#[derive(serde::Deserialize)]
pub struct RootDatabase {
identity: Identity,
names: BTreeSet<String>,
}

Ok(())
#[derive(serde::Deserialize)]
pub struct DatabaseInfo {
names: BTreeSet<String>,
parent: Option<Identity>,
}
69 changes: 63 additions & 6 deletions crates/cli/src/subcommands/publish.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use anyhow::{ensure, Context};
use clap::Arg;
use clap::ArgAction::{Set, SetTrue};
use clap::ArgMatches;
use reqwest::{StatusCode, Url};
use spacetimedb_client_api_messages::name::{is_identity, parse_database_name, PublishResult};
use spacetimedb_client_api_messages::name::{PrePublishResult, PrettyPrintStyle, PublishOp};
use spacetimedb_client_api_messages::name::{DatabaseNameError, PrePublishResult, PrettyPrintStyle, PublishOp};
use std::path::PathBuf;
use std::{env, fs};

Expand Down Expand Up @@ -64,6 +65,17 @@ pub fn cli() -> clap::Command {
.arg(
common_args::anonymous()
)
.arg(
Arg::new("parent")
.help("Domain or identity of a parent for this database")
.long("parent")
.long_help(
"A valid domain or identity of an existing database that should be the parent of this database.

If a parent is given, the new database inherits the team permissions from the parent.
A parent can only be set when a database is created, not when it is updated."
)
)
.arg(
Arg::new("name|identity")
.help("A valid domain or identity for this database")
Expand Down Expand Up @@ -94,13 +106,17 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E
let build_options = args.get_one::<String>("build_options").unwrap();
let num_replicas = args.get_one::<u8>("num_replicas");
let break_clients_flag = args.get_flag("break_clients");
let parent = args.get_one::<String>("parent");

// If the user didn't specify an identity and we didn't specify an anonymous identity, then
// we want to use the default identity
// TODO(jdetter): We should maybe have some sort of user prompt here for them to be able to
// easily create a new identity with an email
let auth_header = get_auth_header(&mut config, anon_identity, server, !force).await?;

let (name_or_identity, parent) =
validate_name_and_parent(name_or_identity.map(String::as_str), parent.map(String::as_str))?;

if !path_to_project.exists() {
return Err(anyhow::anyhow!(
"Project path does not exist: {}",
Expand Down Expand Up @@ -135,14 +151,11 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E
);

let client = reqwest::Client::new();
// If a domain or identity was provided, we should locally make sure it looks correct and
// If a name was given, ensure to percent-encode it.
// We also use PUT with a name or identity, and POST otherwise.
let mut builder = if let Some(name_or_identity) = name_or_identity {
if !is_identity(name_or_identity) {
parse_database_name(name_or_identity)?;
}
let encode_set = const { &percent_encoding::NON_ALPHANUMERIC.remove(b'_').remove(b'-') };
let domain = percent_encoding::percent_encode(name_or_identity.as_bytes(), encode_set);

let mut builder = client.put(format!("{database_host}/v1/database/{domain}"));

if !clear_database {
Expand Down Expand Up @@ -186,6 +199,9 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E
eprintln!("WARNING: Use of unstable option `--num-replicas`.\n");
builder = builder.query(&[("num_replicas", *n)]);
}
if let Some(parent) = parent {
builder = builder.query(&[("parent", parent)]);
}

println!("Publishing module...");

Expand Down Expand Up @@ -242,6 +258,47 @@ pub async fn exec(mut config: Config, args: &ArgMatches) -> Result<(), anyhow::E
Ok(())
}

fn validate_name_or_identity(name_or_identity: &str) -> Result<(), DatabaseNameError> {
if is_identity(name_or_identity) {
Ok(())
} else {
parse_database_name(name_or_identity).map(drop)
}
}

fn invalid_parent_name(name: &str) -> String {
format!("invalid parent database name `{name}`")
}

fn validate_name_and_parent<'a>(
name: Option<&'a str>,
parent: Option<&'a str>,
) -> anyhow::Result<(Option<&'a str>, Option<&'a str>)> {
if let Some(parent) = parent.as_ref() {
validate_name_or_identity(parent).with_context(|| invalid_parent_name(parent))?;
}

match name {
Some(name) => match name.split_once('/') {
Some((parent_alt, child)) => {
ensure!(
parent.is_none() || parent.is_some_and(|parent| parent == parent_alt),
"cannot specify both --parent and <parent>/<child>"
);
validate_name_or_identity(parent_alt).with_context(|| invalid_parent_name(parent_alt))?;
validate_name_or_identity(child)?;

Ok((Some(child), Some(parent_alt)))
}
None => {
validate_name_or_identity(name)?;
Ok((Some(name), parent))
}
},
None => Ok((None, parent)),
}
}

/// Determine the pretty print style based on the NO_COLOR environment variable.
///
/// See: https://no-color.org
Expand Down
6 changes: 6 additions & 0 deletions crates/client-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ pub struct DatabaseDef {
pub num_replicas: Option<NonZeroU8>,
/// The host type of the supplied program.
pub host_type: HostType,
pub parent: Option<Identity>,
}

/// API of the SpacetimeDB control plane.
Expand Down Expand Up @@ -239,6 +240,7 @@ pub trait ControlStateWriteAccess: Send + Sync {
async fn migrate_plan(&self, spec: DatabaseDef, style: PrettyPrintStyle) -> anyhow::Result<MigratePlanResult>;

async fn delete_database(&self, caller_identity: &Identity, database_identity: &Identity) -> anyhow::Result<()>;
async fn clear_database(&self, caller_identity: &Identity, database_identity: &Identity) -> anyhow::Result<()>;

// Energy
async fn add_energy(&self, identity: &Identity, amount: EnergyQuanta) -> anyhow::Result<()>;
Expand Down Expand Up @@ -339,6 +341,10 @@ impl<T: ControlStateWriteAccess + ?Sized> ControlStateWriteAccess for Arc<T> {
(**self).delete_database(caller_identity, database_identity).await
}

async fn clear_database(&self, caller_identity: &Identity, database_identity: &Identity) -> anyhow::Result<()> {
(**self).clear_database(caller_identity, database_identity).await
}

async fn add_energy(&self, identity: &Identity, amount: EnergyQuanta) -> anyhow::Result<()> {
(**self).add_energy(identity, amount).await
}
Expand Down
Loading