Skip to content

Commit

Permalink
Merge pull request #103 from holochain/2023-12-01-fs-lock
Browse files Browse the repository at this point in the history
use create new for serialized module cache
  • Loading branch information
thedavidmeister authored Dec 1, 2023
2 parents 4bb3c36 + 3989623 commit 737fce8
Showing 1 changed file with 38 additions and 6 deletions.
44 changes: 38 additions & 6 deletions crates/host/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use holochain_wasmer_common::WasmError;
use parking_lot::Mutex;
use std::collections::BTreeMap;
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
use wasmer::Cranelift;
Expand Down Expand Up @@ -183,11 +185,22 @@ impl SerializedModuleCache {
let (module, serialized_module) = match maybe_module_path.as_ref().map(|module_path| {
// We do this the long way to get `Bytes` instead of `Vec<u8>` so
// that the clone when we both deserialize and cache is cheap.
let mut file = File::open(module_path)
.map_err(|e| wasm_error!(WasmErrorInner::Compile(e.to_string())))?;
let mut file = File::open(module_path).map_err(|e| {
wasm_error!(WasmErrorInner::Compile(format!(
"{} Path: {}",
e,
module_path.display()
)))
})?;
let mut bytes_mut = BytesMut::new().writer();
std::io::copy(&mut file, &mut bytes_mut)
.map_err(|e| wasm_error!(WasmErrorInner::Compile(e.to_string())))?;

std::io::copy(&mut file, &mut bytes_mut).map_err(|e| {
wasm_error!(WasmErrorInner::Compile(format!(
"{} Path: {}",
e,
module_path.display()
)))
})?;
Ok::<bytes::Bytes, wasmer::RuntimeError>(bytes_mut.into_inner().freeze())
}) {
Some(Ok(serialized_module)) => (
Expand All @@ -201,10 +214,29 @@ impl SerializedModuleCache {
let serialized_module = module
.serialize()
.map_err(|e| wasm_error!(WasmErrorInner::Compile(e.to_string())))?;

if let Some(module_path) = maybe_module_path {
std::fs::write(module_path, &serialized_module)
.map_err(|e| wasm_error!(WasmErrorInner::Compile(e.to_string())))?;
match OpenOptions::new()
.write(true)
// Using create_new here so that cache stampedes don't
// cause corruption. Each file can only be written once.
.create_new(true)
.open(&module_path)
{
Ok(mut file) => {
if let Err(e) = file.write_all(&serialized_module) {
tracing::error!("{} Path: {}", e, module_path.display());
}
}
Err(e) => {
// This is just a warning because it is expected that
// multiple concurrent calls to build the same wasm
// will sometimes happen.
tracing::warn!("{} Path: {}", e, module_path.display());
}
}
}

(module, serialized_module)
}
};
Expand Down

0 comments on commit 737fce8

Please sign in to comment.