Mirror every Tauri command in test-http-api

Several commands had no route or returned stubs, so e2e tests silently got
null or empty data. A missing route now fails loudly, the profile loads on
first use so onboarding works, and node status is polled over HTTP. A
parity test keeps the routes from drifting from the Tauri handlers again;
it also caught revisions_by_patch being registered twice.
This commit is contained in:
Rūdolfs Ošiņš
2026-10-01 18:16:29 +02:00
parent aed733ade6
commit b0a519d1c5
12 changed files with 575 additions and 131 deletions
+5 -2
View File
@@ -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<T>("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<AppState>, ...) -> Result<T, Error>`
- 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 = "<dir>/")]`
-1
View File
@@ -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,
+13
View File
@@ -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}");
}
+295 -88
View File
@@ -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<radicle::Profile>,
patches: Arc<Service<Sqlite>>,
issues: Arc<IssueService<Sqlite>>,
inbox: Arc<InboxService<Sqlite>>,
}
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<radicle::Profile>,
patches: Arc<Service<Sqlite>>,
issues: Arc<IssueService<Sqlite>>,
) -> Self {
Self {
profile,
patches,
issues,
}
fn load() -> Result<Self, Error> {
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<RwLock<Option<Context>>>,
}
pub struct Ctx(Context);
impl FromRequestParts<Shared> for Ctx {
type Rejection = Error;
async fn from_request_parts(_: &mut Parts, shared: &Shared) -> Result<Self, Error> {
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<Context>) -> 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<AliasBody>,
) -> impl IntoResponse {
Ok::<_, Error>(Json(ctx.alias(nid)))
}
#[derive(Deserialize)]
struct AuthBody {
#[serde(default)]
pub passphrase: Option<String>,
}
async fn auth_handler(
Ctx(ctx): Ctx,
Json(AuthBody { passphrase }): Json<AuthBody>,
) -> 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<InitBody>) -> 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<Context>,
Ctx(ctx): Ctx,
Json(Options { show }): Json<Options>,
) -> 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<Context>) -> 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<Context>,
Ctx(ctx): Ctx,
Json(Options { show }): Json<Options>,
) -> impl IntoResponse {
let repos = ctx.list_repos_summary(show)?;
Ok::<_, Error>(Json(repos))
}
async fn seeded_not_replicated_handler(State(ctx): State<Context>) -> 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<Context>,
Json(RepoBody { rid }): Json<RepoBody>,
) -> impl IntoResponse {
async fn seed_handler(Ctx(ctx): Ctx, Json(RepoBody { rid }): Json<RepoBody>) -> impl IntoResponse {
ctx.seed(rid)?;
Ok::<_, Error>(Json(()))
}
async fn unseed_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(RepoBody { rid }): Json<RepoBody>,
) -> impl IntoResponse {
ctx.unseed(rid)?;
@@ -219,26 +320,43 @@ async fn unseed_handler(
Ok::<_, Error>(Json(()))
}
async fn clean_handler(
State(ctx): State<Context>,
Json(RepoBody { rid }): Json<RepoBody>,
) -> impl IntoResponse {
async fn clean_handler(Ctx(ctx): Ctx, Json(RepoBody { rid }): Json<RepoBody>) -> 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<ListNotificationsBody>,
) -> 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<ClearNotificationsBody>,
) -> 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<Context>,
Json(RepoBody { rid }): Json<RepoBody>,
) -> impl IntoResponse {
async fn repo_handler(Ctx(ctx): Ctx, Json(RepoBody { rid }): Json<RepoBody>) -> impl IntoResponse {
let info = ctx.repo_by_id(rid)?;
Ok::<_, Error>(Json(info))
}
async fn identity_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(RepoBody { rid }): Json<RepoBody>,
) -> 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<Context>,
Ctx(ctx): Ctx,
Json(RepoBody { rid }): Json<RepoBody>,
) -> 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<Context>,
Ctx(ctx): Ctx,
Json(DiffStatsBody { rid, base, head }): Json<DiffStatsBody>,
) -> impl IntoResponse {
let info = ctx.diff_stats(rid, base, head)?;
@@ -321,7 +438,7 @@ struct ReadmeBody {
}
async fn readme_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(ReadmeBody {
rid,
sha,
@@ -347,7 +464,7 @@ struct TreeBody {
}
async fn tree_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(TreeBody {
rid,
path,
@@ -370,7 +487,7 @@ struct BlobBody {
}
async fn blob_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(BlobBody { rid, path, sha }): Json<BlobBody>,
) -> 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<Context>,
Ctx(ctx): Ctx,
Json(DiffBody { rid, options }): Json<DiffBody>,
) -> impl IntoResponse {
let info = ctx.get_diff(rid, options)?;
@@ -397,7 +514,7 @@ struct DiffTextBody {
}
async fn diff_text_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(DiffTextBody {
rid,
base,
@@ -426,6 +543,14 @@ struct SaveDiffBody {
async fn save_diff_handler(
Json(SaveDiffBody { name, content }): Json<SaveDiffBody>,
) -> 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<PathBuf, Error> {
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<Context>,
Ctx(ctx): Ctx,
Json(CommitDiffBody { rid, sha }): Json<CommitDiffBody>,
) -> 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<ListCommitsBody>,
) -> 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<Context>,
Ctx(ctx): Ctx,
Json(ListRepoCommitsBody {
rid,
head,
@@ -488,7 +628,7 @@ struct RepoCommitCountBody {
}
async fn repo_commit_count_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(RepoCommitCountBody { rid, head }): Json<RepoCommitCountBody>,
) -> impl IntoResponse {
let count = ctx.repo_commit_count(rid, head)?;
@@ -508,7 +648,7 @@ struct RepoCommitBody {
}
async fn repo_commit_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(RepoCommitBody {
rid,
sha,
@@ -531,7 +671,7 @@ struct IssuesBody {
}
async fn issues_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(IssuesBody {
rid,
status,
@@ -555,7 +695,7 @@ struct CreateIssuesBody {
}
async fn create_issue_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(CreateIssuesBody { rid, opts, new }): Json<CreateIssuesBody>,
) -> 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<Context>,
Ctx(ctx): Ctx,
Json(CreateIssueCommentBody { rid, opts, new }): Json<CreateIssueCommentBody>,
) -> 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<CreatePatchCommentBody>,
) -> 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<RepoBody>,
) -> impl IntoResponse {
ctx.rebuild_issue_cache(rid, |_| Ok(()))?;
Ok::<_, Error>(Json(()))
}
async fn rebuild_patch_cache_handler(
Ctx(ctx): Ctx,
Json(RepoBody { rid }): Json<RepoBody>,
) -> 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<Context>,
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<A> + serde::Serialize,
>(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(ActivityBody { rid, id }): Json<ActivityBody>,
) -> impl IntoResponse {
let activity = ctx.activity_by_id::<A, B>(rid, &radicle::cob::issue::TYPENAME, id)?;
@@ -625,7 +799,7 @@ async fn activity_patch_handler<
A: serde::Serialize + serde::de::DeserializeOwned,
B: FromRadicleAction<A> + serde::Serialize,
>(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(ActivityBody { rid, id }): Json<ActivityBody>,
) -> impl IntoResponse {
let activity = ctx.activity_by_id::<A, B>(rid, &radicle::cob::patch::TYPENAME, id)?;
@@ -641,7 +815,7 @@ struct EmbedBody {
}
async fn get_embeds_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(EmbedBody { rid, name, oid }): Json<EmbedBody>,
) -> 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<Context>,
Json(CreateEmbedBody { rid, path }): Json<CreateEmbedBody>,
async fn save_embed_by_path_handler(
Ctx(ctx): Ctx,
Json(SaveEmbedByPathBody { rid, path }): Json<SaveEmbedByPathBody>,
) -> 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<u8>,
}
async fn save_embed_by_bytes_handler(
Ctx(ctx): Ctx,
Json(SaveEmbedByBytesBody { rid, name, bytes }): Json<SaveEmbedByBytesBody>,
) -> 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<SaveEmbedToDiskBody>,
) -> 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<Context>,
Ctx(ctx): Ctx,
Json(IssueBody { rid, id }): Json<IssueBody>,
) -> 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<Context>,
Ctx(ctx): Ctx,
Json(IssueBody { rid, id }): Json<IssueBody>,
) -> 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<Context>,
Ctx(ctx): Ctx,
Json(PatchesBody {
rid,
skip,
@@ -722,7 +929,7 @@ struct PatchBody {
}
async fn patch_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(PatchBody { rid, id }): Json<PatchBody>,
) -> impl IntoResponse {
let patch = ctx.get_patch(rid, id)?;
@@ -731,7 +938,7 @@ async fn patch_handler(
}
async fn revision_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(PatchBody { rid, id }): Json<PatchBody>,
) -> impl IntoResponse {
let revisions = ctx.revisions_by_patch(rid, id)?;
@@ -749,7 +956,7 @@ struct EditPatchBody {
}
async fn edit_patch_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(EditPatchBody {
rid,
cob_id,
@@ -770,7 +977,7 @@ struct CreatePatchReviewBody {
}
async fn create_patch_review_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(CreatePatchReviewBody { args }): Json<CreatePatchReviewBody>,
) -> impl IntoResponse {
let review_id = ctx.create_patch_review(args)?;
@@ -787,7 +994,7 @@ struct DeleteIssueBody {
}
async fn delete_issue_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(DeleteIssueBody { rid, cob_id, opts }): Json<DeleteIssueBody>,
) -> impl IntoResponse {
ctx.delete_issue(rid, cob_id, opts)?;
@@ -804,7 +1011,7 @@ struct DeletePatchBody {
}
async fn delete_patch_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(DeletePatchBody { rid, cob_id, opts }): Json<DeletePatchBody>,
) -> impl IntoResponse {
ctx.delete_patch(rid, cob_id, opts)?;
@@ -819,7 +1026,7 @@ struct JobsBody {
}
async fn jobs_handler(
State(ctx): State<Context>,
Ctx(ctx): Ctx,
Json(JobsBody { rid, sha }): Json<JobsBody>,
) -> impl IntoResponse {
let jobs = ctx.list_jobs(rid, sha)?;
+4 -23
View File
@@ -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::<SocketAddr>();
// 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::<SocketAddr>();
axum::serve(listener, app)
.await
.map_err(anyhow::Error::from)
}
fn router(profile: Profile) -> anyhow::Result<Router> {
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))
}
+1 -1
View File
@@ -30,6 +30,6 @@ fn parse_options() -> Result<api::Options, lexopt::Error> {
}
}
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()),
})
}
+214
View File
@@ -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<String> {
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<String> {
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<PathBuf>) {
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<String> {
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<String> {
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::<Vec<_>>()
})
.collect()
}
fn names(list: &[(&str, &str)]) -> BTreeSet<String> {
list.iter().map(|(name, _)| name.to_string()).collect()
}
fn duplicates(list: &[String]) -> BTreeSet<String> {
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");
}
}
+9
View File
@@ -186,6 +186,15 @@
nodeRunning.set(event.payload);
}),
);
} else {
// The test backend can't emit events.
const pollNodeRunning = () =>
invoke<boolean>("node_running")
.then(running => nodeRunning.set(running))
.catch(console.error);
void pollNodeRunning();
const interval = setInterval(pollNodeRunning, 2_000);
setUnlistenNodeEvents(() => clearInterval(interval));
}
try {
+2
View File
@@ -2,6 +2,8 @@ declare global {
interface Window {
// eslint-disable-next-line @typescript-eslint/naming-convention
__TAURI_INTERNALS__: Record<string, unknown>;
// eslint-disable-next-line @typescript-eslint/naming-convention
__TEST_HTTP_API_PORT__?: number;
}
}
+28 -10
View File
@@ -63,17 +63,18 @@ async function withTestBackend<T>(
}
});
} 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<T>(
}
}
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<T>(
onMessage: (message: T) => void,
): tauri.Channel<T> | undefined {
return window.__TAURI_INTERNALS__
? new tauri.Channel<T>(onMessage)
: undefined;
}
async function getDiff(rid: string, options: DiffOptions): Promise<Diff> {
return withTestBackend(tauri.invoke, "get_diff", {
rid,
+2 -3
View File
@@ -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<CacheEvent>(message => {
onEvent: channel<CacheEvent>(message => {
cacheState = message;
}),
});
+2 -3
View File
@@ -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<CacheEvent>(message => {
onEvent: channel<CacheEvent>(message => {
cacheState = message;
}),
});