Skip to content

Commit

Permalink
refactor(core): return 200 on any IPC call, closes #10286 (#10585)
Browse files Browse the repository at this point in the history
* refactor(core): return 200 on any IPC call, closes #10286

By default the webview prints a `Failed to load resource: the server responded with a status of 400 (Bad Request) ipc://localhost` error message when a command returns an error, which is confusing to users.

This changes the IPC to return status 200 on any call, with a header to indicate whether the result was ok or not. This removes the console error, which would only log the actual error result if it isn't caught by the user.

* add change file

* apply code review changes
  • Loading branch information
lucasfernog authored Aug 13, 2024
1 parent b1d9ffa commit fedf93e
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changes/refactor-ipc-error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tauri": patch:changes
---

Change how IPC handles errors to simplify what's logged in the console.
3 changes: 2 additions & 1 deletion core/tauri/scripts/ipc-protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
}
})
.then((response) => {
const cb = response.ok ? callback : error
const cb =
response.headers.get('Tauri-Response') === 'ok' ? callback : error
// we need to split here because on Android the content-type gets duplicated
switch ((response.headers.get('content-type') || '').split(',')[0]) {
case 'application/json':
Expand Down
37 changes: 28 additions & 9 deletions core/tauri/src/ipc/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ use crate::{
Runtime,
};
use http::{
header::{ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_ORIGIN, CONTENT_TYPE},
header::{
ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_EXPOSE_HEADERS,
CONTENT_TYPE,
},
HeaderValue, Method, Request, StatusCode,
};
use url::Url;
Expand All @@ -21,6 +24,10 @@ const TAURI_CALLBACK_HEADER_NAME: &str = "Tauri-Callback";
const TAURI_ERROR_HEADER_NAME: &str = "Tauri-Error";
const TAURI_INVOKE_KEY_HEADER_NAME: &str = "Tauri-Invoke-Key";

const TAURI_RESPONSE_HEADER_NAME: &str = "Tauri-Response";
const TAURI_RESPONSE_HEADER_ERROR: &str = "error";
const TAURI_RESPONSE_HEADER_OK: &str = "ok";

pub fn message_handler<R: Runtime>(
manager: Arc<AppManager<R>>,
) -> crate::runtime::webview::WebviewIpcHandler<crate::EventLoopMessage, R> {
Expand All @@ -44,6 +51,10 @@ pub fn get<R: Runtime>(manager: Arc<AppManager<R>>, label: String) -> UriSchemeP
response
.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
response.headers_mut().insert(
ACCESS_CONTROL_EXPOSE_HEADERS,
HeaderValue::from_static(TAURI_RESPONSE_HEADER_NAME),
);
responder.respond(response);
};

Expand Down Expand Up @@ -81,6 +92,11 @@ pub fn get<R: Runtime>(manager: Arc<AppManager<R>>, label: String) -> UriSchemeP
)
.entered();

let response_header = match &response {
InvokeResponse::Ok(_) => TAURI_RESPONSE_HEADER_OK,
InvokeResponse::Err(_) => TAURI_RESPONSE_HEADER_ERROR,
};

let (mut response, mime_type) = match response {
InvokeResponse::Ok(InvokeBody::Json(v)) => (
http::Response::new(serde_json::to_vec(&v).unwrap().into()),
Expand All @@ -90,14 +106,16 @@ pub fn get<R: Runtime>(manager: Arc<AppManager<R>>, label: String) -> UriSchemeP
http::Response::new(v.into()),
mime::APPLICATION_OCTET_STREAM,
),
InvokeResponse::Err(e) => {
let mut response =
http::Response::new(serde_json::to_vec(&e.0).unwrap().into());
*response.status_mut() = StatusCode::BAD_REQUEST;
(response, mime::APPLICATION_JSON)
}
InvokeResponse::Err(e) => (
http::Response::new(serde_json::to_vec(&e.0).unwrap().into()),
mime::APPLICATION_JSON,
),
};

response
.headers_mut()
.insert(TAURI_RESPONSE_HEADER_NAME, response_header.parse().unwrap());

#[cfg(feature = "tracing")]
response_span.record("mime_type", mime_type.essence_str());

Expand All @@ -113,7 +131,7 @@ pub fn get<R: Runtime>(manager: Arc<AppManager<R>>, label: String) -> UriSchemeP
Err(e) => {
respond(
http::Response::builder()
.status(StatusCode::BAD_REQUEST)
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.body(e.as_bytes().to_vec().into())
.unwrap(),
Expand All @@ -123,7 +141,7 @@ pub fn get<R: Runtime>(manager: Arc<AppManager<R>>, label: String) -> UriSchemeP
} else {
respond(
http::Response::builder()
.status(StatusCode::BAD_REQUEST)
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.body(
"failed to acquire webview reference"
Expand All @@ -140,6 +158,7 @@ pub fn get<R: Runtime>(manager: Arc<AppManager<R>>, label: String) -> UriSchemeP
let mut r = http::Response::new(Vec::new().into());
r.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_HEADERS, HeaderValue::from_static("*"));

respond(r);
}

Expand Down
2 changes: 1 addition & 1 deletion core/tauri/src/protocol/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub fn get(scope: scope::fs::Scope, window_origin: String) -> UriSchemeProtocolH
Ok(response) => responder.respond(response),
Err(e) => responder.respond(
http::Response::builder()
.status(http::StatusCode::BAD_REQUEST)
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.header("Access-Control-Allow-Origin", &window_origin)
.body(e.to_string().as_bytes().to_vec())
Expand Down
2 changes: 1 addition & 1 deletion core/tauri/src/protocol/isolation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ pub fn get<R: Runtime>(
} else {
responder.respond(
http::Response::builder()
.status(http::StatusCode::BAD_REQUEST)
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.body("failed to get response".as_bytes().to_vec())
.unwrap(),
);
Expand Down
2 changes: 1 addition & 1 deletion core/tauri/src/protocol/tauri.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub fn get<R: Runtime>(
Ok(response) => responder.respond(response),
Err(e) => responder.respond(
HttpResponse::builder()
.status(StatusCode::BAD_REQUEST)
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, mime::TEXT_PLAIN.essence_str())
.header("Access-Control-Allow-Origin", &window_origin)
.body(e.to_string().as_bytes().to_vec())
Expand Down
2 changes: 1 addition & 1 deletion examples/streaming/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ fn main() {
Ok(http_response) => responder.respond(http_response),
Err(e) => responder.respond(
ResponseBuilder::new()
.status(StatusCode::BAD_REQUEST)
.status(StatusCode::INTERNAL_SERVER_ERROR)
.header(CONTENT_TYPE, "text/plain")
.body(e.to_string().as_bytes().to_vec())
.unwrap(),
Expand Down

0 comments on commit fedf93e

Please sign in to comment.