Skip to content

fix(http): fix aborting a streaming response #2562

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: v2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changes/http-stream-cancel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"http": "patch"
"http-js": "patch"
---

Fix aborting a request in the middle of a streaming response.

2 changes: 1 addition & 1 deletion plugins/http/api-iife.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion plugins/http/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@
#[allow(dead_code)]
mod scope;

const COMMANDS: &[&str] = &["fetch", "fetch_cancel", "fetch_send", "fetch_read_body"];
const COMMANDS: &[&str] = &[
"fetch",
"fetch_cancel",
"fetch_send",
"fetch_read_body",
"fetch_cancel_body",
];

/// HTTP scope entry.
#[derive(schemars::JsonSchema)]
Expand Down
72 changes: 44 additions & 28 deletions plugins/http/guest-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
* @module
*/

import { Channel, invoke } from '@tauri-apps/api/core'
import { invoke } from '@tauri-apps/api/core'

/**
* Configuration of a proxy that a Client should pass requests to.
Expand Down Expand Up @@ -229,37 +229,53 @@ export async function fetch(
rid
})

const readableStreamBody = new ReadableStream({
const dropBody = () => {
return invoke('plugin:http|fetch_cancel_body', { rid: responseRid })
}

const readChunk = async (
controller: ReadableStreamDefaultController<Uint8Array>
) => {
let data: ArrayBuffer
try {
data = await invoke('plugin:http|fetch_read_body', {
rid: responseRid
})
} catch (e) {
// close the stream if an error occurs
// and drop the body on Rust side
controller.error(e)
void dropBody()
return
}

const dataUint8 = new Uint8Array(data)
const lastByte = dataUint8[dataUint8.byteLength - 1]
const actualData = dataUint8.slice(0, dataUint8.byteLength - 1)

// close when the signal to close (last byte is 1) is sent from the IPC.
if (lastByte === 1) {
controller.close()
}

controller.enqueue(actualData)
}

const readableStreamBody = new ReadableStream<Uint8Array>({
start: (controller) => {
const streamChannel = new Channel<ArrayBuffer | number[]>()
streamChannel.onmessage = (res: ArrayBuffer | number[]) => {
// close early if aborted
if (signal?.aborted) {
controller.error(ERROR_REQUEST_CANCELLED)
return
}

const resUint8 = new Uint8Array(res)
const lastByte = resUint8[resUint8.byteLength - 1]
const actualRes = resUint8.slice(0, resUint8.byteLength - 1)

// close when the signal to close (last byte is 1) is sent from the IPC.
if (lastByte == 1) {
controller.close()
return
}

controller.enqueue(actualRes)
// abort early here if needed and drop the body
if (signal?.aborted) {
controller.error(ERROR_REQUEST_CANCELLED)
void dropBody()
return
}

// run a non-blocking body stream fetch
invoke('plugin:http|fetch_read_body', {
rid: responseRid,
streamChannel
}).catch((e) => {
controller.error(e)
signal?.addEventListener('abort', () => {
controller.error(ERROR_REQUEST_CANCELLED)
void dropBody()
})
}
},
pull: async (controller) => readChunk(controller)
})

const res = new Response(status !== 204 ? readableStreamBody : null, {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Automatically generated - DO NOT EDIT!

"$schema" = "../../schemas/schema.json"

[[permission]]
identifier = "allow-fetch-cancel-body"
description = "Enables the fetch_cancel_body command without any pre-configured scope."
commands.allow = ["fetch_cancel_body"]

[[permission]]
identifier = "deny-fetch-cancel-body"
description = "Denies the fetch_cancel_body command without any pre-configured scope."
commands.deny = ["fetch_cancel_body"]
29 changes: 28 additions & 1 deletion plugins/http/permissions/autogenerated/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ All fetch operations are enabled.

- `allow-fetch`
- `allow-fetch-cancel`
- `allow-fetch-read-body`
- `allow-fetch-send`
- `allow-fetch-read-body`
- `allow-fetch-cancel-body`

## Permission Table

Expand Down Expand Up @@ -84,6 +85,32 @@ Denies the fetch_cancel command without any pre-configured scope.
<tr>
<td>

`http:allow-fetch-cancel-body`

</td>
<td>

Enables the fetch_cancel_body command without any pre-configured scope.

</td>
</tr>

<tr>
<td>

`http:deny-fetch-cancel-body`

</td>
<td>

Denies the fetch_cancel_body command without any pre-configured scope.

</td>
</tr>

<tr>
<td>

`http:allow-fetch-read-body`

</td>
Expand Down
3 changes: 2 additions & 1 deletion plugins/http/permissions/default.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ All fetch operations are enabled.
permissions = [
"allow-fetch",
"allow-fetch-cancel",
"allow-fetch-read-body",
"allow-fetch-send",
"allow-fetch-read-body",
"allow-fetch-cancel-body",
]
10 changes: 10 additions & 0 deletions plugins/http/permissions/schemas/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,16 @@
"const": "deny-fetch-cancel",
"markdownDescription": "Denies the fetch_cancel command without any pre-configured scope."
},
{
"description": "Enables the fetch_cancel_body command without any pre-configured scope.",
"type": "string",
"const": "allow-fetch-cancel-body"
},
{
"description": "Denies the fetch_cancel_body command without any pre-configured scope.",
"type": "string",
"const": "deny-fetch-cancel-body"
},
{
"description": "Enables the fetch_read_body command without any pre-configured scope.",
"type": "string",
Expand Down
46 changes: 31 additions & 15 deletions plugins/http/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};
use tauri::{
async_runtime::Mutex,
command,
ipc::{Channel, CommandScope, GlobalScope},
ipc::{CommandScope, GlobalScope},
Manager, ResourceId, ResourceTable, Runtime, State, Webview,
};
use tokio::sync::oneshot::{channel, Receiver, Sender};
Expand Down Expand Up @@ -415,26 +415,42 @@ pub async fn fetch_send<R: Runtime>(
pub async fn fetch_read_body<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
stream_channel: Channel<tauri::ipc::InvokeResponseBody>,
) -> crate::Result<()> {
) -> crate::Result<tauri::ipc::Response> {
let res = {
let mut resources_table = webview.resources_table();
resources_table.take::<ReqwestResponse>(rid)?
let resources_table = webview.resources_table();
resources_table.get::<ReqwestResponse>(rid)?
};

let mut res = Arc::into_inner(res).unwrap().0;
// SAFETY: we can access the inner value mutably
// because we are the only ones with a reference to it
// and we don't want to use `Arc::into_inner` because we want to keep the value in the table
// for potential future calls to `fetch_cancel_body`
let res_ptr = Arc::as_ptr(&res) as *mut ReqwestResponse;
let res = unsafe { &mut *res_ptr };
let res = &mut res.0;

// send response through IPC channel
while let Some(chunk) = res.chunk().await? {
let mut chunk = chunk.to_vec();
// append 0 to indicate we are not done yet
chunk.push(0);
stream_channel.send(tauri::ipc::InvokeResponseBody::Raw(chunk))?;
}
let Some(chunk) = res.chunk().await? else {
let mut resources_table = webview.resources_table();
resources_table.close(rid)?;

// send 1 to indicate we are done
stream_channel.send(tauri::ipc::InvokeResponseBody::Raw(vec![1]))?;
// return a response with a single byte to indicate that the body is empty
return Ok(tauri::ipc::Response::new(vec![1]));
};

let mut chunk = chunk.to_vec();
// append a 0 byte to indicate that the body is not empty
chunk.push(0);

Ok(tauri::ipc::Response::new(chunk))
}

#[command]
pub async fn fetch_cancel_body<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
) -> crate::Result<()> {
let mut resources_table = webview.resources_table();
resources_table.close(rid)?;
Ok(())
}

Expand Down
3 changes: 2 additions & 1 deletion plugins/http/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
commands::fetch,
commands::fetch_cancel,
commands::fetch_send,
commands::fetch_read_body
commands::fetch_read_body,
commands::fetch_cancel_body,
])
.build()
}
Loading