Skip to content

Commit a881370

Browse files
authored
Merge pull request #3614 from jarhodes314/refactor/flush-file-buffers
refactor: flush after calling write_all
2 parents ab37411 + e108a93 commit a881370

File tree

19 files changed

+81
-53
lines changed

19 files changed

+81
-53
lines changed

crates/common/certificate/src/parse_root_certificate/mod.rs

+20-16
Original file line numberDiff line numberDiff line change
@@ -282,16 +282,18 @@ mod tests {
282282
let temp_dir = TempDir::new().unwrap();
283283

284284
// Add a first chain with 1 certificate
285-
let mut cert_1 = File::create(temp_dir.path().join("cert_1")).unwrap();
286-
cert_1
287-
.write_all(include_str!("../test_root_cert_1.txt").as_bytes())
288-
.unwrap();
285+
fs::write(
286+
temp_dir.path().join("cert_1"),
287+
include_str!("../test_root_cert_1.txt"),
288+
)
289+
.unwrap();
289290

290291
// Add a second chain with 2 certificates
291-
let mut cert_2 = File::create(temp_dir.path().join("cert_2")).unwrap();
292-
cert_2
293-
.write_all(include_str!("../test_root_cert_2.txt").as_bytes())
294-
.unwrap();
292+
fs::write(
293+
temp_dir.path().join("cert_2"),
294+
include_str!("../test_root_cert_2.txt"),
295+
)
296+
.unwrap();
295297

296298
let root_certs = new_root_store(temp_dir.path()).unwrap();
297299
assert_eq!(root_certs.len(), 3);
@@ -302,17 +304,19 @@ mod tests {
302304
let temp_dir = TempDir::new().unwrap();
303305

304306
// Add a first chain with 1 certificate
305-
let mut cert_1 = File::create(temp_dir.path().join("cert_1")).unwrap();
306-
cert_1
307-
.write_all(include_str!("../test_root_cert_1.txt").as_bytes())
308-
.unwrap();
307+
fs::write(
308+
temp_dir.path().join("cert_1"),
309+
include_str!("../test_root_cert_1.txt"),
310+
)
311+
.unwrap();
309312

310313
// Add a second chain with 2 certificates in a sub directory
311314
fs::create_dir(temp_dir.path().join("sub_certs")).unwrap();
312-
let mut cert_2 = File::create(temp_dir.path().join("sub_certs/cert_2")).unwrap();
313-
cert_2
314-
.write_all(include_str!("../test_root_cert_2.txt").as_bytes())
315-
.unwrap();
315+
fs::write(
316+
temp_dir.path().join("sub_certs/cert_2"),
317+
include_str!("../test_root_cert_2.txt"),
318+
)
319+
.unwrap();
316320

317321
let root_certs = new_root_store(temp_dir.path()).unwrap();
318322
assert_eq!(root_certs.len(), 3);

crates/common/download/src/download.rs

+4
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,7 @@ async fn save_chunks_to_file_at(
415415
while let Some(bytes) = response.chunk().await? {
416416
writer.write_all(&bytes)?;
417417
}
418+
writer.flush()?;
418419
Ok(())
419420
}
420421

@@ -800,6 +801,7 @@ mod tests {
800801
let msg = format!("{header}\r\n{size}\r\n{body}\r\n");
801802
debug!("sending message = {msg}");
802803
writer.write_all(msg.as_bytes()).await.unwrap();
804+
writer.flush().await.unwrap();
803805
} else {
804806
let header = "\
805807
HTTP/1.1 200 OK\r\n\
@@ -811,6 +813,7 @@ mod tests {
811813
let body = "AAAA";
812814
let msg = format!("{header}\r\n4\r\n{body}\r\n");
813815
writer.write_all(msg.as_bytes()).await.unwrap();
816+
writer.flush().await.unwrap();
814817
}
815818
};
816819
tokio::spawn(response_task);
@@ -1005,6 +1008,7 @@ mod tests {
10051008
}
10061009

10071010
file.write_all(buffer.as_bytes()).unwrap();
1011+
file.flush().unwrap();
10081012

10091013
Ok(file)
10101014
}

crates/common/tedge_config/src/system_toml/log_level.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ pub fn set_log_level(log_level: tracing::Level) {
8787
mod tests {
8888
use super::*;
8989
use camino::Utf8PathBuf;
90-
use std::io::Write;
9190
use tempfile::TempDir;
9291
use tracing::Level;
9392

@@ -154,8 +153,7 @@ mod tests {
154153
let temp_dir = TempDir::new()?;
155154
let config_root = temp_dir.path().to_path_buf();
156155
let config_file_path = config_root.join("system.toml");
157-
let mut file = std::fs::File::create(config_file_path.as_path())?;
158-
file.write_all(content.as_bytes())?;
156+
std::fs::write(config_file_path.as_path(), content.as_bytes())?;
159157
Ok((temp_dir, config_root.try_into().unwrap()))
160158
}
161159
}

crates/common/tedge_config/src/system_toml/mod.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,6 @@ impl Default for SystemSpecificCommands {
8989
mod tests {
9090
use super::*;
9191
use camino::Utf8PathBuf;
92-
use std::io::Write;
9392
use tempfile::TempDir;
9493

9594
#[test]
@@ -196,8 +195,7 @@ mod tests {
196195
let temp_dir = TempDir::new()?;
197196
let config_root = Utf8Path::from_path(temp_dir.path()).unwrap().to_owned();
198197
let config_file_path = config_root.join(SYSTEM_CONFIG_FILE);
199-
let mut file = std::fs::File::create(config_file_path.as_path())?;
200-
file.write_all(content.as_bytes())?;
198+
std::fs::write(config_file_path.as_path(), content.as_bytes())?;
201199
Ok((temp_dir, config_root))
202200
}
203201
}

crates/common/tedge_utils/src/file.rs

+12-10
Original file line numberDiff line numberDiff line change
@@ -314,18 +314,19 @@ impl PermissionEntry {
314314
match options.create_new(true).write(true).open(file).await {
315315
Ok(mut f) => {
316316
self.clone().apply(file).await?;
317-
f.sync_all().await.map_err(|from| FileError::FailedToSync {
318-
file: file.to_path_buf(),
319-
from,
320-
})?;
321317
if let Some(default_content) = default_content {
322318
f.write_all(default_content.as_bytes())
323319
.map_err(|e| FileError::WriteContentFailed {
324320
file: file.display().to_string(),
325321
from: e,
326322
})
327323
.await?;
324+
f.flush().await?;
328325
}
326+
f.sync_all().await.map_err(|from| FileError::FailedToSync {
327+
file: file.to_path_buf(),
328+
from,
329+
})?;
329330
Ok(())
330331
}
331332

@@ -347,18 +348,19 @@ pub async fn overwrite_file(file: &Path, content: &str) -> Result<(), FileError>
347348
.await
348349
{
349350
Ok(mut f) => {
350-
f.sync_all()
351-
.map_err(|from| FileError::FailedToSync {
352-
file: file.to_path_buf(),
353-
from,
354-
})
355-
.await?;
356351
f.write_all(content.as_bytes())
357352
.map_err(|e| FileError::WriteContentFailed {
358353
file: file.display().to_string(),
359354
from: e,
360355
})
361356
.await?;
357+
f.flush().await?;
358+
f.sync_all()
359+
.map_err(|from| FileError::FailedToSync {
360+
file: file.to_path_buf(),
361+
from,
362+
})
363+
.await?;
362364
Ok(())
363365
}
364366
Err(e) => Err(FileError::FileCreateFailed {

crates/common/tedge_utils/src/paths.rs

+11-4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ use std::path::PathBuf;
66

77
use async_tempfile::TempFile;
88
use tokio::io::AsyncWrite;
9+
use tokio::io::AsyncWriteExt;
10+
use tokio::io::BufWriter;
911

1012
#[derive(thiserror::Error, Debug)]
1113
pub enum PathsError {
@@ -43,8 +45,13 @@ pub fn create_directories(dir_path: impl AsRef<Path>) -> Result<(), PathsError>
4345
.map_err(|error| PathsError::DirCreationFailed(error, dir_path.into()))
4446
}
4547

46-
pub async fn persist_tempfile(file: TempFile, path_to: impl AsRef<Path>) -> Result<(), PathsError> {
47-
tokio::fs::rename(file.file_path(), &path_to)
48+
pub async fn persist_tempfile(
49+
mut file: BufWriter<TempFile>,
50+
path_to: impl AsRef<Path>,
51+
) -> Result<(), PathsError> {
52+
file.flush().await?;
53+
file.get_ref().sync_all().await?;
54+
tokio::fs::rename(file.get_ref().file_path(), &path_to)
4855
.await
4956
.map_err(|error| PathsError::FileCreationFailed(error, path_to.as_ref().into()))?;
5057

@@ -65,7 +72,7 @@ pub fn ok_if_not_found(err: std::io::Error) -> std::io::Result<()> {
6572
#[pin_project::pin_project]
6673
pub struct DraftFile {
6774
#[pin]
68-
file: TempFile,
75+
file: BufWriter<TempFile>,
6976
target: PathBuf,
7077
mode: Option<u32>,
7178
}
@@ -82,7 +89,7 @@ impl DraftFile {
8289
.ok_or_else(|| PathsError::ParentDirNotFound {
8390
path: target.as_os_str().into(),
8491
})?;
85-
let file = TempFile::new_in(dir).await?;
92+
let file = BufWriter::new(TempFile::new_in(dir).await?);
8693

8794
let target = target.to_path_buf();
8895

crates/common/upload/src/upload.rs

+1
Original file line numberDiff line numberDiff line change
@@ -531,5 +531,6 @@ mod tests {
531531
}
532532

533533
file.write_all(buffer.as_bytes()).await.unwrap();
534+
file.flush().await.unwrap();
534535
}
535536
}

crates/core/plugin_sm/src/plugin.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,8 @@ impl Plugin for ExternalPluginCommand {
466466
}
467467
};
468468

469-
child_stdin.write_all(action.as_bytes()).await?
469+
child_stdin.write_all(action.as_bytes()).await?;
470+
child_stdin.flush().await?;
470471
}
471472

472473
let output = child.wait_with_output(command_log).await?;

crates/core/plugin_sm/tests/plugin.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ mod tests {
44
use plugin_sm::plugin::deserialize_module_info;
55
use plugin_sm::plugin::sm_path;
66
use plugin_sm::plugin::ExternalPluginCommand;
7-
use std::io::Write;
87
use std::path::Path;
98
use std::path::PathBuf;
109
use tedge_api::SoftwareError;
@@ -206,8 +205,7 @@ mod tests {
206205
let toml_conf = &format!("[software]\nmax_packages = {max_packages}");
207206

208207
let config_location = TEdgeConfigLocation::from_custom_root(dir.path());
209-
let mut file = std::fs::File::create(config_location.tedge_config_file_path())?;
210-
file.write_all(toml_conf.as_bytes())?;
208+
std::fs::write(config_location.tedge_config_file_path(), toml_conf)?;
211209
Ok(dir)
212210
}
213211
}

crates/core/tedge/src/bridge/common_mosquitto_config.rs

+1
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ impl CommonMosquittoConfig {
137137

138138
self.internal_listener.write(writer).await?;
139139
self.external_listener.write(writer).await?;
140+
writer.flush().await?;
140141

141142
Ok(())
142143
}

crates/core/tedge/src/bridge/config.rs

+2
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,8 @@ impl BridgeConfig {
135135
writeln_async!(writer, "topic {}", topic)?;
136136
}
137137

138+
writer.flush().await?;
139+
138140
Ok(())
139141
}
140142

crates/core/tedge/src/cli/certificate/create.rs

+2
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ async fn persist_private_key(
169169
// Make sure the key is secret, before write
170170
File::set_permissions(&key_file, Permissions::from_mode(0o600)).await?;
171171
key_file.write_all(cert_key.as_bytes()).await?;
172+
key_file.flush().await?;
172173
key_file.sync_all().await?;
173174

174175
// Prevent the key to be overwritten
@@ -178,6 +179,7 @@ async fn persist_private_key(
178179

179180
async fn persist_public_key(mut key_file: File, cert_pem: String) -> Result<(), std::io::Error> {
180181
key_file.write_all(cert_pem.as_bytes()).await?;
182+
key_file.flush().await?;
181183
key_file.sync_all().await?;
182184

183185
// Make the file public

crates/core/tedge/tests/mqtt.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ mod tests {
33

44
// These test cases need mosquitto on localhost on GH hosted machine.
55

6-
use std::io::Write;
76
use std::time::Duration;
87

98
use assert_cmd::assert::OutputAssertExt;
@@ -19,8 +18,10 @@ mod tests {
1918
let toml_conf = &format!("[mqtt]\nclient_port = {port}");
2019

2120
let config_location = TEdgeConfigLocation::from_custom_root(dir.path());
22-
let mut file = std::fs::File::create(config_location.tedge_config_file_path())?;
23-
file.write_all(toml_conf.as_bytes())?;
21+
std::fs::write(
22+
config_location.tedge_config_file_path(),
23+
toml_conf.as_bytes(),
24+
)?;
2425
Ok(dir)
2526
}
2627

crates/core/tedge_agent/src/state_repository/state.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ use log::info;
44
use log::warn;
55
use serde::de::DeserializeOwned;
66
use serde::Serialize;
7-
use std::fs::File;
8-
use std::io::Write;
97
use std::marker::PhantomData;
108
use tedge_utils::fs::atomically_write_file_async;
119
use tokio::fs;
@@ -29,9 +27,9 @@ pub fn agent_default_state_dir(tedge_root: Utf8PathBuf) -> Utf8PathBuf {
2927
pub fn agent_state_dir(state_dir: Utf8PathBuf, tedge_root: Utf8PathBuf) -> Utf8PathBuf {
3028
// Check that the given directory is actually writable, by creating an empty test file
3129
let test_file = state_dir.join(state_dir.join(".--test--"));
32-
match File::create(test_file.clone()).and_then(|mut file| file.write_all(b"")) {
30+
match std::fs::write(&test_file, "") {
3331
Ok(_) => {
34-
let _ = std::fs::remove_file(test_file);
32+
let _ = std::fs::remove_file(&test_file);
3533
state_dir
3634
}
3735
Err(err) => {

crates/extensions/tedge_log_manager/src/manager/log_utils.rs

+5
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,14 @@ pub fn new_read_logs(
3737
break;
3838
}
3939
Err(error) => {
40+
temp_file.flush()?;
4041
return Err(error);
4142
}
4243
};
4344
}
4445

46+
temp_file.flush()?;
47+
4548
Ok(temp_path)
4649
}
4750

@@ -329,6 +332,7 @@ mod tests {
329332
let data = "this is the first line.\nthis is the second line.\nthis is the third line.\nthis is the forth line.\nthis is the fifth line.";
330333

331334
log_file.write_all(data.as_bytes()).unwrap();
335+
log_file.flush().unwrap();
332336

333337
let line_counter = 0;
334338
let max_lines = 4;
@@ -381,6 +385,7 @@ mod tests {
381385
let data = &format!("this is the first line of {file_name}.\nthis is the second line of {file_name}.\nthis is the third line of {file_name}.\nthis is the forth line of {file_name}.\nthis is the fifth line of {file_name}.");
382386

383387
log_file.write_all(data.as_bytes()).unwrap();
388+
log_file.flush().unwrap();
384389

385390
let new_mtime = FileTime::from_unix_time(m_time, 0);
386391
set_file_mtime(file_path, new_mtime).unwrap();

crates/extensions/tedge_uploader_ext/src/tests.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
use std::fs::File;
2-
use std::io::Write;
31
use std::time::Duration;
42

53
use camino::Utf8Path;
@@ -42,8 +40,7 @@ async fn upload_without_auth() -> Result<(), DynError> {
4240
.unwrap()
4341
.join("file_to_upload.txt");
4442

45-
let mut tmp_file = File::create(&target_path).unwrap();
46-
tmp_file.write_all(b"Hello, world!").unwrap();
43+
std::fs::write(&target_path, "Hello, world!").unwrap();
4744

4845
let server_url = server.url();
4946
let download_request = UploadRequest::new(&server_url, &target_path);
@@ -80,8 +77,7 @@ async fn upload_with_auth() -> Result<(), DynError> {
8077
.unwrap()
8178
.join("file_to_upload.txt");
8279

83-
let mut tmp_file = File::create(&target_path).unwrap();
84-
tmp_file.write_all(b"Hello, world!").unwrap();
80+
std::fs::write(&target_path, "Hello, world!").unwrap();
8581

8682
let server_url = server.url();
8783
let download_request =

0 commit comments

Comments
 (0)