Skip to content
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

feat(duvet-core): add concurrency limits to open files #137

Merged
merged 1 commit into from
Nov 14, 2024
Merged
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
22 changes: 20 additions & 2 deletions duvet-core/src/vfs/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,20 @@ use crate::{
query::Query,
};
use miette::Context;
use tokio::{fs, io::AsyncReadExt};
use tokio::{fs, io::AsyncReadExt, sync::Semaphore};

#[cfg(target_os = "linux")]
/// Linux usually defaults to 1024 but we lower it just in case it's lower
const MAX_CONCURRENCY: usize = 256;

#[cfg(not(target_os = "linux"))]
/// If it's not Linux, assume the `ulimit -n` is low.
///
/// For example, macOS seems to default to 256.
const MAX_CONCURRENCY: usize = 64;

/// Limits the number of open files
static CONCURRENCY: Semaphore = Semaphore::const_new(MAX_CONCURRENCY);

#[derive(Clone, Default)]
pub struct Fs(());
Expand Down Expand Up @@ -70,7 +83,9 @@ impl Vfs for Fs {
let modified_time = metadata.modified_time.as_ref().ok().copied();

cache.get_or_init((path.clone(), modified_time), || {
Query::spawn(async {
Query::spawn(async move {
let concurrency = CONCURRENCY.acquire().await.unwrap();

let mut file = fs::OpenOptions::new()
.read(true)
.open(&path)
Expand All @@ -84,6 +99,9 @@ impl Vfs for Fs {
.into_diagnostic()
.wrap_err_with(|| path.clone())?;

drop(file);
drop(concurrency);

let contents = Contents::from(data);

Result::<_, diagnostic::Error>::Ok(BinaryFile { path, contents })
Expand Down
Loading