Skip to main content

scopedb_client/
append_stream.rs

1// Copyright 2024 ScopeDB, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16use std::mem;
17use std::panic::AssertUnwindSafe;
18use std::sync::Arc;
19use std::sync::Mutex;
20use std::sync::MutexGuard;
21use std::time::Duration;
22use std::time::Instant;
23use std::time::SystemTime;
24
25use serde::Serialize;
26use tokio::sync::Notify;
27use tokio::sync::OwnedSemaphorePermit;
28use tokio::sync::Semaphore;
29use tokio::sync::mpsc;
30use tokio::sync::oneshot;
31use tokio::task::JoinHandle;
32use tokio::task::JoinSet;
33
34use crate::AppendDeliveryOutcome;
35use crate::AppendErrorDetails;
36use crate::AppendFailurePolicy;
37use crate::AppendOutcome;
38use crate::AppendRowsResult;
39use crate::Error;
40use crate::ErrorKind;
41use crate::ErrorOperation;
42use crate::Table;
43use crate::append::AppendOptions;
44use crate::append::RecordError;
45use crate::append::append_batch;
46use crate::append::config_error;
47use crate::append::encode_record;
48use crate::append::validate_deadline;
49use crate::append::validate_positive;
50
51const DEFAULT_FLUSH_INTERVAL: Duration = Duration::from_secs(1);
52const DEFAULT_CHANNEL_CAPACITY: usize = 1024;
53const DEFAULT_MAX_PENDING_BYTES: usize = 64 * 1024 * 1024;
54const DEFAULT_CIRCUIT_FAILURE_THRESHOLD: usize = 5;
55const DEFAULT_CIRCUIT_COOLDOWN: Duration = Duration::from_secs(30);
56
57/// Lifecycle state of an [`AppendStream`].
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum AppendStreamState {
61    Open,
62    Closing,
63    Closed,
64    Failed,
65}
66
67/// State of the [`AppendFailurePolicy::Continue`] availability circuit breaker.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[non_exhaustive]
70pub enum AppendCircuitState {
71    Closed,
72    Open,
73    HalfOpen,
74}
75
76/// Number of rows admitted to an [`AppendStream`] by [`AppendStream::send_all`].
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub struct AppendAdmissionResult {
79    pub accepted_rows: u64,
80}
81
82/// Settlement counts for an [`AppendStream`] interval since the previous completed barrier.
83///
84/// Counts aggregate across batches in the interval and do not identify
85/// individual rows; use application keys to reconcile rows when
86/// `ambiguous_rows > 0` or `outcome == AppendDeliveryOutcome::Partial`.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct AppendDeliveryReport {
89    pub outcome: AppendDeliveryOutcome,
90    pub accepted_rows: u64,
91    /// Rows in batches acknowledged as committed.
92    pub committed_rows: u64,
93    pub failed_rows: u64,
94    pub ambiguous_rows: u64,
95    pub dropped_rows: u64,
96    pub committed_batches: u64,
97    pub failed_batches: u64,
98    pub ambiguous_batches: u64,
99    pub retries: u64,
100    /// Elapsed wall time waiting for this barrier.
101    pub duration: Duration,
102}
103
104/// Cumulative rows rejected at local [`AppendStream::try_send`] admission, by reason.
105#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
106pub struct AppendDroppedRows {
107    pub buffer_full: u64,
108    pub invalid_record: u64,
109    pub record_too_large: u64,
110    pub circuit_open: u64,
111    pub closed: u64,
112}
113
114/// Most recent remote batch failure observed by an [`AppendStream`].
115#[derive(Debug, Clone)]
116pub struct AppendLastFailure {
117    pub at: SystemTime,
118    pub error: Error,
119}
120
121/// Point-in-time cumulative counters and state for an [`AppendStream`].
122#[derive(Debug, Clone)]
123pub struct AppendStreamStats {
124    pub state: AppendStreamState,
125    pub circuit_state: AppendCircuitState,
126    pub accepted_rows: u64,
127    pub committed_rows: u64,
128    pub failed_rows: u64,
129    pub ambiguous_rows: u64,
130    pub dropped_rows: u64,
131    pub dropped_by_reason: AppendDroppedRows,
132    pub retries: u64,
133    pub pending_rows: u64,
134    pub pending_bytes: usize,
135    pub in_flight_batches: usize,
136    pub last_failure: Option<AppendLastFailure>,
137    pub last_report: Option<AppendDeliveryReport>,
138}
139
140/// Stream action taken after a batch failure in [`AppendBatchFailureEvent`].
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum AppendBatchFailureAction {
144    Continuing,
145    CircuitOpened,
146    Stopped,
147}
148
149/// Event passed to [`AppendStreamBuilder::on_batch_failure`] when a batch fails after retries.
150pub struct AppendBatchFailureEvent {
151    pub error: Error,
152    pub batch_rows: usize,
153    pub batch_bytes: usize,
154    pub outcome: AppendOutcome,
155    pub action: AppendBatchFailureAction,
156}
157
158impl fmt::Debug for AppendBatchFailureEvent {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        f.debug_struct("AppendBatchFailureEvent")
161            .field("error", &self.error)
162            .field("batch_rows", &self.batch_rows)
163            .field("batch_bytes", &self.batch_bytes)
164            .field("outcome", &self.outcome)
165            .field("action", &self.action)
166            .finish()
167    }
168}
169
170/// Availability circuit breaker settings for [`AppendFailurePolicy::Continue`].
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172#[non_exhaustive]
173pub struct AppendCircuitBreakerOptions {
174    pub failure_threshold: usize,
175    pub cooldown: Duration,
176}
177
178impl AppendCircuitBreakerOptions {
179    pub fn new(failure_threshold: usize, cooldown: Duration) -> Self {
180        Self {
181            failure_threshold,
182            cooldown,
183        }
184    }
185}
186
187impl Default for AppendCircuitBreakerOptions {
188    fn default() -> Self {
189        Self::new(DEFAULT_CIRCUIT_FAILURE_THRESHOLD, DEFAULT_CIRCUIT_COOLDOWN)
190    }
191}
192
193/// Synchronous local-admission error returned by [`AppendStream::try_send`].
194#[derive(Debug)]
195#[non_exhaustive]
196pub enum AppendTrySendError {
197    Serialization(serde_json::Error),
198    InvalidRecord,
199    RecordTooLarge { bytes: usize, limit: usize },
200    BufferFull,
201    CircuitOpen,
202    Closed,
203}
204
205impl From<RecordError> for AppendTrySendError {
206    fn from(error: RecordError) -> Self {
207        match error {
208            RecordError::Serialization(error) => Self::Serialization(error),
209            RecordError::InvalidRecord => Self::InvalidRecord,
210            RecordError::RecordTooLarge { bytes, limit } => Self::RecordTooLarge { bytes, limit },
211        }
212    }
213}
214
215impl fmt::Display for AppendTrySendError {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        match self {
218            Self::Serialization(err) => write!(f, "failed to serialize append row: {err}"),
219            Self::InvalidRecord => write!(f, "append row must serialize to a JSON object"),
220            Self::RecordTooLarge { bytes, limit } => {
221                write!(
222                    f,
223                    "append row is {bytes} bytes, exceeding the {limit}-byte limit"
224                )
225            }
226            Self::BufferFull => write!(f, "append stream local buffer is full"),
227            Self::CircuitOpen => write!(f, "append stream circuit breaker is open"),
228            Self::Closed => write!(f, "append stream is closed"),
229        }
230    }
231}
232
233impl std::error::Error for AppendTrySendError {
234    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
235        match self {
236            Self::Serialization(err) => Some(err),
237            _ => None,
238        }
239    }
240}
241
242type BatchFailureListener = Arc<dyn Fn(&AppendBatchFailureEvent) + Send + Sync>;
243
244/// Builder for an [`AppendStream`].
245///
246/// Defaults to 4 MiB target batches, 4 concurrent requests, and
247/// [`AppendFailurePolicy::Stop`]. Validated HTTP 429 admission refusals are retried; retrying
248/// ambiguous outcomes requires opting into [`retry_ambiguous`](Self::retry_ambiguous).
249///
250/// # Telemetry
251///
252/// For log or telemetry sinks that should keep running after a batch fails, use
253/// [`AppendFailurePolicy::Continue`] with [`AppendStream::try_send`] and monitor
254/// [`AppendStream::stats`] or [`on_batch_failure`](Self::on_batch_failure):
255///
256/// ```no_run
257/// use scopedb_client::AppendFailurePolicy;
258///
259/// # async fn example(client: scopedb_client::Client) -> Result<(), scopedb_client::Error> {
260/// let stream = client.table("events").append_stream()
261///     .failure_policy(AppendFailurePolicy::Continue)
262///     .max_concurrent_batches(1)
263///     .build()?;
264///
265/// if let Err(error) = stream.try_send(&serde_json::json!({"name": "request.completed"})) {
266///     eprintln!("telemetry row not admitted: {error}");
267/// }
268/// let report = stream.shutdown().await?;
269/// println!("Write results: {report:?}");
270/// # Ok(())
271/// # }
272/// ```
273pub struct AppendStreamBuilder {
274    table: Table,
275    flush_interval: Duration,
276    channel_capacity: usize,
277    max_pending_bytes: usize,
278    failure_policy: AppendFailurePolicy,
279    circuit_breaker: Option<AppendCircuitBreakerOptions>,
280    batch_failure_listeners: Vec<BatchFailureListener>,
281    options: AppendOptions,
282}
283
284impl AppendStreamBuilder {
285    /// Sets whether the stream stops or continues after a batch fails (default
286    /// [`AppendFailurePolicy::Stop`]).
287    pub fn failure_policy(mut self, failure_policy: AppendFailurePolicy) -> Self {
288        self.failure_policy = failure_policy;
289        self
290    }
291
292    /// Sets the target uncompressed NDJSON batch size (default 4 MiB, maximum 8 MiB).
293    ///
294    /// A single row larger than this target is sent in its own batch up to 8 MiB.
295    pub fn target_batch_bytes(mut self, target_batch_bytes: usize) -> Self {
296        self.options.batch_bytes = target_batch_bytes;
297        self
298    }
299
300    /// Sets the maximum rows per HTTP batch (default and maximum 200,000).
301    pub fn max_batch_rows(mut self, max_batch_rows: usize) -> Self {
302        self.options.max_batch_rows = max_batch_rows;
303        self
304    }
305
306    /// Sets the flush interval for partially filled batches (default 1 s).
307    pub fn flush_interval(mut self, flush_interval: Duration) -> Self {
308        self.flush_interval = flush_interval;
309        self
310    }
311
312    /// Sets the maximum number of queued commands in the local admission channel (default 1,024).
313    pub fn channel_capacity(mut self, channel_capacity: usize) -> Self {
314        self.channel_capacity = channel_capacity;
315        self
316    }
317
318    /// Sets the maximum uncompressed bytes admitted locally and awaiting remote settlement (default
319    /// 64 MiB).
320    pub fn max_buffered_bytes(mut self, max_buffered_bytes: usize) -> Self {
321        self.max_pending_bytes = max_buffered_bytes;
322        self
323    }
324
325    /// Sets the maximum in-flight HTTP batches for this stream (default 4).
326    pub fn max_concurrent_batches(mut self, max_concurrent_batches: usize) -> Self {
327        self.options.max_in_flight_requests = max_concurrent_batches;
328        self
329    }
330
331    /// Sets the maximum retry attempts after an initial batch failure (default 8).
332    pub fn max_retries(mut self, max_retries: usize) -> Self {
333        self.options.retry.max_retries = max_retries;
334        self
335    }
336
337    /// Enables retrying transient [`AppendOutcome::Ambiguous`] responses (default `false`).
338    ///
339    /// Retrying an ambiguous outcome can insert duplicate rows. Client timeouts
340    /// are never replayed automatically.
341    pub fn retry_ambiguous(mut self, enabled: bool) -> Self {
342        self.options.retry.retry_ambiguous = enabled;
343        self
344    }
345
346    /// Sets the initial retry backoff delay (default 100 ms).
347    pub fn initial_backoff(mut self, initial_backoff: Duration) -> Self {
348        self.options.retry.initial_backoff = initial_backoff;
349        self
350    }
351
352    /// Sets the maximum retry delay, capping exponential backoff and `Retry-After` headers (default
353    /// 5 s).
354    pub fn max_backoff(mut self, max_backoff: Duration) -> Self {
355        self.options.retry.max_backoff = max_backoff;
356        self
357    }
358
359    /// Overrides the client's [`ClientBuilder::write_timeout`](crate::ClientBuilder::write_timeout)
360    /// with a positive per-attempt timeout.
361    pub fn attempt_timeout(mut self, attempt_timeout: Duration) -> Self {
362        self.options.attempt_timeout = Some(attempt_timeout);
363        self
364    }
365
366    /// Configures the [`AppendFailurePolicy::Continue`] circuit breaker, or disables it with
367    /// `None`.
368    ///
369    /// Defaults to opening for 30 seconds after 5 consecutive availability failures.
370    pub fn circuit_breaker(mut self, circuit_breaker: Option<AppendCircuitBreakerOptions>) -> Self {
371        self.circuit_breaker = circuit_breaker;
372        self
373    }
374
375    /// Registers a synchronous callback for a batch's final failure.
376    pub fn on_batch_failure<F>(mut self, listener: F) -> Self
377    where
378        F: Fn(&AppendBatchFailureEvent) + Send + Sync + 'static,
379    {
380        self.batch_failure_listeners.push(Arc::new(listener));
381        self
382    }
383
384    /// Validates configuration and spawns the background stream worker on the current Tokio
385    /// runtime.
386    pub fn build(self) -> Result<AppendStream, Error> {
387        validate_builder(&self)
388            .map_err(|error| error.with_operation(ErrorOperation::BuildAppendStream))?;
389        tokio::runtime::Handle::try_current().map_err(|err| {
390            Error::new(
391                ErrorKind::InvalidInput,
392                ErrorOperation::BuildAppendStream,
393                "append stream must be built inside a Tokio runtime",
394            )
395            .set_source(err)
396        })?;
397
398        Ok(AppendStream::new(AppendStreamConfig {
399            table: self.table,
400            options: self.options,
401            flush_interval: self.flush_interval,
402            channel_capacity: self.channel_capacity,
403            max_pending_bytes: self.max_pending_bytes,
404            failure_policy: self.failure_policy,
405            circuit_breaker: self.circuit_breaker,
406            batch_failure_listeners: self.batch_failure_listeners,
407        }))
408    }
409
410    pub(crate) fn new(table: Table) -> Self {
411        Self {
412            table,
413            flush_interval: DEFAULT_FLUSH_INTERVAL,
414            channel_capacity: DEFAULT_CHANNEL_CAPACITY,
415            max_pending_bytes: DEFAULT_MAX_PENDING_BYTES,
416            options: AppendOptions::default(),
417            failure_policy: AppendFailurePolicy::Stop,
418            circuit_breaker: Some(AppendCircuitBreakerOptions::default()),
419            batch_failure_listeners: Vec::new(),
420        }
421    }
422}
423
424fn validate_builder(builder: &AppendStreamBuilder) -> Result<(), Error> {
425    builder.table.validate_append()?;
426    builder.options.validate()?;
427    if builder.channel_capacity > Semaphore::MAX_PERMITS {
428        return Err(config_error("channel_capacity is too large"));
429    }
430    if builder.flush_interval.is_zero() {
431        return Err(config_error("flush_interval must be greater than zero"));
432    }
433    validate_deadline("flush_interval", builder.flush_interval)?;
434    validate_positive("channel_capacity", builder.channel_capacity)?;
435    validate_positive("max_buffered_bytes", builder.max_pending_bytes)?;
436    if builder.max_pending_bytes > (u32::MAX as usize).min(Semaphore::MAX_PERMITS) {
437        return Err(config_error(format!(
438            "max_buffered_bytes must not exceed {}",
439            u32::MAX
440        )));
441    }
442    if let Some(circuit) = builder.circuit_breaker {
443        validate_positive(
444            "circuit_breaker.failure_threshold",
445            circuit.failure_threshold,
446        )?;
447        if circuit.cooldown.is_zero() {
448            return Err(config_error(
449                "circuit_breaker.cooldown must be greater than zero",
450            ));
451        }
452        validate_deadline("circuit_breaker.cooldown", circuit.cooldown)?;
453    }
454    Ok(())
455}
456
457struct AppendStreamConfig {
458    table: Table,
459    flush_interval: Duration,
460    channel_capacity: usize,
461    max_pending_bytes: usize,
462    failure_policy: AppendFailurePolicy,
463    circuit_breaker: Option<AppendCircuitBreakerOptions>,
464    batch_failure_listeners: Vec<BatchFailureListener>,
465    options: AppendOptions,
466}
467
468enum AppendCommand {
469    Record(BufferedRecord),
470    Flush(BarrierCommand),
471    Shutdown(BarrierCommand),
472}
473
474struct BarrierCommand {
475    dropped_rows_at_barrier: u64,
476    started_at: Instant,
477    ack: oneshot::Sender<Result<AppendDeliveryReport, Error>>,
478}
479
480struct BufferedRecord {
481    payload: String,
482    reserved_bytes: usize,
483    _reservation: OwnedSemaphorePermit,
484}
485
486struct PendingBytesBudget {
487    capacity: usize,
488    semaphore: Arc<Semaphore>,
489}
490
491impl PendingBytesBudget {
492    fn new(capacity: usize) -> Self {
493        Self {
494            capacity,
495            semaphore: Arc::new(Semaphore::new(capacity)),
496        }
497    }
498
499    async fn acquire(&self, bytes: usize) -> Result<OwnedSemaphorePermit, PendingAcquireError> {
500        if bytes > self.capacity {
501            return Err(PendingAcquireError::ExceedsCapacity);
502        }
503        self.semaphore
504            .clone()
505            .acquire_many_owned(bytes as u32)
506            .await
507            .map_err(|_| PendingAcquireError::Closed)
508    }
509
510    fn try_acquire(&self, bytes: usize) -> Result<OwnedSemaphorePermit, PendingAcquireError> {
511        if bytes > self.capacity {
512            return Err(PendingAcquireError::ExceedsCapacity);
513        }
514        self.semaphore
515            .clone()
516            .try_acquire_many_owned(bytes as u32)
517            .map_err(|err| match err {
518                tokio::sync::TryAcquireError::Closed => PendingAcquireError::Closed,
519                tokio::sync::TryAcquireError::NoPermits => PendingAcquireError::Full,
520            })
521    }
522
523    fn close(&self) {
524        self.semaphore.close();
525    }
526}
527
528#[derive(Debug, Clone, Copy, PartialEq, Eq)]
529enum PendingAcquireError {
530    Closed,
531    Full,
532    ExceedsCapacity,
533}
534
535#[derive(Debug, Clone, Copy, Default)]
536struct DeliveryCounters {
537    accepted_rows: u64,
538    committed_rows: u64,
539    failed_rows: u64,
540    ambiguous_rows: u64,
541    committed_batches: u64,
542    failed_batches: u64,
543    ambiguous_batches: u64,
544    retries: u64,
545}
546
547struct CircuitRuntime {
548    state: AppendCircuitState,
549    opened_until: Option<Instant>,
550    consecutive_failures: usize,
551    probe_admission_claimed: bool,
552}
553
554impl Default for CircuitRuntime {
555    fn default() -> Self {
556        Self {
557            state: AppendCircuitState::Closed,
558            opened_until: None,
559            consecutive_failures: 0,
560            probe_admission_claimed: false,
561        }
562    }
563}
564
565struct SharedState {
566    lifecycle: AppendStreamState,
567    fatal: Option<Error>,
568    final_result: Option<Result<AppendDeliveryReport, Error>>,
569    accepted_rows: u64,
570    committed_rows: u64,
571    failed_rows: u64,
572    ambiguous_rows: u64,
573    dropped_rows: u64,
574    dropped_by_reason: AppendDroppedRows,
575    retries: u64,
576    pending_rows: u64,
577    pending_bytes: usize,
578    in_flight_batches: usize,
579    last_failure: Option<AppendLastFailure>,
580    last_report: Option<AppendDeliveryReport>,
581    // Retain unreported settlement even if the worker is aborted.
582    interval: DeliveryCounters,
583    reported_dropped_rows: u64,
584    circuit: CircuitRuntime,
585}
586
587impl Default for SharedState {
588    fn default() -> Self {
589        Self {
590            lifecycle: AppendStreamState::Open,
591            fatal: None,
592            final_result: None,
593            accepted_rows: 0,
594            committed_rows: 0,
595            failed_rows: 0,
596            ambiguous_rows: 0,
597            dropped_rows: 0,
598            dropped_by_reason: AppendDroppedRows::default(),
599            retries: 0,
600            pending_rows: 0,
601            pending_bytes: 0,
602            in_flight_batches: 0,
603            last_failure: None,
604            last_report: None,
605            interval: DeliveryCounters::default(),
606            reported_dropped_rows: 0,
607            circuit: CircuitRuntime::default(),
608        }
609    }
610}
611
612impl SharedState {
613    fn take_report(
614        &mut self,
615        dropped_rows_at_barrier: u64,
616        duration: Duration,
617    ) -> AppendDeliveryReport {
618        let dropped_rows = dropped_rows_at_barrier.saturating_sub(self.reported_dropped_rows);
619        self.reported_dropped_rows = self.reported_dropped_rows.max(dropped_rows_at_barrier);
620        let lost_rows = self
621            .interval
622            .failed_rows
623            .saturating_add(self.interval.ambiguous_rows)
624            .saturating_add(dropped_rows);
625        let outcome = if lost_rows == 0 {
626            AppendDeliveryOutcome::Succeeded
627        } else if self.interval.committed_rows > 0 {
628            AppendDeliveryOutcome::Partial
629        } else if self.interval.ambiguous_rows > 0 {
630            AppendDeliveryOutcome::Ambiguous
631        } else {
632            AppendDeliveryOutcome::Failed
633        };
634        let report = AppendDeliveryReport {
635            outcome,
636            accepted_rows: self.interval.accepted_rows,
637            committed_rows: self.interval.committed_rows,
638            failed_rows: self.interval.failed_rows,
639            ambiguous_rows: self.interval.ambiguous_rows,
640            dropped_rows,
641            committed_batches: self.interval.committed_batches,
642            failed_batches: self.interval.failed_batches,
643            ambiguous_batches: self.interval.ambiguous_batches,
644            retries: self.interval.retries,
645            duration,
646        };
647        self.interval = DeliveryCounters::default();
648        self.last_report = Some(report.clone());
649        report
650    }
651}
652
653struct AppendStreamInner {
654    tx: mpsc::Sender<AppendCommand>,
655    shared: Arc<Mutex<SharedState>>,
656    pending_bytes: Arc<PendingBytesBudget>,
657    shutdown_notify: Arc<Notify>,
658}
659
660/// Cloneable handle to a bounded background append stream.
661///
662/// Admitted rows belong to the stream rather than an individual producer call.
663/// Call [`flush`](Self::flush) to await an intermediate barrier or [`shutdown`](Self::shutdown)
664/// to close admission and await final settlement. If all handles are dropped
665/// without calling `shutdown`, the background worker drains already admitted
666/// rows while the Tokio runtime remains active.
667#[derive(Clone)]
668pub struct AppendStream {
669    inner: Arc<AppendStreamInner>,
670}
671
672impl AppendStream {
673    /// Serializes `row` and waits for local buffer capacity to admit it into the stream.
674    ///
675    /// Returning `Ok(())` confirms local admission; call [`flush`](Self::flush) or
676    /// [`shutdown`](Self::shutdown) to observe remote delivery outcomes.
677    pub async fn send<T>(&self, row: &T) -> Result<(), Error>
678    where
679        T: Serialize + ?Sized,
680    {
681        self.check_open()?;
682        let payload = encode_record(row)?;
683        let reserved_bytes = payload.len().saturating_add(1);
684        let reservation = self
685            .inner
686            .pending_bytes
687            .acquire(reserved_bytes)
688            .await
689            .map_err(|err| self.map_pending_error(err, reserved_bytes))?;
690        let permit = match self.inner.tx.reserve().await {
691            Ok(permit) => permit,
692            Err(_) => {
693                drop(reservation);
694                return Err(self.closed_or_fatal_error());
695            }
696        };
697
698        let mut shared = lock(&self.inner.shared);
699        if shared.lifecycle != AppendStreamState::Open {
700            drop(shared);
701            drop(permit);
702            drop(reservation);
703            return Err(self.closed_or_fatal_error());
704        }
705        shared.accepted_rows = shared.accepted_rows.saturating_add(1);
706        shared.pending_rows = shared.pending_rows.saturating_add(1);
707        shared.pending_bytes = shared.pending_bytes.saturating_add(reserved_bytes);
708        permit.send(AppendCommand::Record(BufferedRecord {
709            payload,
710            reserved_bytes,
711            _reservation: reservation,
712        }));
713        Ok(())
714    }
715
716    /// Attempts to serialize and admit `row` without waiting for local buffer capacity.
717    ///
718    /// Rejected rows increment [`AppendStreamStats::dropped_rows`] and
719    /// [`AppendStreamStats::dropped_by_reason`].
720    pub fn try_send<T>(&self, row: &T) -> Result<(), AppendTrySendError>
721    where
722        T: Serialize + ?Sized,
723    {
724        {
725            let shared = lock(&self.inner.shared);
726            if shared.lifecycle != AppendStreamState::Open {
727                drop(shared);
728                note_drop(&mut lock(&self.inner.shared), DropReason::Closed);
729                return Err(AppendTrySendError::Closed);
730            }
731            if !circuit_admission_available(&shared) {
732                drop(shared);
733                note_drop(&mut lock(&self.inner.shared), DropReason::CircuitOpen);
734                return Err(AppendTrySendError::CircuitOpen);
735            }
736        }
737
738        let payload = match encode_record(row).map_err(AppendTrySendError::from) {
739            Ok(payload) => payload,
740            Err(err) => {
741                let reason = match err {
742                    AppendTrySendError::RecordTooLarge { .. } => DropReason::RecordTooLarge,
743                    _ => DropReason::InvalidRecord,
744                };
745                note_drop(&mut lock(&self.inner.shared), reason);
746                return Err(err);
747            }
748        };
749        let reserved_bytes = payload.len().saturating_add(1);
750        let reservation = match self.inner.pending_bytes.try_acquire(reserved_bytes) {
751            Ok(reservation) => reservation,
752            Err(PendingAcquireError::Closed) => {
753                note_drop(&mut lock(&self.inner.shared), DropReason::Closed);
754                return Err(AppendTrySendError::Closed);
755            }
756            Err(PendingAcquireError::Full) => {
757                note_drop(&mut lock(&self.inner.shared), DropReason::BufferFull);
758                return Err(AppendTrySendError::BufferFull);
759            }
760            Err(PendingAcquireError::ExceedsCapacity) => {
761                note_drop(&mut lock(&self.inner.shared), DropReason::RecordTooLarge);
762                return Err(AppendTrySendError::RecordTooLarge {
763                    bytes: reserved_bytes,
764                    limit: self.inner.pending_bytes.capacity,
765                });
766            }
767        };
768        let permit = match self.inner.tx.try_reserve() {
769            Ok(permit) => permit,
770            Err(mpsc::error::TrySendError::Full(_)) => {
771                drop(reservation);
772                note_drop(&mut lock(&self.inner.shared), DropReason::BufferFull);
773                return Err(AppendTrySendError::BufferFull);
774            }
775            Err(mpsc::error::TrySendError::Closed(_)) => {
776                drop(reservation);
777                note_drop(&mut lock(&self.inner.shared), DropReason::Closed);
778                return Err(AppendTrySendError::Closed);
779            }
780        };
781
782        let mut shared = lock(&self.inner.shared);
783        if shared.lifecycle != AppendStreamState::Open {
784            drop(shared);
785            drop(permit);
786            drop(reservation);
787            note_drop(&mut lock(&self.inner.shared), DropReason::Closed);
788            return Err(AppendTrySendError::Closed);
789        }
790        if !try_claim_circuit_admission(&mut shared) {
791            drop(shared);
792            drop(permit);
793            drop(reservation);
794            note_drop(&mut lock(&self.inner.shared), DropReason::CircuitOpen);
795            return Err(AppendTrySendError::CircuitOpen);
796        }
797        shared.accepted_rows = shared.accepted_rows.saturating_add(1);
798        shared.pending_rows = shared.pending_rows.saturating_add(1);
799        shared.pending_bytes = shared.pending_bytes.saturating_add(reserved_bytes);
800        permit.send(AppendCommand::Record(BufferedRecord {
801            payload,
802            reserved_bytes,
803            _reservation: reservation,
804        }));
805        Ok(())
806    }
807
808    /// Serializes and admits an iterator of rows sequentially, awaiting local buffer capacity as
809    /// needed.
810    ///
811    /// If an item fails encoding or the stream closes mid-iteration,
812    /// [`Error::append_admission`] reports how many rows from this call were
813    /// admitted. Those rows remain owned by the stream; call [`flush`](Self::flush) or
814    /// [`shutdown`](Self::shutdown) to observe their delivery.
815    /// Dropping this future stops admitting further rows while leaving already
816    /// admitted rows in the stream.
817    pub async fn send_all<I>(&self, rows: I) -> Result<AppendAdmissionResult, Error>
818    where
819        I: IntoIterator,
820        I::Item: Serialize,
821    {
822        let mut accepted_rows = 0u64;
823        for row in rows {
824            self.send(&row)
825                .await
826                .map_err(|error| error.with_append_admission(accepted_rows))?;
827            accepted_rows = accepted_rows.saturating_add(1);
828        }
829        Ok(AppendAdmissionResult { accepted_rows })
830    }
831
832    /// Dispatches buffered rows and waits for all rows admitted before this call to settle.
833    ///
834    /// Returns an [`AppendDeliveryReport`] covering activity since the previous
835    /// completed barrier while keeping the stream open. Under
836    /// [`AppendFailurePolicy::Stop`], a batch failure transitions the stream to
837    /// [`AppendStreamState::Failed`], settles all in-flight batches, and
838    /// returns [`Error`] with the terminal [`Error::append_delivery_report`]
839    /// (shared with any concurrent `flush` or [`shutdown`](Self::shutdown) callers).
840    /// Under [`AppendFailurePolicy::Continue`], `flush` returns `Ok(report)`
841    /// and records any batch losses in `report.outcome`.
842    ///
843    /// Once the barrier is enqueued, dropping this future stops waiting without
844    /// cancelling settlement in the background worker.
845    pub async fn flush(&self) -> Result<AppendDeliveryReport, Error> {
846        loop {
847            let notified = self.inner.shutdown_notify.notified();
848            match self.current_terminal_result() {
849                TerminalResult::Open => {}
850                TerminalResult::Waiting => {
851                    notified.await;
852                    continue;
853                }
854                TerminalResult::Complete(result) => {
855                    return result.map_err(|error| error.with_operation(ErrorOperation::Flush));
856                }
857            }
858
859            let permit = match self.inner.tx.reserve().await {
860                Ok(permit) => permit,
861                Err(_) => return self.wait_for_terminal(ErrorOperation::Flush).await,
862            };
863            let (ack, response) = oneshot::channel();
864            {
865                let shared = lock(&self.inner.shared);
866                if shared.lifecycle != AppendStreamState::Open {
867                    drop(shared);
868                    drop(permit);
869                    continue;
870                }
871                permit.send(AppendCommand::Flush(BarrierCommand {
872                    dropped_rows_at_barrier: shared.dropped_rows,
873                    started_at: Instant::now(),
874                    ack,
875                }));
876            }
877            return match response.await {
878                Ok(Ok(report)) => Ok(report),
879                Ok(Err(_)) | Err(_) => self.wait_for_terminal(ErrorOperation::Flush).await,
880            };
881        }
882    }
883
884    /// Closes row admission, settles all admitted rows, and returns the final
885    /// [`AppendDeliveryReport`].
886    ///
887    /// Idempotent across cloned handles: concurrent and subsequent calls
888    /// observe the same terminal result (or [`Error::append_delivery_report`]
889    /// on a [`AppendFailurePolicy::Stop`] failure). Dropping the future stops
890    /// local waiting while background settlement continues; call `shutdown`
891    /// again to await completion.
892    pub async fn shutdown(&self) -> Result<AppendDeliveryReport, Error> {
893        let should_start = {
894            let mut shared = lock(&self.inner.shared);
895            match shared.lifecycle {
896                AppendStreamState::Open => {
897                    shared.lifecycle = AppendStreamState::Closing;
898                    true
899                }
900                AppendStreamState::Closing | AppendStreamState::Failed => false,
901                AppendStreamState::Closed if shared.final_result.is_some() => {
902                    return terminal_result(&shared)
903                        .map_err(|error| error.with_operation(ErrorOperation::Shutdown));
904                }
905                AppendStreamState::Closed => false,
906            }
907        };
908
909        if should_start {
910            let inner = self.inner.clone();
911            tokio::spawn(async move {
912                let _ = enqueue_shutdown(inner).await;
913            });
914        }
915
916        self.wait_for_terminal(ErrorOperation::Shutdown).await
917    }
918
919    /// Returns a point-in-time snapshot of cumulative stream counters, state, and the latest
920    /// report.
921    pub fn stats(&self) -> AppendStreamStats {
922        let shared = lock(&self.inner.shared);
923        AppendStreamStats {
924            state: shared.lifecycle,
925            circuit_state: shared.circuit.state,
926            accepted_rows: shared.accepted_rows,
927            committed_rows: shared.committed_rows,
928            failed_rows: shared.failed_rows,
929            ambiguous_rows: shared.ambiguous_rows,
930            dropped_rows: shared.dropped_rows,
931            dropped_by_reason: shared.dropped_by_reason,
932            retries: shared.retries,
933            pending_rows: shared.pending_rows,
934            pending_bytes: shared.pending_bytes,
935            in_flight_batches: shared.in_flight_batches,
936            last_failure: shared.last_failure.clone(),
937            last_report: shared.last_report.clone(),
938        }
939    }
940
941    fn new(config: AppendStreamConfig) -> Self {
942        let (tx, rx) = mpsc::channel(config.channel_capacity);
943        let shared = Arc::new(Mutex::new(SharedState::default()));
944        let pending_bytes = Arc::new(PendingBytesBudget::new(config.max_pending_bytes));
945        let shutdown_notify = Arc::new(Notify::new());
946
947        let worker = tokio::spawn(run_append_worker(
948            config,
949            rx,
950            shared.clone(),
951            pending_bytes.clone(),
952            shutdown_notify.clone(),
953        ));
954        tokio::spawn(monitor_append_worker(
955            worker,
956            shared.clone(),
957            pending_bytes.clone(),
958            shutdown_notify.clone(),
959        ));
960
961        Self {
962            inner: Arc::new(AppendStreamInner {
963                tx,
964                shared,
965                pending_bytes,
966                shutdown_notify,
967            }),
968        }
969    }
970
971    fn check_open(&self) -> Result<(), Error> {
972        let shared = lock(&self.inner.shared);
973        if shared.lifecycle == AppendStreamState::Open {
974            Ok(())
975        } else {
976            Err(error_from_shared(&shared))
977        }
978    }
979
980    fn closed_or_fatal_error(&self) -> Error {
981        error_from_shared(&lock(&self.inner.shared))
982    }
983
984    fn map_pending_error(&self, error: PendingAcquireError, requested: usize) -> Error {
985        match error {
986            PendingAcquireError::Closed => self.closed_or_fatal_error(),
987            PendingAcquireError::Full => Error::new(
988                ErrorKind::RateLimited,
989                ErrorOperation::AdmitRows,
990                "append stream local byte budget is full",
991            )
992            .with_transient_failure(true),
993            PendingAcquireError::ExceedsCapacity => Error::new(
994                ErrorKind::InvalidInput,
995                ErrorOperation::AdmitRows,
996                format!(
997                    "append row requires {requested} buffered bytes, exceeding max_pending_bytes={}",
998                    self.inner.pending_bytes.capacity
999                ),
1000            ),
1001        }
1002    }
1003
1004    fn current_terminal_result(&self) -> TerminalResult {
1005        let shared = lock(&self.inner.shared);
1006        match shared.lifecycle {
1007            AppendStreamState::Open => TerminalResult::Open,
1008            AppendStreamState::Closing => TerminalResult::Waiting,
1009            AppendStreamState::Closed | AppendStreamState::Failed
1010                if shared.final_result.is_none() =>
1011            {
1012                TerminalResult::Waiting
1013            }
1014            AppendStreamState::Closed | AppendStreamState::Failed => {
1015                TerminalResult::Complete(terminal_result(&shared))
1016            }
1017        }
1018    }
1019
1020    async fn wait_for_terminal(
1021        &self,
1022        operation: ErrorOperation,
1023    ) -> Result<AppendDeliveryReport, Error> {
1024        loop {
1025            let notified = self.inner.shutdown_notify.notified();
1026            {
1027                let shared = lock(&self.inner.shared);
1028                if matches!(
1029                    shared.lifecycle,
1030                    AppendStreamState::Closed | AppendStreamState::Failed
1031                ) && shared.final_result.is_some()
1032                {
1033                    return terminal_result(&shared)
1034                        .map_err(|error| error.with_operation(operation));
1035                }
1036            }
1037            notified.await;
1038        }
1039    }
1040}
1041
1042enum TerminalResult {
1043    Open,
1044    Waiting,
1045    Complete(Result<AppendDeliveryReport, Error>),
1046}
1047
1048async fn enqueue_shutdown(inner: Arc<AppendStreamInner>) -> Result<AppendDeliveryReport, Error> {
1049    let (ack, response) = oneshot::channel();
1050    let dropped_rows_at_barrier = lock(&inner.shared).dropped_rows;
1051    inner
1052        .tx
1053        .send(AppendCommand::Shutdown(BarrierCommand {
1054            dropped_rows_at_barrier,
1055            started_at: Instant::now(),
1056            ack,
1057        }))
1058        .await
1059        .map_err(|_| error_from_shared(&lock(&inner.shared)))?;
1060    response
1061        .await
1062        .unwrap_or_else(|_| Err(error_from_shared(&lock(&inner.shared))))
1063}
1064
1065fn terminal_result(shared: &SharedState) -> Result<AppendDeliveryReport, Error> {
1066    match shared
1067        .final_result
1068        .as_ref()
1069        .expect("terminal result is present")
1070    {
1071        Ok(report) => Ok(report.clone()),
1072        Err(error) => Err(error.clone().with_append_delivery(
1073            shared
1074                .last_report
1075                .clone()
1076                .expect("terminal settlement is present"),
1077        )),
1078    }
1079}
1080
1081fn error_from_shared(shared: &SharedState) -> Error {
1082    shared
1083        .fatal
1084        .as_ref()
1085        .cloned()
1086        .map(Error::for_closed_stream)
1087        .unwrap_or_else(|| {
1088            Error::new(
1089                ErrorKind::Closed,
1090                ErrorOperation::AdmitRows,
1091                "append stream is closed",
1092            )
1093        })
1094}
1095
1096struct BatchOutcome {
1097    records: Vec<BufferedRecord>,
1098    batch_bytes: usize,
1099    result: Result<AppendRowsResult, Error>,
1100    retries: usize,
1101    circuit_probe: bool,
1102}
1103
1104struct AppendWorker {
1105    config: AppendStreamConfig,
1106    shared: Arc<Mutex<SharedState>>,
1107    pending_bytes: Arc<PendingBytesBudget>,
1108    shutdown_notify: Arc<Notify>,
1109    rows: Vec<BufferedRecord>,
1110    current_bytes: usize,
1111    batch_deadline: Option<Instant>,
1112    in_flight: JoinSet<BatchOutcome>,
1113    fatal: Option<Error>,
1114}
1115
1116async fn run_append_worker(
1117    config: AppendStreamConfig,
1118    mut rx: mpsc::Receiver<AppendCommand>,
1119    shared: Arc<Mutex<SharedState>>,
1120    pending_bytes: Arc<PendingBytesBudget>,
1121    shutdown_notify: Arc<Notify>,
1122) {
1123    let mut worker = AppendWorker {
1124        config,
1125        shared,
1126        pending_bytes,
1127        shutdown_notify,
1128        rows: Vec::new(),
1129        current_bytes: 0,
1130        batch_deadline: None,
1131        in_flight: JoinSet::new(),
1132        fatal: None,
1133    };
1134
1135    loop {
1136        if worker.fatal.is_some() {
1137            worker.finish_fatal(&mut rx, None).await;
1138            return;
1139        }
1140
1141        let deadline = worker
1142            .batch_deadline
1143            .unwrap_or_else(|| Instant::now() + Duration::from_secs(86400 * 365));
1144        tokio::select! {
1145            biased;
1146            outcome = worker.in_flight.join_next(), if !worker.in_flight.is_empty() => {
1147                worker.handle_joined(outcome).await;
1148            }
1149            _ = tokio::time::sleep_until(deadline.into()), if worker.batch_deadline.is_some() => {
1150                worker.dispatch_buffered().await;
1151            }
1152            command = rx.recv() => {
1153                match command {
1154                    Some(AppendCommand::Record(record)) => worker.buffer_record(record).await,
1155                    Some(AppendCommand::Flush(barrier)) => {
1156                        if let Some(barrier) = worker.complete_barrier(barrier).await {
1157                            worker.finish_fatal(&mut rx, Some(barrier)).await;
1158                            return;
1159                        }
1160                    }
1161                    Some(AppendCommand::Shutdown(barrier)) => {
1162                        if let Some(barrier) = worker.complete_barrier(barrier).await {
1163                            worker.finish_fatal(&mut rx, Some(barrier)).await;
1164                        } else {
1165                            worker.finish_closed();
1166                        }
1167                        return;
1168                    }
1169                    None => {
1170                        worker.dispatch_buffered().await;
1171                        worker.drain_in_flight().await;
1172                        if worker.fatal.is_some() {
1173                            worker.finish_fatal(&mut rx, None).await;
1174                        } else {
1175                            let dropped = lock(&worker.shared).dropped_rows;
1176                            let report = lock(&worker.shared).take_report(dropped, Duration::ZERO);
1177                            worker.finish_closed_with_report(report);
1178                        }
1179                        return;
1180                    }
1181                }
1182            }
1183        }
1184    }
1185}
1186
1187async fn monitor_append_worker(
1188    worker: JoinHandle<()>,
1189    shared: Arc<Mutex<SharedState>>,
1190    pending_bytes: Arc<PendingBytesBudget>,
1191    shutdown_notify: Arc<Notify>,
1192) {
1193    let worker_result = worker.await;
1194    let mut shared = lock(&shared);
1195    if shared.final_result.is_some() {
1196        return;
1197    }
1198
1199    let error = match worker_result {
1200        Ok(()) => Error::new(
1201            ErrorKind::Internal,
1202            ErrorOperation::AdmitRows,
1203            "append stream worker stopped before publishing a final result",
1204        ),
1205        Err(error) => {
1206            ambiguous_append_error("append stream worker terminated unexpectedly", Some(error))
1207        }
1208    };
1209    let snapshot = error.clone();
1210    let resolved = shared
1211        .committed_rows
1212        .saturating_add(shared.failed_rows)
1213        .saturating_add(shared.ambiguous_rows);
1214    let unresolved = shared.accepted_rows.saturating_sub(resolved);
1215    shared.ambiguous_rows = shared.ambiguous_rows.saturating_add(unresolved);
1216    shared.interval.ambiguous_rows = shared.interval.ambiguous_rows.saturating_add(unresolved);
1217    if unresolved > 0 {
1218        shared.interval.ambiguous_batches = shared.interval.ambiguous_batches.saturating_add(1);
1219    }
1220    shared.interval.accepted_rows = shared
1221        .interval
1222        .committed_rows
1223        .saturating_add(shared.interval.failed_rows)
1224        .saturating_add(shared.interval.ambiguous_rows);
1225    let dropped = shared.dropped_rows;
1226    shared.take_report(dropped, Duration::ZERO);
1227    shared.pending_rows = 0;
1228    shared.pending_bytes = 0;
1229    shared.in_flight_batches = 0;
1230    shared.lifecycle = AppendStreamState::Failed;
1231    shared.fatal = Some(snapshot.clone());
1232    shared.final_result = Some(Err(snapshot));
1233    drop(shared);
1234    pending_bytes.close();
1235    shutdown_notify.notify_waiters();
1236}
1237
1238impl AppendWorker {
1239    async fn buffer_record(&mut self, record: BufferedRecord) {
1240        {
1241            let mut shared = lock(&self.shared);
1242            shared.interval.accepted_rows = shared.interval.accepted_rows.saturating_add(1);
1243        }
1244        if self.config.options.would_overflow(
1245            self.current_bytes,
1246            self.rows.len(),
1247            record.payload.len(),
1248        ) {
1249            self.dispatch_buffered().await;
1250        }
1251        if self.fatal.is_some() {
1252            self.mark_records_failed(vec![record]);
1253            return;
1254        }
1255
1256        if self.rows.is_empty() {
1257            self.batch_deadline = Some(deadline_after(self.config.flush_interval));
1258        } else {
1259            self.current_bytes = self.current_bytes.saturating_add(1);
1260        }
1261        self.current_bytes = self.current_bytes.saturating_add(record.payload.len());
1262        self.rows.push(record);
1263        if self
1264            .config
1265            .options
1266            .is_full(self.current_bytes, self.rows.len())
1267        {
1268            self.dispatch_buffered().await;
1269        }
1270    }
1271
1272    async fn dispatch_buffered(&mut self) {
1273        if self.rows.is_empty() || self.fatal.is_some() {
1274            return;
1275        }
1276        while self.in_flight.len() >= self.config.options.max_in_flight_requests {
1277            let outcome = self.in_flight.join_next().await;
1278            self.handle_joined(outcome).await;
1279            if self.fatal.is_some() {
1280                return;
1281            }
1282        }
1283
1284        let circuit_probe = self.wait_for_circuit().await;
1285        if self.fatal.is_some() {
1286            return;
1287        }
1288        let records = mem::take(&mut self.rows);
1289        let batch_bytes = mem::take(&mut self.current_bytes);
1290        self.batch_deadline = None;
1291        let payload = records
1292            .iter()
1293            .map(|record| record.payload.as_str())
1294            .collect::<Vec<_>>()
1295            .join("\n");
1296        let table = self.config.table.clone();
1297        let options = self.config.options.clone();
1298        lock(&self.shared).in_flight_batches += 1;
1299        self.in_flight.spawn(async move {
1300            let (result, retries) = append_batch(table, options, payload).await;
1301            BatchOutcome {
1302                records,
1303                batch_bytes,
1304                result,
1305                retries,
1306                circuit_probe,
1307            }
1308        });
1309    }
1310
1311    async fn wait_for_circuit(&mut self) -> bool {
1312        if self.config.failure_policy != AppendFailurePolicy::Continue
1313            || self.config.circuit_breaker.is_none()
1314        {
1315            return false;
1316        }
1317
1318        loop {
1319            let (state, remaining) = {
1320                let shared = lock(&self.shared);
1321                let remaining = shared
1322                    .circuit
1323                    .opened_until
1324                    .and_then(|until| until.checked_duration_since(Instant::now()));
1325                (shared.circuit.state, remaining)
1326            };
1327            match state {
1328                AppendCircuitState::Closed => return false,
1329                AppendCircuitState::Open => {
1330                    if let Some(remaining) = remaining {
1331                        if self.in_flight.is_empty() {
1332                            tokio::time::sleep(remaining).await;
1333                        } else {
1334                            tokio::select! {
1335                                _ = tokio::time::sleep(remaining) => {}
1336                                outcome = self.in_flight.join_next() => {
1337                                    self.handle_joined(outcome).await;
1338                                    if self.fatal.is_some() {
1339                                        return false;
1340                                    }
1341                                }
1342                            }
1343                        }
1344                        continue;
1345                    }
1346                    if !self.in_flight.is_empty() {
1347                        self.drain_in_flight().await;
1348                        if self.fatal.is_some() {
1349                            return false;
1350                        }
1351                        continue;
1352                    }
1353                    let mut shared = lock(&self.shared);
1354                    if shared.circuit.state == AppendCircuitState::Open {
1355                        shared.circuit.state = AppendCircuitState::HalfOpen;
1356                        return true;
1357                    }
1358                }
1359                AppendCircuitState::HalfOpen => {
1360                    if self.in_flight.is_empty() {
1361                        return true;
1362                    }
1363                    let outcome = self.in_flight.join_next().await;
1364                    self.handle_joined(outcome).await;
1365                    if self.fatal.is_some() {
1366                        return false;
1367                    }
1368                }
1369            }
1370        }
1371    }
1372
1373    async fn complete_barrier(&mut self, barrier: BarrierCommand) -> Option<BarrierCommand> {
1374        self.dispatch_buffered().await;
1375        self.drain_in_flight().await;
1376        if self.fatal.is_some() {
1377            return Some(barrier);
1378        }
1379        let report = lock(&self.shared).take_report(
1380            barrier.dropped_rows_at_barrier,
1381            barrier.started_at.elapsed(),
1382        );
1383        let _ = barrier.ack.send(Ok(report));
1384        None
1385    }
1386
1387    async fn drain_in_flight(&mut self) {
1388        while let Some(outcome) = self.in_flight.join_next().await {
1389            self.handle_joined(Some(outcome)).await;
1390        }
1391    }
1392
1393    async fn handle_joined(
1394        &mut self,
1395        outcome: Option<Result<BatchOutcome, tokio::task::JoinError>>,
1396    ) {
1397        let Some(outcome) = outcome else {
1398            return;
1399        };
1400        let outcome = match outcome {
1401            Ok(outcome) => outcome,
1402            Err(error) => {
1403                let fatal = ambiguous_append_error(
1404                    "append stream background request task failed",
1405                    Some(error),
1406                );
1407                self.set_fatal(fatal.clone());
1408                return;
1409            }
1410        };
1411
1412        let rows = outcome.records.len() as u64;
1413        let reserved_bytes = outcome
1414            .records
1415            .iter()
1416            .map(|record| record.reserved_bytes)
1417            .sum::<usize>();
1418        let mut failure_event = None;
1419        {
1420            let mut shared = lock(&self.shared);
1421            shared.in_flight_batches = shared.in_flight_batches.saturating_sub(1);
1422            shared.pending_rows = shared.pending_rows.saturating_sub(rows);
1423            shared.pending_bytes = shared.pending_bytes.saturating_sub(reserved_bytes);
1424            shared.retries = shared.retries.saturating_add(outcome.retries as u64);
1425            shared.interval.retries = shared
1426                .interval
1427                .retries
1428                .saturating_add(outcome.retries as u64);
1429
1430            match &outcome.result {
1431                Ok(result) => {
1432                    let committed = result.num_rows_inserted.max(0) as u64;
1433                    shared.committed_rows = shared.committed_rows.saturating_add(committed);
1434                    shared.interval.committed_rows =
1435                        shared.interval.committed_rows.saturating_add(committed);
1436                    shared.interval.committed_batches =
1437                        shared.interval.committed_batches.saturating_add(1);
1438                    record_circuit_success(&mut shared, outcome.circuit_probe);
1439                }
1440                Err(error) => {
1441                    let snapshot = error.clone();
1442                    let status = snapshot
1443                        .append_details()
1444                        .map(|d| d.status)
1445                        .unwrap_or(AppendOutcome::Ambiguous);
1446                    if status == AppendOutcome::Ambiguous {
1447                        shared.ambiguous_rows = shared.ambiguous_rows.saturating_add(rows);
1448                        shared.interval.ambiguous_rows =
1449                            shared.interval.ambiguous_rows.saturating_add(rows);
1450                        shared.interval.ambiguous_batches =
1451                            shared.interval.ambiguous_batches.saturating_add(1);
1452                    } else {
1453                        shared.failed_rows = shared.failed_rows.saturating_add(rows);
1454                        shared.interval.failed_rows =
1455                            shared.interval.failed_rows.saturating_add(rows);
1456                        shared.interval.failed_batches =
1457                            shared.interval.failed_batches.saturating_add(1);
1458                    }
1459                    shared.last_failure = Some(AppendLastFailure {
1460                        at: SystemTime::now(),
1461                        error: error.clone(),
1462                    });
1463                    let circuit_opened = self.config.failure_policy
1464                        == AppendFailurePolicy::Continue
1465                        && record_circuit_failure(
1466                            &mut shared,
1467                            self.config.circuit_breaker,
1468                            error,
1469                            outcome.circuit_probe,
1470                        );
1471                    let action = if self.config.failure_policy == AppendFailurePolicy::Stop {
1472                        AppendBatchFailureAction::Stopped
1473                    } else if circuit_opened {
1474                        AppendBatchFailureAction::CircuitOpened
1475                    } else {
1476                        AppendBatchFailureAction::Continuing
1477                    };
1478                    failure_event = Some(AppendBatchFailureEvent {
1479                        error: snapshot.clone(),
1480                        batch_rows: rows as usize,
1481                        batch_bytes: outcome.batch_bytes,
1482                        outcome: status,
1483                        action,
1484                    });
1485                    if self.config.failure_policy == AppendFailurePolicy::Stop {
1486                        drop(shared);
1487                        self.set_fatal(snapshot);
1488                    }
1489                }
1490            }
1491        }
1492        drop(outcome.records);
1493
1494        if let Some(event) = &failure_event {
1495            for listener in &self.config.batch_failure_listeners {
1496                let _ = std::panic::catch_unwind(AssertUnwindSafe(|| listener(event)));
1497            }
1498        }
1499    }
1500
1501    fn set_fatal(&mut self, snapshot: Error) {
1502        let replace = match &self.fatal {
1503            None => true,
1504            Some(current) => {
1505                current.append_details().map(|d| d.status) != Some(AppendOutcome::Ambiguous)
1506                    && snapshot.append_details().map(|d| d.status) == Some(AppendOutcome::Ambiguous)
1507            }
1508        };
1509        if replace {
1510            self.fatal = Some(snapshot.clone());
1511        }
1512        let fatal = self.fatal.clone().expect("fatal state must be set");
1513        let mut shared = lock(&self.shared);
1514        shared.lifecycle = AppendStreamState::Failed;
1515        shared.fatal = Some(fatal);
1516        drop(shared);
1517        self.pending_bytes.close();
1518    }
1519
1520    fn mark_records_failed(&mut self, records: Vec<BufferedRecord>) {
1521        if records.is_empty() {
1522            return;
1523        }
1524        let rows = records.len() as u64;
1525        let bytes = records
1526            .iter()
1527            .map(|record| record.reserved_bytes)
1528            .sum::<usize>();
1529        let mut shared = lock(&self.shared);
1530        shared.failed_rows = shared.failed_rows.saturating_add(rows);
1531        shared.pending_rows = shared.pending_rows.saturating_sub(rows);
1532        shared.pending_bytes = shared.pending_bytes.saturating_sub(bytes);
1533        shared.interval.failed_rows = shared.interval.failed_rows.saturating_add(rows);
1534        drop(shared);
1535        drop(records);
1536    }
1537
1538    async fn finish_fatal(
1539        &mut self,
1540        rx: &mut mpsc::Receiver<AppendCommand>,
1541        barrier: Option<BarrierCommand>,
1542    ) {
1543        rx.close();
1544        let buffered = mem::take(&mut self.rows);
1545        self.mark_records_failed(buffered);
1546        self.current_bytes = 0;
1547        self.batch_deadline = None;
1548
1549        let mut barriers: Vec<_> = barrier.into_iter().collect();
1550        while let Some(command) = rx.recv().await {
1551            match command {
1552                AppendCommand::Record(record) => {
1553                    {
1554                        let mut shared = lock(&self.shared);
1555                        shared.interval.accepted_rows =
1556                            shared.interval.accepted_rows.saturating_add(1);
1557                    }
1558                    self.mark_records_failed(vec![record]);
1559                }
1560                AppendCommand::Flush(barrier) | AppendCommand::Shutdown(barrier) => {
1561                    barriers.push(barrier);
1562                }
1563            }
1564        }
1565        // All outstanding barriers observe this settlement; retain the earliest wait.
1566        let started_at = barriers
1567            .iter()
1568            .map(|barrier| barrier.started_at)
1569            .min()
1570            .unwrap_or_else(Instant::now);
1571        self.drain_in_flight().await;
1572
1573        let fatal = self.fatal.clone().unwrap_or_else(|| {
1574            Error::new(
1575                ErrorKind::Internal,
1576                ErrorOperation::AdmitRows,
1577                "append stream failed",
1578            )
1579        });
1580        {
1581            let mut shared = lock(&self.shared);
1582            let resolved = shared
1583                .committed_rows
1584                .saturating_add(shared.failed_rows)
1585                .saturating_add(shared.ambiguous_rows);
1586            let unresolved = shared.accepted_rows.saturating_sub(resolved);
1587            if unresolved > 0 {
1588                shared.ambiguous_rows = shared.ambiguous_rows.saturating_add(unresolved);
1589                shared.interval.ambiguous_rows =
1590                    shared.interval.ambiguous_rows.saturating_add(unresolved);
1591                shared.interval.ambiguous_batches =
1592                    shared.interval.ambiguous_batches.saturating_add(1);
1593            }
1594            shared.pending_rows = 0;
1595            shared.pending_bytes = 0;
1596            shared.in_flight_batches = 0;
1597        }
1598        let dropped = lock(&self.shared).dropped_rows;
1599        lock(&self.shared).take_report(dropped, started_at.elapsed());
1600        {
1601            let mut shared = lock(&self.shared);
1602            shared.lifecycle = AppendStreamState::Failed;
1603            shared.fatal = Some(fatal.clone());
1604            shared.final_result = Some(Err(fatal.clone()));
1605        }
1606        for barrier in barriers {
1607            let _ = barrier.ack.send(Err(fatal.clone()));
1608        }
1609        self.pending_bytes.close();
1610        self.shutdown_notify.notify_waiters();
1611    }
1612
1613    fn finish_closed(&mut self) {
1614        let report = lock(&self.shared)
1615            .last_report
1616            .clone()
1617            .unwrap_or_else(empty_report);
1618        self.finish_closed_with_report(report);
1619    }
1620
1621    fn finish_closed_with_report(&mut self, report: AppendDeliveryReport) {
1622        let mut shared = lock(&self.shared);
1623        shared.lifecycle = AppendStreamState::Closed;
1624        shared.last_report = Some(report.clone());
1625        shared.final_result = Some(Ok(report));
1626        drop(shared);
1627        self.pending_bytes.close();
1628        self.shutdown_notify.notify_waiters();
1629    }
1630}
1631
1632fn ambiguous_append_error<E>(message: impl Into<String>, source: Option<E>) -> Error
1633where
1634    E: std::error::Error + Send + Sync + 'static,
1635{
1636    let mut error = Error::new(ErrorKind::Internal, ErrorOperation::Append, message)
1637        .set_append_details(AppendErrorDetails {
1638            status: AppendOutcome::Ambiguous,
1639            row_errors: Vec::new(),
1640            row_errors_truncated: false,
1641        });
1642    if let Some(source) = source {
1643        error = error.set_source(source);
1644    }
1645    error
1646}
1647
1648fn try_claim_circuit_admission(shared: &mut SharedState) -> bool {
1649    match shared.circuit.state {
1650        AppendCircuitState::Closed => true,
1651        AppendCircuitState::HalfOpen => false,
1652        AppendCircuitState::Open => {
1653            let cooled_down = shared
1654                .circuit
1655                .opened_until
1656                .is_none_or(|until| Instant::now() >= until);
1657            if cooled_down && !shared.circuit.probe_admission_claimed {
1658                shared.circuit.probe_admission_claimed = true;
1659                true
1660            } else {
1661                false
1662            }
1663        }
1664    }
1665}
1666
1667fn circuit_admission_available(shared: &SharedState) -> bool {
1668    match shared.circuit.state {
1669        AppendCircuitState::Closed => true,
1670        AppendCircuitState::HalfOpen => false,
1671        AppendCircuitState::Open => {
1672            shared
1673                .circuit
1674                .opened_until
1675                .is_none_or(|until| Instant::now() >= until)
1676                && !shared.circuit.probe_admission_claimed
1677        }
1678    }
1679}
1680
1681fn record_circuit_success(shared: &mut SharedState, probe: bool) {
1682    shared.circuit.consecutive_failures = 0;
1683    if probe {
1684        shared.circuit.state = AppendCircuitState::Closed;
1685        shared.circuit.opened_until = None;
1686        shared.circuit.probe_admission_claimed = false;
1687    }
1688}
1689
1690fn record_circuit_failure(
1691    shared: &mut SharedState,
1692    options: Option<AppendCircuitBreakerOptions>,
1693    error: &Error,
1694    probe: bool,
1695) -> bool {
1696    let Some(options) = options else {
1697        return false;
1698    };
1699    let availability_failure = error.is_transient()
1700        || matches!(
1701            error.kind(),
1702            ErrorKind::Unavailable | ErrorKind::Timeout | ErrorKind::InvalidResponse
1703        );
1704    if !availability_failure {
1705        if probe {
1706            record_circuit_success(shared, true);
1707        }
1708        return false;
1709    }
1710
1711    shared.circuit.consecutive_failures = shared.circuit.consecutive_failures.saturating_add(1);
1712    if probe || shared.circuit.consecutive_failures >= options.failure_threshold {
1713        shared.circuit.state = AppendCircuitState::Open;
1714        shared.circuit.opened_until = Some(deadline_after(options.cooldown));
1715        shared.circuit.probe_admission_claimed = false;
1716        true
1717    } else {
1718        false
1719    }
1720}
1721
1722#[derive(Debug, Clone, Copy)]
1723enum DropReason {
1724    BufferFull,
1725    InvalidRecord,
1726    RecordTooLarge,
1727    CircuitOpen,
1728    Closed,
1729}
1730
1731fn note_drop(shared: &mut SharedState, reason: DropReason) {
1732    shared.dropped_rows = shared.dropped_rows.saturating_add(1);
1733    let counter = match reason {
1734        DropReason::BufferFull => &mut shared.dropped_by_reason.buffer_full,
1735        DropReason::InvalidRecord => &mut shared.dropped_by_reason.invalid_record,
1736        DropReason::RecordTooLarge => &mut shared.dropped_by_reason.record_too_large,
1737        DropReason::CircuitOpen => &mut shared.dropped_by_reason.circuit_open,
1738        DropReason::Closed => &mut shared.dropped_by_reason.closed,
1739    };
1740    *counter = counter.saturating_add(1);
1741}
1742
1743fn empty_report() -> AppendDeliveryReport {
1744    AppendDeliveryReport {
1745        outcome: AppendDeliveryOutcome::Succeeded,
1746        accepted_rows: 0,
1747        committed_rows: 0,
1748        failed_rows: 0,
1749        ambiguous_rows: 0,
1750        dropped_rows: 0,
1751        committed_batches: 0,
1752        failed_batches: 0,
1753        ambiguous_batches: 0,
1754        retries: 0,
1755        duration: Duration::ZERO,
1756    }
1757}
1758
1759fn deadline_after(duration: Duration) -> Instant {
1760    let now = Instant::now();
1761    now.checked_add(duration).unwrap_or(now)
1762}
1763
1764fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
1765    mutex
1766        .lock()
1767        .unwrap_or_else(|poisoned| poisoned.into_inner())
1768}