-
Notifications
You must be signed in to change notification settings - Fork 71
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
Add once_map package #1665
Open
maciektr
wants to merge
1
commit into
spr/main/3ba8d8f0
Choose a base branch
from
spr/main/293590d9
base: spr/main/3ba8d8f0
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add once_map package #1665
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
[package] | ||
name = "once_map" | ||
version = "0.0.1" | ||
publish = false | ||
edition.workspace = true | ||
homepage.workspace = true | ||
repository.workspace = true | ||
authors.workspace = true | ||
license.workspace = true | ||
|
||
[dependencies] | ||
dashmap.workspace = true | ||
tokio.workspace = true | ||
futures.workspace = true |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
// This file has been copied verbatim from `uv` repository. | ||
// Original code location: https://github.com/astral-sh/uv/blob/main/crates/uv-once-map/src/lib.rs | ||
|
||
use std::borrow::Borrow; | ||
use std::hash::{BuildHasher, Hash, RandomState}; | ||
use std::pin::pin; | ||
use std::sync::Arc; | ||
|
||
use dashmap::DashMap; | ||
use tokio::sync::Notify; | ||
|
||
/// Run tasks only once and store the results in a parallel hash map. | ||
/// | ||
/// We often have jobs `Fn(K) -> V` that we only want to run once and memoize, e.g. network | ||
/// requests for metadata. When multiple tasks start the same query in parallel, e.g. through source | ||
/// dist builds, we want to wait until the other task is done and get a reference to the same | ||
/// result. | ||
/// | ||
/// Note that this always clones the value out of the underlying map. Because | ||
/// of this, it's common to wrap the `V` in an `Arc<V>` to make cloning cheap. | ||
pub struct OnceMap<K, V, H = RandomState> { | ||
pub items: DashMap<K, Value<V>, H>, | ||
} | ||
|
||
impl<K: Eq + Hash, V: Clone, H: BuildHasher + Clone> OnceMap<K, V, H> { | ||
/// Register that you want to start a job. | ||
/// | ||
/// If this method returns `true`, you need to start a job and call [`OnceMap::done`] eventually | ||
/// or other tasks will hang. If it returns `false`, this job is already in progress and you | ||
/// can [`OnceMap::wait`] for the result. | ||
pub fn register(&self, key: K) -> bool { | ||
let entry = self.items.entry(key); | ||
match entry { | ||
dashmap::mapref::entry::Entry::Occupied(_) => false, | ||
dashmap::mapref::entry::Entry::Vacant(entry) => { | ||
entry.insert(Value::Waiting(Arc::new(Notify::new()))); | ||
true | ||
} | ||
} | ||
} | ||
|
||
/// Submit the result of a job you registered. | ||
pub fn done(&self, key: K, value: V) { | ||
if let Some(Value::Waiting(notify)) = self.items.insert(key, Value::Filled(value)) { | ||
notify.notify_waiters(); | ||
} | ||
} | ||
|
||
/// Wait for the result of a job that is running. | ||
/// | ||
/// Will hang if [`OnceMap::done`] isn't called for this key. | ||
pub async fn wait(&self, key: &K) -> Option<V> { | ||
let notify = { | ||
let entry = self.items.get(key)?; | ||
match entry.value() { | ||
Value::Filled(value) => return Some(value.clone()), | ||
Value::Waiting(notify) => notify.clone(), | ||
} | ||
}; | ||
|
||
// Register the waiter for calls to `notify_waiters`. | ||
let notification = pin!(notify.notified()); | ||
|
||
// Make sure the value wasn't inserted in-between us checking the map and registering the waiter. | ||
if let Value::Filled(value) = self.items.get(key).expect("map is append-only").value() { | ||
return Some(value.clone()); | ||
}; | ||
|
||
// Wait until the value is inserted. | ||
notification.await; | ||
|
||
let entry = self.items.get(key).expect("map is append-only"); | ||
match entry.value() { | ||
Value::Filled(value) => Some(value.clone()), | ||
Value::Waiting(_) => unreachable!("notify was called"), | ||
} | ||
} | ||
|
||
/// Wait for the result of a job that is running, in a blocking context. | ||
/// | ||
/// Will hang if [`OnceMap::done`] isn't called for this key. | ||
pub fn wait_blocking(&self, key: &K) -> Option<V> { | ||
let notify = { | ||
let entry = self.items.get(key)?; | ||
match entry.value() { | ||
Value::Filled(value) => return Some(value.clone()), | ||
Value::Waiting(notify) => notify.clone(), | ||
} | ||
}; | ||
|
||
// Register the waiter for calls to `notify_waiters`. | ||
let notification = pin!(notify.notified()); | ||
|
||
// Make sure the value wasn't inserted in-between us checking the map and registering the waiter. | ||
if let Value::Filled(value) = self.items.get(key).expect("map is append-only").value() { | ||
return Some(value.clone()); | ||
}; | ||
|
||
// Wait until the value is inserted. | ||
futures::executor::block_on(notification); | ||
|
||
let entry = self.items.get(key).expect("map is append-only"); | ||
match entry.value() { | ||
Value::Filled(value) => Some(value.clone()), | ||
Value::Waiting(_) => unreachable!("notify was called"), | ||
} | ||
} | ||
|
||
/// Return the result of a previous job, if any. | ||
pub fn get<Q: ?Sized + Hash + Eq>(&self, key: &Q) -> Option<V> | ||
where | ||
K: Borrow<Q>, | ||
{ | ||
let entry = self.items.get(key)?; | ||
match entry.value() { | ||
Value::Filled(value) => Some(value.clone()), | ||
Value::Waiting(_) => None, | ||
} | ||
} | ||
} | ||
|
||
impl<K: Eq + Hash + Clone, V, H: Default + BuildHasher + Clone> Default for OnceMap<K, V, H> { | ||
fn default() -> Self { | ||
Self { | ||
items: DashMap::with_hasher(H::default()), | ||
} | ||
} | ||
} | ||
|
||
#[derive(Debug)] | ||
pub enum Value<V> { | ||
Waiting(Arc<Notify>), | ||
Filled(V), | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is basically dataloader, isn't it?