Unverified Commit b7ede277 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

[Turbopack] bugfixes persistent caching (#71481)

fix race condition in read transaction cache

unset fresh db when persisting DB

avoid restoring data twice

fix syntax in feature flagged code

improve readablility

<!-- 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 21ffe10e
......@@ -183,16 +183,18 @@ where
.set_restored(TaskDataCategory::All);
} else {
for category in category {
// Avoid holding the lock too long since this can also affect other tasks
drop(task);
let items = self.restore_task_data(task_id, category);
task = self.backend.storage.access_mut(task_id);
if !task.persistance_state().is_restored(category) {
for item in items {
task.add(item);
// Avoid holding the lock too long since this can also affect other tasks
drop(task);
let items = self.restore_task_data(task_id, category);
task = self.backend.storage.access_mut(task_id);
if !task.persistance_state().is_restored(category) {
for item in items {
task.add(item);
}
task.persistance_state_mut().set_restored(category);
}
task.persistance_state_mut().set_restored(category);
}
}
}
......
......@@ -114,7 +114,7 @@ impl PersistanceState {
}
pub fn is_restored(&self, category: TaskDataCategory) -> bool {
self.value & category.flag() == 0
(self.value & category.flag()) == 0
}
}
......
use std::{fs, path::Path};
use std::{
borrow::Cow,
fs,
path::Path,
sync::atomic::{AtomicBool, Ordering},
};
use anyhow::Result;
use crate::database::key_value_database::KeyValueDatabase;
use crate::database::key_value_database::{KeySpace, KeyValueDatabase, WriteBatch};
pub fn is_fresh(path: &Path) -> bool {
fs::exists(path).map_or(false, |exists| !exists)
......@@ -10,12 +15,15 @@ pub fn is_fresh(path: &Path) -> bool {
pub struct FreshDbOptimization<T: KeyValueDatabase> {
database: T,
fresh_db: bool,
fresh_db: AtomicBool,
}
impl<T: KeyValueDatabase> FreshDbOptimization<T> {
pub fn new(database: T, fresh_db: bool) -> Self {
Self { database, fresh_db }
Self {
database,
fresh_db: AtomicBool::new(fresh_db),
}
}
}
......@@ -46,7 +54,7 @@ impl<T: KeyValueDatabase> KeyValueDatabase for FreshDbOptimization<T> {
key_space: super::key_value_database::KeySpace,
key: &[u8],
) -> anyhow::Result<Option<Self::ValueBuffer<'l>>> {
if self.fresh_db {
if self.fresh_db.load(Ordering::Acquire) {
// Performance optimization when the database was empty
// It's assumed that no cache entries are removed from the memory cache, but we
// might change that in future.
......@@ -56,11 +64,53 @@ impl<T: KeyValueDatabase> KeyValueDatabase for FreshDbOptimization<T> {
}
type WriteBatch<'l>
= T::WriteBatch<'l>
= FreshDbOptimizationWriteBatch<'l, T>
where
Self: 'l;
fn write_batch(&self) -> Result<Self::WriteBatch<'_>> {
self.database.write_batch()
Ok(FreshDbOptimizationWriteBatch {
write_batch: self.database.write_batch()?,
fresh_db: &self.fresh_db,
})
}
}
pub struct FreshDbOptimizationWriteBatch<'a, T: KeyValueDatabase>
where
T: 'a,
{
write_batch: T::WriteBatch<'a>,
fresh_db: &'a AtomicBool,
}
impl<'a, T: KeyValueDatabase> WriteBatch<'a> for FreshDbOptimizationWriteBatch<'a, T>
where
T: 'a,
{
type ValueBuffer<'l>
= <T::WriteBatch<'a> as WriteBatch<'a>>::ValueBuffer<'l>
where
Self: 'l,
'a: 'l;
fn get<'l>(&'l self, key_space: KeySpace, key: &[u8]) -> Result<Option<Self::ValueBuffer<'l>>>
where
'a: 'l,
{
self.write_batch.get(key_space, key)
}
fn put(&mut self, key_space: KeySpace, key: Cow<[u8]>, value: Cow<[u8]>) -> Result<()> {
self.write_batch.put(key_space, key, value)
}
fn delete(&mut self, key_space: KeySpace, key: Cow<[u8]>) -> Result<()> {
self.write_batch.delete(key_space, key)
}
fn commit(self) -> Result<()> {
self.fresh_db.store(false, Ordering::Release);
self.write_batch.commit()
}
}
......@@ -67,9 +67,10 @@ impl<T: KeyValueDatabase + 'static> KeyValueDatabase for ReadTransactionCache<T>
self.database.begin_read_transaction()?
};
let thread_locals = guard.clone();
Ok(CachedReadTransaction::<T> {
tx: Some(tx),
this: self,
thread_locals,
})
}
......@@ -97,13 +98,13 @@ impl<T: KeyValueDatabase + 'static> KeyValueDatabase for ReadTransactionCache<T>
pub struct CachedReadTransaction<'l, T: KeyValueDatabase + 'static> {
tx: Option<T::ReadTransaction<'l>>,
this: &'l ReadTransactionCache<T>,
thread_locals: Arc<ThreadLocal<ThreadLocalReadTransactionsContainer<T>>>,
}
impl<T: KeyValueDatabase> Drop for CachedReadTransaction<'_, T> {
fn drop(&mut self) {
let guard = self.this.read_transactions_cache.load();
let container = guard
let container = self
.thread_locals
.get_or(|| ThreadLocalReadTransactionsContainer(UnsafeCell::new(Default::default())));
// Safety: We cast it to 'static lifetime, but it will be casted back to 'env when
// taken. It's safe since this will not outlive the environment. We need to
......
......@@ -517,8 +517,7 @@ fn serialize(task: TaskId, mut data: Vec<CachedDataItem>) -> Result<Vec<u8>> {
);
if let Err(err) = deserialize {
println!(
"Data item would not be deserializable {task_id}: \
{err:?}\n{item:#?}"
"Data item would not be deserializable {task}: {err:?}\n{item:#?}"
);
return false;
}
......
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