Skip to content

Commit d730770

Browse files
authored
Refactors (#15117)
* refactor(tauri-build): make better use of OsString Co-authored-by: Tony <68118705+Legend-Master@users.noreply.github.com> * refactor(tauri-build): dont wrap const value in function * refactor(tauri-build): None codepath is never used, replace Option<Vec> with Vec * refactor(tauri): use blocking apis where it makes sense * refactor(tauri): better use of std::fs API * refactor(tauri): rewind to start * refactor(tauri): fmt * add change file
1 parent 80c1425 commit d730770

4 files changed

Lines changed: 59 additions & 82 deletions

File tree

.changes/change-pr-15117.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"tauri-build": patch:enhance
3+
"tauri": patch:enhance
4+
---
5+
6+
Simplify async-sync code boundaries, no externally visible changes

crates/tauri-build/src/lib.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,8 @@ impl Attributes {
411411
}
412412

413413
pub fn is_dev() -> bool {
414-
env::var("DEP_TAURI_DEV").expect("missing `cargo:dev` instruction, please update tauri to latest")
414+
env::var_os("DEP_TAURI_DEV")
415+
.expect("missing `cargo:dev` instruction, please update tauri to latest")
415416
== "true"
416417
}
417418

@@ -458,7 +459,7 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
458459

459460
println!("cargo:rerun-if-env-changed=TAURI_CONFIG");
460461

461-
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
462+
let target_os = env::var_os("CARGO_CFG_TARGET_OS").unwrap();
462463
let mobile = target_os == "ios" || target_os == "android";
463464
cfg_alias("desktop", !mobile);
464465
cfg_alias("mobile", mobile);
@@ -503,7 +504,7 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
503504
let cargo_toml_path = Path::new("Cargo.toml").canonicalize()?;
504505
let mut manifest = Manifest::<cargo_toml::Value>::from_path_with_metadata(cargo_toml_path)?;
505506

506-
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
507+
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
507508

508509
manifest::check(&config, &mut manifest)?;
509510

@@ -538,7 +539,7 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
538539
.bundle
539540
.resources
540541
.clone()
541-
.unwrap_or_else(|| BundleResources::List(Vec::new()));
542+
.unwrap_or(BundleResources::List(Vec::new()));
542543
if target_triple.contains("windows") {
543544
if let Some(fixed_webview2_runtime_path) = match &config.bundle.windows.webview_install_mode {
544545
WebviewInstallMode::FixedRuntime { path } => Some(path),
@@ -682,7 +683,7 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
682683
}
683684
}
684685
"msvc" => {
685-
if env::var("STATIC_VCRUNTIME").is_ok_and(|v| v == "true") {
686+
if env::var_os("STATIC_VCRUNTIME").is_some_and(|v| v == "true") {
686687
static_vcruntime::build();
687688
}
688689
}

crates/tauri-build/src/manifest.rs

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ struct AllowlistedDependency {
2323
name: String,
2424
alias: Option<String>,
2525
kind: DependencyKind,
26-
all_cli_managed_features: Option<Vec<&'static str>>,
26+
all_cli_managed_features: Vec<&'static str>,
2727
expected_features: Vec<String>,
2828
}
2929

@@ -33,7 +33,7 @@ pub fn check(config: &Config, manifest: &mut Manifest) -> Result<()> {
3333
name: "tauri-build".into(),
3434
alias: None,
3535
kind: DependencyKind::Build,
36-
all_cli_managed_features: Some(vec!["isolation"]),
36+
all_cli_managed_features: vec!["isolation"],
3737
expected_features: match config.app.security.pattern {
3838
PatternKind::Isolation { .. } => vec!["isolation".to_string()],
3939
_ => vec![],
@@ -43,12 +43,10 @@ pub fn check(config: &Config, manifest: &mut Manifest) -> Result<()> {
4343
name: "tauri".into(),
4444
alias: None,
4545
kind: DependencyKind::Normal,
46-
all_cli_managed_features: Some(
47-
AppConfig::all_features()
48-
.into_iter()
49-
.filter(|f| f != &"tray-icon")
50-
.collect(),
51-
),
46+
all_cli_managed_features: AppConfig::all_features()
47+
.into_iter()
48+
.filter(|f| f != &"tray-icon")
49+
.collect(),
5250
expected_features: config
5351
.app
5452
.features()
@@ -129,23 +127,13 @@ fn check_features(dependency: Dependency, metadata: &AllowlistedDependency) -> R
129127
Dependency::Inherited(dep) => dep.features,
130128
};
131129

132-
let diff = if let Some(all_cli_managed_features) = &metadata.all_cli_managed_features {
133-
features_diff(
134-
&features
135-
.into_iter()
136-
.filter(|f| all_cli_managed_features.contains(&f.as_str()))
137-
.collect::<Vec<String>>(),
138-
&metadata.expected_features,
139-
)
140-
} else {
141-
features_diff(
142-
&features
143-
.into_iter()
144-
.filter(|f| f.starts_with("allow-"))
145-
.collect::<Vec<String>>(),
146-
&metadata.expected_features,
147-
)
148-
};
130+
let diff = features_diff(
131+
&features
132+
.into_iter()
133+
.filter(|f| metadata.all_cli_managed_features.contains(&f.as_str()))
134+
.collect::<Vec<String>>(),
135+
&metadata.expected_features,
136+
);
149137

150138
let mut error_message = String::new();
151139
if !diff.remove.is_empty() {

crates/tauri/src/protocol/asset.rs

Lines changed: 34 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
use crate::{path::SafePathBuf, scope, webview::UriSchemeProtocolHandler};
66
use http::{header::*, status::StatusCode, Request, Response};
77
use http_range::HttpRange;
8+
use std::fs::File;
9+
use std::io::{Read, Seek, Write};
810
use std::{borrow::Cow, io::SeekFrom};
911
use tauri_utils::mime_type::MimeType;
10-
use tokio::fs::File;
11-
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
1212

1313
pub fn get(scope: scope::fs::Scope, window_origin: String) -> UriSchemeProtocolHandler {
1414
Box::new(
@@ -49,7 +49,7 @@ fn get_response(
4949
}
5050

5151
// Separate block for easier error handling
52-
let mut file = match crate::async_runtime::safe_block_on(File::open(path.clone())) {
52+
let mut file = match File::open(path.clone()) {
5353
Ok(file) => file,
5454
Err(e) => {
5555
#[cfg(target_os = "android")]
@@ -70,32 +70,20 @@ fn get_response(
7070
}
7171
};
7272

73-
let (mut file, len, mime_type, read_bytes) = crate::async_runtime::safe_block_on(async move {
74-
// get file length
75-
let len = {
76-
let old_pos = file.stream_position().await?;
77-
let len = file.seek(SeekFrom::End(0)).await?;
78-
file.seek(SeekFrom::Start(old_pos)).await?;
79-
len
80-
};
81-
73+
let len = file.metadata()?.len();
74+
let (mime_type, read_bytes) = {
8275
// get file mime type
83-
let (mime_type, read_bytes) = {
84-
let nbytes = len.min(8192);
85-
let mut magic_buf = Vec::with_capacity(nbytes as usize);
86-
let old_pos = file.stream_position().await?;
87-
(&mut file).take(nbytes).read_to_end(&mut magic_buf).await?;
88-
file.seek(SeekFrom::Start(old_pos)).await?;
89-
(
90-
MimeType::parse(&magic_buf, &path),
91-
// return the `magic_bytes` if we read the whole file
92-
// to avoid reading it again later if this is not a range request
93-
if len < 8192 { Some(magic_buf) } else { None },
94-
)
95-
};
96-
97-
Ok::<(File, u64, String, Option<Vec<u8>>), anyhow::Error>((file, len, mime_type, read_bytes))
98-
})?;
76+
let nbytes = len.min(8192);
77+
let mut magic_buf = Vec::with_capacity(nbytes as usize);
78+
(&mut file).take(nbytes).read_to_end(&mut magic_buf)?;
79+
file.rewind()?;
80+
(
81+
MimeType::parse(&magic_buf, &path),
82+
// return the `magic_bytes` if we read the whole file
83+
// to avoid reading it again later if this is not a range request
84+
if len < 8192 { Some(magic_buf) } else { None },
85+
)
86+
};
9987

10088
resp = resp.header(CONTENT_TYPE, &mime_type);
10189

@@ -148,12 +136,12 @@ fn get_response(
148136
// calculate number of bytes needed to be read
149137
let nbytes = end + 1 - start;
150138

151-
let buf = crate::async_runtime::safe_block_on(async move {
139+
let buf = {
152140
let mut buf = Vec::with_capacity(nbytes as usize);
153-
file.seek(SeekFrom::Start(start)).await?;
154-
file.take(nbytes).read_to_end(&mut buf).await?;
155-
Ok::<Vec<u8>, anyhow::Error>(buf)
156-
})?;
141+
file.seek(SeekFrom::Start(start))?;
142+
file.take(nbytes).read_to_end(&mut buf)?;
143+
buf
144+
};
157145

158146
resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}"));
159147
resp = resp.header(CONTENT_LENGTH, end + 1 - start);
@@ -186,38 +174,34 @@ fn get_response(
186174
format!("multipart/byteranges; boundary={boundary}"),
187175
);
188176

189-
let buf = crate::async_runtime::safe_block_on(async move {
177+
let buf = {
190178
// multi-part range header
191179
let mut buf = Vec::new();
192180

193181
for (start, end) in ranges {
194182
// a new range is being written, write the range boundary
195-
buf.write_all(boundary_sep.as_bytes()).await?;
183+
buf.write_all(boundary_sep.as_bytes())?;
196184

197185
// write the needed headers `Content-Type` and `Content-Range`
198-
buf
199-
.write_all(format!("{CONTENT_TYPE}: {mime_type}\r\n").as_bytes())
200-
.await?;
201-
buf
202-
.write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes())
203-
.await?;
186+
buf.write_all(format!("{CONTENT_TYPE}: {mime_type}\r\n").as_bytes())?;
187+
buf.write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes())?;
204188

205189
// write the separator to indicate the start of the range body
206-
buf.write_all("\r\n".as_bytes()).await?;
190+
buf.write_all("\r\n".as_bytes())?;
207191

208192
// calculate number of bytes needed to be read
209193
let nbytes = end + 1 - start;
210194

211195
let mut local_buf = Vec::with_capacity(nbytes as usize);
212-
file.seek(SeekFrom::Start(start)).await?;
213-
(&mut file).take(nbytes).read_to_end(&mut local_buf).await?;
196+
file.seek(SeekFrom::Start(start))?;
197+
(&mut file).take(nbytes).read_to_end(&mut local_buf)?;
214198
buf.extend_from_slice(&local_buf);
215199
}
216200
// all ranges have been written, write the closing boundary
217-
buf.write_all(boundary_closer.as_bytes()).await?;
201+
buf.write_all(boundary_closer.as_bytes())?;
218202

219-
Ok::<Vec<u8>, anyhow::Error>(buf)
220-
})?;
203+
buf
204+
};
221205
resp.body(buf.into())
222206
}
223207
} else if request.method() == http::Method::HEAD {
@@ -230,11 +214,9 @@ fn get_response(
230214
let buf = if let Some(b) = read_bytes {
231215
b
232216
} else {
233-
crate::async_runtime::safe_block_on(async move {
234-
let mut local_buf = Vec::with_capacity(len as usize);
235-
file.read_to_end(&mut local_buf).await?;
236-
Ok::<Vec<u8>, anyhow::Error>(local_buf)
237-
})?
217+
let mut local_buf = Vec::with_capacity(len as usize);
218+
file.read_to_end(&mut local_buf)?;
219+
local_buf
238220
};
239221
resp = resp.header(CONTENT_LENGTH, len);
240222
resp.body(buf.into())

0 commit comments

Comments
 (0)