### Merger::execute Example Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Demonstrates how to use the `execute` method to run an asynchronous function for a given key. It ensures only one operation is in-flight at a time and handles duplicate calls by waiting for the leader. The key can be passed in a borrowed form. ```rust use uniflight::Merger; async fn example() { let merger: Merger = Merger::new(); let result = merger.execute("my-key", || async { 42 }).await; assert_eq!(result, Ok(42)); } ``` -------------------------------- ### NUMA-Aware Merger Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Illustrates creating a NUMA-aware Merger where each NUMA node gets its own deduplication scope, promoting NUMA-local memory access. ```rust use uniflight::Merger; use thread_aware::PerNuma; async fn example() { // NUMA-aware merger - each NUMA node gets its own deduplication scope let merger: Merger = Merger::new_per_numa(); } ``` -------------------------------- ### Thread-Aware Scoping with PerNuma Strategy Source: https://docs.rs/uniflight/0.1.0/uniflight Illustrates creating a NUMA-aware Merger where each NUMA node gets its own deduplication scope, promoting NUMA-local memory access. ```rust use uniflight::Merger; use thread_aware::PerNuma; // NUMA-aware merger - each NUMA node gets its own deduplication scope let merger: Merger = Merger::new_per_numa(); ``` -------------------------------- ### Merger::new_per_core Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Creates a new Merger with per-core scoping. Each core gets its own deduplication scope. This is useful when work is already partitioned by core and cross-core deduplication is not needed. ```APIDOC ## Merger::new_per_core ### Description Creates a new `Merger` with per-core scoping. Each core gets its own deduplication scope. This is useful when work is already partitioned by core and cross-core deduplication is not needed. ### Method `new_per_core()` ### Parameters None ### Returns A new `Merger` instance with per-core scoping. ### Examples ```rust use uniflight::Merger; let merger = Merger::::new_per_core(); ``` ``` -------------------------------- ### Merger::new_per_numa Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Creates a new Merger with per-NUMA-node scoping. Each NUMA node gets its own deduplication scope, ensuring memory locality for cached results while still deduplicating within each node. ```APIDOC ## Merger::new_per_numa ### Description Creates a new `Merger` with per-NUMA-node scoping. Each NUMA node gets its own deduplication scope, ensuring memory locality for cached results while still deduplicating within each node. ### Method `new_per_numa()` ### Parameters None ### Returns A new `Merger` instance with per-NUMA-node scoping. ### Examples ```rust use uniflight::Merger; let merger = Merger::::new_per_numa(); ``` ``` -------------------------------- ### Getting Type ID for Any Trait Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Gets the `TypeId` of the current type, used for dynamic dispatch and type checking. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Getting Source of LeaderPanicked Error Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Retrieves the underlying source error, if any, that caused the LeaderPanicked error. This is part of the standard Error trait implementation. ```rust fn source(&self) -> Option<&(dyn Error + 'static)> ``` -------------------------------- ### Creating Merger Instances with Different Scoping Strategies Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Demonstrates how to create Merger instances with different thread-aware scoping strategies: PerProcess (default), PerNuma, and PerCore. The type of Merger can often be inferred. ```rust use uniflight::Merger; use thread_aware::{PerNuma, PerCore}; // Default (PerProcess) - type can be inferred let global: Merger = Merger::new(); // NUMA-local scope let numa: Merger = Merger::new(); // Per-core scope let core: Merger = Merger::new(); ``` -------------------------------- ### CloneToUninit Trait Implementation (Nightly) Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Provides the `clone_to_uninit` method for performing copy-assignment to uninitialized memory. This is a nightly-only experimental API. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description 🔬This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit` ### Parameters - `&self`: An immutable reference to the object. - `dest`: A raw pointer to the uninitialized memory location. ### Safety This function is unsafe and requires the caller to ensure that `dest` is valid and points to enough uninitialized memory to hold the cloned value. ``` -------------------------------- ### Create New Merger Instances with Different Scopes Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Demonstrates creating Merger instances with default (PerProcess), PerNuma, and PerCore scoping strategies. The type parameter S controls the scope. ```rust use uniflight::Merger; use thread_aware::{PerNuma, PerCore}; // Default (PerProcess) - type can be inferred let global: Merger = Merger::new(); // NUMA-local scope let numa: Merger = Merger::new(); // Per-core scope let core: Merger = Merger::new(); ``` -------------------------------- ### Concurrent Task Execution and Cleanup Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Demonstrates executing multiple concurrent tasks with the same key and verifies that the group cleans up all entries after all futures complete. Also shows execution and cleanup for multiple distinct keys. ```rust let mut group = UniflightGroup::new(); // Multiple concurrent calls should clean up after all complete let futures: Vec<_> = (0..10) .map(|_| { group.execute("key2", || async { tokio::time::sleep(Duration::from_millis(50)).await; "Result".to_string() }) }) .collect(); // While in flight, map should have an entry assert_eq!(group.len(), 1); for fut in futures { assert_eq!(fut.await, Ok("Result".to_string())); } assert!(group.is_empty(), "Map should be empty after all concurrent calls complete"); // Multiple different keys should all be cleaned up let fut1 = group.execute("a", || async { "A".to_string() }); let fut2 = group.execute("b", || async { "B".to_string() }); let fut3 = group.execute("c", || async { "C".to_string() }); assert_eq!(group.len(), 3); let (r1, r2, r3) = tokio::join!(fut1, fut2, fut3); assert_eq!(r1, Ok("A".to_string())); assert_eq!(r2, Ok("B".to_string())); assert_eq!(r3, Ok("C".to_string())); assert!(group.is_empty(), "Map should be empty after all keys complete"); ``` -------------------------------- ### Merger with Flexible Key Types Source: https://docs.rs/uniflight/0.1.0/uniflight Shows how Merger's execute method accepts keys using Borrow semantics, allowing borrowed forms of the key type (e.g., &str for String keys) without extra allocation. ```rust let merger: Merger = Merger::new(); // Pass &str directly - no need to call .to_string() let result = merger.execute("my-key", || async { 42 }).await; assert_eq!(result, Ok(42)); ``` -------------------------------- ### Merger::new_per_core Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Creates a new `Merger` instance, optimized for per-core operation. This is a constructor that initializes the merger with default settings. ```APIDOC ## Merger::new_per_core ### Description Creates a new `Merger` instance, optimized for per-core operation. This is a constructor that initializes the merger with default settings. ### Signature `pub fn new_per_core() -> Self` ### Example ```rust use uniflight::Merger; let merger = Merger::::new_per_core(); ``` ``` -------------------------------- ### Create Merger with Per-Core Scoping Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Creates a new Merger instance configured for per-core scoping, suitable for scenarios where work is already partitioned by core. ```rust use uniflight::Merger; let merger = Merger::::new_per_core(); ``` -------------------------------- ### Basic Merger Usage Source: https://docs.rs/uniflight/0.1.0/uniflight Demonstrates the core functionality of Merger where multiple concurrent calls with the same key share a single execution. The expensive operation runs only once. ```rust use uniflight::Merger; let group: Merger = Merger::new(); // Multiple concurrent calls with the same key will share a single execution. // Note: you can pass &str directly when the key type is String. let result = group.execute("user:123", || async { // This expensive operation runs only once, even if called concurrently "expensive_result".to_string() }).await.expect("leader should not panic"); ``` -------------------------------- ### Merger Panic Handling Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Demonstrates how Merger handles leader task panics, returning a LeaderPanicked error with the panic message. This allows followers to decide whether to retry. ```rust use uniflight::Merger; async fn example() { let merger: Merger = Merger::new(); match merger.execute("key", || async { "result".to_string() }).await { Ok(value) => println!("got {value}"), Err(err) => { println!("leader panicked: {}", err.message()); // Decide whether to retry } } } ``` -------------------------------- ### PanicAwareCell Handling Async Panics Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Demonstrates how `PanicAwareCell` handles and reports panics that occur during the initialization of its asynchronous value. The error message from the panic should be accessible. ```rust let cell = PanicAwareCell::::new(); let result = cell .get_or_init(async { panic!("test panic"); #[expect(unreachable_code, reason = "Required to satisfy return type after panic")] "never".to_string() }) .await; let err = result.as_ref().unwrap_err(); assert_eq!(err.message(), "test panic"); ``` -------------------------------- ### Cloning to Uninitialized Memory (Nightly) Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html An experimental nightly-only API that performs copy-assignment from `self` to a raw pointer `dest`. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### From Trait Implementation Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Provides the `from` method for creating an instance from another value of the same type. ```APIDOC ## fn from(t: T) -> T ### Description Returns the argument unchanged. ### Method `from` ### Parameters - `t`: The value to convert from. ### Response - `T`: The created instance. ``` -------------------------------- ### Handling Leader Panics Source: https://docs.rs/uniflight/0.1.0/uniflight Demonstrates how to handle errors when the leader task panics. Followers receive a LeaderPanicked error, allowing for explicit error handling and potential retries. ```rust let merger: Merger = Merger::new(); match merger.execute("key", || async { "result".to_string() }).await { Ok(value) => println!("got {value}"), Err(err) => { println!("leader panicked: {}", err.message()); // Decide whether to retry } } ``` -------------------------------- ### Merger::new Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Creates a new Merger instance with a configurable scoping strategy. The default strategy is PerProcess, which offers maximum deduplication across the entire process. Other strategies include PerNuma for NUMA-local deduplication and PerCore for core-specific deduplication. ```APIDOC ## Merger::new ### Description Creates a new `Merger` instance with a configurable scoping strategy. ### Method `new()` ### Parameters None ### Returns A new `Merger` instance. ### Examples ```rust use uniflight::Merger; use thread_aware::{PerNuma, PerCore}; // Default (PerProcess) - type can be inferred let global: Merger = Merger::new(); // NUMA-local scope let numa: Merger = Merger::new(); // Per-core scope let core: Merger = Merger::new(); ``` ``` -------------------------------- ### Create Merger with Per-NUMA Node Scoping Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Creates a new Merger instance configured for per-NUMA node scoping, optimizing for memory locality within each NUMA node. ```rust use uniflight::Merger; let merger = Merger::::new_per_numa(); ``` -------------------------------- ### Merger::new Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Creates a new Merger instance. The scoping strategy is determined by the type parameter S. ```APIDOC ## Merger::new ### Description Creates a new `Merger` instance. The scoping strategy is determined by the type parameter `S`. ### Method `new()` ### Parameters None ### Returns A new `Merger` instance. ### Examples ```rust use uniflight::Merger; use thread_aware::{PerNuma, PerCore}; // Default (PerProcess) - type can be inferred let global: Merger = Merger::new(); // NUMA-local scope let numa: Merger = Merger::new(); // Per-core scope let core: Merger = Merger::new(); ``` ``` -------------------------------- ### Providing Context for LeaderPanicked Error Reports Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html This is a nightly-only experimental API that provides type-based access to context for error reports. ```rust fn provide<'a>(&'a self, request: &mut Request<'a>) ``` -------------------------------- ### Merger Fast Path - Existing Cell Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Tests the fast path of get_or_create_cell, ensuring it returns an existing cell if the key is already present. ```rust #[test] fn fast_path_returns_existing() { let map: DashMap>, RandomState> = DashMap::with_hasher(RandomState::new()); let existing_cell = Arc::new(PanicAwareCell::new()); map.insert("key".to_string(), Arc::downgrade(&existing_cell)); let result = Merger::::get_or_create_cell(&map, "key"); assert!(Arc::ptr_eq(&result, &existing_cell)); } ``` -------------------------------- ### Create Merger with Process-Wide Scoping Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Creates a new Merger instance specifically configured for process-wide scoping, ensuring maximum deduplication across all threads. ```rust use uniflight::Merger; let merger = Merger::::new_per_process(); ``` -------------------------------- ### Converting From a Type Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Converts a value from one type to another. This implementation simply returns the argument unchanged. ```rust fn from(t: T) -> T ``` -------------------------------- ### Into Trait Implementation Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Provides the `into` method for converting an instance into another type that implements `From`. ```APIDOC ## fn into(self) -> U ### Description Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ### Method `into` ### Parameters - `self`: The value to convert. ### Response - `U`: The converted value. ``` -------------------------------- ### Trying to Convert Into a Type Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Attempts to convert a value into another type using the `TryFrom` trait, returning a `Result`. ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### PanicAwareCell Initialization and Execution Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html A cell that wraps a future, catching panics and converting them into LeaderPanicked errors. Ensures results are initialized only once. ```rust struct PanicAwareCell { inner: OnceCell>, } impl PanicAwareCell { fn new() -> Self { Self { inner: OnceCell::new() } } #[expect(clippy::future_not_send, reason = "Send bounds enforced by Merger::execute")] async fn get_or_init(&self, f: F) -> &Result where F: Future, { // Use map combinator instead of async block to avoid extra state machine self.inner .get_or_init(AssertUnwindSafe(f).catch_unwind().map(|result| { result.map_err(|payload| LeaderPanicked { message: extract_panic_message(&*payload), }) })) .await } } ``` -------------------------------- ### Converting to String Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Converts the value to a `String`. This relies on the `Display` trait implementation. ```rust fn to_string(&self) -> String ``` -------------------------------- ### Converting Into a Type Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Converts a value into another type using the `From` trait. This is a blanket implementation. ```rust fn into(self) -> U ``` -------------------------------- ### Checking Equivalence for Hashing/Collections Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Checks if a value is equivalent to a given key, often used in hash maps and sets. ```rust fn equivalent(&self, key: &K) -> bool ``` -------------------------------- ### Deprecated Error Description for LeaderPanicked Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Provides a description of the error. This method is deprecated and users should prefer the Display implementation or `to_string()`. ```rust fn description(&self) -> &str ``` -------------------------------- ### Merger::get_or_create_cell Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Retrieves an existing cell for a given key from the internal map, or creates a new one if it doesn't exist or has expired. This is the fast path for cell access. ```rust fn get_or_create_cell(map: &DashMap>, RandomState>, key: &Q) -> Arc> where K: Borrow, Q: Hash + Eq + ToOwned + ?Sized, { // Fast path: check if entry exists and is still valid if let Some(entry) = map.get(key) && let Some(cell) = entry.value().upgrade() { return cell; } // Slow path: need to insert or replace expired entry Self::insert_or_get_existing(map, key) } ``` -------------------------------- ### Creating Owned Data Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Creates owned data from borrowed data, typically by cloning. This is a blanket implementation. ```rust type Owned = T ``` ```rust fn to_owned(&self) -> T ``` ```rust fn clone_into(&self, target: &mut T) ``` -------------------------------- ### Merger Relocated Method Test Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Verifies that the relocated method on Merger correctly handles affinity changes and returns an empty collection. ```rust #[test] fn relocated_delegates_to_inner() { let affinities = pinned_affinities(&[2]); let source = affinities[0].into(); let destination = affinities[1]; let merger: Merger = Merger::new(); let relocated = merger.relocated(source, destination); // Verify the relocated merger still works assert!(relocated.is_empty()); } ``` -------------------------------- ### Trying to Convert From a Type Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Attempts to convert a value from one type to another, returning a `Result`. The `Error` type is `Infallible` for this implementation. ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Provides the `type_id` method for obtaining the `TypeId` of an instance. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters - `&self`: An immutable reference to the object. ### Response - `TypeId`: The unique identifier for the type of `self`. ``` -------------------------------- ### Comparing LeaderPanicked for Equality Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Tests if two LeaderPanicked errors are equal. This is used by the equality operator `==`. ```rust fn eq(&self, other: &LeaderPanicked) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### TryInto Trait Implementation Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Provides the `try_into` method for attempting a fallible conversion into another type. ```APIDOC ## fn try_into(self) -> Result>::Error> ### Description Performs the conversion. ### Method `try_into` ### Parameters - `self`: The value to convert. ### Response - `Result>::Error>`: Ok containing the converted value on success, or an error on failure. ``` -------------------------------- ### Borrow Trait Implementation Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Provides the `borrow` method for immutably borrowing the object. ```APIDOC ## fn borrow(&self) -> &T ### Description Immutably borrows from an owned value. ### Method `borrow` ### Parameters - `&self`: An immutable reference to the object. ### Response - `&T`: An immutable reference to the borrowed value. ``` -------------------------------- ### Merger::insert_or_get_existing Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Handles the slow path of cell creation or retrieval, including atomic insertion and replacement of expired cells. This function is designed to manage concurrent access and races when inserting new cells. ```rust fn insert_or_get_existing(map: &DashMap>, RandomState>, key: &Q) -> Arc> where K: Borrow, Q: Hash + Eq + ToOwned + ?Sized, { let cell = Arc::new(PanicAwareCell::new()); let weak = Arc::downgrade(&cell); // Use Entry enum to atomically check-and-return or insert match map.entry(key.to_owned()) { Occupied(mut entry) => { // Entry exists - check if still alive if let Some(existing) = entry.get().upgrade() { // Another thread's cell is still alive - use it return existing; } // Expired - replace with ours entry.insert(weak); } Vacant(entry) => { entry.insert(weak); } } cell } ``` -------------------------------- ### Merger::new_per_process Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Creates a new Merger with process-wide scoping (default). All threads share a single deduplication scope, providing maximum work deduplication across the entire process. ```APIDOC ## Merger::new_per_process ### Description Creates a new `Merger` with process-wide scoping (default). All threads share a single deduplication scope, providing maximum work deduplication across the entire process. ### Method `new_per_process()` ### Parameters None ### Returns A new `Merger` instance with process-wide scoping. ### Examples ```rust use uniflight::Merger; let merger = Merger::::new_per_process(); ``` ``` -------------------------------- ### Borrowing Data Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Provides immutable access to borrowed data. This is a blanket implementation for all types. ```rust fn borrow(&self) -> &T ``` -------------------------------- ### TryFrom Trait Implementation Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Provides the `try_from` method for attempting a fallible conversion from another type. ```APIDOC ## fn try_from(value: U) -> Result>::Error> ### Description Performs the conversion. ### Method `try_from` ### Parameters - `value`: The value to convert from. ### Response - `Result>::Error>`: Ok containing the converted value on success, or an error on failure. ``` -------------------------------- ### Merger Cleanup After Completion Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Tests that the Merger cleans up its internal map after a single task completes successfully. ```rust #[tokio::test] async fn cleanup_after_completion() { let group: Merger = Merger::new(); assert!(group.is_empty()); // Single call should clean up after completion let result = group.execute("key1", || async { "Result".to_string() }).await; assert_eq!(result, Ok("Result".to_string())); assert!(group.is_empty(), "Map should be empty after single call completes"); } ``` -------------------------------- ### BorrowMut Trait Implementation Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Provides the `borrow_mut` method for mutably borrowing the object. ```APIDOC ## fn borrow_mut(&mut self) -> &mut T ### Description Mutably borrows from an owned value. ### Method `borrow_mut` ### Parameters - `&mut self`: A mutable reference to the object. ### Response - `&mut T`: A mutable reference to the borrowed value. ``` -------------------------------- ### Debugging LeaderPanicked Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Enables the debugging of LeaderPanicked errors, allowing them to be formatted for inspection during development. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result ``` -------------------------------- ### Cloning LeaderPanicked Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Provides functionality to create a duplicate of a LeaderPanicked error. This is useful for error handling scenarios where the error needs to be propagated or stored. ```rust fn clone(&self) -> LeaderPanicked ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Merger::execute Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Execute and return the value for a given function, making sure that only one operation is in-flight at a given moment. If a duplicate call comes in, that caller will wait until the leader completes and return the same value. ```APIDOC ## Merger::execute ### Description Executes a function and returns its value, ensuring only one operation is in-flight for a given key at a time. Subsequent calls with the same key will wait for the result of the ongoing operation. ### Method `execute(&self, key: &Q, func: F) -> impl Future> + Send` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **key** (`&Q`): The key to identify the operation. `Q` must be borrowable as `K`. * **func** (`F`): A closure that returns a `Future` producing the result `T`. ### Returns A `Future` that resolves to a `Result`. `LeaderPanicked` is returned if the leader task panicked. ### Errors * `LeaderPanicked`: If the leader task panicked during execution. Callers can retry by calling `execute` again. ### Examples ```rust let merger: Merger = Merger::new(); let result = merger.execute("my-key", || async { 42 }).await; assert_eq!(result, Ok(42)); ``` ``` -------------------------------- ### Merger::execute Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Executes a given function for a specific key, ensuring that only one operation is in-flight at any given moment for that key. If a duplicate call is made, the caller will wait for the leader to complete and receive the same result. It returns a `Result` which can be `LeaderPanicked` if the leader task panicked. ```APIDOC ## Merger::execute ### Description Executes a given function for a specific key, ensuring that only one operation is in-flight at any given moment for that key. If a duplicate call is made, the caller will wait for the leader to complete and receive the same result. It returns a `Result` which can be `LeaderPanicked` if the leader task panicked. ### Method `pub fn execute(&self, key: &Q, func: F) -> impl Future> + Send + use` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **key** (`&Q`): A reference to the key used to identify the operation. The key can be passed in any borrowed form of `K`. * **func** (`F`): A closure that returns a `Future` representing the operation to be executed. This closure must be `Send`. ### Returns An `impl Future` that resolves to a `Result`. `T` is the type of the value returned by the function, and `LeaderPanicked` is an error type indicating the leader task panicked. ### Errors * `LeaderPanicked`: Returned if the leader task panicked during execution. Callers can retry by calling `execute` again. ### Example ```rust # use uniflight::Merger; # async fn example() { let merger: Merger = Merger::new(); let result = merger.execute("my-key", || async { 42 }).await; assert_eq!(result, Ok(42)); # } ``` ``` -------------------------------- ### Merger Race Condition - Existing Entry Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Simulates a race condition where another thread inserts an entry between a fast-path check and the actual insertion, ensuring the existing entry is returned. ```rust /// Simulates a race where another thread inserted between fast-path check and `entry()`. #[test] fn race_returns_existing() { let map: DashMap>, RandomState> = DashMap::with_hasher(RandomState::new()); let other_cell = Arc::new(PanicAwareCell::new()); map.insert("key".to_string(), Arc::downgrade(&other_cell)); let result = Merger::::insert_or_get_existing(&map, "key"); assert!(Arc::ptr_eq(&result, &other_cell)); } ``` -------------------------------- ### Merger Replaces Expired Entry Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Tests that get_or_create_cell correctly replaces an expired (weakly held) entry with a new one. ```rust #[test] fn replaces_expired_entry() { let map: DashMap>, RandomState> = DashMap::with_hasher(RandomState::new()); let expired_weak = Arc::downgrade(&Arc::new(PanicAwareCell::::new())); map.insert("key".to_string(), expired_weak); let result = Merger::::get_or_create_cell(&map, "key"); let entry = map.get("key").unwrap(); assert!(Arc::ptr_eq(&result, &entry.value().upgrade().unwrap())); } ``` -------------------------------- ### Mutably Borrowing Data Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Provides mutable access to borrowed data. This is a blanket implementation for all types. ```rust fn borrow_mut(&mut self) -> &mut T ``` -------------------------------- ### Deprecated Error Cause for LeaderPanicked Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Returns the cause of the error. This method is deprecated and replaced by `Error::source`. ```rust fn cause(&self) -> Option<&dyn Error> ``` -------------------------------- ### Accessing LeaderPanicked Message Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Retrieves the panic message from the leader task. This message is captured when the LeaderPanicked error is created. ```rust pub fn message(&self) -> &str ``` -------------------------------- ### LeaderPanicked Struct Definition Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.LeaderPanicked.html Defines the LeaderPanicked struct, which is used to signal that a leader task has panicked. It has private fields. ```rust pub struct LeaderPanicked { /* private fields */ } ``` -------------------------------- ### Execute Function with Deduplication Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Executes a given asynchronous function, ensuring only one operation with the same key is in-flight. If a duplicate call occurs, the caller waits for the result of the original operation. ```rust let merger: Merger = Merger::new(); let result = merger.execute("my-key", || async { 42 }).await; assert_eq!(result, Ok(42)); ``` -------------------------------- ### Catching Panics in Async Code Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Verifies that `catch_unwind` correctly catches panics that occur within an asynchronous block. The result should indicate an error if a panic is caught. ```rust let result = AssertUnwindSafe(async { panic!("test panic"); #[expect(unreachable_code, reason = "Required to satisfy return type after panic")] 42i32 }) .catch_unwind() .await; assert!(result.is_err(), "catch_unwind should catch the panic"); ``` -------------------------------- ### Extracting Panic Message from String Payload Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Tests the `extract_panic_message` utility function with a panic payload that is a `String`. It asserts that the function correctly extracts the string content as the panic message. ```rust let payload: Box = Box::new(String::from("owned string panic")); let message = extract_panic_message(&*payload); assert_eq!(&*message, "owned string panic"); ``` -------------------------------- ### ToOwned Trait Implementation Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Provides methods for creating owned data from borrowed data. ```APIDOC ## fn to_owned(&self) -> T ### Description Creates owned data from borrowed data, usually by cloning. ### Method `to_owned` ### Parameters - `&self`: An immutable reference to the borrowed data. ### Response - `T`: The owned data. ## fn clone_into(&self, target: &mut T) ### Description Uses borrowed data to replace owned data, usually by cloning. ### Method `clone_into` ### Parameters - `&self`: An immutable reference to the borrowed data. - `target`: A mutable reference to the owned data to be replaced. ``` -------------------------------- ### LeaderPanicked Error Structure Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Represents an error when a leader task panics. The panic message is captured and accessible. ```rust pub struct LeaderPanicked { message: Arc, } impl LeaderPanicked { /// Returns the panic message from the leader task. #[must_use] pub fn message(&self) -> &str { &self.message } } impl std::fmt::Display for LeaderPanicked { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "leader task panicked: {}", self.message) } } impl std::error::Error for LeaderPanicked {} ``` -------------------------------- ### Merger Struct Definition Source: https://docs.rs/uniflight/0.1.0/uniflight/struct.Merger.html Defines the Merger struct with generic types K (key) and T (value), and an optional Strategy S. The Strategy determines the thread-aware scoping for deduplication. ```rust pub struct Merger { /* private fields */ } ``` -------------------------------- ### Extracting Panic Message from Unknown Type Payload Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Tests the `extract_panic_message` utility function with a panic payload of an unknown type (an `i32`). It asserts that the function returns a default "unknown panic" message in such cases. ```rust let payload: Box = Box::new(42i32); let message = extract_panic_message(&*payload); assert_eq!(&*message, "unknown panic"); ``` -------------------------------- ### Extracting Panic Message Source: https://docs.rs/uniflight/0.1.0/src/uniflight/lib.rs.html Safely extracts a string message from a panic payload, attempting to downcast to &str or String. ```rust fn extract_panic_message(payload: &(dyn std::any::Any + Send)) -> Arc { if let Some(s) = payload.downcast_ref::<&str>() { return Arc::from(*s); } if let Some(s) = payload.downcast_ref::() { return Arc::from(s.as_str()); } Arc::from("unknown panic") } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.