From 57ab0e5455b956b87731cb9df428ce9ae3c5d500 Mon Sep 17 00:00:00 2001 From: broisnees Date: Tue, 24 Nov 2026 04:49:53 +0000 Subject: [PATCH] Add Convex as a provider and engine The Convex card signs in with Convex's OAuth app flow (team scope), lists every cloud deployment on the authorized team, and creates a deploy key named Stroke on the one I pick. The code exchange goes through the stroke.click token proxy, which holds CONVEX_CLIENT_SECRET. Convex (URL + key) in the type list connects any deployment by URL and deploy or admin key, including self-hosted backends. Once connected, tables and document counts show in the sidebar, and the grid pages documents newest first with filters, inline edits, insert, replace and delete through the dashboard's _system/frontend functions. Int64 values round trip exactly. The console runs deployed functions with JSON args or reads a table with users.limit(n) and users.get(id). Read-only mode and the MCP server's read-only level refuse function calls, since a function can write. Also: bind variables are off for Convex (messages:list read as :list), and a rejected token names the provider's own fields instead of Upstash's. --- .changeset/convex.md | 9 + src-tauri/src/commands.rs | 22 ++ src-tauri/src/db/connection.rs | 8 +- src-tauri/src/db/convex.rs | 427 ++++++++++++++++++++++ src-tauri/src/db/couchdb.rs | 2 + src-tauri/src/db/docdb.rs | 25 +- src-tauri/src/db/mod.rs | 1 + src-tauri/src/lib.rs | 3 + src-tauri/src/mcp/access.rs | 12 + src-tauri/src/mcp/tools.rs | 6 +- src-tauri/src/providers/convex.rs | 217 +++++++++++ src-tauri/src/providers/mod.rs | 20 +- src/lib/ai-query-languages.js | 14 +- src/lib/api.js | 53 ++- src/lib/components/ConnectionModal.svelte | 58 ++- src/lib/components/DocBrowser.svelte | 6 +- src/lib/components/ProviderConnect.svelte | 11 +- src/lib/components/SqlEditor.svelte | 2 +- src/lib/components/StatusBar.svelte | 3 +- src/lib/components/StudioShell.svelte | 18 +- src/lib/components/TerminalPage.svelte | 2 +- src/lib/connection-provider.js | 2 + src/lib/connection-provider.test.js | 9 + src/lib/db-capabilities.js | 5 +- src/lib/doc-adapters.js | 129 ++++++- src/lib/doc-adapters.test.js | 85 ++++- src/lib/engine-tint.js | 2 + src/lib/providers-auth.test.js | 16 +- src/lib/providers.js | 10 +- src/lib/sql-auto-limit.js | 2 +- src/lib/sql-params.js | 5 +- src/lib/sql-params.test.js | 7 + src/lib/sql-write.js | 12 + src/lib/sql-write.test.js | 19 +- src/lib/stores/connections.js | 6 +- 35 files changed, 1179 insertions(+), 49 deletions(-) create mode 100644 .changeset/convex.md create mode 100644 src-tauri/src/db/convex.rs create mode 100644 src-tauri/src/providers/convex.rs diff --git a/.changeset/convex.md b/.changeset/convex.md new file mode 100644 index 00000000..09a746a5 --- /dev/null +++ b/.changeset/convex.md @@ -0,0 +1,9 @@ +### New Features + +#### Connections +- **Convex** - Connect to Convex two ways. The Convex provider card signs in with Convex in the browser, lists every cloud deployment on the team you authorize (production, development and previews), and creates a deploy key named Stroke for the one you pick. Convex (URL + key) connects any deployment by its URL and a deploy or admin key, including self-hosted backends and `npx convex dev --local`. +- **Browse and edit Convex tables** - Tables and their document counts in the sidebar, newest documents first, filters like `age > 30 AND plan == "pro"`, inline cell edits, and insert, replace and delete. Int64 values show and edit as whole numbers without losing precision. +- **Convex console** - Run a deployed function with its arguments, `messages:list {"limit": 5}`, or read a table with `users.limit(20)` and `users.get("")`. A function can write, so read-only mode and the MCP server's read-only access refuse function calls. + +### Bug Fixes +- Rejected tokens for PostHog, Xata and SingleStore no longer ask to check "the email and API key": the message names that provider's own fields. diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 600f60a2..47c28df7 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -1091,6 +1091,28 @@ pub async fn firestore_request( crate::db::firestore::request(&cfg, &method, &path, body.as_ref()).await } +// ── Convex ──────────────────────────────────────────────────────────────────── + +#[tauri::command] +pub async fn test_convex(config: crate::db::convex::ConvexConfig) -> Result<(), String> { + crate::db::convex::ping(&config).await +} + +#[tauri::command] +pub async fn connect_convex_db(state: Db<'_>, config: crate::db::convex::ConvexConfig) -> Result<(), String> { + crate::db::connection::connect_convex(state, config).await +} + +/// One of the dashboard's system functions (`db::convex::SYSTEM` only). +#[tauri::command] +pub async fn convex_call(state: Db<'_>, path: String, args: serde_json::Value) -> Result { + let cfg = match require_conn(&state)? { + ActiveConnection::Doc(crate::db::docdb::DocConn::Convex(cfg)) => cfg, + _ => return Err("Not connected to Convex".into()), + }; + crate::db::convex::system_call(&cfg, &path, args).await +} + // ── Cassandra ───────────────────────────────────────────────────────────────── #[tauri::command] diff --git a/src-tauri/src/db/connection.rs b/src-tauri/src/db/connection.rs index 4500235b..531aa9a8 100644 --- a/src-tauri/src/db/connection.rs +++ b/src-tauri/src/db/connection.rs @@ -437,7 +437,7 @@ pub enum ActiveConnection { Clickhouse(ClickhouseConfig), Redis(RedisConfig), Dynamodb(crate::db::dynamodb::DynamoConfig), - /// CouchDB, Cassandra, Firestore: see `db::docdb`. + /// CouchDB, Cassandra, Firestore, Convex, ...: see `db::docdb`. Doc(crate::db::docdb::DocConn), Duckdb(DuckdbHandle), Mssql(MssqlHandle), @@ -1970,6 +1970,12 @@ pub async fn connect_neo4j(state: Db<'_>, config: crate::db::neo4j::Neo4jConfig) set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Neo4j(config)))) } +/// Convex: a deployment URL and its deploy or admin key. +pub async fn connect_convex(state: Db<'_>, config: crate::db::convex::ConvexConfig) -> Result<(), String> { + crate::db::convex::ping(&config).await?; + set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Convex(config)))) +} + pub async fn connect_firestore(state: Db<'_>, config: crate::db::firestore::FirestoreConfig) -> Result<(), String> { crate::db::firestore::ping(&config).await?; set_conn(&state, Some(ActiveConnection::Doc(crate::db::docdb::DocConn::Firestore(config)))) diff --git a/src-tauri/src/db/convex.rs b/src-tauri/src/db/convex.rs new file mode 100644 index 00000000..eb81f504 --- /dev/null +++ b/src-tauri/src/db/convex.rs @@ -0,0 +1,427 @@ +//! Convex, over a deployment's HTTP API with its admin (deploy) key. +//! +//! Browsing and editing use the same system functions the Convex dashboard +//! calls (`_system/frontend/*`): the table list, a page of documents with the +//! dashboard's filter expression, and insert/replace/delete. They run as +//! ordinary queries and mutations on `POST /api/query` and `/api/mutation` +//! with `Authorization: Convex `. Only the calls in `SYSTEM` go out +//! from the browser; the console runs the app's own deployed functions. +//! +//! Values travel in Convex's encoded JSON, where an int64 is +//! `{"$integer": }`. The app sees it as +//! `{"$integer": ""}` so the grid shows and edits the number; `encode` +//! turns it back on the way in. + +use base64::{engine::general_purpose::STANDARD as B64, Engine as _}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ConvexConfig { + pub name: String, + /// The deployment URL, `https://happy-animal-123.convex.cloud`. + pub url: String, + /// An admin key or deploy key (`prod:happy-animal-123|ey...`). + pub admin_key: String, +} + +impl ConvexConfig { + pub fn base_url(&self) -> String { + let u = self.url.trim().trim_end_matches('/'); + if u.starts_with("http://") || u.starts_with("https://") { u.to_string() } else { format!("https://{u}") } + } +} + +fn client() -> &'static reqwest::Client { + static C: OnceLock = OnceLock::new(); + C.get_or_init(|| { + crate::proxy::http_builder(crate::proxy::Kind::Database) + .user_agent("stroke/1.0") + .connect_timeout(Duration::from_secs(10)) + // Convex stops a query at 1s of database time and a mutation at + // 1s too; actions run up to 10 minutes. + .timeout(Duration::from_secs(120)) + .build() + .expect("failed to build Convex HTTP client") + }) +} + +/// The system functions the browser may call, and whether each one writes. +pub const SYSTEM: &[(&str, bool)] = &[ + ("_system/frontend/getTableMapping", false), + ("_system/frontend/tableSize", false), + ("_system/frontend/paginatedTableDocuments", false), + ("_system/frontend/getById", false), + ("_system/frontend/indexes", false), + ("_system/frontend/addDocument", true), + ("_system/frontend/replaceDocument", true), + ("_system/frontend/deleteDocuments", true), + ("_system/frontend/patchDocumentsFields", true), + ("_system/frontend/createTable", true), +]; + +/// Tables the dashboard lists although their names start with `_`. +const SHOWN_SYSTEM_TABLES: &[&str] = &["_scheduled_jobs", "_file_storage"]; + +// ── Values ─────────────────────────────────────────────────────────────────── + +/// Convex encoded JSON → the app's JSON: `$integer` as a decimal string. +pub fn decode(v: Value) -> Value { + match v { + Value::Array(a) => Value::Array(a.into_iter().map(decode).collect()), + Value::Object(o) => { + if o.len() == 1 { + if let Some(Value::String(b)) = o.get("$integer") { + if let Some(n) = B64.decode(b).ok().and_then(|x| <[u8; 8]>::try_from(x).ok()).map(i64::from_le_bytes) { + return json!({ "$integer": n.to_string() }); + } + } + } + Value::Object(o.into_iter().map(|(k, x)| (k, decode(x))).collect()) + } + other => other, + } +} + +/// The app's JSON → Convex encoded JSON. A `$integer` that is already base64 +/// (as a pasted document might carry) passes through. +pub fn encode(v: Value) -> Result { + Ok(match v { + Value::Array(a) => Value::Array(a.into_iter().map(encode).collect::>()?), + Value::Object(o) => { + if o.len() == 1 { + match o.get("$integer") { + // Eight bytes in base64 always end in one `=`; a decimal never does. + Some(Value::String(s)) if s.ends_with('=') => { + return Ok(Value::Object(o)); + } + Some(Value::String(s)) => { + let n: i64 = s.trim().parse().map_err(|_| format!("\"{s}\" is not a 64-bit integer"))?; + return Ok(json!({ "$integer": B64.encode(n.to_le_bytes()) })); + } + Some(Value::Number(n)) if n.is_i64() => { + return Ok(json!({ "$integer": B64.encode(n.as_i64().unwrap_or(0).to_le_bytes()) })); + } + _ => {} + } + } + Value::Object(o.into_iter().map(|(k, x)| encode(x).map(|x| (k, x))).collect::>()?) + } + other => other, + }) +} + +// ── Calls ──────────────────────────────────────────────────────────────────── + +/// `query` | `mutation` | `action` | `function` (any kind, for the console). +async fn call_raw(cfg: &ConvexConfig, kind: &str, path: &str, args: &Value) -> Result { + if cfg.url.trim().is_empty() { + return Err("Enter the deployment URL".into()); + } + if cfg.admin_key.trim().is_empty() { + return Err("Enter a deploy key or admin key".into()); + } + let url = format!("{}/api/{kind}", cfg.base_url()); + let resp = client() + .post(&url) + .header("Authorization", format!("Convex {}", cfg.admin_key.trim())) + .json(&json!({ "path": path, "args": args, "format": "convex_encoded_json" })) + .send() + .await + .map_err(|e| if e.is_connect() { format!("Could not reach Convex at {}: {e}", cfg.base_url()) } else { e.to_string() })?; + let status = resp.status().as_u16(); + let text = resp.text().await.map_err(|e| e.to_string())?; + let body: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + if status == 401 || body["code"] == "BadAdminKey" || body["code"] == "BadDeployKey" { + // "401" lets the app's auth-failure check mint a fresh deploy key for + // a provider connection whose key was revoked. + return Err("Convex refused the key (401). Use a deploy key or admin key for this deployment.".into()); + } + match body["status"].as_str() { + Some("success") => Ok(decode(body["value"].clone())), + Some("error") => Err(error_text(&body)), + _ if !(200..300).contains(&status) => { + let msg = body["message"].as_str().map(String::from).unwrap_or_else(|| text.chars().take(300).collect()); + Err(format!("Convex error ({status}): {msg}")) + } + _ => Err(format!("Unexpected Convex response: {}", text.chars().take(300).collect::())), + } +} + +/// `errorMessage` without the request id prefix and the `Server Error` line. +fn error_text(body: &Value) -> String { + let raw = body["errorMessage"].as_str().unwrap_or("Convex function failed"); + let mut s = raw.trim(); + if s.starts_with("[Request ID:") { + s = s.split_once(']').map(|(_, r)| r.trim_start()).unwrap_or(s); + } + let s = s.strip_prefix("Server Error").map(str::trim_start).unwrap_or(s); + let s = s.strip_prefix("Uncaught ").unwrap_or(s); + s.trim().to_string() +} + +/// One system function from the browser, checked against `SYSTEM`. +pub async fn system_call(cfg: &ConvexConfig, path: &str, args: Value) -> Result { + let (_, writes) = SYSTEM.iter().find(|(p, _)| *p == path).ok_or_else(|| format!("{path} is not available from Stroke"))?; + // Without `ids` this one patches every document in the table. + if path == "_system/frontend/patchDocumentsFields" && !args["ids"].as_array().is_some_and(|ids| !ids.is_empty()) { + return Err("patchDocumentsFields needs the ids of the documents to change".into()); + } + call_raw(cfg, if *writes { "mutation" } else { "query" }, path, &encode(args)?).await +} + +/// Connection test: the table list. +pub async fn ping(cfg: &ConvexConfig) -> Result<(), String> { + list_tables(cfg).await.map(|_| ()) +} + +/// Table names, user tables first, then the two system tables the dashboard shows. +pub async fn list_tables(cfg: &ConvexConfig) -> Result, String> { + let m = call_raw(cfg, "query", "_system/frontend/getTableMapping", &json!({})).await?; + let mut names: Vec = m.as_object().into_iter().flatten().filter_map(|(_, n)| n.as_str().map(String::from)).collect(); + names.retain(|n| !n.starts_with('_') || SHOWN_SYSTEM_TABLES.contains(&n.as_str())); + names.sort_by(|a, b| a.starts_with('_').cmp(&b.starts_with('_')).then_with(|| a.cmp(b))); + names.dedup(); + Ok(names) +} + +pub async fn table_size(cfg: &ConvexConfig, table: &str) -> Result { + let v = call_raw(cfg, "query", "_system/frontend/tableSize", &json!({ "tableName": table })).await?; + Ok(v.as_f64().map(|n| n as i64).unwrap_or(-1)) +} + +/// One page of a table, newest first, as the dashboard pages it. +pub async fn page(cfg: &ConvexConfig, table: &str, limit: u64, cursor: Option<&str>) -> Result<(Vec, Option), String> { + let v = call_raw( + cfg, + "query", + "_system/frontend/paginatedTableDocuments", + &json!({ "table": table, "filters": null, "paginationOpts": { "numItems": limit, "cursor": cursor } }), + ) + .await?; + let docs = v["page"].as_array().cloned().unwrap_or_default(); + let next = if v["isDone"].as_bool().unwrap_or(true) { None } else { v["continueCursor"].as_str().map(String::from) }; + Ok((docs, next)) +} + +// ── Console ────────────────────────────────────────────────────────────────── + +#[derive(Debug, PartialEq)] +pub enum Statement { + /// `users`, `users.limit(20)`: documents, newest first. + Table { table: String, limit: u64 }, + /// `users.get("j57...")`: one document by id. + Get { id: String }, + /// `messages:list {"limit": 5}`: a deployed function and its arguments. + Call { path: String, args: Value }, +} + +const USAGE: &str = r#"Run a deployed function as messages:list {"limit": 5}, or read a table with users, users.limit(20) or users.get("")"#; + +fn is_ident(s: &str) -> bool { + !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +/// A function path: `module:name`, `dir/module:name`, or `module` (its default export). +fn is_function_path(s: &str) -> bool { + let (module, name) = s.split_once(':').unwrap_or((s, "default")); + is_ident(name) && !module.is_empty() && module.split('/').all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))) +} + +pub fn parse(stmt: &str) -> Result { + let s = stmt.trim().trim_end_matches(';').trim(); + if s.is_empty() { + return Err(USAGE.into()); + } + // `module:fn` then optional JSON args. + let head_end = s.find(|c: char| c.is_whitespace() || c == '(' || c == '{').unwrap_or(s.len()); + let head = &s[..head_end]; + if head.contains(':') { + if !is_function_path(head) { + return Err(format!("\"{head}\" is not a function path. {USAGE}")); + } + if head.starts_with("_system") { + return Err("System functions are not available from the console".into()); + } + let mut rest = s[head_end..].trim(); + if rest.starts_with('(') && rest.ends_with(')') { + rest = rest[1..rest.len() - 1].trim(); + } + let args = if rest.is_empty() { json!({}) } else { serde_json::from_str(rest).map_err(|e| format!("The arguments aren't valid JSON: {e}"))? }; + if !args.is_object() { + return Err("Function arguments are one JSON object, e.g. {\"limit\": 5}".into()); + } + return Ok(Statement::Call { path: head.to_string(), args }); + } + // `table`, `table.limit(n)`, `table.get("id")`. + let (table, call) = match s.split_once('.') { + Some((t, c)) => (t.trim(), Some(c.trim())), + None => (s, None), + }; + if !is_ident(table) { + return Err(USAGE.into()); + } + let arg = |c: &str, name: &str| -> Option { c.strip_prefix(name)?.strip_prefix('(')?.strip_suffix(')').map(|a| a.trim().to_string()) }; + match call { + None => Ok(Statement::Table { table: table.into(), limit: 100 }), + Some(c) => { + if let Some(n) = arg(c, "limit") { + let limit = n.parse::().map_err(|_| format!("limit() takes a number. {USAGE}"))?; + Ok(Statement::Table { table: table.into(), limit: limit.clamp(1, 1000) }) + } else if let Some(id) = arg(c, "get") { + let id: String = serde_json::from_str(&id).map_err(|_| format!("get() takes the id in quotes. {USAGE}"))?; + Ok(Statement::Get { id }) + } else { + Err(USAGE.into()) + } + } + } +} + +/// Whether a statement runs on its own without writing: table reads do; a +/// function call may be a mutation or an action. +pub fn reads(stmt: &str) -> bool { + matches!(parse(stmt), Ok(Statement::Table { .. } | Statement::Get { .. })) +} + +/// The kind of each deployed function, `module:name` → `Query` | `Mutation` | `Action`. +async fn function_kind(cfg: &ConvexConfig, path: &str) -> Result, String> { + let (module, name) = path.split_once(':').unwrap_or((path, "default")); + let mods = call_raw(cfg, "query", "_system/frontend/modules:list", &json!({})).await?; + for m in mods.as_array().into_iter().flatten() { + let file = m[0].as_str().unwrap_or(""); + let stem = file.strip_suffix(".js").or_else(|| file.strip_suffix(".ts")).unwrap_or(file); + if stem != module { + continue; + } + for f in m[1]["functions"].as_array().into_iter().flatten() { + if f["name"] == name { + return Ok(f["udfType"].as_str().map(String::from)); + } + } + } + Ok(None) +} + +pub async fn query(cfg: &ConvexConfig, stmt: &str) -> Result { + query_as(cfg, stmt, true).await +} + +/// Like `query`; with `allow_write` false only query functions run. +pub async fn query_as(cfg: &ConvexConfig, stmt: &str, allow_write: bool) -> Result { + let t0 = Instant::now(); + match parse(stmt)? { + Statement::Table { table, limit } => { + let (docs, _) = page(cfg, &table, limit, None).await?; + Ok(super::couchdb::docs_result(docs, None, stmt, t0)) + } + Statement::Get { id } => { + let d = call_raw(cfg, "query", "_system/frontend/getById", &json!({ "id": id })).await?; + Ok(super::couchdb::docs_result(if d.is_null() { vec![] } else { vec![d] }, None, stmt, t0)) + } + Statement::Call { path, args } => { + if !allow_write { + match function_kind(cfg, &path).await?.as_deref() { + Some("Query") => {} + Some(k) => return Err(format!("{path} is a {}; this connection only runs queries.", k.to_lowercase())), + None => return Err(format!("No deployed function {path}")), + } + } + let v = call_raw(cfg, "function", &path, &encode(args)?).await?; + Ok(value_result(v, stmt, t0)) + } + } +} + +/// A function's return value as a grid: documents as rows, anything else as one cell. +fn value_result(v: Value, stmt: &str, t0: Instant) -> super::query::SqlResult { + let rows = match v { + Value::Array(a) if a.iter().all(Value::is_object) => a, + // A paginated query's result. + Value::Object(ref o) if o.get("page").is_some_and(Value::is_array) && o.contains_key("isDone") => o["page"].as_array().cloned().unwrap_or_default(), + Value::Object(_) => vec![v], + other => vec![json!({ "value": other })], + }; + super::couchdb::docs_result(rows, None, stmt, t0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn int64_round_trips() { + let wire = json!({ "a": { "$integer": "BwAAAAAAAAA=" }, "b": [{ "$integer": "//////////8=" }], "c": 1.5 }); + let app = decode(wire.clone()); + assert_eq!(app, json!({ "a": { "$integer": "7" }, "b": [{ "$integer": "-1" }], "c": 1.5 })); + assert_eq!(encode(app).unwrap(), wire); + // Already base64: unchanged. + assert_eq!(encode(json!({ "$integer": "BwAAAAAAAAA=" })).unwrap(), json!({ "$integer": "BwAAAAAAAAA=" })); + assert_eq!(encode(json!({ "$integer": 7 })).unwrap(), json!({ "$integer": "BwAAAAAAAAA=" })); + assert!(encode(json!({ "$integer": "seven" })).is_err()); + // Other objects with one key are left alone. + assert_eq!(decode(json!({ "$bytes": "AQI=" })), json!({ "$bytes": "AQI=" })); + } + + #[test] + fn console_parses() { + assert_eq!(parse("users").unwrap(), Statement::Table { table: "users".into(), limit: 100 }); + assert_eq!(parse("users.limit(5);").unwrap(), Statement::Table { table: "users".into(), limit: 5 }); + assert_eq!(parse(r#"users.get("j57abc")"#).unwrap(), Statement::Get { id: "j57abc".into() }); + assert_eq!(parse(r#"messages:list {"limit": 5}"#).unwrap(), Statement::Call { path: "messages:list".into(), args: json!({ "limit": 5 }) }); + assert_eq!(parse(r#"admin/users:byEmail({"email": "a@b.c"})"#).unwrap(), Statement::Call { path: "admin/users:byEmail".into(), args: json!({ "email": "a@b.c" }) }); + assert_eq!(parse("messages:count").unwrap(), Statement::Call { path: "messages:count".into(), args: json!({}) }); + assert!(parse("messages:list [1]").is_err()); + assert!(parse("_system/frontend/addDocument:default {}").is_err()); + assert!(parse("SELECT * FROM users").is_err()); + assert!(parse("users.drop()").is_err()); + assert!(reads("users.limit(3)")); + assert!(reads(r#"users.get("x")"#)); + assert!(!reads("messages:send {\"body\": \"x\"}")); + } + + #[test] + fn errors_lose_the_request_id() { + let b = json!({ "errorMessage": "[Request ID: 8fa7] Server Error\nUncaught Error: Object is missing `x`" }); + assert_eq!(error_text(&b), "Error: Object is missing `x`"); + assert_eq!(error_text(&json!({ "errorMessage": "Could not find function" })), "Could not find function"); + } + + #[test] + fn only_listed_system_functions() { + assert!(SYSTEM.iter().any(|(p, w)| *p == "_system/frontend/replaceDocument" && *w)); + assert!(!SYSTEM.iter().any(|(p, _)| p.contains("snapshotImport") || p.contains("clearTablePage"))); + } + + fn live() -> Option { + Some(ConvexConfig { name: "t".into(), url: std::env::var("CONVEX_TEST_URL").ok()?, admin_key: std::env::var("CONVEX_TEST_ADMIN_KEY").ok()? }) + } + + /// Against a local backend (`convex-local-backend`) with the functions in + /// `messages` deployed and a seeded `users` table: + /// `CONVEX_TEST_URL=http://127.0.0.1:3210 CONVEX_TEST_ADMIN_KEY=... cargo test --lib convex_live -- --ignored`. + #[tokio::test] + #[ignore] + async fn convex_live() { + let Some(c) = live() else { return }; + ping(&c).await.unwrap(); + let tables = list_tables(&c).await.unwrap(); + assert!(tables.contains(&"users".to_string()), "{tables:?}"); + assert!(table_size(&c, "users").await.unwrap() >= 1); + let r = query(&c, "users.limit(1)").await.unwrap(); + assert_eq!(r.rows.len(), 1); + let r = query(&c, r#"messages:list {"limit": 1}"#).await.unwrap(); + assert_eq!(r.rows.len(), 1); + let err = query_as(&c, r#"messages:send {"body": "x"}"#, false).await.unwrap_err(); + assert!(err.contains("mutation"), "{err}"); + assert!(query(&c, "nope:missing").await.unwrap_err().contains("Could not find")); + let bad = ConvexConfig { admin_key: "nope".into(), ..c.clone() }; + assert!(ping(&bad).await.unwrap_err().contains("refused the key")); + assert!(system_call(&c, "_system/frontend/clearTablePage", json!({})).await.is_err()); + let all = system_call(&c, "_system/frontend/patchDocumentsFields", json!({ "table": "users", "fields": { "x": 1 } })).await.unwrap_err(); + assert!(all.contains("needs the ids"), "{all}"); + } +} diff --git a/src-tauri/src/db/couchdb.rs b/src-tauri/src/db/couchdb.rs index a56fb7d8..6e0d7f17 100644 --- a/src-tauri/src/db/couchdb.rs +++ b/src-tauri/src/db/couchdb.rs @@ -286,6 +286,8 @@ pub fn grid_cell(v: &Value) -> (Value, &'static str) { ("$numberLong", Value::String(_)) => (x.clone(), "long"), ("$numberDecimal", Value::String(_)) => (x.clone(), "decimal"), ("$uuid", Value::String(_)) => (x.clone(), "uuid"), + // Convex int64, already decimal (see `db::convex::decode`). + ("$integer", Value::String(_)) => (x.clone(), "int64"), _ => (v.clone(), "object"), } } diff --git a/src-tauri/src/db/docdb.rs b/src-tauri/src/db/docdb.rs index 325031ea..1b584fa3 100644 --- a/src-tauri/src/db/docdb.rs +++ b/src-tauri/src/db/docdb.rs @@ -1,6 +1,6 @@ //! Document and wide-column engines that share one connection slot //! (`ActiveConnection::Doc`): CouchDB, Cassandra, Firestore, MongoDB, -//! Elasticsearch/OpenSearch. Each keeps its +//! Elasticsearch/OpenSearch, Convex. Each keeps its //! own module; this file only routes the calls every engine answers. use super::query::SqlResult; @@ -15,6 +15,7 @@ pub enum DocConn { Elastic(super::elastic::EsConfig), Neo4j(super::neo4j::Neo4jConfig), Influx(super::influx::InfluxConfig), + Convex(super::convex::ConvexConfig), } impl DocConn { @@ -28,6 +29,7 @@ impl DocConn { Self::Elastic(_) => "elasticsearch", Self::Neo4j(_) => "neo4j", Self::Influx(_) => "influxdb", + Self::Convex(_) => "convex", } } } @@ -42,6 +44,7 @@ pub async fn query(conn: &DocConn, stmt: &str) -> Result { DocConn::Elastic(c) => super::elastic::query(c, stmt).await, DocConn::Neo4j(c) => super::neo4j::query(c, stmt).await, DocConn::Influx(c) => super::influx::query(c, stmt).await, + DocConn::Convex(c) => super::convex::query(c, stmt).await, } } @@ -51,6 +54,7 @@ pub async fn query(conn: &DocConn, stmt: &str) -> Result { pub async fn query_as(conn: &DocConn, stmt: &str, allow_write: bool) -> Result { match conn { DocConn::Elastic(c) => super::elastic::query_as(c, stmt, allow_write).await, + DocConn::Convex(c) => super::convex::query_as(c, stmt, allow_write).await, _ => query(conn, stmt).await, } } @@ -65,6 +69,7 @@ pub async fn list_tables(conn: &DocConn) -> Result, String> { DocConn::Elastic(c) => super::elastic::list_indices(c).await?.into_iter().map(|i| i.name).collect(), DocConn::Neo4j(c) => super::neo4j::labels(c).await?.into_iter().map(|(n, _)| n).collect(), DocConn::Influx(c) => super::influx::measurements(c).await?, + DocConn::Convex(c) => super::convex::list_tables(c).await?, }; Ok(names .into_iter() @@ -82,7 +87,7 @@ pub async fn list_schemas(conn: &DocConn) -> Result, String> { match conn { DocConn::Mongo(m) => super::mongo::list_databases(m).await, DocConn::Cassandra(s) => super::cassandra::list_keyspaces(s).await, - DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) | DocConn::Neo4j(_) | DocConn::Influx(_) => Ok(vec![FLAT_SCHEMA.to_string()]), + DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) | DocConn::Neo4j(_) | DocConn::Influx(_) | DocConn::Convex(_) => Ok(vec![FLAT_SCHEMA.to_string()]), } } @@ -127,6 +132,16 @@ pub async fn list_tables_in(conn: &DocConn, schema: &str) -> Result Ok(super::elastic::list_indices(c).await?.into_iter().map(|i| info(i.name, i.docs)).collect()), DocConn::Neo4j(c) => Ok(super::neo4j::labels(c).await?.into_iter().map(|(n, k)| info(n, k)).collect()), DocConn::Influx(c) => Ok(super::influx::measurements(c).await?.into_iter().map(|n| info(n, -1)).collect()), + DocConn::Convex(c) => { + let names = super::convex::list_tables(c).await?; + Ok(stream::iter(names.into_iter().map(|n| async move { + let count = super::convex::table_size(c, &n).await.unwrap_or(-1); + info(n, count) + })) + .buffered(8) + .collect() + .await) + } } } @@ -148,7 +163,7 @@ pub async fn use_schema(conn: &DocConn, schema: &str) -> Result<(), String> { } s.use_keyspace(schema, true).await.map_err(|e| format!("Keyspace \"{schema}\": {e}")) } - DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) | DocConn::Neo4j(_) | DocConn::Influx(_) => Ok(()), + DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) | DocConn::Neo4j(_) | DocConn::Influx(_) | DocConn::Convex(_) => Ok(()), } } @@ -165,7 +180,7 @@ pub async fn columns_in(conn: &DocConn, schema: &str, table: &str) -> Result super::elastic::index_columns(c, table).await, - DocConn::Mongo(_) | DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Neo4j(_) | DocConn::Influx(_) => Ok(vec![]), + DocConn::Mongo(_) | DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Neo4j(_) | DocConn::Influx(_) | DocConn::Convex(_) => Ok(vec![]), } } @@ -174,7 +189,7 @@ pub async fn columns_in(conn: &DocConn, schema: &str, table: &str) -> Result Result, String> { match conn { DocConn::Cassandra(s) => Ok(super::cassandra::columns_by_table(super::cassandra::keyspace_columns(s, schema).await?)), - DocConn::Mongo(_) | DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) | DocConn::Neo4j(_) | DocConn::Influx(_) => Ok(vec![]), + DocConn::Mongo(_) | DocConn::Couch(_) | DocConn::Firestore(_) | DocConn::Elastic(_) | DocConn::Neo4j(_) | DocConn::Influx(_) | DocConn::Convex(_) => Ok(vec![]), } } diff --git a/src-tauri/src/db/mod.rs b/src-tauri/src/db/mod.rs index e4c02626..ecf10496 100644 --- a/src-tauri/src/db/mod.rs +++ b/src-tauri/src/db/mod.rs @@ -23,6 +23,7 @@ pub mod couchdb; pub mod elastic; pub mod cassandra; pub mod firestore; +pub mod convex; pub mod neo4j; pub mod influx; pub mod google_auth; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 631893c0..c4472b3d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -772,6 +772,8 @@ pub fn run() { commands::cassandra_tables, commands::cassandra_describe, commands::cassandra_page, + commands::test_convex, + commands::connect_convex_db, commands::cassandra_save, commands::cassandra_delete, commands::test_firestore, @@ -795,6 +797,7 @@ pub fn run() { commands::test_odbc, commands::connect_odbc_db, commands::test_snowflake, + commands::convex_call, commands::connect_snowflake_db, commands::odbc_drivers, commands::odbc_data_sources, diff --git a/src-tauri/src/mcp/access.rs b/src-tauri/src/mcp/access.rs index d1ec6c4a..e7006d74 100644 --- a/src-tauri/src/mcp/access.rs +++ b/src-tauri/src/mcp/access.rs @@ -42,6 +42,8 @@ pub enum Dialect { Dynamo, /// Neo4j: Cypher, read by its clauses (see `db::neo4j::cypher_level`). Cypher, + /// Convex: a table read, or a deployed function that may write. + Convex, } impl Dialect { @@ -56,6 +58,7 @@ impl Dialect { "couchdb" | "firestore" | "influxdb" => Self::ReadOnlyDoc, "dynamodb" => Self::Dynamo, "neo4j" => Self::Cypher, + "convex" => Self::Convex, _ => Self::Sql, } } @@ -76,6 +79,10 @@ pub fn script_level_in(dialect: Dialect, sql: &str) -> u8 { Dialect::Redis => redis_level(sql), Dialect::Dynamo => dynamo_level(sql), Dialect::ReadOnlyDoc => READ, + // A function's kind is only known by asking the deployment, so any + // call counts as a write here; `convex::query_as` lets a read-only + // session run the ones that are queries. + Dialect::Convex => if crate::db::convex::reads(sql) { READ } else { WRITE }, Dialect::Cypher => crate::db::neo4j::cypher_level(sql), Dialect::Elastic => match crate::db::elastic::parse(sql) { Ok(crate::db::elastic::Statement::Raw { method, path, .. }) => crate::db::elastic::request_level(&method, &path), @@ -693,6 +700,11 @@ mod tests { assert_eq!(Dialect::for_driver("neo4j"), Dialect::Cypher); assert_eq!(script_level_in(Dialect::Cypher, "MATCH (n) WITH n DETACH DELETE n"), WRITE); assert_eq!(script_level_in(Dialect::Cypher, "MATCH (n) RETURN n"), READ); + assert_eq!(Dialect::for_driver("convex"), Dialect::Convex); + assert_eq!(script_level_in(Dialect::Convex, "users.limit(5)"), READ); + assert_eq!(script_level_in(Dialect::Convex, r#"users.get("j57")"#), READ); + assert_eq!(script_level_in(Dialect::Convex, r#"messages:send {"body": "x"}"#), WRITE); + assert_eq!(script_level_in(Dialect::Convex, "not a statement"), WRITE); let m = |s: &str| script_level_in(Dialect::Mongo, s); assert_eq!(m(r#"db.createCollection("shop")"#), MODIFY); assert_eq!(m("db.users.createIndex({email: 1}, {unique: true})"), MODIFY); diff --git a/src-tauri/src/mcp/tools.rs b/src-tauri/src/mcp/tools.rs index f068e7f5..baaf3c0b 100644 --- a/src-tauri/src/mcp/tools.rs +++ b/src-tauri/src/mcp/tools.rs @@ -249,7 +249,7 @@ fn sample_sql(conn: &ActiveConnection, schema: &str, table: &str, n: usize) -> R "mongodb" => format!("db.getCollection(\"{table}\").find({{}}).limit({n})"), "couchdb" => format!("{table}.find({{}}, {{\"limit\": {n}}})"), "elasticsearch" | "opensearch" => format!("GET {table}/_search\n{{\"size\": {n}}}"), - "firestore" => format!("{table}.limit({n})"), + "firestore" | "convex" => format!("{table}.limit({n})"), "cassandra" => format!("SELECT * FROM {}.{} LIMIT {n}", dq(schema), dq(table)), other => return Err(format!("sample_rows is not available for {other}. Use execute_sql.")), }, @@ -1149,6 +1149,10 @@ async fn describe_table( let info = crate::db::influx::describe(c, table).await?; Ok(json!({"table":table,"engine":"influxdb","tags":info["tags"],"fields":info["fields"],"note":"Read-only. Tags are indexed strings, fields hold the values, `time` is the timestamp. Always bound time and add LIMIT."}).to_string()) } + DocConn::Convex(c) => { + let count = crate::db::convex::table_size(c, table).await.unwrap_or(-1); + Ok(json!({"table":table,"engine":"convex","document_count":count,"note":"Convex tables are documents with _id and _creationTime. Read them with `table.limit(20)` or `table.get(\"\")`; run a deployed function with `module:function {\"arg\": 1}`. Function calls may write."}).to_string()) + } // Typed columns where the engine keeps them (CQL, index mappings). DocConn::Cassandra(_) | DocConn::Elastic(_) => { let cols = crate::db::docdb::columns_in(d, schema, table).await?; diff --git a/src-tauri/src/providers/convex.rs b/src-tauri/src/providers/convex.rs new file mode 100644 index 00000000..7be77175 --- /dev/null +++ b/src-tauri/src/providers/convex.rs @@ -0,0 +1,217 @@ +/*! + * Convex adapter - the provider-picker side of the Convex engine + * (`db/convex.rs`). Sign-in is Convex's OAuth app flow for team tokens: the + * browser asks which team to authorize, and every cloud deployment on that + * team is listed. Connecting mints a deploy key for the picked deployment + * through the Management API, so no key is copied by hand. + * + * Convex OAuth apps are confidential clients, so the code exchange goes through + * the stroke.click proxy, which adds CONVEX_CLIENT_SECRET. The app token has no + * expiry or refresh token; a revoked one comes back as a 401 and the card asks + * to sign in again. A project token also works here (`Scope::Project`). + */ + +use super::SendRetry; +use super::{http, OAuthConfig, ProviderConnection, ProviderDatabase}; +use serde_json::{json, Value}; +use std::collections::HashMap; + +/// Stroke's OAuth app, registered in the Convex dashboard under Team Settings, +/// Applications, with the redirect URIs `http://localhost:{8989..8993}/oauth/callback`. +/// The scope comes from the authorize path (team), not a `scope` parameter. +pub const OAUTH: OAuthConfig = OAuthConfig { + client_id: "573ebae448004ff7", + auth_url: "https://dashboard.convex.dev/oauth/authorize/team", + token_url: "https://api.convex.dev/oauth/token", + scopes: "", +}; + +const API: &str = "https://api.convex.dev/v1"; +/// Cap on listing pages (100 a page). +const MAX_PAGES: usize = 20; + +async fn send(req: reqwest::RequestBuilder) -> Result { + let resp = req.send_retrying().await.map_err(|e| format!("Convex request failed: {}", super::describe(&e)))?; + let status = resp.status().as_u16(); + // A wrong or revoked token is a 401; twice in a row the command layer + // ends the "session" and the token form comes back. + if status == 401 { + return Err(super::UNAUTHORIZED.into()); + } + let text = resp.text().await.map_err(|e| format!("Convex read failed: {e}"))?; + let body: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + if !(200..300).contains(&status) { + let detail = body["message"].as_str().map(String::from).unwrap_or_else(|| text.chars().take(200).collect()); + return Err(if status == 403 { + format!("Convex refused the token: {detail}") + } else { + format!("Convex API error ({status}): {detail}") + }); + } + Ok(body) +} + +async fn get(token: &str, path: &str) -> Result { + send(http().get(format!("{API}{path}")).bearer_auth(token.trim())).await +} + +/// What the token can see: a whole team, or one project. +#[derive(Debug, PartialEq)] +enum Scope { + Team(String), + Project(String), +} + +fn id_str(v: &Value) -> Option { + v.as_i64().map(|n| n.to_string()).or_else(|| v.as_str().map(String::from)) +} + +fn scope_of(details: &Value) -> Result { + match details["type"].as_str() { + Some("teamToken") => id_str(&details["teamId"]).map(Scope::Team), + Some("projectToken") => id_str(&details["projectId"]).map(Scope::Project), + _ => None, + } + .ok_or_else(|| "This token is not a Convex team or project access token.".to_string()) +} + +/// Every page of a cursor-paginated `{ items, pagination }` listing. +async fn all_pages(token: &str, path: &str) -> Result, String> { + let mut out = Vec::new(); + let mut cursor: Option = None; + for _ in 0..MAX_PAGES { + let sep = if path.contains('?') { '&' } else { '?' }; + let url = match &cursor { + Some(c) => format!("{path}{sep}limit=100&cursor={}", urlencoding::encode(c)), + None => format!("{path}{sep}limit=100"), + }; + let body = get(token, &url).await?; + out.extend(body["items"].as_array().cloned().unwrap_or_default()); + match (body["pagination"]["hasMore"].as_bool(), body["pagination"]["nextCursor"].as_str()) { + (Some(true), Some(c)) if !c.is_empty() => cursor = Some(c.to_string()), + _ => break, + } + } + Ok(out) +} + +/// Deployments → picker rows, `Project · prod` style, production first. +/// `db_ref` carries everything connecting needs, so it makes no second lookup. +fn rows(deployments: &[Value], projects: &HashMap) -> Vec { + let mut out: Vec<(u8, ProviderDatabase)> = deployments + .iter() + // Local deployments run on someone's laptop: nothing to reach. + .filter(|d| d["kind"].as_str().unwrap_or("cloud") == "cloud") + .filter_map(|d| { + let name = d["name"].as_str()?.to_string(); + let url = d["deploymentUrl"].as_str().map(String::from).unwrap_or_else(|| format!("https://{name}.convex.cloud")); + let kind = d["deploymentType"].as_str().unwrap_or("dev").to_string(); + let project = id_str(&d["projectId"]).and_then(|p| projects.get(&p).cloned()); + let label = match (&project, d["reference"].as_str()) { + (Some(p), Some(r)) if kind == "preview" || kind == "custom" => format!("{p} · {r}"), + (Some(p), _) => format!("{p} · {kind}"), + (None, _) => name.clone(), + }; + let rank = match kind.as_str() { + "prod" => 0, + "dev" => 1, + _ => 2, + }; + Some(( + rank, + ProviderDatabase { + db_ref: json!({ "d": name, "u": url, "n": label }).to_string(), + name: label, + region: d["region"].as_str().map(String::from), + kind: Some(match kind.as_str() { + "prod" => "Production".into(), + "dev" => "Development".into(), + "preview" => "Preview".into(), + _ => "Custom".into(), + }), + host: Some(url.trim_start_matches("https://").to_string()), + }, + )) + }) + .collect(); + out.sort_by(|a, b| a.1.name.split(" · ").next().cmp(&b.1.name.split(" · ").next()).then(a.0.cmp(&b.0)).then_with(|| a.1.name.cmp(&b.1.name))); + out.into_iter().map(|(_, d)| d).collect() +} + +pub async fn list_databases(token: &str) -> Result, String> { + let details = get(token, "/token_details").await?; + match scope_of(&details)? { + Scope::Team(team) => { + let (dep_path, proj_path) = (format!("/teams/{team}/list_deployments"), format!("/teams/{team}/projects")); + let (deployments, projects) = tokio::try_join!(all_pages(token, &dep_path), all_pages(token, &proj_path))?; + let names = projects.iter().filter_map(|p| Some((id_str(&p["id"])?, p["name"].as_str()?.to_string()))).collect(); + Ok(rows(&deployments, &names)) + } + Scope::Project(project) => { + let (dep_path, proj_path) = (format!("/projects/{project}/list_deployments"), format!("/projects/{project}")); + let (deployments, p) = tokio::try_join!(get(token, &dep_path), get(token, &proj_path))?; + let names = HashMap::from([(project, p["name"].as_str().unwrap_or("Project").to_string())]); + Ok(rows(deployments.as_array().map(Vec::as_slice).unwrap_or_default(), &names)) + } + } +} + +pub async fn build_connection(token: &str, db_ref: &str) -> Result { + let r: Value = serde_json::from_str(db_ref).map_err(|_| "Invalid Convex deployment reference")?; + let deployment = r["d"].as_str().filter(|d| !d.is_empty()).ok_or("Invalid Convex deployment reference")?; + let url = r["u"].as_str().unwrap_or_default(); + let label = r["n"].as_str().unwrap_or(deployment); + // A deploy key, shown in the deployment's settings as "Stroke", revocable there. + let key = send( + http() + .post(format!("{API}/deployments/{}/create_deploy_key", urlencoding::encode(deployment))) + .bearer_auth(token.trim()) + .json(&json!({ "name": "Stroke" })), + ) + .await?; + let key = key["deployKey"].as_str().ok_or("Convex returned no deploy key")?; + // The engine's adapter contract: the deployment URL in `host`, the key in + // `password`. The frontend maps these to a `convex` connection ({ url, adminKey }). + Ok(ProviderConnection { + db_type: "convex".into(), + host: if url.is_empty() { format!("https://{deployment}.convex.cloud") } else { url.to_string() }, + port: 443, + username: String::new(), + password: key.to_string(), + database: deployment.to_string(), + ssl: true, + needs_password: false, + name: format!("Convex · {label}"), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_scope() { + assert_eq!(scope_of(&json!({ "type": "teamToken", "teamId": 41 })).unwrap(), Scope::Team("41".into())); + assert_eq!(scope_of(&json!({ "type": "projectToken", "projectId": 7 })).unwrap(), Scope::Project("7".into())); + assert!(scope_of(&json!({ "type": "other" })).is_err()); + } + + #[test] + fn deployments_become_rows() { + let deps = json!([ + { "name": "happy-otter-123", "deploymentType": "dev", "projectId": 7, "region": "aws-us-east-1", "deploymentUrl": "https://happy-otter-123.convex.cloud", "kind": "cloud" }, + { "name": "brave-cat-9", "deploymentType": "prod", "projectId": 7, "deploymentUrl": "https://brave-cat-9.convex.cloud", "kind": "cloud" }, + { "name": "pr-42", "deploymentType": "preview", "projectId": 7, "reference": "feat-x", "deploymentUrl": "https://pr-42.convex.cloud", "kind": "cloud" }, + { "name": "local-1", "deploymentType": "dev", "projectId": 7, "kind": "local" }, + ]); + let names = HashMap::from([("7".to_string(), "Chat".to_string())]); + let r = rows(deps.as_array().unwrap(), &names); + assert_eq!(r.iter().map(|d| d.name.as_str()).collect::>(), ["Chat · prod", "Chat · dev", "Chat · feat-x"]); + assert_eq!(r[0].kind.as_deref(), Some("Production")); + assert_eq!(r[1].host.as_deref(), Some("happy-otter-123.convex.cloud")); + let rf: Value = serde_json::from_str(&r[1].db_ref).unwrap(); + assert_eq!((rf["d"].as_str(), rf["u"].as_str()), (Some("happy-otter-123"), Some("https://happy-otter-123.convex.cloud"))); + // No project name: the deployment's own name. + assert_eq!(rows(&deps.as_array().unwrap()[..1], &HashMap::new())[0].name, "happy-otter-123"); + } +} diff --git a/src-tauri/src/providers/mod.rs b/src-tauri/src/providers/mod.rs index b3cc7152..75b3ced8 100644 --- a/src-tauri/src/providers/mod.rs +++ b/src-tauri/src/providers/mod.rs @@ -20,6 +20,7 @@ * dashboard link instead. */ +mod convex; mod neon; mod planetscale; mod posthog; @@ -79,6 +80,7 @@ pub enum Provider { PostHog, Xata, SingleStore, + Convex, } /// How a provider signs the user in. @@ -109,14 +111,15 @@ impl Provider { "posthog" => Ok(Self::PostHog), "xata" => Ok(Self::Xata), "singlestore" => Ok(Self::SingleStore), + "convex" => Ok(Self::Convex), other => Err(format!("Unknown provider: {other}")), } } - const ALL: [Provider; 12] = [ + const ALL: [Provider; 13] = [ Self::Neon, Self::Supabase, Self::PlanetScale, Self::Prisma, Self::TiDB, Self::Turso, Self::Railway, Self::Nile, Self::Upstash, Self::PostHog, - Self::Xata, Self::SingleStore, + Self::Xata, Self::SingleStore, Self::Convex, ]; /// The API host each listing and connect talks to, for `provider_warm`. @@ -134,6 +137,7 @@ impl Provider { Self::Upstash => "https://api.upstash.com", Self::Xata => "https://api.xata.tech", Self::SingleStore => "https://api.singlestore.com", + Self::Convex => "https://api.convex.dev", Self::PostHog => return None, }) } @@ -153,6 +157,7 @@ impl Provider { Self::PostHog => "posthog", Self::Xata => "xata", Self::SingleStore => "singlestore", + Self::Convex => "convex", } } @@ -171,6 +176,7 @@ impl Provider { Self::PostHog => "PostHog", Self::Xata => "Xata", Self::SingleStore => "SingleStore", + Self::Convex => "Convex", } } @@ -196,6 +202,7 @@ impl Provider { Self::PostHog => posthog::OAUTH, Self::Xata => xata::OAUTH, Self::SingleStore => singlestore::OAUTH, + Self::Convex => convex::OAUTH, } } @@ -263,6 +270,7 @@ impl Provider { Self::PostHog => posthog::list_databases(token).await, Self::Xata => xata::list_databases(token).await, Self::SingleStore => singlestore::list_databases(token).await, + Self::Convex => convex::list_databases(token).await, } } @@ -284,6 +292,7 @@ impl Provider { Self::PostHog => posthog::build_connection(token, db_ref).await, Self::Xata => xata::build_connection(token, db_ref).await, Self::SingleStore => singlestore::build_connection(token, db_ref).await, + Self::Convex => convex::build_connection(token, db_ref).await, } } @@ -298,7 +307,7 @@ impl Provider { Self::Turso => turso::create_options(token, scope).await, Self::Nile => nile::create_options(token, scope).await, Self::Upstash => Ok(upstash::create_options()), - Self::PlanetScale | Self::Railway | Self::PostHog | Self::Xata | Self::SingleStore => Err(self.create_unsupported()), + Self::PlanetScale | Self::Railway | Self::PostHog | Self::Xata | Self::SingleStore | Self::Convex => Err(self.create_unsupported()), } } @@ -311,7 +320,7 @@ impl Provider { Self::Turso => turso::create_database(token, req).await, Self::Nile => nile::create_database(token, req).await, Self::Upstash => upstash::create_database(token, req).await, - Self::PlanetScale | Self::Railway | Self::PostHog | Self::Xata | Self::SingleStore => Err(self.create_unsupported()), + Self::PlanetScale | Self::Railway | Self::PostHog | Self::Xata | Self::SingleStore | Self::Convex => Err(self.create_unsupported()), } } @@ -325,7 +334,7 @@ impl Provider { Self::Upstash => upstash::database_status(token, db_ref).await, // Turso databases are usable the moment the create call returns. Self::Turso => Ok(DatabaseStatus::ready("ready")), - Self::PlanetScale | Self::Railway | Self::PostHog | Self::Xata | Self::SingleStore => Err(self.create_unsupported()), + Self::PlanetScale | Self::Railway | Self::PostHog | Self::Xata | Self::SingleStore | Self::Convex => Err(self.create_unsupported()), } } @@ -344,6 +353,7 @@ impl Provider { Self::PostHog => "PostHog projects are created in PostHog.".into(), Self::Xata => "Create Xata projects and branches in the Xata console, then refresh.".into(), Self::SingleStore => "Create SingleStore workspaces in the SingleStore portal, then refresh.".into(), + Self::Convex => "Create Convex projects with `npx convex dev` or in the Convex dashboard, then refresh.".into(), _ => format!("{} databases can't be created from Stroke yet.", self.label()), } } diff --git a/src/lib/ai-query-languages.js b/src/lib/ai-query-languages.js index 71463a30..5b31800a 100644 --- a/src/lib/ai-query-languages.js +++ b/src/lib/ai-query-languages.js @@ -63,6 +63,17 @@ export const QUERY_LANGUAGES = { - One document: users.get("u1"). A bare collection path lists its documents: products - Range filters on one field plus orderBy on another need a composite index in Firestore. The editor is read-only for Firestore: changes are made in the Browse page.`, + }, + convex: { + name: 'Convex console', + fence: 'javascript', + collectionNoun: 'table', + guide: `Write one statement per block. Not SQL. The query editor takes: +- A table: users lists its newest 100 documents; users.limit(20) the newest 20. +- One document: users.get(""). +- A deployed function and its arguments as one JSON object: messages:list {"limit": 5}. A function in a folder: admin/users:byEmail {"email": "a@b.co"}. Default exports: messages {}. +- Function calls may be mutations or actions that write, so they need write access. Documents are edited in the Browse page. +- Every document has _id and _creationTime (milliseconds since the epoch). Int64 values show as {"$integer": "7"}.`, }, influxdb: { name: 'InfluxDB queries (SQL, InfluxQL or Flux)', @@ -178,6 +189,7 @@ export function sampleQuery(engine, schema, coll, n) { case 'opensearch': return `GET ${coll}/_search\n{"size": ${n}}` case 'firestore': + case 'convex': return `${coll}.limit(${n})` case 'influxdb': return `SELECT * FROM "${coll.replace(/"/g, '\\"')}" ORDER BY time DESC LIMIT ${n}` @@ -218,6 +230,6 @@ export function describeFromSample(coll, result) { export function runnableFences(engine) { const lang = queryLanguageFor(engine) if (!lang) return null - const extra = { mongodb: ['javascript', 'js', 'mongodb', 'mongo'], couchdb: ['javascript', 'js', 'json'], elasticsearch: ['json', 'http', 'text', 'sql'], opensearch: ['json', 'http', 'text', 'sql'], firestore: ['javascript', 'js'], neo4j: ['cypher', 'sql', 'text'], influxdb: ['sql', 'influxql', 'flux', 'text'], cassandra: ['sql', 'cql'], dynamodb: ['sql', 'partiql'], redis: ['redis', 'text', 'bash'], valkey: ['redis', 'text', 'bash'] } + const extra = { mongodb: ['javascript', 'js', 'mongodb', 'mongo'], couchdb: ['javascript', 'js', 'json'], elasticsearch: ['json', 'http', 'text', 'sql'], opensearch: ['json', 'http', 'text', 'sql'], firestore: ['javascript', 'js'], convex: ['javascript', 'js', 'json', 'text'], neo4j: ['cypher', 'sql', 'text'], influxdb: ['sql', 'influxql', 'flux', 'text'], cassandra: ['sql', 'cql'], dynamodb: ['sql', 'partiql'], redis: ['redis', 'text', 'bash'], valkey: ['redis', 'text', 'bash'] } return new Set([lang.fence, ...(/** @type {Record} */ (extra)[/** @type {string} */ (engine)] ?? [])]) } diff --git a/src/lib/api.js b/src/lib/api.js index 61395e0b..a4acb9c3 100644 --- a/src/lib/api.js +++ b/src/lib/api.js @@ -4,7 +4,7 @@ import { traceIpc, traceRows } from '$lib/perf.js' import { recordQuery } from '$lib/stores/query-log.js' import { assertWritable } from '$lib/stores/read-only.js' import { getLastConnection } from '$lib/stores/connections.js' -import { isWriteSql } from '$lib/sql-write.js' +import { isWriteSql, isConvexCall } from '$lib/sql-write.js' import { odbcConfigOf } from '$lib/odbc-presets.js' import { setOdbcDialect, setSpannerDialect } from '$lib/sql-ident.js' @@ -922,6 +922,47 @@ export async function connectFirestore(config) { return connectInv('connect_firestore_db', { config: normalizeFirestore(config) }) } +// ── Convex ──────────────────────────────────────────────────────────────────── + +/** + * A Convex deployment: its URL and a deploy or admin key (kept under `apiKey`, + * a secret field, in the saved connection). + * @typedef {{ name?: string, url?: string, apiKey?: string }} ConvexConnConfig + */ + +/** @param {ConvexConnConfig} config */ +function normalizeConvex(config) { + return { + name: String(config.name || 'Convex'), + url: String(config.url || '').trim(), + adminKey: String(config.apiKey || '').trim(), + } +} + +/** @param {ConvexConnConfig} config */ +export async function testConvex(config) { + return inv('test_convex', { config: normalizeConvex(config) }) +} + +/** @param {ConvexConnConfig} config */ +export async function connectConvex(config) { + return connectInv('connect_convex_db', { config: normalizeConvex(config) }) +} + +/** The dashboard's system functions that write (src-tauri/src/db/convex.rs `SYSTEM`). */ +const CONVEX_WRITES = new Set(['addDocument', 'replaceDocument', 'deleteDocuments', 'patchDocumentsFields', 'createTable']) + +/** + * One Convex system function on the active connection, e.g. + * `_system/frontend/paginatedTableDocuments`. Only the ones the browser needs + * are allowed through. + * @param {string} path @param {Record} [args] + */ +export async function convexCall(path, args = {}) { + if (CONVEX_WRITES.has(path.split('/').pop() ?? '')) assertWritable('change documents') + return inv('convex_call', { path, args }) +} + // ── InfluxDB (beta, read-only) ──────────────────────────────────────────────── /** @@ -1811,7 +1852,7 @@ export async function sqlAccessLevel(sql) { } export async function executeSql(sql, queryId) { - if (isWriteSql(sql)) assertWritable('run that statement') + if (isWriteSql(sql) || isConvexCall(sql)) assertWritable('run that statement') const _t0 = performance.now() try { const r = await inv('pg_execute_sql', { sql, queryId: queryId ?? null }) @@ -1826,7 +1867,7 @@ export async function executeSql(sql, queryId) { /** Execute one or more SQL statements and return each result as a separate entry. * @param {string} sql @param {string} [queryId] cancel handle for this run */ export async function executeSqlMulti(sql, queryId) { - if (isWriteSql(sql)) assertWritable('run that statement') + if (isWriteSql(sql) || isConvexCall(sql)) assertWritable('run that statement') return await inv('pg_execute_sql_multi', { sql, queryId: queryId ?? null }) } @@ -1849,7 +1890,7 @@ export async function executeSqlMulti(sql, queryId) { * @param {{ keepInStore?: boolean }} [opts] */ export async function executeSqlStream(sql, queryId, onRows, opts = {}) { - if (isWriteSql(sql)) assertWritable('run that statement') + if (isWriteSql(sql) || isConvexCall(sql)) assertWritable('run that statement') /** @type {(v?: unknown) => void} */ let landed = () => {} const allLanded = new Promise((resolve) => { landed = resolve }) @@ -1994,7 +2035,7 @@ export async function explainSql(sql, opts = {}) { * @param {string} sql */ export async function executeSqlOnConnection(connectionConfig, sql) { - if (isWriteSql(sql)) assertWritable('run that statement') + if (isWriteSql(sql) || isConvexCall(sql)) assertWritable('run that statement') try { return await invoke('execute_sql_on_connection', { config: connectionConfig, sql }) } catch (err) { @@ -2277,7 +2318,7 @@ export async function txBegin(sessionId) { * @param {string} sql */ export async function txExecute(sessionId, sql) { - if (isWriteSql(sql)) assertWritable('run that statement') + if (isWriteSql(sql) || isConvexCall(sql)) assertWritable('run that statement') const _t0 = performance.now() try { const r = await inv('tx_execute', { sessionId, sql }) diff --git a/src/lib/components/ConnectionModal.svelte b/src/lib/components/ConnectionModal.svelte index 1b4f3649..bc7c9431 100644 --- a/src/lib/components/ConnectionModal.svelte +++ b/src/lib/components/ConnectionModal.svelte @@ -43,6 +43,8 @@ connectInflux, testFirestore, connectFirestore, + testConvex, + connectConvex, testSpanner, connectSpanner, testBigquery, @@ -230,6 +232,7 @@ { id: "cassandra", label: "Cassandra", desc: "Wide-column store (CQL)" }, { id: "scylladb", label: "ScyllaDB", desc: "Cassandra-compatible wide-column store (CQL)" }, { id: "firestore", label: "Firestore", desc: "Google Cloud document database" }, + { id: "convex-url", label: "Convex (URL + key)", desc: "Self-hosted, local or cloud deployment with its admin key" }, { id: "neo4j", label: "Neo4j", desc: "Graph database, also Aura (over HTTP)", beta: true }, { id: "influxdb", label: "InfluxDB", desc: "Time series, 1.x, 2.x and 3.x (read-only)", beta: true }, ], @@ -287,6 +290,11 @@ label: "PostHog", desc: "Product analytics in HogQL, read-only", }, + { + id: "convex", + label: "Convex", + desc: "Reactive backend database, connect with a team token", + }, ], }, ]; @@ -323,6 +331,7 @@ "nile", "upstash", "posthog", + "convex", "d1", "spanner", "bigquery", @@ -341,6 +350,7 @@ "cassandra", "scylladb", "firestore", + "convex-url", ]; const driverItems = DRIVER_ORDER.map((id) => ALL_DRIVERS.find((d) => d.id === id), @@ -355,7 +365,7 @@ // Provider (sign-in) ids are surfaced as cards on their own tab, so keep them // out of the manual Type dropdown. - const PROVIDER_IDS = ["neon", "supabase", "planetscale", "prisma", "tidb", "turso", "railway", "nile", "upstash", "posthog"]; + const PROVIDER_IDS = ["neon", "supabase", "planetscale", "prisma", "tidb", "turso", "railway", "nile", "upstash", "posthog", "convex"]; // Providers temporarily turned off (shown as a disabled tab, not connectable). /** @type {Set} */ const DISABLED_TABS = new Set(); @@ -565,6 +575,9 @@ // Cassandra: contact points and an optional default keyspace. let cqlHosts = $state("127.0.0.1:9042"); let cqlKeyspace = $state(""); + // Convex by hand: the deployment URL and its admin or deploy key. + let cxUrl = $state(""); + let cxKey = $state(""); // Firestore: project, optional database, and how to sign in. let fsProject = $state(""); let fsDatabase = $state(""); @@ -849,7 +862,7 @@ /** Providers with an account flow, in the order they are offered. */ - const PROVIDER_CARDS = ["neon", "supabase", "prisma", "planetscale", "tidb", "turso", "railway", "nile", "upstash", "posthog", "d1"]; + const PROVIDER_CARDS = ["neon", "supabase", "prisma", "planetscale", "tidb", "turso", "railway", "nile", "upstash", "posthog", "convex", "d1"]; /** Names for providers a URI can identify but the catalog has no card for. */ const PROVIDER_LABELS = { "prisma-postgres": "Prisma Postgres" }; @@ -1294,6 +1307,8 @@ }; if (dbType === "mongodb") return { type: "mongodb", name: nm, uri: mongoUri.trim(), database: mongoDb.trim(), ...(ssh && { ssh }) }; + if (dbType === "convex-url") + return { type: "convex", name: nm, url: cxUrl.trim(), apiKey: cxKey.trim() }; if (dbType === "firestore") return { type: "firestore", @@ -1484,7 +1499,11 @@ conn.filePath === ":memory:" && (conn.type === "sqlite" || conn.type === "duckdb") ? `${conn.type}-memory` - : engineId(conn) || "postgres"; + // Convex by hand has its own form; through the provider it opens + // on the provider's page. + : conn.type === "convex" && !conn.provider + ? "convex-url" + : engineId(conn) || "postgres"; dbType = t; name = conn.name ?? ""; host = conn.host ?? "127.0.0.1"; @@ -1510,6 +1529,8 @@ mongoDb = conn.type === "mongodb" ? (conn.database ?? "") : ""; fsProject = conn.projectId ?? ""; fsDatabase = conn.type === "firestore" ? (conn.database ?? "") : ""; + cxUrl = conn.type === "convex" ? (conn.url ?? "") : ""; + cxKey = conn.type === "convex" ? (conn.apiKey ?? "") : ""; fsAuth = conn.auth ?? "serviceAccount"; fsKeyFile = conn.keyFile ?? ""; fsEmulator = conn.emulatorHost ?? "localhost:8080"; @@ -1609,6 +1630,8 @@ d1Oauth = false; libsqlUrl = ""; libsqlToken = ""; + cxUrl = ""; + cxKey = ""; couchUrl = "http://localhost:5984"; ifxVersion = "2"; ifxOrg = ""; @@ -1832,6 +1855,7 @@ cassandra: { database: "", user: "" }, scylladb: { database: "", user: "" }, firestore: { database: "", user: "" }, + "convex-url": { database: "", user: "" }, spanner: { database: "", user: "" }, bigquery: { database: "", user: "" }, snowflake: { database: "", user: "" }, @@ -2064,6 +2088,11 @@ return where && odbcMode === "fields" ? `${activeDriver.label} · ${where}` : activeDriver.label; } if (dbType === "firestore") return fsProject.trim() || "Firestore"; + // A cloud deployment by its name (happy-otter-123); a local one keeps its port. + if (dbType === "convex-url") + return ((h) => (/^(\d+\.){3}\d+(:\d+)?$|^localhost(:\d+)?$/.test(h) ? h : h.split(".")[0]))( + cxUrl.trim().replace(/^\w+:\/\//, "").split("/")[0], + ) || "Convex"; if (dbType === "influxdb") return database.trim() ? `${database.trim()} · InfluxDB` : "InfluxDB"; if (dbType === "neo4j") { const at = couchUrl.trim().replace(/^\w+:\/\//, "").split(/[/:]/)[0]; @@ -2279,6 +2308,7 @@ if (conn.type === "bigquery") return [[conn.projectId, conn.dataset].filter(Boolean).join("."), conn.auth === "emulator" ? "emulator" : null].filter(Boolean).join(" · ") || "—"; if (conn.type === "spanner") return [conn.instanceId && conn.databaseId ? `${conn.instanceId}/${conn.databaseId}` : conn.projectId, conn.auth === "emulator" ? "emulator" : null].filter(Boolean).join(" · ") || "—"; if (conn.type === "firestore") return [conn.projectId, conn.auth === "emulator" ? "emulator" : null].filter(Boolean).join(" · ") || "—"; + if (conn.type === "convex") return String(conn.url ?? "").replace(/^https?:\/\//, "") || "—"; if (conn.type === "cassandra") return [conn.hosts, conn.keyspace].filter(Boolean).join(" · ") || "—"; if (conn.type === "dynamodb") return conn.endpoint || [conn.profile, conn.region].filter(Boolean).join(" · ") || "AWS"; return conn.database || "—"; @@ -2392,6 +2422,7 @@ if (conn.type === "elasticsearch" || conn.type === "opensearch") return connectElastic(conn); if (conn.type === "cassandra") return connectCassandra(conn); if (conn.type === "firestore") return connectFirestore(conn); + if (conn.type === "convex") return connectConvex(conn); if (conn.type === "spanner") return connectSpanner(conn); if (conn.type === "bigquery") return connectBigquery(conn); if (conn.type === "snowflake") return connectSnowflake(conn); @@ -2961,6 +2992,7 @@ } else if (p.type === "cassandra") await testCassandra(p); else if (p.type === "firestore") await testFirestore(p); + else if (p.type === "convex") await testConvex(p); else if (p.type === "spanner") await testSpanner(p); else if (p.type === "bigquery") await testBigquery(p); else if (p.type === "snowflake") await testSnowflake(p); @@ -3164,6 +3196,8 @@ apiToken, libsqlUrl, libsqlToken, + cxUrl, + cxKey, readOnly, sshEnabled, sshHost, @@ -3201,6 +3235,7 @@ if (dbType === "influxdb") return [couchUrl, database].filter(Boolean).join(" · ") || "—"; if (isCqlForm) return cqlHosts || "—"; if (dbType === "firestore") return fsProject || "—"; + if (dbType === "convex-url") return cxUrl.replace(/^https?:\/\//, "") || "—"; if (dbType === "spanner") return [fsProject, spInstance, spDatabase].filter(Boolean).join("/") || "—"; if (dbType === "bigquery") return [fsProject, bqDataset].filter(Boolean).join(".") || "—"; if (dbType === "snowflake") return [sfAccount, database].filter(Boolean).join(" · ") || "—"; @@ -3985,7 +4020,7 @@ the rail's far end, and in a 48px row against the panel's 40px, it jumped across and down on every collapse. -->