diff --git a/CLAUDE.md b/CLAUDE.md index 1b9b23d37..741135c56 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -81,7 +81,8 @@ Adding or changing a Tauri command touches these layers in order: default implementation goes here, not in the command handler 3. `crates/radicle-tauri/src/commands/` — add the `#[tauri::command]` handler (thin wrapper: `ctx.method()`), register in `crates/radicle-tauri/src/lib.rs` -4. `crates/test-http-api/src/` — mirror the same route so E2E tests keep working +4. `crates/test-http-api/src/` — mirror the same route so E2E tests keep working; + `cargo test -p test-http-api --test parity` fails until you do 5. `src/` — call via `invoke("command_name", args)`, import types from `@bindings` ### Pre-push checklist @@ -259,7 +260,9 @@ Read these when you need domain context for UI work: not in command handlers - Tauri command signature: `pub fn cmd(ctx: tauri::State, ...) -> Result` - Commands are registered in `crates/radicle-tauri/src/lib.rs` via `tauri::generate_handler![...]` -- Mirror every new command in `crates/test-http-api/src/` so E2E tests continue to work +- Mirror every new command in `crates/test-http-api/src/` so E2E tests continue to work. + A command that can't work over HTTP goes in `TAURI_ONLY` in + `crates/test-http-api/tests/parity.rs`, with the reason - All serialized types live in `crates/radicle-types/src/`; annotate new types with `#[derive(Serialize, TS)]`, `#[serde(rename_all = "camelCase")]`, `#[ts(export)]`, and `#[ts(export_to = "/")]` diff --git a/crates/radicle-tauri/src/lib.rs b/crates/radicle-tauri/src/lib.rs index 0cc25c67a..2d9e9a44f 100644 --- a/crates/radicle-tauri/src/lib.rs +++ b/crates/radicle-tauri/src/lib.rs @@ -61,7 +61,6 @@ pub fn run() { cob::patch::create_patch_review, cob::patch::rebuild_patch_cache, cob::patch::revisions_by_patch, - cob::patch::revisions_by_patch, cob::save_embed_by_bytes, cob::save_embed_by_clipboard, cob::save_embed_by_path, diff --git a/crates/test-http-api/build.rs b/crates/test-http-api/build.rs new file mode 100644 index 000000000..550aa24d3 --- /dev/null +++ b/crates/test-http-api/build.rs @@ -0,0 +1,13 @@ +use std::env; +use std::process::Command; + +fn main() { + let head = env::var("GIT_HEAD").unwrap_or_else(|_| { + Command::new("git") + .args(["rev-parse", "--short", "HEAD"]) + .output() + .map(|output| String::from_utf8(output.stdout).expect("output from Git is UTF-8")) + .unwrap_or("unknown".into()) + }); + println!("cargo::rustc-env=GIT_HEAD={head}"); +} diff --git a/crates/test-http-api/src/api.rs b/crates/test-http-api/src/api.rs index e831e855d..1a7045bfd 100644 --- a/crates/test-http-api/src/api.rs +++ b/crates/test-http-api/src/api.rs @@ -3,17 +3,20 @@ use std::path::PathBuf; use std::sync::Arc; use axum::Router; -use axum::extract::{Request, State}; +use axum::extract::{FromRequestParts, Request, State}; use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Json, Response}; use axum::routing::post; use hyper::Method; -use hyper::header::CONTENT_TYPE; +use hyper::header::{CONTENT_TYPE, HeaderValue}; +use hyper::http::request::Parts; use serde::{Deserialize, Serialize}; -use tokio::sync::Mutex; +use tokio::sync::{Mutex, RwLock}; use tower_http::cors::{self, CorsLayer}; -use radicle::node::NodeId; +use radicle::cob::cache::COBS_DB_FILE; +use radicle::crypto::ssh::Passphrase; +use radicle::node::{NOTIFICATIONS_DB_FILE, NodeId}; use radicle::storage::{ReadRepository as _, ReadStorage as _}; use radicle::{git, identity}; use radicle_types as types; @@ -22,6 +25,8 @@ use radicle_types::cobs::FromRadicleAction; use radicle_types::cobs::issue; use radicle_types::cobs::issue::NewIssue; use radicle_types::config::Version; +use radicle_types::domain::inbox::models::notification; +use radicle_types::domain::inbox::service::Service as InboxService; use radicle_types::domain::issue::service::Service as IssueService; use radicle_types::domain::issue::traits::IssueService as _; use radicle_types::domain::patch::models; @@ -32,6 +37,7 @@ use radicle_types::outbound::sqlite::Sqlite; use radicle_types::traits::Profile; use radicle_types::traits::cobs::Cobs; use radicle_types::traits::identity::Identity; +use radicle_types::traits::inbox::Inbox; use radicle_types::traits::issue::{Issues, IssuesMut}; use radicle_types::traits::job::Jobs; use radicle_types::traits::patch::{Patches, PatchesMut}; @@ -43,11 +49,13 @@ pub struct Context { profile: Arc, patches: Arc>, issues: Arc>, + inbox: Arc>, } impl Repo for Context {} impl Cobs for Context {} impl Identity for Context {} +impl Inbox for Context {} impl Thread for Context {} impl Issues for Context {} impl IssuesMut for Context {} @@ -61,26 +69,68 @@ impl Profile for Context { } impl Context { - pub fn new( - profile: Arc, - patches: Arc>, - issues: Arc>, - ) -> Self { - Self { - profile, - patches, - issues, - } + fn load() -> Result { + let profile = radicle::Profile::load()?; + let cobs_db = Sqlite::reader(profile.cobs().join(COBS_DB_FILE))?; + let inbox_db = Sqlite::reader(profile.node().join(NOTIFICATIONS_DB_FILE))?; + + Ok(Self { + profile: Arc::new(profile), + patches: Arc::new(Service::new(cobs_db.clone())), + issues: Arc::new(IssueService::new(cobs_db)), + inbox: Arc::new(InboxService::new(inbox_db)), + }) } } -pub fn router(ctx: Context) -> Router { +/// Loads the profile on first use, so the server can run before `init`. +#[derive(Clone, Default)] +pub struct Shared { + ctx: Arc>>, +} + +pub struct Ctx(Context); + +impl FromRequestParts for Ctx { + type Rejection = Error; + + async fn from_request_parts(_: &mut Parts, shared: &Shared) -> Result { + if let Some(ctx) = shared.ctx.read().await.as_ref() { + return Ok(Ctx(ctx.clone())); + } + let mut guard = shared.ctx.write().await; + let ctx = match guard.as_ref() { + Some(ctx) => ctx.clone(), + None => guard.insert(Context::load()?).clone(), + }; + + Ok(Ctx(ctx)) + } +} + +// The API acts on a real profile, so only the app's own dev servers may call +// it: Vite on 1420 (`npm run start`) and the e2e preview on 3001. +const ALLOWED_ORIGINS: [&str; 4] = [ + "http://localhost:1420", + "http://127.0.0.1:1420", + "http://localhost:3001", + "http://127.0.0.1:3001", +]; + +pub fn router(shared: Shared) -> Router { let writes = Router::new() .route("/seed", post(seed_handler)) .route("/unseed", post(unseed_handler)) .route("/clean", post(clean_handler)) .route("/create_issue", post(create_issue_handler)) .route("/create_issue_comment", post(create_issue_comment_handler)) + .route("/create_patch_comment", post(create_patch_comment_handler)) + .route("/rebuild_issue_cache", post(rebuild_issue_cache_handler)) + .route("/rebuild_patch_cache", post(rebuild_patch_cache_handler)) + .route("/save_embed_by_path", post(save_embed_by_path_handler)) + .route("/save_embed_by_bytes", post(save_embed_by_bytes_handler)) + .route("/clear_notifications", post(clear_notifications_handler)) + .route("/init", post(init_handler)) .route("/edit_issue", post(edit_issue_handler)) .route("/delete_issue", post(delete_issue_handler)) .route("/edit_patch", post(edit_patch_handler)) @@ -92,8 +142,12 @@ pub fn router(ctx: Context) -> Router { )); Router::new() + .route("/startup", post(startup_handler)) .route("/config", post(config_handler)) + .route("/alias", post(alias_handler)) .route("/authenticate", post(auth_handler)) + .route("/check_radicle_cli", post(check_radicle_cli_handler)) + .route("/node_running", post(node_running_handler)) .route("/repo_count", post(repo_count_handler)) .route("/list_repos", post(repo_root_handler)) .route("/list_repos_summary", post(list_repos_summary_handler)) @@ -122,6 +176,7 @@ pub fn router(ctx: Context) -> Router { .route("/get_diff_text", post(diff_text_handler)) .route("/save_diff_to_disk", post(save_diff_handler)) .route("/get_commit_diff", post(commit_diff_handler)) + .route("/list_commits", post(list_commits_handler)) .route("/list_repo_commits", post(list_repo_commits_handler)) .route("/repo_commit_count", post(repo_commit_count_handler)) .route("/repo_commit", post(repo_commit_handler)) @@ -132,22 +187,20 @@ pub fn router(ctx: Context) -> Router { .route("/patch_by_id", post(patch_handler)) .route("/revisions_by_patch", post(revision_handler)) .route("/get_embed", post(get_embeds_handler)) - .route("/save_embed_by_path", post(save_embed_handler)) - .route("/save_embed_by_clipboard", post(save_embed_handler)) - .route("/save_embed_by_bytes", post(save_embed_handler)) - .route("/save_embed_to_disk", post(save_embed_handler)) + .route("/save_embed_to_disk", post(save_embed_to_disk_handler)) .route("/list_jobs", post(jobs_handler)) .route("/list_notifications", post(list_notifications_handler)) .route("/notification_count", post(notification_count_handler)) - .route("/clear_notifications", post(clear_notifications_handler)) .merge(writes) .layer( CorsLayer::new() - .allow_origin(cors::Any) + .allow_origin(cors::AllowOrigin::list( + ALLOWED_ORIGINS.map(HeaderValue::from_static), + )) .allow_methods([Method::POST, Method::GET]) .allow_headers([CONTENT_TYPE]), ) - .with_state(ctx) + .with_state(shared) } async fn serialize_writes( @@ -159,23 +212,74 @@ async fn serialize_writes( next.run(request).await } -async fn config_handler(State(ctx): State) -> impl IntoResponse { +async fn config_handler(Ctx(ctx): Ctx) -> impl IntoResponse { let config = ctx.config(); Ok::<_, Error>(Json(config)) } -async fn auth_handler() -> impl IntoResponse { +async fn startup_handler(Ctx(ctx): Ctx) -> impl IntoResponse { + ctx.check_cobs_cache()?; + + Ok::<_, Error>(Json(ctx.config())) +} + +#[derive(Deserialize)] +struct AliasBody { + pub nid: NodeId, +} + +async fn alias_handler( + Ctx(ctx): Ctx, + Json(AliasBody { nid }): Json, +) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.alias(nid))) +} + +#[derive(Deserialize)] +struct AuthBody { + #[serde(default)] + pub passphrase: Option, +} + +async fn auth_handler( + Ctx(ctx): Ctx, + Json(AuthBody { passphrase }): Json, +) -> impl IntoResponse { + radicle_types::auth::authenticate(&ctx.profile, passphrase.map(Passphrase::from))?; + Ok::<_, Error>(Json(())) } +#[derive(Deserialize)] +struct InitBody { + pub alias: String, + pub passphrase: String, +} + +async fn init_handler(Json(InitBody { alias, passphrase }): Json) -> impl IntoResponse { + radicle_types::auth::init(alias, Passphrase::from(passphrase))?; + + Ok::<_, Error>(Json(())) +} + +async fn check_radicle_cli_handler(Ctx(ctx): Ctx) -> impl IntoResponse { + radicle_types::binaries::check_radicle_cli(&ctx.profile)?; + + Ok::<_, Error>(Json(())) +} + +async fn node_running_handler(Ctx(ctx): Ctx) -> impl IntoResponse { + Ok::<_, Error>(Json(ctx.node_running())) +} + #[derive(Serialize, Deserialize)] pub struct Options { show: Show, } async fn repo_root_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(Options { show }): Json, ) -> impl IntoResponse { let repos = ctx.list_repos(show)?; @@ -183,35 +287,32 @@ async fn repo_root_handler( Ok::<_, Error>(Json(repos)) } -async fn repo_count_handler(State(ctx): State) -> impl IntoResponse { +async fn repo_count_handler(Ctx(ctx): Ctx) -> impl IntoResponse { let repos = ctx.repo_count()?; Ok::<_, Error>(Json(repos)) } async fn list_repos_summary_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(Options { show }): Json, ) -> impl IntoResponse { let repos = ctx.list_repos_summary(show)?; Ok::<_, Error>(Json(repos)) } -async fn seeded_not_replicated_handler(State(ctx): State) -> impl IntoResponse { +async fn seeded_not_replicated_handler(Ctx(ctx): Ctx) -> impl IntoResponse { let rids = ctx.seeded_not_replicated()?; Ok::<_, Error>(Json(rids)) } -async fn seed_handler( - State(ctx): State, - Json(RepoBody { rid }): Json, -) -> impl IntoResponse { +async fn seed_handler(Ctx(ctx): Ctx, Json(RepoBody { rid }): Json) -> impl IntoResponse { ctx.seed(rid)?; Ok::<_, Error>(Json(())) } async fn unseed_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(RepoBody { rid }): Json, ) -> impl IntoResponse { ctx.unseed(rid)?; @@ -219,26 +320,43 @@ async fn unseed_handler( Ok::<_, Error>(Json(())) } -async fn clean_handler( - State(ctx): State, - Json(RepoBody { rid }): Json, -) -> impl IntoResponse { +async fn clean_handler(Ctx(ctx): Ctx, Json(RepoBody { rid }): Json) -> impl IntoResponse { ctx.clean(rid)?; Ok::<_, Error>(Json(())) } -async fn list_notifications_handler() -> impl IntoResponse { - Ok::<_, Error>(Json(Vec::< - radicle_types::domain::inbox::models::notification::NotificationsByRepo, - >::new())) +#[derive(Deserialize)] +struct ListNotificationsBody { + pub params: notification::RepoGroupParams, } -async fn notification_count_handler() -> impl IntoResponse { - Ok::<_, Error>(Json(0_usize)) +async fn list_notifications_handler( + Ctx(ctx): Ctx, + Json(ListNotificationsBody { params }): Json, +) -> impl IntoResponse { + let notifications = ctx.list_notifications(&ctx.inbox, params)?; + + Ok::<_, Error>(Json(notifications)) } -async fn clear_notifications_handler() -> impl IntoResponse { +async fn notification_count_handler(Ctx(ctx): Ctx) -> impl IntoResponse { + let count = ctx.notification_count(&ctx.inbox)?; + + Ok::<_, Error>(Json(count)) +} + +#[derive(Deserialize)] +struct ClearNotificationsBody { + pub params: notification::SetStatusNotifications, +} + +async fn clear_notifications_handler( + Ctx(ctx): Ctx, + Json(ClearNotificationsBody { params }): Json, +) -> impl IntoResponse { + ctx.clear_notifications(params)?; + Ok::<_, Error>(Json(())) } @@ -247,17 +365,14 @@ struct RepoBody { pub rid: identity::RepoId, } -async fn repo_handler( - State(ctx): State, - Json(RepoBody { rid }): Json, -) -> impl IntoResponse { +async fn repo_handler(Ctx(ctx): Ctx, Json(RepoBody { rid }): Json) -> impl IntoResponse { let info = ctx.repo_by_id(rid)?; Ok::<_, Error>(Json(info)) } async fn identity_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(RepoBody { rid }): Json, ) -> impl IntoResponse { let identity = ctx.identity_by_repo(rid)?; @@ -266,7 +381,7 @@ async fn identity_handler( } async fn list_repo_refs_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(RepoBody { rid }): Json, ) -> impl IntoResponse { let refs = ctx.list_repo_refs(rid)?; @@ -279,9 +394,11 @@ async fn git_info_handler() -> impl IntoResponse { } async fn version_handler() -> impl IntoResponse { + let config: serde_json::Value = + serde_json::from_str(include_str!("../../radicle-tauri/tauri.conf.json"))?; let version = Version { - version: String::from("0.6.1"), - head: String::from("51cf6cfbfe0be992ee709c49e6da589aa0f148c5"), + version: config["version"].as_str().unwrap_or("unknown").to_string(), + head: env!("GIT_HEAD").to_string(), }; Ok::<_, Error>(Json(version)) @@ -295,7 +412,7 @@ struct DiffStatsBody { } async fn diff_stats_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(DiffStatsBody { rid, base, head }): Json, ) -> impl IntoResponse { let info = ctx.diff_stats(rid, base, head)?; @@ -321,7 +438,7 @@ struct ReadmeBody { } async fn readme_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(ReadmeBody { rid, sha, @@ -347,7 +464,7 @@ struct TreeBody { } async fn tree_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(TreeBody { rid, path, @@ -370,7 +487,7 @@ struct BlobBody { } async fn blob_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(BlobBody { rid, path, sha }): Json, ) -> impl IntoResponse { let info = ctx.repo_blob(rid, path, sha)?; @@ -379,7 +496,7 @@ async fn blob_handler( } async fn diff_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(DiffBody { rid, options }): Json, ) -> impl IntoResponse { let info = ctx.get_diff(rid, options)?; @@ -397,7 +514,7 @@ struct DiffTextBody { } async fn diff_text_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(DiffTextBody { rid, base, @@ -426,6 +543,14 @@ struct SaveDiffBody { async fn save_diff_handler( Json(SaveDiffBody { name, content }): Json, ) -> impl IntoResponse { + std::fs::write(temp_file_path(&name)?, content)?; + + Ok::<_, Error>(Json(())) +} + +/// The server is reachable over the network, so a suggested file name is +/// reduced to its basename and must not traverse paths. +fn temp_file_path(name: &str) -> Result { let name = PathBuf::from(name); let Some(file_name) = name.file_name() else { return Err(Error::Io(std::io::Error::new( @@ -433,9 +558,8 @@ async fn save_diff_handler( "suggested file name has no basename component", ))); }; - std::fs::write(std::env::temp_dir().join(file_name), content)?; - Ok::<_, Error>(Json(())) + Ok(std::env::temp_dir().join(file_name)) } #[derive(Serialize, Deserialize)] @@ -445,7 +569,7 @@ struct CommitDiffBody { } async fn commit_diff_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(CommitDiffBody { rid, sha }): Json, ) -> impl IntoResponse { let diff = ctx.get_commit_diff(rid, sha)?; @@ -453,6 +577,22 @@ async fn commit_diff_handler( Ok::<_, Error>(Json(diff)) } +#[derive(Deserialize)] +struct ListCommitsBody { + pub rid: identity::RepoId, + pub base: String, + pub head: String, +} + +async fn list_commits_handler( + Ctx(ctx): Ctx, + Json(ListCommitsBody { rid, base, head }): Json, +) -> impl IntoResponse { + let commits = ctx.list_commits(rid, base, head)?; + + Ok::<_, Error>(Json(commits)) +} + #[derive(Serialize, Deserialize)] struct ListRepoCommitsBody { pub rid: identity::RepoId, @@ -466,7 +606,7 @@ struct ListRepoCommitsBody { } async fn list_repo_commits_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(ListRepoCommitsBody { rid, head, @@ -488,7 +628,7 @@ struct RepoCommitCountBody { } async fn repo_commit_count_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(RepoCommitCountBody { rid, head }): Json, ) -> impl IntoResponse { let count = ctx.repo_commit_count(rid, head)?; @@ -508,7 +648,7 @@ struct RepoCommitBody { } async fn repo_commit_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(RepoCommitBody { rid, sha, @@ -531,7 +671,7 @@ struct IssuesBody { } async fn issues_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(IssuesBody { rid, status, @@ -555,7 +695,7 @@ struct CreateIssuesBody { } async fn create_issue_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(CreateIssuesBody { rid, opts, new }): Json, ) -> impl IntoResponse { let issues = ctx.create_issue(rid, new, opts)?; @@ -571,7 +711,7 @@ struct CreateIssueCommentBody { } async fn create_issue_comment_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(CreateIssueCommentBody { rid, opts, new }): Json, ) -> impl IntoResponse { let comment = ctx.create_issue_comment(rid, new, opts)?; @@ -579,6 +719,40 @@ async fn create_issue_comment_handler( Ok::<_, Error>(Json(comment)) } +#[derive(Deserialize)] +struct CreatePatchCommentBody { + pub rid: identity::RepoId, + pub new: types::cobs::thread::NewPatchComment, + pub opts: types::cobs::CobOptions, +} + +async fn create_patch_comment_handler( + Ctx(ctx): Ctx, + Json(CreatePatchCommentBody { rid, opts, new }): Json, +) -> impl IntoResponse { + let comment = ctx.create_patch_comment(rid, new, opts)?; + + Ok::<_, Error>(Json(comment)) +} + +async fn rebuild_issue_cache_handler( + Ctx(ctx): Ctx, + Json(RepoBody { rid }): Json, +) -> impl IntoResponse { + ctx.rebuild_issue_cache(rid, |_| Ok(()))?; + + Ok::<_, Error>(Json(())) +} + +async fn rebuild_patch_cache_handler( + Ctx(ctx): Ctx, + Json(RepoBody { rid }): Json, +) -> impl IntoResponse { + ctx.rebuild_patch_cache(rid, |_| Ok(()))?; + + Ok::<_, Error>(Json(())) +} + #[derive(Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct EditIssuesBody { @@ -589,7 +763,7 @@ struct EditIssuesBody { } async fn edit_issue_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(EditIssuesBody { rid, cob_id, @@ -613,7 +787,7 @@ async fn activity_issue_handler< A: serde::Serialize + serde::de::DeserializeOwned, B: FromRadicleAction + serde::Serialize, >( - State(ctx): State, + Ctx(ctx): Ctx, Json(ActivityBody { rid, id }): Json, ) -> impl IntoResponse { let activity = ctx.activity_by_id::(rid, &radicle::cob::issue::TYPENAME, id)?; @@ -625,7 +799,7 @@ async fn activity_patch_handler< A: serde::Serialize + serde::de::DeserializeOwned, B: FromRadicleAction + serde::Serialize, >( - State(ctx): State, + Ctx(ctx): Ctx, Json(ActivityBody { rid, id }): Json, ) -> impl IntoResponse { let activity = ctx.activity_by_id::(rid, &radicle::cob::patch::TYPENAME, id)?; @@ -641,7 +815,7 @@ struct EmbedBody { } async fn get_embeds_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(EmbedBody { rid, name, oid }): Json, ) -> impl IntoResponse { let embed = ctx.get_embed(rid, name, oid)?; @@ -649,19 +823,52 @@ async fn get_embeds_handler( Ok::<_, Error>(Json(embed)) } -#[derive(Serialize, Deserialize)] -struct CreateEmbedBody { +#[derive(Deserialize)] +struct SaveEmbedByPathBody { pub rid: identity::RepoId, pub path: PathBuf, } -async fn save_embed_handler( - State(ctx): State, - Json(CreateEmbedBody { rid, path }): Json, +async fn save_embed_by_path_handler( + Ctx(ctx): Ctx, + Json(SaveEmbedByPathBody { rid, path }): Json, ) -> impl IntoResponse { - let embed = ctx.save_embed_by_path(rid, path)?; + let oid = ctx.save_embed_by_path(rid, path)?; - Ok::<_, Error>(Json(embed)) + Ok::<_, Error>(Json(oid)) +} + +#[derive(Deserialize)] +struct SaveEmbedByBytesBody { + pub rid: identity::RepoId, + pub name: String, + pub bytes: Vec, +} + +async fn save_embed_by_bytes_handler( + Ctx(ctx): Ctx, + Json(SaveEmbedByBytesBody { rid, name, bytes }): Json, +) -> impl IntoResponse { + let oid = ctx.save_embed_by_bytes(rid, name, bytes)?; + + Ok::<_, Error>(Json(oid)) +} + +#[derive(Deserialize)] +struct SaveEmbedToDiskBody { + pub rid: identity::RepoId, + pub oid: git::Oid, + pub name: String, +} + +async fn save_embed_to_disk_handler( + Ctx(ctx): Ctx, + Json(SaveEmbedToDiskBody { rid, oid, name }): Json, +) -> impl IntoResponse { + let path = temp_file_path(&name)?; + ctx.save_embed_to_disk(rid, oid, path)?; + + Ok::<_, Error>(Json(())) } #[derive(Serialize, Deserialize)] @@ -671,7 +878,7 @@ struct IssueBody { } async fn issue_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(IssueBody { rid, id }): Json, ) -> impl IntoResponse { let issue = ctx.issue_by_id(rid, id)?; @@ -680,7 +887,7 @@ async fn issue_handler( } async fn issue_threads_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(IssueBody { rid, id }): Json, ) -> impl IntoResponse { let issue_threads = ctx.comment_threads_by_issue_id(rid, id)?; @@ -698,7 +905,7 @@ struct PatchesBody { } async fn patches_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(PatchesBody { rid, skip, @@ -722,7 +929,7 @@ struct PatchBody { } async fn patch_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(PatchBody { rid, id }): Json, ) -> impl IntoResponse { let patch = ctx.get_patch(rid, id)?; @@ -731,7 +938,7 @@ async fn patch_handler( } async fn revision_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(PatchBody { rid, id }): Json, ) -> impl IntoResponse { let revisions = ctx.revisions_by_patch(rid, id)?; @@ -749,7 +956,7 @@ struct EditPatchBody { } async fn edit_patch_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(EditPatchBody { rid, cob_id, @@ -770,7 +977,7 @@ struct CreatePatchReviewBody { } async fn create_patch_review_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(CreatePatchReviewBody { args }): Json, ) -> impl IntoResponse { let review_id = ctx.create_patch_review(args)?; @@ -787,7 +994,7 @@ struct DeleteIssueBody { } async fn delete_issue_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(DeleteIssueBody { rid, cob_id, opts }): Json, ) -> impl IntoResponse { ctx.delete_issue(rid, cob_id, opts)?; @@ -804,7 +1011,7 @@ struct DeletePatchBody { } async fn delete_patch_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(DeletePatchBody { rid, cob_id, opts }): Json, ) -> impl IntoResponse { ctx.delete_patch(rid, cob_id, opts)?; @@ -819,7 +1026,7 @@ struct JobsBody { } async fn jobs_handler( - State(ctx): State, + Ctx(ctx): Ctx, Json(JobsBody { rid, sha }): Json, ) -> impl IntoResponse { let jobs = ctx.list_jobs(rid, sha)?; diff --git a/crates/test-http-api/src/lib.rs b/crates/test-http-api/src/lib.rs index be2b90858..8028d3d4f 100644 --- a/crates/test-http-api/src/lib.rs +++ b/crates/test-http-api/src/lib.rs @@ -1,15 +1,7 @@ use std::net::SocketAddr; -use std::sync::Arc; -use axum::Router; use tokio::net::TcpListener; -use radicle::Profile; -use radicle::cob::cache::COBS_DB_FILE; - -use radicle_types::domain::issue::service::Service as IssueService; -use radicle_types::domain::patch::service::Service as PatchService; - mod api; #[derive(Debug, Clone)] @@ -18,24 +10,13 @@ pub struct Options { } pub async fn run(options: Options) -> anyhow::Result<()> { - let profile = Profile::load()?; let listener = TcpListener::bind(options.listen).await?; - let app = router(profile)?.into_make_service_with_connect_info::(); + // Read by the e2e harness to learn the port when it asked for port 0. + println!("listening on {}", listener.local_addr()?); + let app = + api::router(api::Shared::default()).into_make_service_with_connect_info::(); axum::serve(listener, app) .await .map_err(anyhow::Error::from) } - -fn router(profile: Profile) -> anyhow::Result { - let profile = Arc::new(profile); - - let cobs_db = - radicle_types::outbound::sqlite::Sqlite::reader(profile.cobs().join(COBS_DB_FILE))?; - let patch_service = PatchService::new(cobs_db.clone()); - let issue_service = IssueService::new(cobs_db); - - let ctx = api::Context::new(profile, Arc::new(patch_service), Arc::new(issue_service)); - - Ok(api::router(ctx)) -} diff --git a/crates/test-http-api/src/main.rs b/crates/test-http-api/src/main.rs index d285eb2ee..16d52d5da 100644 --- a/crates/test-http-api/src/main.rs +++ b/crates/test-http-api/src/main.rs @@ -30,6 +30,6 @@ fn parse_options() -> Result { } } Ok(api::Options { - listen: listen.unwrap_or_else(|| ([0, 0, 0, 0], 8081).into()), + listen: listen.unwrap_or_else(|| ([127, 0, 0, 1], 8081).into()), }) } diff --git a/crates/test-http-api/tests/parity.rs b/crates/test-http-api/tests/parity.rs new file mode 100644 index 000000000..24a327623 --- /dev/null +++ b/crates/test-http-api/tests/parity.rs @@ -0,0 +1,214 @@ +//! Checks that the Tauri commands, the HTTP routes and the frontend's +//! `invoke` calls match. + +use std::collections::BTreeSet; +use std::fs; +use std::path::{Path, PathBuf}; + +/// Tauri commands with no HTTP route, and why. +const TAURI_ONLY: &[(&str, &str)] = &[( + "save_embed_by_clipboard", + "reads the native clipboard, which the HTTP server has no access to", +)]; + +/// HTTP routes with no Tauri command, and why. +const HTTP_ONLY: &[(&str, &str)] = &[( + "node_running", + "stands in for the `node_running` event that the Tauri driver emits", +)]; + +fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +fn read(path: &str) -> String { + fs::read_to_string(root().join(path)).unwrap_or_else(|e| panic!("reading {path}: {e}")) +} + +fn tauri_commands() -> Vec { + let source = read("crates/radicle-tauri/src/lib.rs"); + let start = source + .find("generate_handler![") + .expect("`generate_handler!` in radicle-tauri") + + "generate_handler![".len(); + let end = start + + source[start..] + .find(']') + .expect("end of `generate_handler!`"); + + source[start..end] + .split(',') + .map(|path| path.trim()) + .filter(|path| !path.is_empty()) + .map(|path| path.rsplit("::").next().unwrap_or(path).to_string()) + .collect() +} + +fn http_routes() -> Vec { + let source = read("crates/test-http-api/src/api.rs"); + + source + .split(".route(") + .skip(1) + .filter_map(|rest| rest.trim_start().strip_prefix("\"/")) + .filter_map(|rest| rest.split('"').next()) + .map(str::to_string) + .collect() +} + +fn source_files(dir: &Path, files: &mut Vec) { + for entry in fs::read_dir(dir).unwrap_or_else(|e| panic!("reading {dir:?}: {e}")) { + let path = entry.expect("directory entry").path(); + if path.is_dir() { + source_files(&path, files); + } else if path + .extension() + .is_some_and(|ext| ext == "ts" || ext == "svelte") + { + files.push(path); + } + } +} + +fn invoked_command(after: &str) -> Option { + let mut rest = after; + if rest.starts_with('<') { + let mut depth = 0; + let end = rest.char_indices().find_map(|(i, c)| { + match c { + '<' => depth += 1, + '>' => depth -= 1, + _ => {} + } + (depth == 0).then_some(i) + })?; + rest = &rest[end + 1..]; + } + let rest = rest.strip_prefix('(').or_else(|| rest.strip_prefix(','))?; + let rest = rest.trim_start().strip_prefix('"')?; + let name = &rest[..rest.find('"')?]; + + name.chars() + .all(|c| c.is_ascii_lowercase() || c == '_') + .then(|| name.to_string()) +} + +fn frontend_commands() -> BTreeSet { + let mut files = Vec::new(); + source_files(&root().join("src"), &mut files); + + files + .iter() + .flat_map(|file| { + let source = fs::read_to_string(file).expect("frontend source"); + source + .split("invoke") + .skip(1) + .filter_map(invoked_command) + .collect::>() + }) + .collect() +} + +fn names(list: &[(&str, &str)]) -> BTreeSet { + list.iter().map(|(name, _)| name.to_string()).collect() +} + +fn duplicates(list: &[String]) -> BTreeSet { + let mut seen = BTreeSet::new(); + list.iter() + .filter(|name| !seen.insert(name.as_str())) + .cloned() + .collect() +} + +#[test] +fn commands_are_registered_once() { + assert_eq!(duplicates(&tauri_commands()), BTreeSet::new(), "Tauri"); + assert_eq!(duplicates(&http_routes()), BTreeSet::new(), "HTTP"); +} + +#[test] +fn every_tauri_command_has_an_http_route() { + let tauri: BTreeSet<_> = tauri_commands().into_iter().collect(); + let http: BTreeSet<_> = http_routes().into_iter().collect(); + let missing: BTreeSet<_> = tauri + .difference(&http) + .filter(|name| !names(TAURI_ONLY).contains(*name)) + .cloned() + .collect(); + + assert_eq!( + missing, + BTreeSet::new(), + "Add a route to crates/test-http-api/src/api.rs, or list the command in TAURI_ONLY" + ); +} + +#[test] +fn every_http_route_has_a_tauri_command() { + let tauri: BTreeSet<_> = tauri_commands().into_iter().collect(); + let http: BTreeSet<_> = http_routes().into_iter().collect(); + let extra: BTreeSet<_> = http + .difference(&tauri) + .filter(|name| !names(HTTP_ONLY).contains(*name)) + .cloned() + .collect(); + + assert_eq!( + extra, + BTreeSet::new(), + "Remove the route, or list it in HTTP_ONLY" + ); +} + +#[test] +fn exceptions_are_still_needed() { + let tauri: BTreeSet<_> = tauri_commands().into_iter().collect(); + let http: BTreeSet<_> = http_routes().into_iter().collect(); + + for name in names(TAURI_ONLY) { + assert!( + tauri.contains(&name), + "{name} in TAURI_ONLY is not a Tauri command" + ); + assert!( + !http.contains(&name), + "{name} in TAURI_ONLY has an HTTP route" + ); + } + for name in names(HTTP_ONLY) { + assert!( + http.contains(&name), + "{name} in HTTP_ONLY is not an HTTP route" + ); + assert!( + !tauri.contains(&name), + "{name} in HTTP_ONLY is a Tauri command" + ); + } +} + +#[test] +fn every_frontend_command_exists() { + let backend: BTreeSet<_> = tauri_commands() + .into_iter() + .chain(names(HTTP_ONLY)) + .collect(); + let unknown: BTreeSet<_> = frontend_commands().difference(&backend).cloned().collect(); + + assert_eq!( + unknown, + BTreeSet::new(), + "The frontend invokes commands that no driver implements" + ); +} + +#[test] +fn frontend_command_scan_finds_commands() { + // Guards against the scan above silently matching nothing. + let commands = frontend_commands(); + for name in ["startup", "list_issues", "list_patches", "node_running"] { + assert!(commands.contains(name), "{name} not found in the frontend"); + } +} diff --git a/src/App.svelte b/src/App.svelte index 89810e90b..a35b9abbc 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -186,6 +186,15 @@ nodeRunning.set(event.payload); }), ); + } else { + // The test backend can't emit events. + const pollNodeRunning = () => + invoke("node_running") + .then(running => nodeRunning.set(running)) + .catch(console.error); + void pollNodeRunning(); + const interval = setInterval(pollNodeRunning, 2_000); + setUnlistenNodeEvents(() => clearInterval(interval)); } try { diff --git a/src/global.d.ts b/src/global.d.ts index 88c82d94e..be2c7fe71 100644 --- a/src/global.d.ts +++ b/src/global.d.ts @@ -2,6 +2,8 @@ declare global { interface Window { // eslint-disable-next-line @typescript-eslint/naming-convention __TAURI_INTERNALS__: Record; + // eslint-disable-next-line @typescript-eslint/naming-convention + __TEST_HTTP_API_PORT__?: number; } } diff --git a/src/lib/invoke.ts b/src/lib/invoke.ts index 2caea5f4a..bc0dffde4 100644 --- a/src/lib/invoke.ts +++ b/src/lib/invoke.ts @@ -63,17 +63,18 @@ async function withTestBackend( } }); } else { - return fetch( - `http://127.0.0.1:${import.meta.env.VITE_TEST_HTTP_API_PORT ?? 8081}/${cmd}`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(args), - }, - ).then(async response => { + return fetch(`http://127.0.0.1:${testHttpApiPort()}/${cmd}`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(args ?? {}, (_key, value: unknown) => + value instanceof Uint8Array ? Array.from(value) : value, + ), + }).then(async response => { if (response.status === 404) { - console.log("Got a 404 response:", response); - return null; + throw new InvokeError( + `test-http-api has no route for \`${cmd}\``, + "TestHttpApi.MissingRoute", + ); } const json = await response.json(); if (!response.ok) { @@ -89,6 +90,23 @@ async function withTestBackend( } } +function testHttpApiPort(): number | string { + return ( + window.__TEST_HTTP_API_PORT__ ?? + import.meta.env.VITE_TEST_HTTP_API_PORT ?? + 8081 + ); +} + +// The test backend can't stream, so outside Tauri events are dropped. +export function channel( + onMessage: (message: T) => void, +): tauri.Channel | undefined { + return window.__TAURI_INTERNALS__ + ? new tauri.Channel(onMessage) + : undefined; +} + async function getDiff(rid: string, options: DiffOptions): Promise { return withTestBackend(tauri.invoke, "get_diff", { rid, diff --git a/src/views/repo/Issues.svelte b/src/views/repo/Issues.svelte index 21cb0651f..2a1a33a7b 100644 --- a/src/views/repo/Issues.svelte +++ b/src/views/repo/Issues.svelte @@ -6,11 +6,10 @@ import type { RepoInfo } from "@bindings/repo/RepoInfo"; import { DEFAULT_TAKE } from "@app/views/repo/router"; - import { Channel } from "@tauri-apps/api/core"; import fuzzysort from "fuzzysort"; import delay from "lodash/delay"; - import { invoke } from "@app/lib/invoke"; + import { channel, invoke } from "@app/lib/invoke"; import { issueCountMismatch, resetIssueCounts, @@ -107,7 +106,7 @@ try { await invoke("rebuild_issue_cache", { rid: repo.rid, - onEvent: new Channel(message => { + onEvent: channel(message => { cacheState = message; }), }); diff --git a/src/views/repo/Patches.svelte b/src/views/repo/Patches.svelte index 928bbf93c..91a9ce632 100644 --- a/src/views/repo/Patches.svelte +++ b/src/views/repo/Patches.svelte @@ -6,11 +6,10 @@ import type { RepoInfo } from "@bindings/repo/RepoInfo"; import { DEFAULT_TAKE } from "@app/views/repo/router"; - import { Channel } from "@tauri-apps/api/core"; import fuzzysort from "fuzzysort"; import delay from "lodash/delay"; - import { invoke } from "@app/lib/invoke"; + import { channel, invoke } from "@app/lib/invoke"; import { createPaginatedList } from "@app/lib/paginatedList.svelte"; import { patchCountMismatch, @@ -98,7 +97,7 @@ try { await invoke("rebuild_patch_cache", { rid: repo.rid, - onEvent: new Channel(message => { + onEvent: channel(message => { cacheState = message; }), });