forked from ChatGPTNextWeb/NextChat
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
using stream: schema to fetch in App
- Loading branch information
Showing
7 changed files
with
204 additions
and
122 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
// using tauri register_uri_scheme_protocol, register `stream:` protocol | ||
// see src-tauri/src/stream.rs, and src-tauri/src/main.rs | ||
// 1. window.fetch(`stream://localhost/${fetchUrl}`), get request_id | ||
// 2. listen event: `stream-response` multi times to get response headers and body | ||
|
||
type ResponseEvent = { | ||
id: number; | ||
payload: { | ||
request_id: number; | ||
status?: number; | ||
error?: string; | ||
name?: string; | ||
value?: string; | ||
chunk?: number[]; | ||
}; | ||
}; | ||
|
||
export function fetch(url: string, options?: RequestInit): Promise<any> { | ||
if (window.__TAURI__) { | ||
const tauriUri = window.__TAURI__.convertFileSrc(url, "stream"); | ||
const { signal, ...rest } = options || {}; | ||
return window | ||
.fetch(tauriUri, rest) | ||
.then((r) => r.text()) | ||
.then((rid) => parseInt(rid)) | ||
.then((request_id: number) => { | ||
// 1. using event to get status and statusText and headers, and resolve it | ||
let resolve: Function | undefined; | ||
let reject: Function | undefined; | ||
let status: number; | ||
let writable: WritableStream | undefined; | ||
let writer: WritableStreamDefaultWriter | undefined; | ||
const headers = new Headers(); | ||
let unlisten: Function | undefined; | ||
|
||
if (signal) { | ||
signal.addEventListener("abort", () => { | ||
// Reject the promise with the abort reason. | ||
unlisten && unlisten(); | ||
reject && reject(signal.reason); | ||
}); | ||
} | ||
// @ts-ignore 2. listen response multi times, and write to Response.body | ||
window.__TAURI__.event | ||
.listen("stream-response", (e: ResponseEvent) => { | ||
const { id, payload } = e; | ||
const { | ||
request_id: rid, | ||
status: _status, | ||
name, | ||
value, | ||
error, | ||
chunk, | ||
} = payload; | ||
if (request_id != rid) { | ||
return; | ||
} | ||
/** | ||
* 1. get status code | ||
* 2. get headers | ||
* 3. start get body, then resolve response | ||
* 4. get body chunk | ||
*/ | ||
if (error) { | ||
unlisten && unlisten(); | ||
return reject && reject(error); | ||
} else if (_status) { | ||
status = _status; | ||
} else if (name && value) { | ||
headers.append(name, value); | ||
} else if (chunk) { | ||
if (resolve) { | ||
const ts = new TransformStream(); | ||
writable = ts.writable; | ||
writer = writable.getWriter(); | ||
resolve(new Response(ts.readable, { status, headers })); | ||
resolve = undefined; | ||
} | ||
writer && | ||
writer.ready.then(() => { | ||
writer && writer.write(new Uint8Array(chunk)); | ||
}); | ||
} else if (_status === 0) { | ||
// end of body | ||
unlisten && unlisten(); | ||
writer && | ||
writer.ready.then(() => { | ||
writer && writer.releaseLock(); | ||
writable && writable.close(); | ||
}); | ||
} | ||
}) | ||
.then((u: Function) => (unlisten = u)); | ||
return new Promise( | ||
(_resolve, _reject) => ([resolve, reject] = [_resolve, _reject]), | ||
); | ||
}); | ||
} | ||
return window.fetch(url, options); | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,57 +1,14 @@ | ||
// Prevents additional console window on Windows in release, DO NOT REMOVE!! | ||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] | ||
|
||
use futures_util::{StreamExt}; | ||
use reqwest::Client; | ||
use tauri::{ Manager}; | ||
use tauri::http::{ResponseBuilder}; | ||
mod stream; | ||
|
||
fn main() { | ||
tauri::Builder::default() | ||
.plugin(tauri_plugin_window_state::Builder::default().build()) | ||
.register_uri_scheme_protocol("sse", |app_handle, request| { | ||
let path = request.uri().strip_prefix("sse://localhost/").unwrap(); | ||
let path = percent_encoding::percent_decode(path.as_bytes()) | ||
.decode_utf8_lossy() | ||
.to_string(); | ||
// println!("path : {}", path); | ||
let client = Client::new(); | ||
let window = app_handle.get_window("main").unwrap(); | ||
// send http request | ||
let body = reqwest::Body::from(request.body().clone()); | ||
let response_future = client.request(request.method().clone(), path) | ||
.headers(request.headers().clone()) | ||
.body(body).send(); | ||
|
||
// get response and emit to client | ||
tauri::async_runtime::spawn(async move { | ||
let res = response_future.await; | ||
|
||
match res { | ||
Ok(res) => { | ||
let mut stream = res.bytes_stream(); | ||
|
||
while let Some(chunk) = stream.next().await { | ||
match chunk { | ||
Ok(bytes) => { | ||
window.emit("sse-response", bytes).unwrap(); | ||
} | ||
Err(err) => { | ||
println!("Error: {:?}", err); | ||
} | ||
} | ||
} | ||
window.emit("sse-response", 0).unwrap(); | ||
} | ||
Err(err) => { | ||
println!("Error: {:?}", err); | ||
} | ||
} | ||
}); | ||
ResponseBuilder::new() | ||
.header("Access-Control-Allow-Origin", "*") | ||
.status(200).body("OK".into()) | ||
}) | ||
.register_uri_scheme_protocol("stream", move |app_handle, request| { | ||
stream::stream(app_handle, request) | ||
}) | ||
.run(tauri::generate_context!()) | ||
.expect("error while running tauri application"); | ||
} |
Oops, something went wrong.