chore: cargo fmt

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Gregory Schier
2026-09-10 19:35:33 -07:00
co-authored by Claude Fable 5.1
parent 7f8b7bf567
commit 2f5639a26f
23 changed files with 676 additions and 318 deletions
@@ -68,7 +68,9 @@ async fn import(
); );
} }
let destination = match workspace_id { let destination = match workspace_id {
Some(workspace_id) => ImportDestination::ExistingWorkspace { workspace_id, folder_id: None }, Some(workspace_id) => {
ImportDestination::ExistingWorkspace { workspace_id, folder_id: None }
}
None => ImportDestination::NewWorkspace, None => ImportDestination::NewWorkspace,
}; };
let plan = import::plan_import_resources( let plan = import::plan_import_resources(
+2 -5
View File
@@ -883,11 +883,8 @@ mod tests {
fs::create_dir_all(root.join("build")).expect("create build"); fs::create_dir_all(root.join("build")).expect("create build");
fs::create_dir_all(root.join("vendor")).expect("create vendor"); fs::create_dir_all(root.join("vendor")).expect("create vendor");
fs::write(root.join("vendor/core_bg.wasm"), "asset").expect("write asset"); fs::write(root.join("vendor/core_bg.wasm"), "asset").expect("write asset");
fs::write( fs::write(root.join("package.json"), r#"{"yaak":{"buildAssets":["vendor/core_bg.wasm"]}}"#)
root.join("package.json"), .expect("write package.json");
r#"{"yaak":{"buildAssets":["vendor/core_bg.wasm"]}}"#,
)
.expect("write package.json");
copy_build_assets(root).expect("copy assets"); copy_build_assets(root).expect("copy assets");
+1 -1
View File
@@ -13,7 +13,6 @@ use tokio::task::JoinHandle;
use yaak::plugin_events::{ use yaak::plugin_events::{
GroupedPluginEvent, HostRequest, SharedPluginEventContext, handle_shared_plugin_event, GroupedPluginEvent, HostRequest, SharedPluginEventContext, handle_shared_plugin_event,
}; };
use yaak_models::render::{render_grpc_request, render_http_request};
use yaak::response_body::FileResponseBodyStore; use yaak::response_body::FileResponseBodyStore;
use yaak::send::{SendHttpRequestWithPluginsParams, send_http_request_with_plugins}; use yaak::send::{SendHttpRequestWithPluginsParams, send_http_request_with_plugins};
use yaak_crypto::manager::EncryptionManager; use yaak_crypto::manager::EncryptionManager;
@@ -24,6 +23,7 @@ use yaak_models::models::Environment;
use yaak_models::queries::any_request::AnyRequest; use yaak_models::queries::any_request::AnyRequest;
use yaak_models::query_manager::QueryManager; use yaak_models::query_manager::QueryManager;
use yaak_models::render::make_vars_hashmap; use yaak_models::render::make_vars_hashmap;
use yaak_models::render::{render_grpc_request, render_http_request};
use yaak_models::util::UpdateSource; use yaak_models::util::UpdateSource;
use yaak_plugins::events::{ use yaak_plugins::events::{
EmptyPayload, ErrorResponse, FormInput, GetCookieValueResponse, InternalEvent, EmptyPayload, ErrorResponse, FormInput, GetCookieValueResponse, InternalEvent,
@@ -210,7 +210,10 @@ fn re_import_merges_into_linked_workspace() {
], ],
); );
cli_cmd(data_dir) cli_cmd(data_dir)
.args(["import", import_path.to_str().expect("import path is utf-8")]) .args([
"import",
import_path.to_str().expect("import path is utf-8"),
])
.assert() .assert()
.success() .success()
.stdout(contains("Imported 1 workspace, 2 HTTP requests")); .stdout(contains("Imported 1 workspace, 2 HTTP requests"));
@@ -273,7 +276,10 @@ fn re_import_leaves_deleted_resources_alone() {
], ],
); );
cli_cmd(data_dir) cli_cmd(data_dir)
.args(["import", import_path.to_str().expect("import path is utf-8")]) .args([
"import",
import_path.to_str().expect("import path is utf-8"),
])
.assert() .assert()
.success(); .success();
@@ -293,8 +299,7 @@ fn re_import_leaves_deleted_resources_alone() {
.into_iter() .into_iter()
.find(|r| r.name == "Request B") .find(|r| r.name == "Request B")
.expect("request B imported"); .expect("request B imported");
db.delete_http_request_by_id(&request_b.id, &UpdateSource::Sync) db.delete_http_request_by_id(&request_b.id, &UpdateSource::Sync).expect("delete request B");
.expect("delete request B");
workspace_id workspace_id
}; };
+2 -5
View File
@@ -145,11 +145,8 @@ async fn cache_control(req: Request, next: Next) -> Response {
.get(header::CONTENT_TYPE) .get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok()) .and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("text/html")); .is_some_and(|v| v.starts_with("text/html"));
let value = if hashed_name && !is_html { let value =
"public, max-age=31536000, immutable" if hashed_name && !is_html { "public, max-age=31536000, immutable" } else { "no-cache" };
} else {
"no-cache"
};
res.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(value)); res.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(value));
res res
} }
-1
View File
@@ -19,7 +19,6 @@ pub(crate) fn metadata_to_map(metadata: MetadataMap) -> BTreeMap<String, String>
entries entries
} }
pub(crate) async fn build_metadata<R: Runtime>( pub(crate) async fn build_metadata<R: Runtime>(
window: &WebviewWindow<R>, window: &WebviewWindow<R>,
request: &GrpcRequest, request: &GrpcRequest,
@@ -177,4 +177,3 @@ async fn send_http_request_inner<R: Runtime>(
Ok(SentHttpRequest { response: result.response, body: result.response_body }) Ok(SentHttpRequest { response: result.response, body: result.response_body })
} }
+3 -18
View File
@@ -29,16 +29,16 @@ use tokio::sync::Mutex;
use tokio::task::block_in_place; use tokio::task::block_in_place;
use tokio::time; use tokio::time;
use yaak::send::ResponseBody; use yaak::send::ResponseBody;
use yaak_commands::responses::locate_response_body;
use yaak_commands::resolve::resolve_grpc_request; use yaak_commands::resolve::resolve_grpc_request;
use yaak_commands::responses::locate_response_body;
use yaak_common::command::new_checked_command; use yaak_common::command::new_checked_command;
use yaak_crypto::manager::EncryptionManager; use yaak_crypto::manager::EncryptionManager;
use yaak_grpc::manager::{GrpcConfig, GrpcHandle}; use yaak_grpc::manager::{GrpcConfig, GrpcHandle};
use yaak_grpc::{Code, ServiceDefinition}; use yaak_grpc::{Code, ServiceDefinition};
use yaak_mac_window::AppHandleMacWindowExt; use yaak_mac_window::AppHandleMacWindowExt;
use yaak_models::models::{ use yaak_models::models::{
CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent, CookieJar, Environment, GrpcConnection, GrpcConnectionState, GrpcEvent, GrpcEventType,
GrpcEventType, HttpRequest, HttpResponse, HttpResponseState, Workspace, HttpRequest, HttpResponse, HttpResponseState, Workspace,
}; };
use yaak_models::util::{BatchUpsertResult, ImportDestination, ImportPlan, UpdateSource}; use yaak_models::util::{BatchUpsertResult, ImportDestination, ImportPlan, UpdateSource};
use yaak_plugins::events::{ use yaak_plugins::events::{
@@ -1033,20 +1033,6 @@ async fn cmd_commit_import<R: Runtime>(
commit_import(&window, plan) commit_import(&window, plan)
} }
/// Decodes base64 and writes the bytes to a file the user picked. /// Decodes base64 and writes the bytes to a file the user picked.
/// ///
/// The webview can't do this itself: its `fs` permissions are read-only and scoped to the app /// The webview can't do this itself: its `fs` permissions are read-only and scoped to the app
@@ -1141,7 +1127,6 @@ async fn cmd_send_http_request<R: Runtime>(
Ok(r) Ok(r)
} }
async fn cmd_new_child_window<R: Runtime>( async fn cmd_new_child_window<R: Runtime>(
parent_window: WebviewWindow<R>, parent_window: WebviewWindow<R>,
url: &str, url: &str,
@@ -16,8 +16,7 @@ use std::time::{Duration, Instant};
use tauri::path::BaseDirectory; use tauri::path::BaseDirectory;
use tauri::plugin::{Builder, TauriPlugin}; use tauri::plugin::{Builder, TauriPlugin};
use tauri::{ use tauri::{
AppHandle, Emitter, Manager, RunEvent, Runtime, State, WebviewWindow, WindowEvent, AppHandle, Emitter, Manager, RunEvent, Runtime, State, WebviewWindow, WindowEvent, is_dev,
is_dev,
}; };
use tokio::sync::Mutex; use tokio::sync::Mutex;
use ts_rs::TS; use ts_rs::TS;
@@ -28,10 +27,10 @@ use yaak_plugins::api::{
PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse, check_plugin_updates, PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse, check_plugin_updates,
search_plugins, search_plugins,
}; };
use yaak_plugins::error::Error::PluginErr;
use yaak_plugins::events::{Color, PluginContext, ShowToastRequest}; use yaak_plugins::events::{Color, PluginContext, ShowToastRequest};
use yaak_plugins::install::{delete_and_uninstall, download_and_install}; use yaak_plugins::install::{delete_and_uninstall, download_and_install};
use yaak_plugins::manager::PluginManager; use yaak_plugins::manager::PluginManager;
use yaak_plugins::error::Error::PluginErr;
use yaak_plugins::plugin_meta::get_plugin_meta; use yaak_plugins::plugin_meta::get_plugin_meta;
static EXITING: AtomicBool = AtomicBool::new(false); static EXITING: AtomicBool = AtomicBool::new(false);
@@ -355,9 +354,11 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
), ),
) )
.await .await
.unwrap_or_else(|_| Err(yaak_plugins::error::Error::PluginErr( .unwrap_or_else(|_| {
"Timed out starting the plugin runtime".to_string(), Err(yaak_plugins::error::Error::PluginErr(
))); "Timed out starting the plugin runtime".to_string(),
))
});
let manager = match result { let manager = match result {
Ok(manager) => manager, Ok(manager) => manager,
+1 -1
View File
@@ -4,5 +4,5 @@
//! `yaak-commands` when the template commands did. Callers in this crate do not //! `yaak-commands` when the template commands did. Callers in this crate do not
//! need to track which is which. //! need to track which is which.
pub use yaak_models::render::{render_grpc_request, render_http_request};
pub use yaak_commands::render::{render_json_value, render_template}; pub use yaak_commands::render::{render_json_value, render_template};
pub use yaak_models::render::{render_grpc_request, render_http_request};
+472 -123
View File
@@ -21,9 +21,9 @@ use crate::notifications::YaakNotifier;
use crate::updates::YaakUpdater; use crate::updates::YaakUpdater;
use log::warn; use log::warn;
use serde::Serialize; use serde::Serialize;
use tauri::{Manager, Runtime, State, WebviewWindow};
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use tauri::{Manager, Runtime, State, WebviewWindow};
use tokio::sync::Mutex; use tokio::sync::Mutex;
use yaak_commands::{Host, PluginHost}; use yaak_commands::{Host, PluginHost};
use yaak_core::WorkspaceContext; use yaak_core::WorkspaceContext;
@@ -32,8 +32,8 @@ use yaak_git::{
BranchDeleteResult, CloneResult, GitBranchInfo, GitCommit, GitFileDiff, GitRemote, BranchDeleteResult, CloneResult, GitBranchInfo, GitCommit, GitFileDiff, GitRemote,
GitStatusSummary, GitWorktreeStatus, PullResult, PushResult, GitStatusSummary, GitWorktreeStatus, PullResult, PushResult,
}; };
use yaak_grpc::manager::GrpcHandle;
use yaak_grpc::ServiceDefinition; use yaak_grpc::ServiceDefinition;
use yaak_grpc::manager::GrpcHandle;
use yaak_models::blob_manager::BlobManager; use yaak_models::blob_manager::BlobManager;
use yaak_models::models::{ use yaak_models::models::{
GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader, HttpResponse, GraphQlIntrospection, GrpcEvent, HttpRequest, HttpRequestHeader, HttpResponse,
@@ -42,26 +42,26 @@ use yaak_models::models::{
}; };
use yaak_models::query_manager::QueryManager; use yaak_models::query_manager::QueryManager;
use yaak_models::util::{BatchUpsertResult, ImportPlan}; use yaak_models::util::{BatchUpsertResult, ImportPlan};
use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse};
use yaak_plugins::events::{ use yaak_plugins::events::{
CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest, CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest,
CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse, ImportResponse, CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse,
JsonPrimitive, RenderPurpose, GetFolderActionsResponse, GetGrpcRequestActionsResponse, GetFolderActionsResponse, GetGrpcRequestActionsResponse, GetHttpAuthenticationConfigResponse,
GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse, GetHttpAuthenticationSummaryResponse, GetHttpRequestActionsResponse,
GetHttpRequestActionsResponse, GetTemplateFunctionConfigResponse, GetTemplateFunctionConfigResponse, GetTemplateFunctionSummaryResponse, GetThemesResponse,
GetTemplateFunctionSummaryResponse, GetThemesResponse, GetWebsocketRequestActionsResponse, GetWebsocketRequestActionsResponse, GetWorkspaceActionsResponse, ImportResponse, JsonPrimitive,
GetWorkspaceActionsResponse, RenderPurpose,
}; };
use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesResponse};
use yaak_plugins::manager::PluginManager; use yaak_plugins::manager::PluginManager;
use yaak_plugins::native_template_functions::encrypt_secure_template_function; use yaak_plugins::native_template_functions::encrypt_secure_template_function;
use yaak_plugins::template_callback::PluginTemplateCallback;
use yaak_plugins::plugin_meta::PluginMetadata; use yaak_plugins::plugin_meta::PluginMetadata;
use yaak_plugins::template_callback::PluginTemplateCallback;
use yaak_rpc::RpcRouter; use yaak_rpc::RpcRouter;
use yaak_rpc_schema::*; use yaak_rpc_schema::*;
use yaak_sse::sse::ServerSentEvent; use yaak_sse::sse::ServerSentEvent;
use yaak_sync::sync::SyncOp; use yaak_sync::sync::SyncOp;
use yaak_templates::TemplateCallback;
use yaak_tauri_utils::window::WorkspaceWindowTrait; use yaak_tauri_utils::window::WorkspaceWindowTrait;
use yaak_templates::TemplateCallback;
use yaak_ws::WebsocketManager; use yaak_ws::WebsocketManager;
/// Per-call context: the window a command was invoked from. /// Per-call context: the window a command was invoked from.
@@ -231,17 +231,15 @@ impl<R: Runtime> PluginHost for ClientCtx<R> {
Ok(self.pm().await?.call_workspace_action(&self.plugin_context(), req).await?) Ok(self.pm().await?.call_workspace_action(&self.plugin_context(), req).await?)
} }
async fn call_folder_action( async fn call_folder_action(&self, req: CallFolderActionRequest) -> yaak_commands::Result<()> {
&self,
req: CallFolderActionRequest,
) -> yaak_commands::Result<()> {
Ok(self.pm().await?.call_folder_action(&self.plugin_context(), req).await?) Ok(self.pm().await?.call_folder_action(&self.plugin_context(), req).await?)
} }
async fn http_authentication_summaries( async fn http_authentication_summaries(
&self, &self,
) -> yaak_commands::Result<Vec<GetHttpAuthenticationSummaryResponse>> { ) -> yaak_commands::Result<Vec<GetHttpAuthenticationSummaryResponse>> {
let results = self.pm().await?.get_http_authentication_summaries(&self.plugin_context()).await?; let results =
self.pm().await?.get_http_authentication_summaries(&self.plugin_context()).await?;
Ok(results.into_iter().map(|(_, a)| a).collect()) Ok(results.into_iter().map(|(_, a)| a).collect())
} }
@@ -393,11 +391,17 @@ async fn cmd_metadata<R: Runtime>(ctx: ClientCtx<R>, _req: CmdMetadataReq) -> Re
Ok(crate::cmd_metadata(ctx.window.app_handle().clone()).await?) Ok(crate::cmd_metadata(ctx.window.app_handle().clone()).await?)
} }
async fn cmd_template_tokens_to_string<R: Runtime>(ctx: ClientCtx<R>, req: CmdTemplateTokensToStringReq) -> Result<String> { async fn cmd_template_tokens_to_string<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdTemplateTokensToStringReq,
) -> Result<String> {
Ok(yaak_commands::templates::cmd_template_tokens_to_string(ctx, req).await?) Ok(yaak_commands::templates::cmd_template_tokens_to_string(ctx, req).await?)
} }
async fn cmd_render_template<R: Runtime>(ctx: ClientCtx<R>, req: CmdRenderTemplateReq) -> Result<String> { async fn cmd_render_template<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdRenderTemplateReq,
) -> Result<String> {
Ok(yaak_commands::templates::cmd_render_template(ctx, req).await?) Ok(yaak_commands::templates::cmd_render_template(ctx, req).await?)
} }
@@ -405,55 +409,114 @@ async fn cmd_send_feedback<R: Runtime>(ctx: ClientCtx<R>, req: CmdSendFeedbackRe
Ok(crate::cmd_send_feedback(ctx.window.app_handle().clone(), req.feature, req.text).await?) Ok(crate::cmd_send_feedback(ctx.window.app_handle().clone(), req.feature, req.text).await?)
} }
async fn cmd_dismiss_notification<R: Runtime>(ctx: ClientCtx<R>, req: CmdDismissNotificationReq) -> Result<()> { async fn cmd_dismiss_notification<R: Runtime>(
Ok(crate::cmd_dismiss_notification(ctx.window.clone(), &req.notification_id, ctx.window.app_handle().state::<Mutex<YaakNotifier>>()).await?) ctx: ClientCtx<R>,
req: CmdDismissNotificationReq,
) -> Result<()> {
Ok(crate::cmd_dismiss_notification(
ctx.window.clone(),
&req.notification_id,
ctx.window.app_handle().state::<Mutex<YaakNotifier>>(),
)
.await?)
} }
async fn cmd_grpc_reflect<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcReflectReq) -> Result<Vec<ServiceDefinition>> { async fn cmd_grpc_reflect<R: Runtime>(
Ok(crate::cmd_grpc_reflect(&req.request_id, req.environment_id.as_deref(), req.proto_files, ctx.window.clone(), ctx.window.app_handle().clone(), ctx.window.app_handle().state::<Mutex<GrpcHandle>>()).await?) ctx: ClientCtx<R>,
req: CmdGrpcReflectReq,
) -> Result<Vec<ServiceDefinition>> {
Ok(crate::cmd_grpc_reflect(
&req.request_id,
req.environment_id.as_deref(),
req.proto_files,
ctx.window.clone(),
ctx.window.app_handle().clone(),
ctx.window.app_handle().state::<Mutex<GrpcHandle>>(),
)
.await?)
} }
async fn cmd_grpc_go<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcGoReq) -> Result<String> { async fn cmd_grpc_go<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcGoReq) -> Result<String> {
Ok(crate::cmd_grpc_go(&req.request_id, req.environment_id.as_deref(), req.proto_files, ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<GrpcHandle>>()).await?) Ok(crate::cmd_grpc_go(
&req.request_id,
req.environment_id.as_deref(),
req.proto_files,
ctx.window.app_handle().clone(),
ctx.window.clone(),
ctx.window.app_handle().state::<Mutex<GrpcHandle>>(),
)
.await?)
} }
async fn cmd_restart<R: Runtime>(ctx: ClientCtx<R>, _req: CmdRestartReq) -> Result<()> { async fn cmd_restart<R: Runtime>(ctx: ClientCtx<R>, _req: CmdRestartReq) -> Result<()> {
Ok(crate::cmd_restart(ctx.window.app_handle().clone()).await?) Ok(crate::cmd_restart(ctx.window.app_handle().clone()).await?)
} }
async fn cmd_send_ephemeral_request<R: Runtime>(ctx: ClientCtx<R>, req: CmdSendEphemeralRequestReq) -> Result<EphemeralHttpResponse> { async fn cmd_send_ephemeral_request<R: Runtime>(
Ok(crate::cmd_send_ephemeral_request(req.request, req.environment_id.as_deref(), req.cookie_jar_id.as_deref(), ctx.window.clone(), ctx.window.app_handle().clone()).await?) ctx: ClientCtx<R>,
req: CmdSendEphemeralRequestReq,
) -> Result<EphemeralHttpResponse> {
Ok(crate::cmd_send_ephemeral_request(
req.request,
req.environment_id.as_deref(),
req.cookie_jar_id.as_deref(),
ctx.window.clone(),
ctx.window.app_handle().clone(),
)
.await?)
} }
async fn cmd_format_json<R: Runtime>(ctx: ClientCtx<R>, req: CmdFormatJsonReq) -> Result<String> { async fn cmd_format_json<R: Runtime>(ctx: ClientCtx<R>, req: CmdFormatJsonReq) -> Result<String> {
Ok(yaak_commands::data::cmd_format_json(ctx, req).await?) Ok(yaak_commands::data::cmd_format_json(ctx, req).await?)
} }
async fn cmd_format_graphql<R: Runtime>(_ctx: ClientCtx<R>, req: CmdFormatGraphqlReq) -> Result<String> { async fn cmd_format_graphql<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdFormatGraphqlReq,
) -> Result<String> {
Ok(crate::cmd_format_graphql(&req.text).await?) Ok(crate::cmd_format_graphql(&req.text).await?)
} }
async fn cmd_http_response_body<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpResponseBodyReq) -> Result<FilterResponse> { async fn cmd_http_response_body<R: Runtime>(
Ok(crate::cmd_http_response_body(ctx.window.clone(), &req.response_id, req.filter.as_deref()).await?) ctx: ClientCtx<R>,
req: CmdHttpResponseBodyReq,
) -> Result<FilterResponse> {
Ok(crate::cmd_http_response_body(ctx.window.clone(), &req.response_id, req.filter.as_deref())
.await?)
} }
async fn cmd_http_response_body_path<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpResponseBodyPathReq) -> Result<Option<String>> { async fn cmd_http_response_body_path<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdHttpResponseBodyPathReq,
) -> Result<Option<String>> {
Ok(yaak_commands::responses::cmd_http_response_body_path(ctx, req).await?) Ok(yaak_commands::responses::cmd_http_response_body_path(ctx, req).await?)
} }
async fn cmd_http_request_body<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpRequestBodyReq) -> Result<Option<Vec<u8>>> { async fn cmd_http_request_body<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdHttpRequestBodyReq,
) -> Result<Option<Vec<u8>>> {
Ok(yaak_commands::responses::cmd_http_request_body(ctx, req).await?) Ok(yaak_commands::responses::cmd_http_request_body(ctx, req).await?)
} }
async fn cmd_get_sse_events<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetSseEventsReq) -> Result<Vec<ServerSentEvent>> { async fn cmd_get_sse_events<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdGetSseEventsReq,
) -> Result<Vec<ServerSentEvent>> {
Ok(crate::cmd_get_sse_events(ctx.window.app_handle().clone(), &req.response_id).await?) Ok(crate::cmd_get_sse_events(ctx.window.app_handle().clone(), &req.response_id).await?)
} }
async fn cmd_get_http_response_events<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetHttpResponseEventsReq) -> Result<Vec<HttpResponseEvent>> { async fn cmd_get_http_response_events<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdGetHttpResponseEventsReq,
) -> Result<Vec<HttpResponseEvent>> {
Ok(yaak_commands::responses::cmd_get_http_response_events(ctx, req).await?) Ok(yaak_commands::responses::cmd_get_http_response_events(ctx, req).await?)
} }
async fn cmd_import_data<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportDataReq) -> Result<ImportPlan> { async fn cmd_import_data<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdImportDataReq,
) -> Result<ImportPlan> {
Ok(crate::cmd_import_data(ctx.window.clone(), &req.file_path, req.destination).await?) Ok(crate::cmd_import_data(ctx.window.clone(), &req.file_path, req.destination).await?)
} }
@@ -461,16 +524,25 @@ async fn cmd_import_url<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportUrlReq) ->
Ok(crate::cmd_import_url(ctx.window.clone(), &req.url, req.destination).await?) Ok(crate::cmd_import_url(ctx.window.clone(), &req.url, req.destination).await?)
} }
async fn cmd_commit_import<R: Runtime>(ctx: ClientCtx<R>, req: CmdCommitImportReq) -> Result<BatchUpsertResult> { async fn cmd_commit_import<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdCommitImportReq,
) -> Result<BatchUpsertResult> {
Ok(crate::cmd_commit_import(ctx.window.clone(), req.plan).await?) Ok(crate::cmd_commit_import(ctx.window.clone(), req.plan).await?)
} }
async fn cmd_list_import_sources<R: Runtime>(ctx: ClientCtx<R>, req: CmdListImportSourcesReq) -> Result<Vec<ImportSource>> { async fn cmd_list_import_sources<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdListImportSourcesReq,
) -> Result<Vec<ImportSource>> {
use crate::models_ext::QueryManagerExt; use crate::models_ext::QueryManagerExt;
Ok(ctx.window.db().list_import_sources(&req.workspace_id)?) Ok(ctx.window.db().list_import_sources(&req.workspace_id)?)
} }
async fn cmd_import_sources_for_origin<R: Runtime>(ctx: ClientCtx<R>, req: CmdImportSourcesForOriginReq) -> Result<Vec<ImportSource>> { async fn cmd_import_sources_for_origin<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdImportSourcesForOriginReq,
) -> Result<Vec<ImportSource>> {
use crate::models_ext::QueryManagerExt; use crate::models_ext::QueryManagerExt;
let origin = match (req.file_path, req.url) { let origin = match (req.file_path, req.url) {
(Some(file_path), _) => crate::import::file_origin(&file_path).origin, (Some(file_path), _) => crate::import::file_origin(&file_path).origin,
@@ -483,67 +555,115 @@ async fn cmd_import_sources_for_origin<R: Runtime>(ctx: ClientCtx<R>, req: CmdIm
Ok(ctx.window.db().list_import_sources_by_origin(&origin)?) Ok(ctx.window.db().list_import_sources_by_origin(&origin)?)
} }
async fn cmd_http_request_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdHttpRequestActionsReq) -> Result<Vec<GetHttpRequestActionsResponse>> { async fn cmd_http_request_actions<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdHttpRequestActionsReq,
) -> Result<Vec<GetHttpRequestActionsResponse>> {
Ok(yaak_commands::actions::cmd_http_request_actions(ctx, req).await?) Ok(yaak_commands::actions::cmd_http_request_actions(ctx, req).await?)
} }
async fn cmd_websocket_request_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdWebsocketRequestActionsReq) -> Result<Vec<GetWebsocketRequestActionsResponse>> { async fn cmd_websocket_request_actions<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdWebsocketRequestActionsReq,
) -> Result<Vec<GetWebsocketRequestActionsResponse>> {
Ok(yaak_commands::actions::cmd_websocket_request_actions(ctx, req).await?) Ok(yaak_commands::actions::cmd_websocket_request_actions(ctx, req).await?)
} }
async fn cmd_call_websocket_request_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallWebsocketRequestActionReq) -> Result<()> { async fn cmd_call_websocket_request_action<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdCallWebsocketRequestActionReq,
) -> Result<()> {
Ok(yaak_commands::actions::cmd_call_websocket_request_action(ctx, req).await?) Ok(yaak_commands::actions::cmd_call_websocket_request_action(ctx, req).await?)
} }
async fn cmd_workspace_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdWorkspaceActionsReq) -> Result<Vec<GetWorkspaceActionsResponse>> { async fn cmd_workspace_actions<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdWorkspaceActionsReq,
) -> Result<Vec<GetWorkspaceActionsResponse>> {
Ok(yaak_commands::actions::cmd_workspace_actions(ctx, req).await?) Ok(yaak_commands::actions::cmd_workspace_actions(ctx, req).await?)
} }
async fn cmd_call_workspace_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallWorkspaceActionReq) -> Result<()> { async fn cmd_call_workspace_action<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdCallWorkspaceActionReq,
) -> Result<()> {
Ok(yaak_commands::actions::cmd_call_workspace_action(ctx, req).await?) Ok(yaak_commands::actions::cmd_call_workspace_action(ctx, req).await?)
} }
async fn cmd_folder_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdFolderActionsReq) -> Result<Vec<GetFolderActionsResponse>> { async fn cmd_folder_actions<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdFolderActionsReq,
) -> Result<Vec<GetFolderActionsResponse>> {
Ok(yaak_commands::actions::cmd_folder_actions(ctx, req).await?) Ok(yaak_commands::actions::cmd_folder_actions(ctx, req).await?)
} }
async fn cmd_call_folder_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallFolderActionReq) -> Result<()> { async fn cmd_call_folder_action<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdCallFolderActionReq,
) -> Result<()> {
Ok(yaak_commands::actions::cmd_call_folder_action(ctx, req).await?) Ok(yaak_commands::actions::cmd_call_folder_action(ctx, req).await?)
} }
async fn cmd_grpc_request_actions<R: Runtime>(ctx: ClientCtx<R>, req: CmdGrpcRequestActionsReq) -> Result<Vec<GetGrpcRequestActionsResponse>> { async fn cmd_grpc_request_actions<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdGrpcRequestActionsReq,
) -> Result<Vec<GetGrpcRequestActionsResponse>> {
Ok(yaak_commands::actions::cmd_grpc_request_actions(ctx, req).await?) Ok(yaak_commands::actions::cmd_grpc_request_actions(ctx, req).await?)
} }
async fn cmd_template_function_summaries<R: Runtime>(ctx: ClientCtx<R>, req: CmdTemplateFunctionSummariesReq) -> Result<Vec<GetTemplateFunctionSummaryResponse>> { async fn cmd_template_function_summaries<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdTemplateFunctionSummariesReq,
) -> Result<Vec<GetTemplateFunctionSummaryResponse>> {
Ok(yaak_commands::templates::cmd_template_function_summaries(ctx, req).await?) Ok(yaak_commands::templates::cmd_template_function_summaries(ctx, req).await?)
} }
async fn cmd_template_function_config<R: Runtime>(ctx: ClientCtx<R>, req: CmdTemplateFunctionConfigReq) -> Result<GetTemplateFunctionConfigResponse> { async fn cmd_template_function_config<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdTemplateFunctionConfigReq,
) -> Result<GetTemplateFunctionConfigResponse> {
Ok(yaak_commands::templates::cmd_template_function_config(ctx, req).await?) Ok(yaak_commands::templates::cmd_template_function_config(ctx, req).await?)
} }
async fn cmd_get_http_authentication_summaries<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetHttpAuthenticationSummariesReq) -> Result<Vec<GetHttpAuthenticationSummaryResponse>> { async fn cmd_get_http_authentication_summaries<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdGetHttpAuthenticationSummariesReq,
) -> Result<Vec<GetHttpAuthenticationSummaryResponse>> {
Ok(yaak_commands::auth::cmd_get_http_authentication_summaries(ctx, req).await?) Ok(yaak_commands::auth::cmd_get_http_authentication_summaries(ctx, req).await?)
} }
async fn cmd_get_http_authentication_config<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetHttpAuthenticationConfigReq) -> Result<GetHttpAuthenticationConfigResponse> { async fn cmd_get_http_authentication_config<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdGetHttpAuthenticationConfigReq,
) -> Result<GetHttpAuthenticationConfigResponse> {
Ok(yaak_commands::auth::cmd_get_http_authentication_config(ctx, req).await?) Ok(yaak_commands::auth::cmd_get_http_authentication_config(ctx, req).await?)
} }
async fn cmd_call_http_request_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallHttpRequestActionReq) -> Result<()> { async fn cmd_call_http_request_action<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdCallHttpRequestActionReq,
) -> Result<()> {
Ok(yaak_commands::actions::cmd_call_http_request_action(ctx, req).await?) Ok(yaak_commands::actions::cmd_call_http_request_action(ctx, req).await?)
} }
async fn cmd_call_grpc_request_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallGrpcRequestActionReq) -> Result<()> { async fn cmd_call_grpc_request_action<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdCallGrpcRequestActionReq,
) -> Result<()> {
Ok(yaak_commands::actions::cmd_call_grpc_request_action(ctx, req).await?) Ok(yaak_commands::actions::cmd_call_grpc_request_action(ctx, req).await?)
} }
async fn cmd_call_http_authentication_action<R: Runtime>(ctx: ClientCtx<R>, req: CmdCallHttpAuthenticationActionReq) -> Result<()> { async fn cmd_call_http_authentication_action<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdCallHttpAuthenticationActionReq,
) -> Result<()> {
Ok(yaak_commands::auth::cmd_call_http_authentication_action(ctx, req).await?) Ok(yaak_commands::auth::cmd_call_http_authentication_action(ctx, req).await?)
} }
async fn cmd_curl_to_request<R: Runtime>(ctx: ClientCtx<R>, req: CmdCurlToRequestReq) -> Result<HttpRequest> { async fn cmd_curl_to_request<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdCurlToRequestReq,
) -> Result<HttpRequest> {
Ok(yaak_commands::actions::cmd_curl_to_request(ctx, req).await?) Ok(yaak_commands::actions::cmd_curl_to_request(ctx, req).await?)
} }
@@ -551,83 +671,159 @@ async fn cmd_export_data<R: Runtime>(ctx: ClientCtx<R>, req: CmdExportDataReq) -
Ok(yaak_commands::data::cmd_export_data(ctx, req).await?) Ok(yaak_commands::data::cmd_export_data(ctx, req).await?)
} }
async fn cmd_save_base64_to_binary<R: Runtime>(ctx: ClientCtx<R>, req: CmdSaveBase64ToBinaryReq) -> Result<()> { async fn cmd_save_base64_to_binary<R: Runtime>(
Ok(crate::cmd_save_base64_to_binary(ctx.window.app_handle().clone(), &req.filepath, &req.data).await?) ctx: ClientCtx<R>,
req: CmdSaveBase64ToBinaryReq,
) -> Result<()> {
Ok(crate::cmd_save_base64_to_binary(ctx.window.app_handle().clone(), &req.filepath, &req.data)
.await?)
} }
async fn cmd_save_response<R: Runtime>(ctx: ClientCtx<R>, req: CmdSaveResponseReq) -> Result<()> { async fn cmd_save_response<R: Runtime>(ctx: ClientCtx<R>, req: CmdSaveResponseReq) -> Result<()> {
Ok(yaak_commands::responses::cmd_save_response(ctx, req).await?) Ok(yaak_commands::responses::cmd_save_response(ctx, req).await?)
} }
async fn cmd_send_http_request<R: Runtime>(ctx: ClientCtx<R>, req: CmdSendHttpRequestReq) -> Result<HttpResponse> { async fn cmd_send_http_request<R: Runtime>(
Ok(crate::cmd_send_http_request(ctx.window.app_handle().clone(), ctx.window.clone(), req.environment_id.as_deref(), req.cookie_jar_id.as_deref(), req.request_id).await?) ctx: ClientCtx<R>,
req: CmdSendHttpRequestReq,
) -> Result<HttpResponse> {
Ok(crate::cmd_send_http_request(
ctx.window.app_handle().clone(),
ctx.window.clone(),
req.environment_id.as_deref(),
req.cookie_jar_id.as_deref(),
req.request_id,
)
.await?)
} }
async fn cmd_reload_plugins<R: Runtime>(ctx: ClientCtx<R>, req: CmdReloadPluginsReq) -> Result<Vec<(String, String)>> { async fn cmd_reload_plugins<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdReloadPluginsReq,
) -> Result<Vec<(String, String)>> {
Ok(yaak_commands::actions::cmd_reload_plugins(ctx, req).await?) Ok(yaak_commands::actions::cmd_reload_plugins(ctx, req).await?)
} }
async fn cmd_plugin_info<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginInfoReq) -> Result<PluginMetadata> { async fn cmd_plugin_info<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdPluginInfoReq,
) -> Result<PluginMetadata> {
Ok(yaak_commands::plugins::cmd_plugin_info(ctx, req).await?) Ok(yaak_commands::plugins::cmd_plugin_info(ctx, req).await?)
} }
async fn cmd_delete_all_grpc_connections<R: Runtime>(ctx: ClientCtx<R>, req: CmdDeleteAllGrpcConnectionsReq) -> Result<()> { async fn cmd_delete_all_grpc_connections<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdDeleteAllGrpcConnectionsReq,
) -> Result<()> {
Ok(yaak_commands::models::cmd_delete_all_grpc_connections(ctx, req).await?) Ok(yaak_commands::models::cmd_delete_all_grpc_connections(ctx, req).await?)
} }
async fn cmd_delete_send_history<R: Runtime>(ctx: ClientCtx<R>, req: CmdDeleteSendHistoryReq) -> Result<()> { async fn cmd_delete_send_history<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdDeleteSendHistoryReq,
) -> Result<()> {
Ok(yaak_commands::models::cmd_delete_send_history(ctx, req).await?) Ok(yaak_commands::models::cmd_delete_send_history(ctx, req).await?)
} }
async fn cmd_delete_all_http_responses<R: Runtime>(ctx: ClientCtx<R>, req: CmdDeleteAllHttpResponsesReq) -> Result<()> { async fn cmd_delete_all_http_responses<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdDeleteAllHttpResponsesReq,
) -> Result<()> {
Ok(yaak_commands::models::cmd_delete_all_http_responses(ctx, req).await?) Ok(yaak_commands::models::cmd_delete_all_http_responses(ctx, req).await?)
} }
async fn cmd_get_workspace_meta<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetWorkspaceMetaReq) -> Result<WorkspaceMeta> { async fn cmd_get_workspace_meta<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdGetWorkspaceMetaReq,
) -> Result<WorkspaceMeta> {
Ok(yaak_commands::models::cmd_get_workspace_meta(ctx, req).await?) Ok(yaak_commands::models::cmd_get_workspace_meta(ctx, req).await?)
} }
async fn cmd_new_child_window<R: Runtime>(ctx: ClientCtx<R>, req: CmdNewChildWindowReq) -> Result<()> { async fn cmd_new_child_window<R: Runtime>(
Ok(crate::cmd_new_child_window(ctx.window.clone(), &req.url, &req.label, &req.title, req.inner_size).await?) ctx: ClientCtx<R>,
req: CmdNewChildWindowReq,
) -> Result<()> {
Ok(crate::cmd_new_child_window(
ctx.window.clone(),
&req.url,
&req.label,
&req.title,
req.inner_size,
)
.await?)
} }
async fn cmd_new_main_window<R: Runtime>(ctx: ClientCtx<R>, req: CmdNewMainWindowReq) -> Result<()> { async fn cmd_new_main_window<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdNewMainWindowReq,
) -> Result<()> {
Ok(crate::cmd_new_main_window(ctx.window.app_handle().clone(), &req.url).await?) Ok(crate::cmd_new_main_window(ctx.window.app_handle().clone(), &req.url).await?)
} }
async fn cmd_check_for_updates<R: Runtime>(ctx: ClientCtx<R>, _req: CmdCheckForUpdatesReq) -> Result<bool> { async fn cmd_check_for_updates<R: Runtime>(
Ok(crate::cmd_check_for_updates(ctx.window.clone(), ctx.window.app_handle().state::<Mutex<YaakUpdater>>()).await?) ctx: ClientCtx<R>,
_req: CmdCheckForUpdatesReq,
) -> Result<bool> {
Ok(crate::cmd_check_for_updates(
ctx.window.clone(),
ctx.window.app_handle().state::<Mutex<YaakUpdater>>(),
)
.await?)
} }
async fn cmd_decrypt_template<R: Runtime>(ctx: ClientCtx<R>, req: CmdDecryptTemplateReq) -> Result<String> { async fn cmd_decrypt_template<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdDecryptTemplateReq,
) -> Result<String> {
Ok(yaak_commands::encryption::cmd_decrypt_template(ctx, req).await?) Ok(yaak_commands::encryption::cmd_decrypt_template(ctx, req).await?)
} }
async fn cmd_secure_template<R: Runtime>(ctx: ClientCtx<R>, req: CmdSecureTemplateReq) -> Result<String> { async fn cmd_secure_template<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdSecureTemplateReq,
) -> Result<String> {
Ok(yaak_commands::encryption::cmd_secure_template(ctx, req).await?) Ok(yaak_commands::encryption::cmd_secure_template(ctx, req).await?)
} }
async fn cmd_get_themes<R: Runtime>(ctx: ClientCtx<R>, req: CmdGetThemesReq) -> Result<Vec<GetThemesResponse>> { async fn cmd_get_themes<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdGetThemesReq,
) -> Result<Vec<GetThemesResponse>> {
Ok(yaak_commands::templates::cmd_get_themes(ctx, req).await?) Ok(yaak_commands::templates::cmd_get_themes(ctx, req).await?)
} }
async fn cmd_enable_encryption<R: Runtime>(ctx: ClientCtx<R>, req: CmdEnableEncryptionReq) -> Result<()> { async fn cmd_enable_encryption<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdEnableEncryptionReq,
) -> Result<()> {
Ok(yaak_commands::encryption::cmd_enable_encryption(ctx, req).await?) Ok(yaak_commands::encryption::cmd_enable_encryption(ctx, req).await?)
} }
async fn cmd_reveal_workspace_key<R: Runtime>(ctx: ClientCtx<R>, req: CmdRevealWorkspaceKeyReq) -> Result<String> { async fn cmd_reveal_workspace_key<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdRevealWorkspaceKeyReq,
) -> Result<String> {
Ok(yaak_commands::encryption::cmd_reveal_workspace_key(ctx, req).await?) Ok(yaak_commands::encryption::cmd_reveal_workspace_key(ctx, req).await?)
} }
async fn cmd_set_workspace_key<R: Runtime>(ctx: ClientCtx<R>, req: CmdSetWorkspaceKeyReq) -> Result<()> { async fn cmd_set_workspace_key<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdSetWorkspaceKeyReq,
) -> Result<()> {
Ok(yaak_commands::encryption::cmd_set_workspace_key(ctx, req).await?) Ok(yaak_commands::encryption::cmd_set_workspace_key(ctx, req).await?)
} }
async fn cmd_disable_encryption<R: Runtime>(ctx: ClientCtx<R>, req: CmdDisableEncryptionReq) -> Result<()> { async fn cmd_disable_encryption<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdDisableEncryptionReq,
) -> Result<()> {
Ok(yaak_commands::encryption::cmd_disable_encryption(ctx, req).await?) Ok(yaak_commands::encryption::cmd_disable_encryption(ctx, req).await?)
} }
async fn cmd_default_headers<R: Runtime>(ctx: ClientCtx<R>, req: CmdDefaultHeadersReq) -> Result<Vec<HttpRequestHeader>> { async fn cmd_default_headers<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdDefaultHeadersReq,
) -> Result<Vec<HttpRequestHeader>> {
Ok(yaak_commands::models::cmd_default_headers(ctx, req).await?) Ok(yaak_commands::models::cmd_default_headers(ctx, req).await?)
} }
@@ -649,27 +845,45 @@ async fn models_delete<R: Runtime>(ctx: ClientCtx<R>, req: ModelsDeleteReq) -> R
Ok(deleted?) Ok(deleted?)
} }
async fn models_duplicate<R: Runtime>(ctx: ClientCtx<R>, req: ModelsDuplicateReq) -> Result<String> { async fn models_duplicate<R: Runtime>(
ctx: ClientCtx<R>,
req: ModelsDuplicateReq,
) -> Result<String> {
Ok(yaak_commands::models::models_duplicate(ctx, req).await?) Ok(yaak_commands::models::models_duplicate(ctx, req).await?)
} }
async fn models_websocket_events<R: Runtime>(ctx: ClientCtx<R>, req: ModelsWebsocketEventsReq) -> Result<Vec<WebsocketEvent>> { async fn models_websocket_events<R: Runtime>(
ctx: ClientCtx<R>,
req: ModelsWebsocketEventsReq,
) -> Result<Vec<WebsocketEvent>> {
Ok(yaak_commands::models::models_websocket_events(ctx, req).await?) Ok(yaak_commands::models::models_websocket_events(ctx, req).await?)
} }
async fn models_grpc_events<R: Runtime>(ctx: ClientCtx<R>, req: ModelsGrpcEventsReq) -> Result<Vec<GrpcEvent>> { async fn models_grpc_events<R: Runtime>(
ctx: ClientCtx<R>,
req: ModelsGrpcEventsReq,
) -> Result<Vec<GrpcEvent>> {
Ok(yaak_commands::models::models_grpc_events(ctx, req).await?) Ok(yaak_commands::models::models_grpc_events(ctx, req).await?)
} }
async fn models_get_settings<R: Runtime>(ctx: ClientCtx<R>, req: ModelsGetSettingsReq) -> Result<Settings> { async fn models_get_settings<R: Runtime>(
ctx: ClientCtx<R>,
req: ModelsGetSettingsReq,
) -> Result<Settings> {
Ok(yaak_commands::models::models_get_settings(ctx, req).await?) Ok(yaak_commands::models::models_get_settings(ctx, req).await?)
} }
async fn models_get_graphql_introspection<R: Runtime>(ctx: ClientCtx<R>, req: ModelsGetGraphqlIntrospectionReq) -> Result<Option<GraphQlIntrospection>> { async fn models_get_graphql_introspection<R: Runtime>(
ctx: ClientCtx<R>,
req: ModelsGetGraphqlIntrospectionReq,
) -> Result<Option<GraphQlIntrospection>> {
Ok(yaak_commands::models::models_get_graphql_introspection(ctx, req).await?) Ok(yaak_commands::models::models_get_graphql_introspection(ctx, req).await?)
} }
async fn models_upsert_graphql_introspection<R: Runtime>(ctx: ClientCtx<R>, req: ModelsUpsertGraphqlIntrospectionReq) -> Result<GraphQlIntrospection> { async fn models_upsert_graphql_introspection<R: Runtime>(
ctx: ClientCtx<R>,
req: ModelsUpsertGraphqlIntrospectionReq,
) -> Result<GraphQlIntrospection> {
Ok(yaak_commands::models::models_upsert_graphql_introspection(ctx, req).await?) Ok(yaak_commands::models::models_upsert_graphql_introspection(ctx, req).await?)
} }
@@ -680,7 +894,10 @@ async fn models_upsert_graphql_introspection<R: Runtime>(ctx: ClientCtx<R>, req:
/// freezes the app"). Escape sequences sidestep it. This is a quirk of the /// freezes the app"). Escape sequences sidestep it. This is a quirk of the
/// webview transport, not of the data, so it lives in the adapter rather than /// webview transport, not of the data, so it lives in the adapter rather than
/// the shared handler. /// the shared handler.
async fn models_workspace_models<R: Runtime>(ctx: ClientCtx<R>, req: ModelsWorkspaceModelsReq) -> Result<String> { async fn models_workspace_models<R: Runtime>(
ctx: ClientCtx<R>,
req: ModelsWorkspaceModelsReq,
) -> Result<String> {
let json = yaak_commands::models::models_workspace_models(ctx, req).await?; let json = yaak_commands::models::models_workspace_models(ctx, req).await?;
Ok(escape_str_for_webview(&json)) Ok(escape_str_for_webview(&json))
} }
@@ -706,7 +923,10 @@ fn escape_str_for_webview(input: &str) -> String {
.collect() .collect()
} }
async fn cmd_git_checkout<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitCheckoutReq) -> Result<String> { async fn cmd_git_checkout<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitCheckoutReq,
) -> Result<String> {
Ok(crate::git_ext::cmd_git_checkout(&req.dir, &req.branch, req.force).await?) Ok(crate::git_ext::cmd_git_checkout(&req.dir, &req.branch, req.force).await?)
} }
@@ -714,31 +934,52 @@ async fn cmd_git_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitBranchReq) ->
Ok(crate::git_ext::cmd_git_branch(&req.dir, &req.branch, req.base.as_deref()).await?) Ok(crate::git_ext::cmd_git_branch(&req.dir, &req.branch, req.base.as_deref()).await?)
} }
async fn cmd_git_delete_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitDeleteBranchReq) -> Result<BranchDeleteResult> { async fn cmd_git_delete_branch<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitDeleteBranchReq,
) -> Result<BranchDeleteResult> {
Ok(crate::git_ext::cmd_git_delete_branch(&req.dir, &req.branch, req.force).await?) Ok(crate::git_ext::cmd_git_delete_branch(&req.dir, &req.branch, req.force).await?)
} }
async fn cmd_git_delete_remote_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitDeleteRemoteBranchReq) -> Result<()> { async fn cmd_git_delete_remote_branch<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitDeleteRemoteBranchReq,
) -> Result<()> {
Ok(crate::git_ext::cmd_git_delete_remote_branch(&req.dir, &req.branch).await?) Ok(crate::git_ext::cmd_git_delete_remote_branch(&req.dir, &req.branch).await?)
} }
async fn cmd_git_merge_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitMergeBranchReq) -> Result<()> { async fn cmd_git_merge_branch<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitMergeBranchReq,
) -> Result<()> {
Ok(crate::git_ext::cmd_git_merge_branch(&req.dir, &req.branch).await?) Ok(crate::git_ext::cmd_git_merge_branch(&req.dir, &req.branch).await?)
} }
async fn cmd_git_rename_branch<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRenameBranchReq) -> Result<()> { async fn cmd_git_rename_branch<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitRenameBranchReq,
) -> Result<()> {
Ok(crate::git_ext::cmd_git_rename_branch(&req.dir, &req.old_name, &req.new_name).await?) Ok(crate::git_ext::cmd_git_rename_branch(&req.dir, &req.old_name, &req.new_name).await?)
} }
async fn cmd_git_status<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitStatusReq) -> Result<GitStatusSummary> { async fn cmd_git_status<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitStatusReq,
) -> Result<GitStatusSummary> {
Ok(crate::git_ext::cmd_git_status(&req.dir).await?) Ok(crate::git_ext::cmd_git_status(&req.dir).await?)
} }
async fn cmd_git_branch_info<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitBranchInfoReq) -> Result<GitBranchInfo> { async fn cmd_git_branch_info<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitBranchInfoReq,
) -> Result<GitBranchInfo> {
Ok(crate::git_ext::cmd_git_branch_info(&req.dir).await?) Ok(crate::git_ext::cmd_git_branch_info(&req.dir).await?)
} }
async fn cmd_git_worktree_status<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitWorktreeStatusReq) -> Result<GitWorktreeStatus> { async fn cmd_git_worktree_status<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitWorktreeStatusReq,
) -> Result<GitWorktreeStatus> {
Ok(crate::git_ext::cmd_git_worktree_status(&req.dir).await?) Ok(crate::git_ext::cmd_git_worktree_status(&req.dir).await?)
} }
@@ -746,15 +987,25 @@ async fn cmd_git_log<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitLogReq) -> Resul
Ok(crate::git_ext::cmd_git_log(&req.dir).await?) Ok(crate::git_ext::cmd_git_log(&req.dir).await?)
} }
async fn cmd_git_log_for_file<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitLogForFileReq) -> Result<Vec<GitCommit>> { async fn cmd_git_log_for_file<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitLogForFileReq,
) -> Result<Vec<GitCommit>> {
Ok(crate::git_ext::cmd_git_log_for_file(&req.dir, req.rela_path).await?) Ok(crate::git_ext::cmd_git_log_for_file(&req.dir, req.rela_path).await?)
} }
async fn cmd_git_file_diff_for_commit<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitFileDiffForCommitReq) -> Result<GitFileDiff> { async fn cmd_git_file_diff_for_commit<R: Runtime>(
Ok(crate::git_ext::cmd_git_file_diff_for_commit(&req.dir, &req.commit_oid, req.rela_path).await?) _ctx: ClientCtx<R>,
req: CmdGitFileDiffForCommitReq,
) -> Result<GitFileDiff> {
Ok(crate::git_ext::cmd_git_file_diff_for_commit(&req.dir, &req.commit_oid, req.rela_path)
.await?)
} }
async fn cmd_git_initialize<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitInitializeReq) -> Result<()> { async fn cmd_git_initialize<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitInitializeReq,
) -> Result<()> {
Ok(crate::git_ext::cmd_git_initialize(&req.dir).await?) Ok(crate::git_ext::cmd_git_initialize(&req.dir).await?)
} }
@@ -778,11 +1029,17 @@ async fn cmd_git_pull<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitPullReq) -> Res
Ok(crate::git_ext::cmd_git_pull(&req.dir).await?) Ok(crate::git_ext::cmd_git_pull(&req.dir).await?)
} }
async fn cmd_git_pull_force_reset<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitPullForceResetReq) -> Result<PullResult> { async fn cmd_git_pull_force_reset<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitPullForceResetReq,
) -> Result<PullResult> {
Ok(crate::git_ext::cmd_git_pull_force_reset(&req.dir, &req.remote, &req.branch).await?) Ok(crate::git_ext::cmd_git_pull_force_reset(&req.dir, &req.remote, &req.branch).await?)
} }
async fn cmd_git_pull_merge<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitPullMergeReq) -> Result<PullResult> { async fn cmd_git_pull_merge<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitPullMergeReq,
) -> Result<PullResult> {
Ok(crate::git_ext::cmd_git_pull_merge(&req.dir, &req.remote, &req.branch).await?) Ok(crate::git_ext::cmd_git_pull_merge(&req.dir, &req.remote, &req.branch).await?)
} }
@@ -794,27 +1051,47 @@ async fn cmd_git_unstage<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitUnstageReq)
Ok(crate::git_ext::cmd_git_unstage(&req.dir, req.rela_paths).await?) Ok(crate::git_ext::cmd_git_unstage(&req.dir, req.rela_paths).await?)
} }
async fn cmd_git_reset_changes<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitResetChangesReq) -> Result<()> { async fn cmd_git_reset_changes<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitResetChangesReq,
) -> Result<()> {
Ok(crate::git_ext::cmd_git_reset_changes(&req.dir).await?) Ok(crate::git_ext::cmd_git_reset_changes(&req.dir).await?)
} }
async fn cmd_git_restore_files<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRestoreFilesReq) -> Result<()> { async fn cmd_git_restore_files<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitRestoreFilesReq,
) -> Result<()> {
Ok(crate::git_ext::cmd_git_restore_files(&req.dir, req.rela_paths).await?) Ok(crate::git_ext::cmd_git_restore_files(&req.dir, req.rela_paths).await?)
} }
async fn cmd_git_restore_file_from_commit<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRestoreFileFromCommitReq) -> Result<()> { async fn cmd_git_restore_file_from_commit<R: Runtime>(
Ok(crate::git_ext::cmd_git_restore_file_from_commit(&req.dir, &req.commit_oid, req.rela_path).await?) _ctx: ClientCtx<R>,
req: CmdGitRestoreFileFromCommitReq,
) -> Result<()> {
Ok(crate::git_ext::cmd_git_restore_file_from_commit(&req.dir, &req.commit_oid, req.rela_path)
.await?)
} }
async fn cmd_git_add_credential<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitAddCredentialReq) -> Result<()> { async fn cmd_git_add_credential<R: Runtime>(
Ok(crate::git_ext::cmd_git_add_credential(&req.remote_url, &req.username, &req.password).await?) _ctx: ClientCtx<R>,
req: CmdGitAddCredentialReq,
) -> Result<()> {
Ok(crate::git_ext::cmd_git_add_credential(&req.remote_url, &req.username, &req.password)
.await?)
} }
async fn cmd_git_remotes<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRemotesReq) -> Result<Vec<GitRemote>> { async fn cmd_git_remotes<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitRemotesReq,
) -> Result<Vec<GitRemote>> {
Ok(crate::git_ext::cmd_git_remotes(&req.dir).await?) Ok(crate::git_ext::cmd_git_remotes(&req.dir).await?)
} }
async fn cmd_git_add_remote<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitAddRemoteReq) -> Result<GitRemote> { async fn cmd_git_add_remote<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdGitAddRemoteReq,
) -> Result<GitRemote> {
Ok(crate::git_ext::cmd_git_add_remote(&req.dir, &req.name, &req.url).await?) Ok(crate::git_ext::cmd_git_add_remote(&req.dir, &req.name, &req.url).await?)
} }
@@ -822,58 +1099,130 @@ async fn cmd_git_rm_remote<R: Runtime>(_ctx: ClientCtx<R>, req: CmdGitRmRemoteRe
Ok(crate::git_ext::cmd_git_rm_remote(&req.dir, &req.name).await?) Ok(crate::git_ext::cmd_git_rm_remote(&req.dir, &req.name).await?)
} }
async fn cmd_sync_calculate<R: Runtime>(ctx: ClientCtx<R>, req: CmdSyncCalculateReq) -> Result<Vec<SyncOp>> { async fn cmd_sync_calculate<R: Runtime>(
Ok(crate::sync_ext::cmd_sync_calculate(ctx.window.app_handle().clone(), &req.workspace_id, &req.sync_dir).await?) ctx: ClientCtx<R>,
req: CmdSyncCalculateReq,
) -> Result<Vec<SyncOp>> {
Ok(crate::sync_ext::cmd_sync_calculate(
ctx.window.app_handle().clone(),
&req.workspace_id,
&req.sync_dir,
)
.await?)
} }
async fn cmd_sync_calculate_fs<R: Runtime>(_ctx: ClientCtx<R>, req: CmdSyncCalculateFsReq) -> Result<Vec<SyncOp>> { async fn cmd_sync_calculate_fs<R: Runtime>(
_ctx: ClientCtx<R>,
req: CmdSyncCalculateFsReq,
) -> Result<Vec<SyncOp>> {
Ok(crate::sync_ext::cmd_sync_calculate_fs(&req.dir).await?) Ok(crate::sync_ext::cmd_sync_calculate_fs(&req.dir).await?)
} }
async fn cmd_sync_apply<R: Runtime>(ctx: ClientCtx<R>, req: CmdSyncApplyReq) -> Result<()> { async fn cmd_sync_apply<R: Runtime>(ctx: ClientCtx<R>, req: CmdSyncApplyReq) -> Result<()> {
Ok(crate::sync_ext::cmd_sync_apply(ctx.window.app_handle().clone(), req.sync_ops, &req.sync_dir, &req.workspace_id).await?) Ok(crate::sync_ext::cmd_sync_apply(
ctx.window.app_handle().clone(),
req.sync_ops,
&req.sync_dir,
&req.workspace_id,
)
.await?)
} }
async fn cmd_ws_delete_connections<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsDeleteConnectionsReq) -> Result<()> { async fn cmd_ws_delete_connections<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdWsDeleteConnectionsReq,
) -> Result<()> {
Ok(yaak_commands::models::cmd_ws_delete_connections(ctx, req).await?) Ok(yaak_commands::models::cmd_ws_delete_connections(ctx, req).await?)
} }
async fn cmd_ws_send<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsSendReq) -> Result<WebsocketConnection> { async fn cmd_ws_send<R: Runtime>(
Ok(crate::ws_ext::cmd_ws_send(&req.connection_id, req.environment_id.as_deref(), ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?) ctx: ClientCtx<R>,
req: CmdWsSendReq,
) -> Result<WebsocketConnection> {
Ok(crate::ws_ext::cmd_ws_send(
&req.connection_id,
req.environment_id.as_deref(),
ctx.window.app_handle().clone(),
ctx.window.clone(),
ctx.window.app_handle().state::<Mutex<WebsocketManager>>(),
)
.await?)
} }
async fn cmd_ws_close<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsCloseReq) -> Result<WebsocketConnection> { async fn cmd_ws_close<R: Runtime>(
Ok(crate::ws_ext::cmd_ws_close(&req.connection_id, ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?) ctx: ClientCtx<R>,
req: CmdWsCloseReq,
) -> Result<WebsocketConnection> {
Ok(crate::ws_ext::cmd_ws_close(
&req.connection_id,
ctx.window.app_handle().clone(),
ctx.window.clone(),
ctx.window.app_handle().state::<Mutex<WebsocketManager>>(),
)
.await?)
} }
async fn cmd_ws_connect<R: Runtime>(ctx: ClientCtx<R>, req: CmdWsConnectReq) -> Result<WebsocketConnection> { async fn cmd_ws_connect<R: Runtime>(
Ok(crate::ws_ext::cmd_ws_connect(&req.request_id, req.environment_id.as_deref(), req.cookie_jar_id.as_deref(), ctx.window.app_handle().clone(), ctx.window.clone(), ctx.window.app_handle().state::<Mutex<WebsocketManager>>()).await?) ctx: ClientCtx<R>,
req: CmdWsConnectReq,
) -> Result<WebsocketConnection> {
Ok(crate::ws_ext::cmd_ws_connect(
&req.request_id,
req.environment_id.as_deref(),
req.cookie_jar_id.as_deref(),
ctx.window.app_handle().clone(),
ctx.window.clone(),
ctx.window.app_handle().state::<Mutex<WebsocketManager>>(),
)
.await?)
} }
async fn cmd_plugins_search<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsSearchReq) -> Result<PluginSearchResponse> { async fn cmd_plugins_search<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdPluginsSearchReq,
) -> Result<PluginSearchResponse> {
Ok(crate::plugins_ext::cmd_plugins_search(ctx.window.app_handle().clone(), &req.query).await?) Ok(crate::plugins_ext::cmd_plugins_search(ctx.window.app_handle().clone(), &req.query).await?)
} }
async fn cmd_plugins_install<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsInstallReq) -> Result<()> { async fn cmd_plugins_install<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdPluginsInstallReq,
) -> Result<()> {
Ok(crate::plugins_ext::cmd_plugins_install(ctx.window.clone(), &req.name, req.version).await?) Ok(crate::plugins_ext::cmd_plugins_install(ctx.window.clone(), &req.name, req.version).await?)
} }
async fn cmd_plugins_install_from_directory<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsInstallFromDirectoryReq) -> Result<Plugin> { async fn cmd_plugins_install_from_directory<R: Runtime>(
Ok(crate::plugins_ext::cmd_plugins_install_from_directory(ctx.window.clone(), &req.directory).await?) ctx: ClientCtx<R>,
req: CmdPluginsInstallFromDirectoryReq,
) -> Result<Plugin> {
Ok(crate::plugins_ext::cmd_plugins_install_from_directory(ctx.window.clone(), &req.directory)
.await?)
} }
async fn cmd_plugins_uninstall<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginsUninstallReq) -> Result<Plugin> { async fn cmd_plugins_uninstall<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdPluginsUninstallReq,
) -> Result<Plugin> {
Ok(crate::plugins_ext::cmd_plugins_uninstall(&req.plugin_id, ctx.window.clone()).await?) Ok(crate::plugins_ext::cmd_plugins_uninstall(&req.plugin_id, ctx.window.clone()).await?)
} }
async fn cmd_plugin_init_errors<R: Runtime>(ctx: ClientCtx<R>, req: CmdPluginInitErrorsReq) -> Result<Vec<(String, String)>> { async fn cmd_plugin_init_errors<R: Runtime>(
ctx: ClientCtx<R>,
req: CmdPluginInitErrorsReq,
) -> Result<Vec<(String, String)>> {
Ok(yaak_commands::plugins::cmd_plugin_init_errors(ctx, req).await?) Ok(yaak_commands::plugins::cmd_plugin_init_errors(ctx, req).await?)
} }
async fn cmd_plugins_updates<R: Runtime>(ctx: ClientCtx<R>, _req: CmdPluginsUpdatesReq) -> Result<PluginUpdatesResponse> { async fn cmd_plugins_updates<R: Runtime>(
ctx: ClientCtx<R>,
_req: CmdPluginsUpdatesReq,
) -> Result<PluginUpdatesResponse> {
Ok(crate::plugins_ext::cmd_plugins_updates(ctx.window.app_handle().clone()).await?) Ok(crate::plugins_ext::cmd_plugins_updates(ctx.window.app_handle().clone()).await?)
} }
async fn cmd_plugins_update_all<R: Runtime>(ctx: ClientCtx<R>, _req: CmdPluginsUpdateAllReq) -> Result<Vec<PluginNameVersion>> { async fn cmd_plugins_update_all<R: Runtime>(
ctx: ClientCtx<R>,
_req: CmdPluginsUpdateAllReq,
) -> Result<Vec<PluginNameVersion>> {
Ok(crate::plugins_ext::cmd_plugins_update_all(ctx.window.clone()).await?) Ok(crate::plugins_ext::cmd_plugins_update_all(ctx.window.clone()).await?)
} }
+1 -2
View File
@@ -13,6 +13,7 @@ use tauri::{AppHandle, Manager, Runtime, State, WebviewWindow};
use tokio::sync::{Mutex, mpsc}; use tokio::sync::{Mutex, mpsc};
use tokio_tungstenite::tungstenite::Message; use tokio_tungstenite::tungstenite::Message;
use url::Url; use url::Url;
use yaak_commands::resolve::resolve_websocket_request;
use yaak_crypto::manager::EncryptionManager; use yaak_crypto::manager::EncryptionManager;
use yaak_http::cookies::CookieStore; use yaak_http::cookies::CookieStore;
use yaak_http::path_placeholders::apply_path_placeholders; use yaak_http::path_placeholders::apply_path_placeholders;
@@ -26,7 +27,6 @@ use yaak_plugins::template_callback::PluginTemplateCallback;
use yaak_templates::strip_json_comments::maybe_strip_json_comments; use yaak_templates::strip_json_comments::maybe_strip_json_comments;
use yaak_templates::{RenderErrorBehavior, RenderOptions}; use yaak_templates::{RenderErrorBehavior, RenderOptions};
use yaak_tls::find_client_certificate; use yaak_tls::find_client_certificate;
use yaak_commands::resolve::resolve_websocket_request;
use yaak_ws::{WebsocketManager, render_websocket_request}; use yaak_ws::{WebsocketManager, render_websocket_request};
pub async fn cmd_ws_send<R: Runtime>( pub async fn cmd_ws_send<R: Runtime>(
@@ -453,7 +453,6 @@ pub async fn cmd_ws_connect<R: Runtime>(
Ok(connection) Ok(connection)
} }
/// Convert WS URL to HTTP URL for cookie filtering /// Convert WS URL to HTTP URL for cookie filtering
/// WebSocket upgrade requests are HTTP requests initially, so HttpOnly cookies should apply /// WebSocket upgrade requests are HTTP requests initially, so HttpOnly cookies should apply
fn convert_ws_url_to_http(ws_url: &Url) -> Url { fn convert_ws_url_to_http(ws_url: &Url) -> Url {
@@ -20,7 +20,9 @@ impl UpdateSource {
#[derive(Debug, Clone, Serialize, Deserialize, TS)] #[derive(Debug, Clone, Serialize, Deserialize, TS)]
#[serde(rename_all = "snake_case", tag = "type")] #[serde(rename_all = "snake_case", tag = "type")]
pub enum ModelChangeEvent { pub enum ModelChangeEvent {
Upsert { created: bool }, Upsert {
created: bool,
},
/// A delete for a workspace implies deletion of every model in that /// A delete for a workspace implies deletion of every model in that
/// workspace — children are bulk-deleted without their own change rows or /// workspace — children are bulk-deleted without their own change rows or
/// events, and consumers must prune the subtree themselves (the frontend /// events, and consumers must prune the subtree themselves (the frontend
+4 -5
View File
@@ -29,11 +29,10 @@ use yaak_plugins::api::{PluginNameVersion, PluginSearchResponse, PluginUpdatesRe
use yaak_plugins::events::{ use yaak_plugins::events::{
CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest, CallFolderActionRequest, CallGrpcRequestActionRequest, CallHttpRequestActionRequest,
CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse, CallWebsocketRequestActionRequest, CallWorkspaceActionRequest, FilterResponse,
GetFolderActionsResponse, GetGrpcRequestActionsResponse, GetFolderActionsResponse, GetGrpcRequestActionsResponse, GetHttpAuthenticationConfigResponse,
GetHttpAuthenticationConfigResponse, GetHttpAuthenticationSummaryResponse, GetHttpAuthenticationSummaryResponse, GetHttpRequestActionsResponse,
GetHttpRequestActionsResponse, GetTemplateFunctionConfigResponse, GetTemplateFunctionConfigResponse, GetTemplateFunctionSummaryResponse, GetThemesResponse,
GetTemplateFunctionSummaryResponse, GetThemesResponse, GetWebsocketRequestActionsResponse, GetWebsocketRequestActionsResponse, GetWorkspaceActionsResponse, JsonPrimitive, RenderPurpose,
GetWorkspaceActionsResponse, JsonPrimitive, RenderPurpose,
}; };
use yaak_plugins::plugin_meta::PluginMetadata; use yaak_plugins::plugin_meta::PluginMetadata;
use yaak_sse::sse::ServerSentEvent; use yaak_sse::sse::ServerSentEvent;
+5 -5
View File
@@ -13,8 +13,9 @@ pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
/// `dispatch` call frame, so it cannot borrow, and contexts are cheap clones /// `dispatch` call frame, so it cannot borrow, and contexts are cheap clones
/// (handles and `Arc`s). Synchronous handlers wrap into this via `rpc_handler!` /// (handles and `Arc`s). Synchronous handlers wrap into this via `rpc_handler!`
/// with no visible change. /// with no visible change.
type HandlerFn<Ctx> = type HandlerFn<Ctx> = Box<
Box<dyn Fn(Ctx, serde_json::Value) -> BoxFuture<Result<serde_json::Value, RpcError>> + Send + Sync>; dyn Fn(Ctx, serde_json::Value) -> BoxFuture<Result<serde_json::Value, RpcError>> + Send + Sync,
>;
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RpcError { pub struct RpcError {
@@ -249,9 +250,8 @@ macro_rules! rpc_handler_async {
Box::new(|ctx, payload| { Box::new(|ctx, payload| {
Box::pin(async move { Box::pin(async move {
let req = serde_json::from_value(payload).map_err($crate::RpcError::from)?; let req = serde_json::from_value(payload).map_err($crate::RpcError::from)?;
let res = $f(ctx, req) let res =
.await $f(ctx, req).await.map_err(|e| $crate::RpcError { message: e.to_string() })?;
.map_err(|e| $crate::RpcError { message: e.to_string() })?;
serde_json::to_value(res).map_err($crate::RpcError::from) serde_json::to_value(res).map_err($crate::RpcError::from)
}) })
}) })
+1 -1
View File
@@ -10,8 +10,8 @@ use yaak_database::SqlitePool;
pub mod blob_manager; pub mod blob_manager;
pub mod client_db; pub mod client_db;
pub mod cookies;
mod connection_or_tx; mod connection_or_tx;
pub mod cookies;
pub mod error; pub mod error;
pub mod migrate; pub mod migrate;
pub mod models; pub mod models;
@@ -96,8 +96,7 @@ impl<'a> ClientDb<'a> {
let Some(response_id) = path.file_name().and_then(|n| n.to_str()) else { let Some(response_id) = path.file_name().and_then(|n| n.to_str()) else {
continue; continue;
}; };
if self.find_optional::<HttpResponse>(HttpResponseIden::Id, response_id).is_some() if self.find_optional::<HttpResponse>(HttpResponseIden::Id, response_id).is_some() {
{
continue; continue;
} }
if fs::remove_file(&path).is_ok() { if fs::remove_file(&path).is_ok() {
+1 -1
View File
@@ -24,8 +24,8 @@ mod websocket_events;
mod websocket_requests; mod websocket_requests;
mod workspace_metas; mod workspace_metas;
pub mod workspaces; pub mod workspaces;
pub use model_changes::PersistedModelChange;
pub(crate) use duplicate_name::conflict_free_name; pub(crate) use duplicate_name::conflict_free_name;
pub use model_changes::PersistedModelChange;
const MAX_HISTORY_ITEMS: usize = 20; const MAX_HISTORY_ITEMS: usize = 20;
+3 -3
View File
@@ -8,9 +8,9 @@ use crate::models::{
GrpcEventIden, GrpcRequest, GrpcRequestIden, HttpRequest, HttpRequestHeader, HttpRequestIden, GrpcEventIden, GrpcRequest, GrpcRequestIden, HttpRequest, HttpRequestHeader, HttpRequestIden,
HttpResponse, HttpResponseEvent, HttpResponseEventIden, HttpResponseIden, ImportSource, HttpResponse, HttpResponseEvent, HttpResponseEventIden, HttpResponseIden, ImportSource,
ImportSourceIden, ResolvedHttpRequestSettings, ResolvedSetting, SyncState, SyncStateIden, ImportSourceIden, ResolvedHttpRequestSettings, ResolvedSetting, SyncState, SyncStateIden,
WebsocketConnection, WebsocketConnection, WebsocketConnectionIden, WebsocketEvent, WebsocketEventIden,
WebsocketConnectionIden, WebsocketEvent, WebsocketEventIden, WebsocketRequest, WebsocketRequest, WebsocketRequestIden, Workspace, WorkspaceIden, WorkspaceMeta,
WebsocketRequestIden, Workspace, WorkspaceIden, WorkspaceMeta, WorkspaceMetaIden, WorkspaceMetaIden,
}; };
use crate::util::UpdateSource; use crate::util::UpdateSource;
use log::warn; use log::warn;
+2 -10
View File
@@ -125,19 +125,11 @@ pub enum ImportPlanWarningLevel {
impl ImportPlanWarning { impl ImportPlanWarning {
pub fn info(title: impl Into<String>, detail: impl Into<String>) -> Self { pub fn info(title: impl Into<String>, detail: impl Into<String>) -> Self {
Self { Self { title: title.into(), detail: detail.into(), level: ImportPlanWarningLevel::Info }
title: title.into(),
detail: detail.into(),
level: ImportPlanWarningLevel::Info,
}
} }
pub fn warning(title: impl Into<String>, detail: impl Into<String>) -> Self { pub fn warning(title: impl Into<String>, detail: impl Into<String>) -> Self {
Self { Self { title: title.into(), detail: detail.into(), level: ImportPlanWarningLevel::Warning }
title: title.into(),
detail: detail.into(),
level: ImportPlanWarningLevel::Warning,
}
} }
} }
+1 -1
View File
@@ -1,5 +1,4 @@
use crate::error::Result; use crate::error::Result;
use yaak_models::blob_manager::BlobManager;
use crate::models::SyncModel; use crate::models::SyncModel;
use chrono::Utc; use chrono::Utc;
use log::{info, warn}; use log::{info, warn};
@@ -11,6 +10,7 @@ use std::fs::File;
use std::io::Write; use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use ts_rs::TS; use ts_rs::TS;
use yaak_models::blob_manager::BlobManager;
use yaak_models::client_db::ClientDb; use yaak_models::client_db::ClientDb;
use yaak_models::models::{SyncState, WorkspaceMeta}; use yaak_models::models::{SyncState, WorkspaceMeta};
use yaak_models::util::{UpdateSource, get_workspace_export_resources}; use yaak_models::util::{UpdateSource, get_workspace_export_resources};
+141 -114
View File
@@ -521,16 +521,11 @@ fn record_import_source(
}; };
let incoming_keys: BTreeSet<String> = plan.source_keys.values().cloned().collect(); let incoming_keys: BTreeSet<String> = plan.source_keys.values().cloned().collect();
let existing = match resolve_linked_source( let existing =
db, match resolve_linked_source(db, &workspace_id, &plan.importer, origin, &incoming_keys)? {
&workspace_id, LinkedSource::Linked(source) => Some(source),
&plan.importer, LinkedSource::Ambiguous(_) | LinkedSource::Unlinked => None,
origin, };
&incoming_keys,
)? {
LinkedSource::Linked(source) => Some(source),
LinkedSource::Ambiguous(_) | LinkedSource::Unlinked => None,
};
let import_source = db.upsert_import_source( let import_source = db.upsert_import_source(
&ImportSource { &ImportSource {
id: existing.map(|s| s.id).unwrap_or_default(), id: existing.map(|s| s.id).unwrap_or_default(),
@@ -659,9 +654,8 @@ fn resolve_linked_source(
incoming_keys: &BTreeSet<String>, incoming_keys: &BTreeSet<String>,
) -> Result<LinkedSource> { ) -> Result<LinkedSource> {
let sources = db.list_import_sources(workspace_id)?; let sources = db.list_import_sources(workspace_id)?;
let same_origin = |source: &ImportSource| { let same_origin =
source.importer == importer && source.origin == origin.origin |source: &ImportSource| source.importer == importer && source.origin == origin.origin;
};
let mut overlapping = Vec::new(); let mut overlapping = Vec::new();
for source in &sources { for source in &sources {
@@ -743,12 +737,18 @@ fn merge_with_linked_source(
let mut current_models: BTreeMap<String, Value> = BTreeMap::new(); let mut current_models: BTreeMap<String, Value> = BTreeMap::new();
{ {
let mut consider = |planned_id: &str, resource: ImportResourceType| -> Result<()> { let mut consider = |planned_id: &str, resource: ImportResourceType| -> Result<()> {
let Some(key) = plan.source_keys.get(planned_id) else { return Ok(()) }; let Some(key) = plan.source_keys.get(planned_id) else {
let Some(row) = rows.get(key) else { return Ok(()) }; return Ok(());
};
let Some(row) = rows.get(key) else {
return Ok(());
};
if ImportResourceType::from_str(&row.model_type) != Some(resource) { if ImportResourceType::from_str(&row.model_type) != Some(resource) {
return Ok(()); return Ok(());
} }
let Some(model_id) = row.model_id.as_deref() else { return Ok(()) }; let Some(model_id) = row.model_id.as_deref() else {
return Ok(());
};
let Some(current) = existing_model_json(&db, resource, model_id)? else { let Some(current) = existing_model_json(&db, resource, model_id)? else {
return Ok(()); return Ok(());
}; };
@@ -819,11 +819,9 @@ fn merge_with_linked_source(
// environment: it came from this source, so the imported-copy separation does not apply. // environment: it came from this source, so the imported-copy separation does not apply.
let mut restored_base_names = BTreeSet::new(); let mut restored_base_names = BTreeSet::new();
for (i, v) in plan.resources.environments.iter_mut().enumerate() { for (i, v) in plan.resources.environments.iter_mut().enumerate() {
let is_current_base = current_models let is_current_base =
.get(&v.id) current_models.get(&v.id).and_then(|m| m.get("parentModel")).and_then(|p| p.as_str())
.and_then(|m| m.get("parentModel")) == Some("workspace");
.and_then(|p| p.as_str())
== Some("workspace");
if !is_current_base { if !is_current_base {
continue; continue;
} }
@@ -936,16 +934,13 @@ fn merge_with_linked_source(
(false, false) => (ImportPlanAction::Unchanged, false, None), (false, false) => (ImportPlanAction::Unchanged, false, None),
(true, false) => (ImportPlanAction::Update, true, None), (true, false) => (ImportPlanAction::Update, true, None),
(false, true) => (ImportPlanAction::KeepLocal, false, None), (false, true) => (ImportPlanAction::KeepLocal, false, None),
(true, true) => ( (true, true) => {
ImportPlanAction::Conflict, (ImportPlanAction::Conflict, true, Some(ImportConflictResolution::KeepMine))
true, }
Some(ImportConflictResolution::KeepMine),
),
}; };
// A resource the source moved into a folder that isn't imported keeps its place // A resource the source moved into a folder that isn't imported keeps its place
// until that folder is: nothing can be written into a folder that will not exist. // until that folder is: nothing can be written into a folder that will not exist.
let reason = let reason = (!reachable).then_some(ImportPlanReason::MovedIntoIgnoredFolder);
(!reachable).then_some(ImportPlanReason::MovedIntoIgnoredFolder);
let mut planned = item(action, selected && reachable, resolution, reason); let mut planned = item(action, selected && reachable, resolution, reason);
planned.changed_fields = changed_fields(&incoming, &current); planned.changed_fields = changed_fields(&incoming, &current);
items.push(planned); items.push(planned);
@@ -956,16 +951,32 @@ fn merge_with_linked_source(
classify(AnyModel::Folder(v.clone()), ImportResourceType::Folder, v.folder_id.clone())?; classify(AnyModel::Folder(v.clone()), ImportResourceType::Folder, v.folder_id.clone())?;
} }
for v in &plan.resources.http_requests { for v in &plan.resources.http_requests {
classify(AnyModel::HttpRequest(v.clone()), ImportResourceType::HttpRequest, v.folder_id.clone())?; classify(
AnyModel::HttpRequest(v.clone()),
ImportResourceType::HttpRequest,
v.folder_id.clone(),
)?;
} }
for v in &plan.resources.grpc_requests { for v in &plan.resources.grpc_requests {
classify(AnyModel::GrpcRequest(v.clone()), ImportResourceType::GrpcRequest, v.folder_id.clone())?; classify(
AnyModel::GrpcRequest(v.clone()),
ImportResourceType::GrpcRequest,
v.folder_id.clone(),
)?;
} }
for v in &plan.resources.websocket_requests { for v in &plan.resources.websocket_requests {
classify(AnyModel::WebsocketRequest(v.clone()), ImportResourceType::WebsocketRequest, v.folder_id.clone())?; classify(
AnyModel::WebsocketRequest(v.clone()),
ImportResourceType::WebsocketRequest,
v.folder_id.clone(),
)?;
} }
for v in &plan.resources.environments { for v in &plan.resources.environments {
classify(AnyModel::Environment(v.clone()), ImportResourceType::Environment, v.parent_id.clone())?; classify(
AnyModel::Environment(v.clone()),
ImportResourceType::Environment,
v.parent_id.clone(),
)?;
} }
} }
@@ -1030,16 +1041,32 @@ fn create_only_items(plan: &ImportPlan) -> Vec<ImportPlanItem> {
push(AnyModel::Folder(v.clone()), ImportResourceType::Folder, v.folder_id.clone()); push(AnyModel::Folder(v.clone()), ImportResourceType::Folder, v.folder_id.clone());
} }
for v in &plan.resources.http_requests { for v in &plan.resources.http_requests {
push(AnyModel::HttpRequest(v.clone()), ImportResourceType::HttpRequest, v.folder_id.clone()); push(
AnyModel::HttpRequest(v.clone()),
ImportResourceType::HttpRequest,
v.folder_id.clone(),
);
} }
for v in &plan.resources.grpc_requests { for v in &plan.resources.grpc_requests {
push(AnyModel::GrpcRequest(v.clone()), ImportResourceType::GrpcRequest, v.folder_id.clone()); push(
AnyModel::GrpcRequest(v.clone()),
ImportResourceType::GrpcRequest,
v.folder_id.clone(),
);
} }
for v in &plan.resources.websocket_requests { for v in &plan.resources.websocket_requests {
push(AnyModel::WebsocketRequest(v.clone()), ImportResourceType::WebsocketRequest, v.folder_id.clone()); push(
AnyModel::WebsocketRequest(v.clone()),
ImportResourceType::WebsocketRequest,
v.folder_id.clone(),
);
} }
for v in &plan.resources.environments { for v in &plan.resources.environments {
push(AnyModel::Environment(v.clone()), ImportResourceType::Environment, v.parent_id.clone()); push(
AnyModel::Environment(v.clone()),
ImportResourceType::Environment,
v.parent_id.clone(),
);
} }
items items
} }
@@ -1060,7 +1087,14 @@ enum KeyStatus<'a> {
fn comparable(value: Value) -> Value { fn comparable(value: Value) -> Value {
let mut value = strip_ids(value); let mut value = strip_ids(value);
if let Some(object) = value.as_object_mut() { if let Some(object) = value.as_object_mut() {
for field in ["model", "workspaceId", "createdAt", "updatedAt", "base", "sortPriority"] { for field in [
"model",
"workspaceId",
"createdAt",
"updatedAt",
"base",
"sortPriority",
] {
object.remove(field); object.remove(field);
} }
} }
@@ -1208,10 +1242,7 @@ fn validate_plan(plan: &ImportPlan) -> Result<()> {
let updates_own_base = |id: &str| { let updates_own_base = |id: &str| {
plan.items.iter().any(|i| { plan.items.iter().any(|i| {
i.model_id == id i.model_id == id
&& !matches!( && !matches!(i.action, ImportPlanAction::Create | ImportPlanAction::Ignored)
i.action,
ImportPlanAction::Create | ImportPlanAction::Ignored
)
}) })
}; };
if plan if plan
@@ -1376,9 +1407,8 @@ fn assign_source_keys(
for (i, v) in resources.environments.iter().enumerate() { for (i, v) in resources.environments.iter().enumerate() {
let source = original.environments.get(i); let source = original.environments.get(i);
let name = source.map(|s| s.name.as_str()).unwrap_or(v.name.as_str()); let name = source.map(|s| s.name.as_str()).unwrap_or(v.name.as_str());
let parent_id = source.and_then(|s| { let parent_id = source
if s.parent_model == "folder" { s.parent_id.as_deref() } else { None } .and_then(|s| if s.parent_model == "folder" { s.parent_id.as_deref() } else { None });
});
let ancestry = ancestry_path(&folder_tree, parent_id); let ancestry = ancestry_path(&folder_tree, parent_id);
let key = fallback_key("environment", &ancestry, name); let key = fallback_key("environment", &ancestry, name);
candidates.push((&v.id, plugin_key(source.map(|s| &s.id)), key.clone(), key)); candidates.push((&v.id, plugin_key(source.map(|s| &s.id)), key.clone(), key));
@@ -1386,8 +1416,7 @@ fn assign_source_keys(
for (i, v) in resources.folders.iter().enumerate() { for (i, v) in resources.folders.iter().enumerate() {
let source = original.folders.get(i); let source = original.folders.get(i);
let name = source.map(|s| s.name.as_str()).unwrap_or(v.name.as_str()); let name = source.map(|s| s.name.as_str()).unwrap_or(v.name.as_str());
let ancestry = let ancestry = ancestry_path(&folder_tree, source.and_then(|s| s.folder_id.as_deref()));
ancestry_path(&folder_tree, source.and_then(|s| s.folder_id.as_deref()));
let key = fallback_key("folder", &ancestry, name); let key = fallback_key("folder", &ancestry, name);
candidates.push((&v.id, plugin_key(source.map(|s| &s.id)), key.clone(), key)); candidates.push((&v.id, plugin_key(source.map(|s| &s.id)), key.clone(), key));
} }
@@ -2602,10 +2631,9 @@ mod tests {
// Anything new inside that folder can't be created either, so it waits for the folder. // Anything new inside that folder can't be created either, so it waits for the folder.
let mut resources = with_extra_folder(true); let mut resources = with_extra_folder(true);
resources.http_requests.push(HttpRequest { resources
folder_id: Some("fl_extra".to_string()), .http_requests
..extra_request() .push(HttpRequest { folder_id: Some("fl_extra".to_string()), ..extra_request() });
});
let plan = replan(&query_manager, &workspace_id, resources); let plan = replan(&query_manager, &workspace_id, resources);
let extra = item_by_name(&plan, "Extra Request"); let extra = item_by_name(&plan, "Extra Request");
assert_eq!(extra.action, ImportPlanAction::Create); assert_eq!(extra.action, ImportPlanAction::Create);
@@ -2930,73 +2958,72 @@ mod tests {
assert_eq!(not_wanted, 2, "the skipped folder and its request are remembered: {rows:?}"); assert_eq!(not_wanted, 2, "the skipped folder and its request are remembered: {rows:?}");
} }
#[test]
#[test] fn desktop_style_json_roundtrip_records_source() {
fn desktop_style_json_roundtrip_records_source() { let (query_manager, _blob_manager, _rx) =
let (query_manager, _blob_manager, _rx) = yaak_models::init_in_memory().expect("initialize database");
yaak_models::init_in_memory().expect("initialize database"); let plan = plan_import_resources(
let plan = plan_import_resources( &query_manager,
&query_manager, "OpenAPI".to_string(),
"OpenAPI".to_string(), ImportDestination::NewWorkspace,
ImportDestination::NewWorkspace, imported_resources(),
imported_resources(), None,
None, Some(linked_origin()),
Some(linked_origin()),
)
.expect("plan import");
let json = serde_json::to_string(&plan).expect("serialize plan");
let plan: ImportPlan = serde_json::from_str(&json).expect("deserialize plan");
let committed = commit_import_plan(&query_manager, plan).expect("commit");
let workspace_id = committed.workspaces[0].id.clone();
let source = query_manager
.connect()
.find_import_source(&workspace_id, "OpenAPI", "/tmp/api.yaml")
.expect("query")
.expect("source recorded after JSON round-trip");
assert_eq!(source.origin_label, "api.yaml");
}
#[test]
fn selected_keep_local_reverts_the_local_edit() {
let (query_manager, _blob_manager, _rx) =
yaak_models::init_in_memory().expect("initialize database");
let committed = first_import(&query_manager);
let workspace_id = committed.workspaces[0].id.clone();
let root_id = committed
.http_requests
.iter()
.find(|r| r.name == "Root Request")
.expect("root request")
.id
.clone();
{
let db = query_manager.connect();
let root = db.get_http_request(&root_id).expect("get root");
db.upsert_http_request(
&HttpRequest { url: "https://example.com/root-local".to_string(), ..root },
&UpdateSource::Background,
) )
.expect("edit root locally"); .expect("plan import");
let json = serde_json::to_string(&plan).expect("serialize plan");
let plan: ImportPlan = serde_json::from_str(&json).expect("deserialize plan");
let committed = commit_import_plan(&query_manager, plan).expect("commit");
let workspace_id = committed.workspaces[0].id.clone();
let source = query_manager
.connect()
.find_import_source(&workspace_id, "OpenAPI", "/tmp/api.yaml")
.expect("query")
.expect("source recorded after JSON round-trip");
assert_eq!(source.origin_label, "api.yaml");
} }
let mut plan = replan(&query_manager, &workspace_id, imported_resources()); #[test]
let root = item_by_name(&plan, "Root Request"); fn selected_keep_local_reverts_the_local_edit() {
assert_eq!(root.action, ImportPlanAction::KeepLocal); let (query_manager, _blob_manager, _rx) =
assert!(!root.selected, "keep-local defaults to keeping the local edit"); yaak_models::init_in_memory().expect("initialize database");
for item in plan.items.iter_mut() { let committed = first_import(&query_manager);
if item.action == ImportPlanAction::KeepLocal { let workspace_id = committed.workspaces[0].id.clone();
item.selected = true; let root_id = committed
.http_requests
.iter()
.find(|r| r.name == "Root Request")
.expect("root request")
.id
.clone();
{
let db = query_manager.connect();
let root = db.get_http_request(&root_id).expect("get root");
db.upsert_http_request(
&HttpRequest { url: "https://example.com/root-local".to_string(), ..root },
&UpdateSource::Background,
)
.expect("edit root locally");
} }
}
commit_import_plan(&query_manager, plan).expect("commit revert");
assert_eq!( let mut plan = replan(&query_manager, &workspace_id, imported_resources());
query_manager.connect().get_http_request(&root_id).expect("get root").url, let root = item_by_name(&plan, "Root Request");
"https://example.com/root", assert_eq!(root.action, ImportPlanAction::KeepLocal);
"selected keep-local must revert to the source version" assert!(!root.selected, "keep-local defaults to keeping the local edit");
); for item in plan.items.iter_mut() {
let plan = replan(&query_manager, &workspace_id, imported_resources()); if item.action == ImportPlanAction::KeepLocal {
assert_eq!(item_by_name(&plan, "Root Request").action, ImportPlanAction::Unchanged); item.selected = true;
} }
}
commit_import_plan(&query_manager, plan).expect("commit revert");
assert_eq!(
query_manager.connect().get_http_request(&root_id).expect("get root").url,
"https://example.com/root",
"selected keep-local must revert to the source version"
);
let plan = replan(&query_manager, &workspace_id, imported_resources());
assert_eq!(item_by_name(&plan, "Root Request").action, ImportPlanAction::Unchanged);
}
} }
+13 -7
View File
@@ -668,9 +668,10 @@ mod tests {
let (query_manager, _temp_dir) = seed_query_manager(); let (query_manager, _temp_dir) = seed_query_manager();
let store = FakeBodyStore { body: b"hello".to_vec(), reads: RefCell::new(Vec::new()) }; let store = FakeBodyStore { body: b"hello".to_vec(), reads: RefCell::new(Vec::new()) };
let info_payload = InternalEventPayload::GetHttpResponseBodyInfoRequest( let info_payload =
GetHttpResponseBodyInfoRequest { response_id: "rs_test".to_string() }, InternalEventPayload::GetHttpResponseBodyInfoRequest(GetHttpResponseBodyInfoRequest {
); response_id: "rs_test".to_string(),
});
let info = handle_shared_plugin_event( let info = handle_shared_plugin_event(
&query_manager, &query_manager,
&store, &store,
@@ -716,9 +717,10 @@ mod tests {
#[test] #[test]
fn an_unreadable_response_body_becomes_an_error_reply() { fn an_unreadable_response_body_becomes_an_error_reply() {
let (query_manager, _temp_dir) = seed_query_manager(); let (query_manager, _temp_dir) = seed_query_manager();
let payload = InternalEventPayload::GetHttpResponseBodyInfoRequest( let payload =
GetHttpResponseBodyInfoRequest { response_id: "rs_never_persisted".to_string() }, InternalEventPayload::GetHttpResponseBodyInfoRequest(GetHttpResponseBodyInfoRequest {
); response_id: "rs_never_persisted".to_string(),
});
let result = dispatch( let result = dispatch(
&query_manager, &query_manager,
&payload, &payload,
@@ -727,7 +729,11 @@ mod tests {
match result { match result {
GroupedPluginEvent::Handled(Some(InternalEventPayload::ErrorResponse(resp))) => { GroupedPluginEvent::Handled(Some(InternalEventPayload::ErrorResponse(resp))) => {
assert!(resp.error.contains("rs_never_persisted"), "unhelpful error: {}", resp.error) assert!(
resp.error.contains("rs_never_persisted"),
"unhelpful error: {}",
resp.error
)
} }
other => panic!("unexpected missing-response result: {other:?}"), other => panic!("unexpected missing-response result: {other:?}"),
} }