use std::collections::BTreeSet;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use aws_sdk_lambda::types::OperationUpdate;
use tokio::sync::Notify;
use tokio::sync::futures::Notified;
use tokio::task::AbortHandle;
use crate::client::{CheckpointOutput, ExecutionClientError};
use crate::coordinator::{InvocationCoordinator, Permit, PermitKind};
use crate::tracing_layer::PendingTransitionEvent;
#[derive(Debug)]
pub(crate) struct TrackedUpdate {
pub(crate) update: OperationUpdate,
pub(crate) event: Option<PendingTransitionEvent>,
}
impl TrackedUpdate {
pub(crate) fn capture(update: OperationUpdate, attempt: u32) -> Self {
let event = Some(PendingTransitionEvent::capture(&update, attempt));
Self { update, event }
}
pub(crate) fn untracked(update: OperationUpdate) -> Self {
Self {
update,
event: None,
}
}
}
#[derive(Debug, Default)]
pub(crate) struct Admission {
state: Mutex<AdmissionState>,
}
#[derive(Debug, Default)]
struct AdmissionState {
abandoned: BTreeSet<String>,
tasks: Vec<(Vec<String>, AbortHandle)>,
}
impl Admission {
pub(crate) fn new() -> Self {
Self::default()
}
fn lock(&self) -> std::sync::MutexGuard<'_, AdmissionState> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn abandon<'a>(&self, owners: impl IntoIterator<Item = &'a str>) {
let stopped = {
let mut guard = self.lock();
let state = &mut *guard;
state
.abandoned
.extend(owners.into_iter().map(str::to_owned));
let abandoned = &state.abandoned;
let (stopped, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut state.tasks)
.into_iter()
.partition(|(owners, _)| owners.iter().any(|owner| abandoned.contains(owner)));
state.tasks = kept;
stopped
};
for (_, task) in stopped {
task.abort();
}
}
pub(crate) fn admits(&self, owners: &[String]) -> bool {
let state = self.lock();
!owners.iter().any(|owner| state.abandoned.contains(owner))
}
#[cfg(test)]
pub(crate) fn has_task_in(&self, owner: &str) -> bool {
self.lock()
.tasks
.iter()
.any(|(owners, _)| owners.iter().any(|o| o == owner))
}
pub(crate) fn register_task(&self, owners: &[String], task: AbortHandle) {
let late = {
let mut state = self.lock();
if owners.iter().any(|owner| state.abandoned.contains(owner)) {
Some(task)
} else {
state.tasks.retain(|(_, task)| !task.is_finished());
state.tasks.push((owners.to_vec(), task));
None
}
};
if let Some(task) = late {
task.abort();
}
}
#[cfg(test)]
fn registered(&self) -> usize {
self.lock().tasks.len()
}
}
pub(crate) struct ScopeClose {
admission: Arc<Admission>,
scope: String,
}
impl ScopeClose {
pub(crate) fn new(admission: &Arc<Admission>, scope: &str) -> Self {
Self {
admission: Arc::clone(admission),
scope: scope.to_owned(),
}
}
}
impl Drop for ScopeClose {
fn drop(&mut self) {
self.admission.abandon([self.scope.as_str()]);
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct BatchLimits {
pub(crate) max_operations: usize,
pub(crate) max_payload_bytes: usize,
}
impl Default for BatchLimits {
fn default() -> Self {
Self {
max_operations: 250,
max_payload_bytes: 750 * 1024,
}
}
}
pub(crate) fn json_escaped_len(s: &str) -> usize {
s.chars()
.map(|c| match c {
'"' | '\\' | '\u{08}' | '\t' | '\n' | '\u{0C}' | '\r' => 2,
c if (c as u32) < 0x20 => 6,
c => c.len_utf8(),
})
.sum()
}
pub(crate) fn estimated_update_size(update: &OperationUpdate) -> usize {
const STRUCTURAL_OVERHEAD: usize = 256;
let opt_len = |s: &Option<String>| s.as_deref().map_or(0, json_escaped_len);
let error_len = update.error.as_ref().map_or(0, |e| {
e.error_message.as_deref().map_or(0, json_escaped_len)
+ e.error_type.as_deref().map_or(0, json_escaped_len)
+ e.error_data.as_deref().map_or(0, json_escaped_len)
+ e.stack_trace()
.iter()
.map(|s| json_escaped_len(s))
.sum::<usize>()
});
json_escaped_len(&update.id)
+ opt_len(&update.parent_id)
+ opt_len(&update.name)
+ opt_len(&update.sub_type)
+ opt_len(&update.payload)
+ error_len
+ STRUCTURAL_OVERHEAD
}
pub(crate) fn split_into_requests(
updates: Vec<TrackedUpdate>,
limits: &BatchLimits,
) -> Vec<Vec<TrackedUpdate>> {
let mut requests: Vec<Vec<TrackedUpdate>> = Vec::new();
let mut current: Vec<TrackedUpdate> = Vec::new();
let mut current_bytes = 0_usize;
for tracked in updates {
let size = estimated_update_size(&tracked.update);
let over_count = current.len() >= limits.max_operations.max(1);
let over_bytes = !current.is_empty() && current_bytes + size > limits.max_payload_bytes;
if over_count || over_bytes {
requests.push(std::mem::take(&mut current));
current_bytes = 0;
}
current_bytes += size;
current.push(tracked);
}
if !current.is_empty() {
requests.push(current);
}
requests
}
#[derive(Debug)]
pub(crate) struct CheckpointCoalescer {
delay: Duration,
state: Mutex<CoalescerState>,
writer: tokio::sync::Mutex<()>,
limits: BatchLimits,
unheld: Notify,
}
#[derive(Debug, Default)]
struct CoalescerState {
pending: Vec<TrackedUpdate>,
permits: Vec<Permit>,
batch: Option<Arc<CheckpointBatch>>,
holds: usize,
}
#[derive(Debug)]
pub(crate) struct BatchPermits {
#[cfg_attr(not(test), expect(dead_code))]
held: Vec<Permit>,
}
impl BatchPermits {
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.held.len()
}
}
#[derive(Debug, Default)]
pub(crate) struct CheckpointBatch {
notify: Notify,
result: Mutex<Option<Result<CheckpointOutput, ExecutionClientError>>>,
refresh_id: Mutex<Option<String>>,
}
impl CheckpointBatch {
pub(crate) fn result_clone(&self) -> Option<Result<CheckpointOutput, ExecutionClientError>> {
self.result
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
pub(crate) fn publish(&self, result: Result<CheckpointOutput, ExecutionClientError>) {
*self.result.lock().unwrap_or_else(PoisonError::into_inner) = Some(result);
self.notify.notify_waiters();
}
pub(crate) fn refresh_id(&self) -> Option<String> {
self.refresh_id
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
pub(crate) fn notified(&self) -> Notified<'_> {
self.notify.notified()
}
}
impl CheckpointCoalescer {
pub(crate) fn new(delay: Duration) -> Self {
Self::with_limits(delay, BatchLimits::default())
}
pub(crate) fn with_limits(delay: Duration, limits: BatchLimits) -> Self {
Self {
delay,
state: Mutex::new(CoalescerState::default()),
writer: tokio::sync::Mutex::new(()),
limits,
unheld: Notify::new(),
}
}
pub(crate) fn delay(&self) -> Duration {
self.delay
}
pub(crate) fn limits(&self) -> BatchLimits {
self.limits
}
pub(crate) fn writer_lock(&self) -> &tokio::sync::Mutex<()> {
&self.writer
}
#[cfg(test)]
pub(crate) fn join(
&self,
admission: &Admission,
coordinator: &Arc<InvocationCoordinator>,
owners: &[String],
updates: Vec<TrackedUpdate>,
) -> Option<(Arc<CheckpointBatch>, bool)> {
self.join_owned(admission, coordinator, owners, updates, None, false)
}
pub(crate) fn join_owned(
&self,
admission: &Admission,
coordinator: &Arc<InvocationCoordinator>,
owners: &[String],
updates: Vec<TrackedUpdate>,
refresh_id: Option<&str>,
reserve: bool,
) -> Option<(Arc<CheckpointBatch>, bool)> {
#[cfg(test)]
crate::coordinator::race_points::reach(
crate::coordinator::race_points::RacePoint::BufferLock,
);
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
if !admission.admits(owners) {
return None;
}
let permit = coordinator.acquire(PermitKind::Checkpoint)?;
state.pending.extend(updates);
state.permits.push(permit);
if reserve {
state.holds = state.holds.saturating_add(1);
}
let opened = state.batch.is_none();
let batch = Arc::clone(state.batch.get_or_insert_with(Arc::default));
if let Some(refresh_id) = refresh_id {
batch
.refresh_id
.lock()
.unwrap_or_else(PoisonError::into_inner)
.get_or_insert_with(|| refresh_id.to_owned());
}
Some((batch, opened))
}
pub(crate) fn release_hold(&self) {
{
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
state.holds = state.holds.saturating_sub(1);
}
self.unheld.notify_waiters();
}
async fn when_unheld<T>(&self, take: impl Fn(&mut CoalescerState) -> T) -> T {
loop {
let mut unheld = std::pin::pin!(self.unheld.notified());
unheld.as_mut().enable();
{
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
if state.holds == 0 {
return take(&mut state);
}
}
unheld.await;
}
}
pub(crate) async fn take_batch_unheld(
&self,
target: &Arc<CheckpointBatch>,
) -> Option<(Vec<TrackedUpdate>, BatchPermits)> {
self.when_unheld(|state| take_target(state, target)).await
}
pub(crate) fn claim_unspawned(
&self,
target: &Arc<CheckpointBatch>,
coordinator: &InvocationCoordinator,
) -> Option<(Vec<TrackedUpdate>, BatchPermits)> {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
if coordinator.write_failed() {
return None;
}
take_target(&mut state, target)
}
#[cfg(test)]
pub(crate) fn take_batch(
&self,
target: &Arc<CheckpointBatch>,
) -> Option<(Vec<TrackedUpdate>, BatchPermits)> {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
take_target(&mut state, target)
}
pub(crate) async fn take_any_unheld(
&self,
) -> Option<(Arc<CheckpointBatch>, Vec<TrackedUpdate>, BatchPermits)> {
self.when_unheld(take_open).await
}
#[cfg(test)]
pub(crate) fn take_any(
&self,
) -> Option<(Arc<CheckpointBatch>, Vec<TrackedUpdate>, BatchPermits)> {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
take_open(&mut state)
}
pub(crate) fn abandon_pending(&self) -> BatchPermits {
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
state.batch = None;
state.pending.clear();
BatchPermits {
held: std::mem::take(&mut state.permits),
}
}
#[cfg(test)]
pub(crate) fn hold_buffer_lock(&self) -> impl Sized + '_ {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
pub(crate) fn pending_len(&self) -> usize {
self.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.pending
.len()
}
#[cfg(test)]
pub(crate) fn pending_ids(&self) -> Vec<String> {
self.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
.pending
.iter()
.map(|tracked| tracked.update.id().to_owned())
.collect()
}
}
fn take_target(
state: &mut CoalescerState,
target: &Arc<CheckpointBatch>,
) -> Option<(Vec<TrackedUpdate>, BatchPermits)> {
match &state.batch {
Some(open) if Arc::ptr_eq(open, target) => {
state.batch = None;
Some((
std::mem::take(&mut state.pending),
BatchPermits {
held: std::mem::take(&mut state.permits),
},
))
}
_ => None,
}
}
fn take_open(
state: &mut CoalescerState,
) -> Option<(Arc<CheckpointBatch>, Vec<TrackedUpdate>, BatchPermits)> {
let batch = state.batch.take()?;
Some((
batch,
std::mem::take(&mut state.pending),
BatchPermits {
held: std::mem::take(&mut state.permits),
},
))
}
#[cfg(test)]
#[expect(clippy::disallowed_methods)]
mod tests {
use super::*;
fn dummy_update(id: &str) -> OperationUpdate {
OperationUpdate::builder()
.id(id.to_owned())
.r#type(aws_sdk_lambda::types::OperationType::Step)
.action(aws_sdk_lambda::types::OperationAction::Start)
.build()
.expect("all required OperationUpdate fields set")
}
fn track(update: OperationUpdate) -> TrackedUpdate {
TrackedUpdate::capture(update, 1)
}
fn join(coalescer: &CheckpointCoalescer, id: &str) -> Arc<CheckpointBatch> {
coalescer
.join(
&Admission::new(),
&InvocationCoordinator::new(),
&[],
vec![track(dummy_update(id))],
)
.expect("the root is always admitted")
.0
}
#[test]
fn admission_rejects_an_abandoned_owner_and_its_descendants() {
let admission = Admission::new();
let outer = vec!["item".to_owned()];
let nested = vec!["item".to_owned(), "inner".to_owned()];
let sibling = vec!["other".to_owned()];
assert!(admission.admits(&outer), "nothing is abandoned yet");
admission.abandon(["item"]);
assert!(!admission.admits(&outer), "the abandoned owner is rejected");
assert!(
!admission.admits(&nested),
"a context nested in the abandoned owner is rejected"
);
assert!(admission.admits(&sibling), "a sibling owner is admitted");
assert!(admission.admits(&[]), "the root is admitted");
}
fn parked() -> (tokio::task::JoinHandle<()>, AbortHandle) {
#[expect(clippy::disallowed_methods)]
let task = tokio::spawn(std::future::pending::<()>());
let abort = task.abort_handle();
(task, abort)
}
async fn is_cancelled(task: tokio::task::JoinHandle<()>) -> bool {
tokio::time::timeout(Duration::from_secs(5), task)
.await
.is_ok_and(|joined| joined.is_err_and(|err| err.is_cancelled()))
}
#[tokio::test]
async fn closing_a_scope_aborts_its_nested_tasks_only() {
let admission = Admission::new();
let (nested, nested_abort) = parked();
let (sibling, sibling_abort) = parked();
admission.register_task(&["item".to_owned(), "inner".to_owned()], nested_abort);
admission.register_task(&["other".to_owned()], sibling_abort);
admission.abandon(["item"]);
assert!(is_cancelled(nested).await, "the nested task is aborted");
assert!(!sibling.is_finished(), "the sibling task keeps running");
assert_eq!(admission.registered(), 1, "the sibling stays registered");
sibling.abort();
}
#[tokio::test]
async fn a_task_registered_in_a_closed_scope_is_aborted_at_once() {
let admission = Admission::new();
admission.abandon(["item"]);
let (task, abort) = parked();
admission.register_task(&["item".to_owned()], abort);
assert!(is_cancelled(task).await, "the late task is aborted");
assert_eq!(admission.registered(), 0);
}
#[tokio::test]
async fn registration_forgets_finished_tasks() {
let admission = Admission::new();
let (finished, finished_abort) = parked();
finished.abort();
assert!(is_cancelled(finished).await);
admission.register_task(&["a".to_owned()], finished_abort);
let (running, running_abort) = parked();
admission.register_task(&["b".to_owned()], running_abort);
assert_eq!(admission.registered(), 1, "the finished task is forgotten");
running.abort();
}
#[tokio::test]
async fn scope_close_closes_its_scope_on_drop() {
let admission = Arc::new(Admission::new());
let guard = ScopeClose::new(&admission, "item");
assert!(admission.admits(&["item".to_owned()]));
drop(guard);
assert!(!admission.admits(&["item".to_owned()]));
}
#[test]
fn join_buffers_nothing_for_an_abandoned_owner() {
let coalescer = CheckpointCoalescer::new(Duration::ZERO);
let admission = Admission::new();
admission.abandon(["item"]);
let rejected = coalescer.join(
&admission,
&InvocationCoordinator::new(),
&["item".to_owned()],
vec![track(dummy_update("a"))],
);
assert!(rejected.is_none(), "the rejected join returns no batch");
assert!(
coalescer.take_any().is_none(),
"the rejected join opened no batch and buffered nothing"
);
}
fn dummy_output() -> CheckpointOutput {
CheckpointOutput {
checkpoint_token: Some("token-1".to_owned()),
updated_operations: Vec::new(),
next_marker: None,
}
}
#[test]
fn joins_accumulate_into_one_batch() {
let coalescer = CheckpointCoalescer::new(Duration::from_millis(10));
let first = join(&coalescer, "a");
let second = join(&coalescer, "b");
assert!(
Arc::ptr_eq(&first, &second),
"concurrent joins share one batch"
);
let (updates, permits) = coalescer.take_batch(&first).expect("batch is open");
assert_eq!(updates.len(), 2, "both joins' updates drain together");
assert_eq!(permits.len(), 2, "each join's permit drains with them");
}
#[test]
fn take_batch_is_a_no_op_for_a_stale_batch() {
let coalescer = CheckpointCoalescer::new(Duration::from_millis(10));
let old = join(&coalescer, "a");
assert!(coalescer.take_batch(&old).is_some());
let new = join(&coalescer, "b");
assert!(!Arc::ptr_eq(&old, &new), "a fresh batch opened");
assert!(
coalescer.take_batch(&old).is_none(),
"stale flusher must not steal the newer batch"
);
assert_eq!(
coalescer.take_any().map(|(_, u, _)| u.len()),
Some(1),
"the newer batch still holds its update"
);
}
#[test]
fn take_any_on_idle_buffer_is_none() {
let coalescer = CheckpointCoalescer::new(Duration::from_millis(10));
assert!(coalescer.take_any().is_none());
}
#[test]
fn split_respects_operation_count_cap_and_preserves_order() {
let limits = BatchLimits {
max_operations: 2,
max_payload_bytes: usize::MAX,
};
let updates = vec![
track(dummy_update("a")),
track(dummy_update("b")),
track(dummy_update("c")),
track(dummy_update("d")),
track(dummy_update("e")),
];
let requests = split_into_requests(updates, &limits);
assert_eq!(
requests.iter().map(Vec::len).collect::<Vec<_>>(),
vec![2, 2, 1],
"five updates under a two-op cap split into 2+2+1"
);
let flat: Vec<&str> = requests
.iter()
.flatten()
.map(|t| t.update.id.as_str())
.collect();
assert_eq!(
flat,
vec!["a", "b", "c", "d", "e"],
"join order is preserved across splits"
);
}
#[test]
fn split_respects_payload_byte_cap() {
let payload_update = |id: &str, payload_len: usize| {
OperationUpdate::builder()
.id(id.to_owned())
.r#type(aws_sdk_lambda::types::OperationType::Step)
.action(aws_sdk_lambda::types::OperationAction::Succeed)
.payload("x".repeat(payload_len))
.build()
.expect("all required OperationUpdate fields set")
};
let limits = BatchLimits {
max_operations: usize::MAX,
max_payload_bytes: 2560,
};
let updates = vec![
track(payload_update("a", 1024)),
track(payload_update("b", 1024)),
track(payload_update("c", 1024)),
];
let requests = split_into_requests(updates, &limits);
assert_eq!(
requests.iter().map(Vec::len).collect::<Vec<_>>(),
vec![1, 1, 1],
"1 KiB payloads plus overhead exceed the cap pairwise, so each goes alone"
);
let small = vec![
track(payload_update("a", 10)),
track(payload_update("b", 10)),
];
let requests = split_into_requests(small, &limits);
assert_eq!(
requests.len(),
1,
"small updates within the cap stay in one request"
);
}
#[test]
fn oversized_single_update_goes_alone() {
let big = OperationUpdate::builder()
.id("big".to_owned())
.r#type(aws_sdk_lambda::types::OperationType::Step)
.action(aws_sdk_lambda::types::OperationAction::Succeed)
.payload("x".repeat(4096))
.build()
.expect("all required OperationUpdate fields set");
let limits = BatchLimits {
max_operations: 10,
max_payload_bytes: 1024,
};
let requests = split_into_requests(
vec![
track(dummy_update("a")),
track(big),
track(dummy_update("b")),
],
&limits,
);
assert_eq!(
requests.iter().map(Vec::len).collect::<Vec<_>>(),
vec![1, 1, 1],
"an update larger than the cap is emitted as its own request"
);
let middle = requests
.get(1)
.and_then(|r| r.first())
.expect("the middle request holds the oversized update");
assert_eq!(middle.update.id, "big");
}
#[test]
fn estimated_size_counts_payload_and_error_strings() {
let with_payload = OperationUpdate::builder()
.id("p".to_owned())
.r#type(aws_sdk_lambda::types::OperationType::Step)
.action(aws_sdk_lambda::types::OperationAction::Succeed)
.payload("y".repeat(500))
.build()
.expect("all required OperationUpdate fields set");
let bare = dummy_update("p");
assert!(
estimated_update_size(&with_payload) >= estimated_update_size(&bare) + 500,
"the payload string must count toward the estimate"
);
}
#[test]
fn json_escaped_len_matches_serde_json_output() {
let cases = [
"plain alphanumeric text",
r#"quote-heavy "" \" \\ payload"#,
"control\tchars\nand\rmore\u{08}\u{0C}",
"\u{01}\u{1F}", "unicode: héllo wörld – 日本語 🦀",
"",
];
for s in cases {
let wire = serde_json::to_string(s).expect("string serializes");
assert_eq!(
json_escaped_len(s),
wire.len() - 2, "escaped length must match serde_json wire bytes for {s:?}"
);
}
}
#[test]
fn split_accounts_for_json_escaping_of_payloads() {
let quote_update = |id: &str| {
OperationUpdate::builder()
.id(id.to_owned())
.r#type(aws_sdk_lambda::types::OperationType::Step)
.action(aws_sdk_lambda::types::OperationAction::Succeed)
.payload("\"".repeat(1000))
.build()
.expect("all required OperationUpdate fields set")
};
let limits = BatchLimits {
max_operations: usize::MAX,
max_payload_bytes: 3000,
};
let updates = vec![track(quote_update("a")), track(quote_update("b"))];
let requests = split_into_requests(updates, &limits);
assert_eq!(
requests.iter().map(Vec::len).collect::<Vec<_>>(),
vec![1, 1],
"escape-heavy payloads must split on their wire size, not raw bytes"
);
}
#[test]
fn estimated_size_uses_escaped_bytes_for_all_string_fields() {
let escaped = OperationUpdate::builder()
.id("\"\"".to_owned())
.r#type(aws_sdk_lambda::types::OperationType::Step)
.action(aws_sdk_lambda::types::OperationAction::Succeed)
.name("\\\\".to_owned())
.payload("\n\n".to_owned())
.build()
.expect("all required OperationUpdate fields set");
let plain = OperationUpdate::builder()
.id("xx".to_owned())
.r#type(aws_sdk_lambda::types::OperationType::Step)
.action(aws_sdk_lambda::types::OperationAction::Succeed)
.name("xx".to_owned())
.payload("xx".to_owned())
.build()
.expect("all required OperationUpdate fields set");
assert_eq!(
estimated_update_size(&escaped),
estimated_update_size(&plain) + 6,
"each of the six escapable characters must count as two wire bytes"
);
}
#[tokio::test]
async fn publish_wakes_an_enabled_waiter() {
let batch = Arc::new(CheckpointBatch::default());
let waiter = {
let batch = Arc::clone(&batch);
tokio::spawn(async move {
loop {
let mut notified = std::pin::pin!(batch.notified());
notified.as_mut().enable();
if let Some(result) = batch.result_clone() {
return result;
}
notified.await;
}
})
};
batch.publish(Ok(dummy_output()));
let result = waiter.await.expect("waiter task completes");
assert_eq!(
result.expect("published Ok").checkpoint_token(),
Some("token-1"),
"waiter observes the published result"
);
}
#[test]
fn batch_keeps_the_first_refresh_id() {
let coordinator = InvocationCoordinator::new();
let coalescer = CheckpointCoalescer::new(Duration::ZERO);
let admission = Admission::new();
let join = |refresh_id: Option<&str>| {
coalescer
.join_owned(&admission, &coordinator, &[], Vec::new(), refresh_id, false)
.expect("admitted")
.0
};
let batch = join(None);
assert_eq!(batch.refresh_id(), None);
join(Some("first"));
join(Some("second"));
join(None);
assert_eq!(batch.refresh_id().as_deref(), Some("first"));
}
#[test]
fn admitted_join_holds_a_checkpoint_permit_until_the_batch_is_released() {
let coordinator = InvocationCoordinator::new();
let coalescer = CheckpointCoalescer::new(Duration::ZERO);
let (batch, opened) = coalescer
.join(
&Admission::new(),
&coordinator,
&[],
vec![track(dummy_update("a"))],
)
.expect("admitted");
assert!(opened, "the first join opens the batch");
let (_, second_opened) = coalescer
.join(
&Admission::new(),
&coordinator,
&[],
vec![track(dummy_update("b"))],
)
.expect("admitted");
assert!(!second_opened, "a later join joins the open batch");
assert_eq!(coordinator.permits(PermitKind::Checkpoint), 2);
let (_, permits) = coalescer.take_batch(&batch).expect("open");
assert_eq!(coordinator.permits(PermitKind::Checkpoint), 2);
drop(permits);
assert_eq!(coordinator.permits(PermitKind::Checkpoint), 0);
}
#[test]
fn join_after_suspension_buffers_nothing() {
let coordinator = InvocationCoordinator::new();
coordinator.finish();
let coalescer = CheckpointCoalescer::new(Duration::ZERO);
let refused = coalescer.join(
&Admission::new(),
&coordinator,
&[],
vec![track(dummy_update("a"))],
);
assert!(refused.is_none());
assert!(coalescer.take_any().is_none(), "nothing was buffered");
}
}