Unverified Commit 450b07e8 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: allow to customize the parallel execution of turbo-persistence (#82668)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to understand the PR)
- When linking to a Slack thread, you might want to share details of the conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent e21ac64c
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
use std::path::PathBuf; use std::path::PathBuf;
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use turbo_persistence::{MetaFileEntryInfo, TurboPersistence}; use turbo_persistence::{MetaFileEntryInfo, SerialScheduler, TurboPersistence};
fn main() -> Result<()> { fn main() -> Result<()> {
// Get CLI argument // Get CLI argument
...@@ -16,7 +16,7 @@ fn main() -> Result<()> { ...@@ -16,7 +16,7 @@ fn main() -> Result<()> {
bail!("The provided path does not exist: {}", path.display()); bail!("The provided path does not exist: {}", path.display());
} }
let db = TurboPersistence::open_read_only(path)?; let db: TurboPersistence<SerialScheduler> = TurboPersistence::open_read_only(path)?;
let meta_info = db let meta_info = db
.meta_info() .meta_info()
.context("Failed to retrieve meta information")?; .context("Failed to retrieve meta information")?;
......
...@@ -22,7 +22,6 @@ memmap2 = "0.9.5" ...@@ -22,7 +22,6 @@ memmap2 = "0.9.5"
parking_lot = { workspace = true } parking_lot = { workspace = true }
qfilter = { version = "0.2.4", features = ["serde"] } qfilter = { version = "0.2.4", features = ["serde"] }
quick_cache = { workspace = true } quick_cache = { workspace = true }
rayon = { workspace = true }
rustc-hash = { workspace = true } rustc-hash = { workspace = true }
smallvec = { workspace = true } smallvec = { workspace = true }
thread_local = { workspace = true } thread_local = { workspace = true }
...@@ -32,6 +31,7 @@ zstd = { version = "0.13.2", features = ["zdict_builder"] } ...@@ -32,6 +31,7 @@ zstd = { version = "0.13.2", features = ["zdict_builder"] }
[dev-dependencies] [dev-dependencies]
rand = { workspace = true, features = ["small_rng"] } rand = { workspace = true, features = ["small_rng"] }
rayon = { workspace = true }
tempfile = { workspace = true } tempfile = { workspace = true }
[lints] [lints]
......
use std::mem::take;
use crate::{ use crate::{
ValueBuffer, ValueBuffer,
collector_entry::{CollectorEntry, CollectorEntryValue, EntryKey}, collector_entry::{CollectorEntry, CollectorEntryValue, EntryKey},
...@@ -111,4 +113,11 @@ impl<K: StoreKey, const SIZE_SHIFT: usize> Collector<K, SIZE_SHIFT> { ...@@ -111,4 +113,11 @@ impl<K: StoreKey, const SIZE_SHIFT: usize> Collector<K, SIZE_SHIFT> {
self.total_value_size = 0; self.total_value_size = 0;
self.entries.drain(..) self.entries.drain(..)
} }
/// Clears the collector and drops the capacity
pub fn drop_contents(&mut self) {
drop(take(&mut self.entries));
self.total_key_size = 0;
self.total_value_size = 0;
}
} }
...@@ -13,19 +13,21 @@ mod db; ...@@ -13,19 +13,21 @@ mod db;
mod key; mod key;
mod lookup_entry; mod lookup_entry;
mod merge_iter; mod merge_iter;
mod meta_file;
mod meta_file_builder;
mod parallel_scheduler;
mod sst_filter;
mod static_sorted_file; mod static_sorted_file;
mod static_sorted_file_builder; mod static_sorted_file_builder;
mod value_buf;
mod write_batch; mod write_batch;
mod meta_file;
mod meta_file_builder;
mod sst_filter;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
mod value_buf;
pub use arc_slice::ArcSlice; pub use arc_slice::ArcSlice;
pub use db::{CompactConfig, MetaFileEntryInfo, MetaFileInfo, TurboPersistence}; pub use db::{CompactConfig, MetaFileEntryInfo, MetaFileInfo, TurboPersistence};
pub use key::{KeyBase, QueryKey, StoreKey}; pub use key::{KeyBase, QueryKey, StoreKey};
pub use parallel_scheduler::{ParallelScheduler, SerialScheduler};
pub use value_buf::ValueBuffer; pub use value_buf::ValueBuffer;
pub use write_batch::WriteBatch; pub use write_batch::WriteBatch;
pub trait ParallelScheduler: Clone + Sync + Send {
fn parallel_for_each<T>(&self, items: &[T], f: impl Fn(&T) + Send + Sync)
where
T: Sync;
fn try_parallel_for_each<'l, T, E>(
&self,
items: &'l [T],
f: impl (Fn(&'l T) -> Result<(), E>) + Send + Sync,
) -> Result<(), E>
where
T: Sync,
E: Send + 'static;
fn try_parallel_for_each_mut<'l, T, E>(
&self,
items: &'l mut [T],
f: impl (Fn(&'l mut T) -> Result<(), E>) + Send + Sync,
) -> Result<(), E>
where
T: Send + Sync,
E: Send + 'static;
fn try_parallel_for_each_owned<T, E>(
&self,
items: Vec<T>,
f: impl (Fn(T) -> Result<(), E>) + Send + Sync,
) -> Result<(), E>
where
T: Send + Sync,
E: Send + 'static;
fn parallel_map_collect<'l, Item, PerItemResult, Result>(
&self,
items: &'l [Item],
f: impl Fn(&'l Item) -> PerItemResult + Send + Sync,
) -> Result
where
Item: Sync,
PerItemResult: Send + Sync + 'l,
Result: FromIterator<PerItemResult>;
fn parallel_map_collect_owned<Item, PerItemResult, Result>(
&self,
items: Vec<Item>,
f: impl Fn(Item) -> PerItemResult + Send + Sync,
) -> Result
where
Item: Send + Sync,
PerItemResult: Send + Sync,
Result: FromIterator<PerItemResult>;
}
#[derive(Clone, Copy, Default)]
pub struct SerialScheduler;
impl ParallelScheduler for SerialScheduler {
fn parallel_for_each<T>(&self, items: &[T], f: impl Fn(&T) + Send + Sync)
where
T: Sync,
{
for item in items {
f(item);
}
}
fn try_parallel_for_each<'l, T, E>(
&self,
items: &'l [T],
f: impl (Fn(&'l T) -> Result<(), E>) + Send + Sync,
) -> Result<(), E>
where
T: Sync,
E: Send,
{
for item in items {
f(item)?;
}
Ok(())
}
fn try_parallel_for_each_mut<'l, T, E>(
&self,
items: &'l mut [T],
f: impl (Fn(&'l mut T) -> Result<(), E>) + Send + Sync,
) -> Result<(), E>
where
T: Sync,
E: Send,
{
for item in items {
f(item)?;
}
Ok(())
}
fn try_parallel_for_each_owned<T, E>(
&self,
items: Vec<T>,
f: impl (Fn(T) -> Result<(), E>) + Send + Sync,
) -> Result<(), E>
where
T: Sync,
E: Send,
{
for item in items {
f(item)?;
}
Ok(())
}
fn parallel_map_collect<'l, Item, PerItemResult, Result>(
&self,
items: &'l [Item],
f: impl Fn(&'l Item) -> PerItemResult + Send + Sync,
) -> Result
where
Item: Sync,
PerItemResult: Send + Sync + 'l,
Result: FromIterator<PerItemResult>,
{
items.iter().map(f).collect()
}
fn parallel_map_collect_owned<Item, PerItemResult, Result>(
&self,
items: Vec<Item>,
f: impl Fn(Item) -> PerItemResult + Send + Sync,
) -> Result
where
Item: Send + Sync,
PerItemResult: Send + Sync,
Result: FromIterator<PerItemResult>,
{
items.into_iter().map(f).collect()
}
}
...@@ -9,15 +9,11 @@ use std::{ ...@@ -9,15 +9,11 @@ use std::{
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use byteorder::{BE, WriteBytesExt}; use byteorder::{BE, WriteBytesExt};
use either::Either;
use lzzzz::lz4::{self, ACC_LEVEL_DEFAULT}; use lzzzz::lz4::{self, ACC_LEVEL_DEFAULT};
use parking_lot::Mutex; use parking_lot::Mutex;
use rayon::{
iter::{Either, IndexedParallelIterator, IntoParallelIterator, ParallelIterator},
scope,
};
use smallvec::SmallVec; use smallvec::SmallVec;
use thread_local::ThreadLocal; use thread_local::ThreadLocal;
use tracing::Span;
use crate::{ use crate::{
ValueBuffer, ValueBuffer,
...@@ -26,6 +22,7 @@ use crate::{ ...@@ -26,6 +22,7 @@ use crate::{
constants::{MAX_MEDIUM_VALUE_SIZE, THREAD_LOCAL_SIZE_SHIFT}, constants::{MAX_MEDIUM_VALUE_SIZE, THREAD_LOCAL_SIZE_SHIFT},
key::StoreKey, key::StoreKey,
meta_file_builder::MetaFileBuilder, meta_file_builder::MetaFileBuilder,
parallel_scheduler::ParallelScheduler,
static_sorted_file_builder::{StaticSortedFileBuilderMeta, write_static_stored_file}, static_sorted_file_builder::{StaticSortedFileBuilderMeta, write_static_stored_file},
}; };
...@@ -68,7 +65,9 @@ enum GlobalCollectorState<K: StoreKey + Send> { ...@@ -68,7 +65,9 @@ enum GlobalCollectorState<K: StoreKey + Send> {
} }
/// A write batch. /// A write batch.
pub struct WriteBatch<K: StoreKey + Send, const FAMILIES: usize> { pub struct WriteBatch<K: StoreKey + Send, S: ParallelScheduler, const FAMILIES: usize> {
/// Parallel scheduler
parallel_scheduler: S,
/// The database path /// The database path
db_path: PathBuf, db_path: PathBuf,
/// The current sequence number counter. Increased for every new SST file or blob file. /// The current sequence number counter. Increased for every new SST file or blob file.
...@@ -84,13 +83,16 @@ pub struct WriteBatch<K: StoreKey + Send, const FAMILIES: usize> { ...@@ -84,13 +83,16 @@ pub struct WriteBatch<K: StoreKey + Send, const FAMILIES: usize> {
new_sst_files: Mutex<Vec<(u32, File)>>, new_sst_files: Mutex<Vec<(u32, File)>>,
} }
impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> { impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
WriteBatch<K, S, FAMILIES>
{
/// Creates a new write batch for a database. /// Creates a new write batch for a database.
pub(crate) fn new(path: PathBuf, current: u32) -> Self { pub(crate) fn new(path: PathBuf, current: u32, parallel_scheduler: S) -> Self {
const { const {
assert!(FAMILIES <= usize_from_u32(u32::MAX)); assert!(FAMILIES <= usize_from_u32(u32::MAX));
}; };
Self { Self {
parallel_scheduler,
db_path: path, db_path: path,
current_sequence_number: AtomicU32::new(current), current_sequence_number: AtomicU32::new(current),
thread_locals: ThreadLocal::new(), thread_locals: ThreadLocal::new(),
...@@ -223,9 +225,8 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> { ...@@ -223,9 +225,8 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> {
} }
} }
let span = Span::current(); self.parallel_scheduler
collectors.into_par_iter().try_for_each(|mut collector| { .try_parallel_for_each_owned(collectors, |mut collector| {
let _span = span.clone().entered();
self.flush_thread_local_collector(family, &mut collector)?; self.flush_thread_local_collector(family, &mut collector)?;
drop(collector); drop(collector);
anyhow::Ok(()) anyhow::Ok(())
...@@ -242,19 +243,19 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> { ...@@ -242,19 +243,19 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> {
} }
} }
GlobalCollectorState::Sharded(_) => { GlobalCollectorState::Sharded(_) => {
let GlobalCollectorState::Sharded(shards) = replace( let GlobalCollectorState::Sharded(mut shards) = replace(
&mut *collector_state, &mut *collector_state,
GlobalCollectorState::Unsharded(Collector::new()), GlobalCollectorState::Unsharded(Collector::new()),
) else { ) else {
unreachable!(); unreachable!();
}; };
shards.into_par_iter().try_for_each(|mut collector| { self.parallel_scheduler
let _span = span.clone().entered(); .try_parallel_for_each_mut(&mut shards, |collector| {
if !collector.is_empty() { if !collector.is_empty() {
let sst = self.create_sst_file(family, collector.sorted())?; let sst = self.create_sst_file(family, collector.sorted())?;
collector.clear(); collector.clear();
self.new_sst_files.lock().push(sst); self.new_sst_files.lock().push(sst);
drop(collector); collector.drop_contents();
} }
anyhow::Ok(()) anyhow::Ok(())
})?; })?;
...@@ -269,10 +270,9 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> { ...@@ -269,10 +270,9 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> {
#[tracing::instrument(level = "trace", skip(self))] #[tracing::instrument(level = "trace", skip(self))]
pub(crate) fn finish(&mut self) -> Result<FinishResult> { pub(crate) fn finish(&mut self) -> Result<FinishResult> {
let mut new_blob_files = Vec::new(); let mut new_blob_files = Vec::new();
let shared_error = Mutex::new(Ok(()));
// First, we flush all thread local collectors to the global collectors. // First, we flush all thread local collectors to the global collectors.
scope(|scope| { {
let _span = tracing::trace_span!("flush thread local collectors").entered(); let _span = tracing::trace_span!("flush thread local collectors").entered();
let mut collectors = [const { Vec::new() }; FAMILIES]; let mut collectors = [const { Vec::new() }; FAMILIES];
for cell in self.thread_locals.iter_mut() { for cell in self.thread_locals.iter_mut() {
...@@ -286,23 +286,24 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> { ...@@ -286,23 +286,24 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> {
} }
} }
} }
for (family, thread_local_collectors) in collectors.into_iter().enumerate() { let to_flush = collectors
for mut collector in thread_local_collectors { .into_iter()
let this = &self; .enumerate()
let shared_error = &shared_error; .flat_map(|(family, collector)| {
let span = Span::current(); collector
scope.spawn(move |_| { .into_iter()
let _span = span.entered(); .map(move |collector| (family as u32, collector))
if let Err(err) = })
this.flush_thread_local_collector(family as u32, &mut collector) .collect::<Vec<_>>();
{ self.parallel_scheduler.try_parallel_for_each_owned(
*shared_error.lock() = Err(err); to_flush,
} |(family, mut collector)| {
self.flush_thread_local_collector(family, &mut collector)?;
drop(collector); drop(collector);
}); anyhow::Ok(())
} },
)?;
} }
});
let _span = tracing::trace_span!("flush collectors").entered(); let _span = tracing::trace_span!("flush collectors").entered();
...@@ -313,25 +314,24 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> { ...@@ -313,25 +314,24 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> {
let new_collectors = let new_collectors =
[(); FAMILIES].map(|_| Mutex::new(GlobalCollectorState::Unsharded(Collector::new()))); [(); FAMILIES].map(|_| Mutex::new(GlobalCollectorState::Unsharded(Collector::new())));
let collectors = replace(&mut self.collectors, new_collectors); let collectors = replace(&mut self.collectors, new_collectors);
let span = Span::current(); let collectors = collectors
collectors .into_iter()
.into_par_iter()
.enumerate() .enumerate()
.flat_map(|(family, state)| { .flat_map(|(family, state)| {
let collector = state.into_inner(); let collector = state.into_inner();
match collector { match collector {
GlobalCollectorState::Unsharded(collector) => { GlobalCollectorState::Unsharded(collector) => {
Either::Left([(family, collector)].into_par_iter()) Either::Left([(family, collector)].into_iter())
}
GlobalCollectorState::Sharded(shards) => {
Either::Right(shards.into_iter().map(move |collector| (family, collector)))
} }
GlobalCollectorState::Sharded(shards) => Either::Right(
shards
.into_par_iter()
.map(move |collector| (family, collector)),
),
} }
}) })
.try_for_each(|(family, mut collector)| { .collect::<Vec<_>>();
let _span = span.clone().entered(); self.parallel_scheduler.try_parallel_for_each_owned(
collectors,
|(family, mut collector)| {
let family = family as u32; let family = family as u32;
if !collector.is_empty() { if !collector.is_empty() {
let sst = self.create_sst_file(family, collector.sorted())?; let sst = self.create_sst_file(family, collector.sorted())?;
...@@ -340,20 +340,24 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> { ...@@ -340,20 +340,24 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> {
shared_new_sst_files.lock().push(sst); shared_new_sst_files.lock().push(sst);
} }
anyhow::Ok(()) anyhow::Ok(())
})?; },
)?;
shared_error.into_inner()?;
// Not we need to write the new meta files. // Not we need to write the new meta files.
let new_meta_collectors = [(); FAMILIES].map(|_| Mutex::new(Vec::new())); let new_meta_collectors = [(); FAMILIES].map(|_| Mutex::new(Vec::new()));
let meta_collectors = replace(&mut self.meta_collectors, new_meta_collectors); let meta_collectors = replace(&mut self.meta_collectors, new_meta_collectors);
let keys_written = AtomicU64::new(0); let keys_written = AtomicU64::new(0);
let new_meta_files = meta_collectors let file_to_write = meta_collectors
.into_par_iter() .into_iter()
.map(|mutex| mutex.into_inner()) .map(|mutex| mutex.into_inner())
.enumerate() .enumerate()
.filter(|(_, sst_files)| !sst_files.is_empty()) .filter(|(_, sst_files)| !sst_files.is_empty())
.map(|(family, sst_files)| { .collect::<Vec<_>>();
let new_meta_files = self
.parallel_scheduler
.parallel_map_collect_owned::<_, _, Result<Vec<_>>>(
file_to_write,
|(family, sst_files)| {
let family = family as u32; let family = family as u32;
let mut entries = 0; let mut entries = 0;
let mut builder = MetaFileBuilder::new(family); let mut builder = MetaFileBuilder::new(family);
...@@ -365,8 +369,8 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> { ...@@ -365,8 +369,8 @@ impl<K: StoreKey + Send + Sync, const FAMILIES: usize> WriteBatch<K, FAMILIES> {
let seq = self.current_sequence_number.fetch_add(1, Ordering::SeqCst) + 1; let seq = self.current_sequence_number.fetch_add(1, Ordering::SeqCst) + 1;
let file = builder.write(&self.db_path, seq)?; let file = builder.write(&self.db_path, seq)?;
Ok((seq, file)) Ok((seq, file))
}) },
.collect::<Result<Vec<_>>>()?; )?;
// Finally we return the new files and sequence number. // Finally we return the new files and sequence number.
let seq = self.current_sequence_number.load(Ordering::SeqCst); let seq = self.current_sequence_number.load(Ordering::SeqCst);
......
...@@ -9,9 +9,12 @@ use turbo_tasks::{JoinHandle, message_queue::TimingEvent, spawn, turbo_tasks}; ...@@ -9,9 +9,12 @@ use turbo_tasks::{JoinHandle, message_queue::TimingEvent, spawn, turbo_tasks};
use crate::database::{ use crate::database::{
key_value_database::{KeySpace, KeyValueDatabase}, key_value_database::{KeySpace, KeyValueDatabase},
turbo::parallel_scheduler::TurboTasksParallelScheduler,
write_batch::{BaseWriteBatch, ConcurrentWriteBatch, WriteBatch, WriteBuffer}, write_batch::{BaseWriteBatch, ConcurrentWriteBatch, WriteBatch, WriteBuffer},
}; };
mod parallel_scheduler;
const MB: u64 = 1024 * 1024; const MB: u64 = 1024 * 1024;
const COMPACT_CONFIG: CompactConfig = CompactConfig { const COMPACT_CONFIG: CompactConfig = CompactConfig {
min_merge_count: 3, min_merge_count: 3,
...@@ -24,7 +27,7 @@ const COMPACT_CONFIG: CompactConfig = CompactConfig { ...@@ -24,7 +27,7 @@ const COMPACT_CONFIG: CompactConfig = CompactConfig {
}; };
pub struct TurboKeyValueDatabase { pub struct TurboKeyValueDatabase {
db: Arc<TurboPersistence>, db: Arc<TurboPersistence<TurboTasksParallelScheduler>>,
compact_join_handle: Mutex<Option<JoinHandle<Result<()>>>>, compact_join_handle: Mutex<Option<JoinHandle<Result<()>>>>,
is_ci: bool, is_ci: bool,
is_short_session: bool, is_short_session: bool,
...@@ -116,7 +119,7 @@ impl KeyValueDatabase for TurboKeyValueDatabase { ...@@ -116,7 +119,7 @@ impl KeyValueDatabase for TurboKeyValueDatabase {
} }
fn do_compact( fn do_compact(
db: &TurboPersistence, db: &TurboPersistence<TurboTasksParallelScheduler>,
message: &'static str, message: &'static str,
max_merge_segment_count: usize, max_merge_segment_count: usize,
) -> Result<()> { ) -> Result<()> {
...@@ -135,8 +138,8 @@ fn do_compact( ...@@ -135,8 +138,8 @@ fn do_compact(
} }
pub struct TurboWriteBatch<'a> { pub struct TurboWriteBatch<'a> {
batch: turbo_persistence::WriteBatch<WriteBuffer<'static>, 5>, batch: turbo_persistence::WriteBatch<WriteBuffer<'static>, TurboTasksParallelScheduler, 5>,
db: &'a Arc<TurboPersistence>, db: &'a Arc<TurboPersistence<TurboTasksParallelScheduler>>,
compact_join_handle: Option<&'a Mutex<Option<JoinHandle<Result<()>>>>>, compact_join_handle: Option<&'a Mutex<Option<JoinHandle<Result<()>>>>>,
} }
......
use turbo_persistence::ParallelScheduler;
use turbo_tasks::parallel;
#[derive(Clone, Copy, Default)]
pub struct TurboTasksParallelScheduler;
impl ParallelScheduler for TurboTasksParallelScheduler {
fn parallel_for_each<T>(&self, items: &[T], f: impl Fn(&T) + Send + Sync)
where
T: Sync,
{
parallel::for_each(items, f);
}
fn try_parallel_for_each<'l, T, E>(
&self,
items: &'l [T],
f: impl (Fn(&'l T) -> Result<(), E>) + Send + Sync,
) -> Result<(), E>
where
T: Sync,
E: Send + 'static,
{
parallel::try_for_each(items, f)
}
fn try_parallel_for_each_mut<'l, T, E>(
&self,
items: &'l mut [T],
f: impl (Fn(&'l mut T) -> Result<(), E>) + Send + Sync,
) -> Result<(), E>
where
T: Send + Sync,
E: Send + 'static,
{
parallel::try_for_each_mut(items, f)
}
fn try_parallel_for_each_owned<T, E>(
&self,
items: Vec<T>,
f: impl (Fn(T) -> Result<(), E>) + Send + Sync,
) -> Result<(), E>
where
T: Send + Sync,
E: Send + 'static,
{
parallel::try_for_each_owned(items, f)
}
fn parallel_map_collect<'l, T, I, R>(
&self,
items: &'l [T],
f: impl Fn(&'l T) -> I + Send + Sync,
) -> R
where
T: Sync,
I: Send + Sync + 'l,
R: FromIterator<I>,
{
parallel::map_collect(items, f)
}
fn parallel_map_collect_owned<T, I, R>(
&self,
items: Vec<T>,
f: impl Fn(T) -> I + Send + Sync,
) -> R
where
T: Send + Sync,
I: Send + Sync,
R: FromIterator<I>,
{
parallel::map_collect_owned(items, f)
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment