Skip to main content

rustium_core/
runtime.rs

1use std::{sync::Arc, time::Duration};
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use tokio::{
6    sync::{RwLock, mpsc, watch},
7    task::JoinHandle,
8    time::{Instant, MissedTickBehavior},
9};
10use tokio_util::sync::CancellationToken;
11use tracing::{error, info, warn};
12
13use crate::{
14    CHECKPOINT_SCHEMA_VERSION, Checkpoint, CheckpointStore, ConnectorIdentity,
15    ConnectorStateEnvelope, DeliveryBatch, EncodedEvent, Error, EventEncoder, RecordBoundary,
16    Result, SignalSender, Sink, SourceConnector, SourceContext, SourcePosition, SourceRecord,
17    signal_channel,
18};
19
20#[derive(Debug, Clone)]
21pub struct RuntimeConfig {
22    pub channel_capacity: usize,
23    pub max_batch_size: usize,
24    pub flush_interval: Duration,
25    pub shutdown_timeout: Duration,
26    pub errors_max_retries: i32,
27    pub errors_retry_delay_initial: Duration,
28    pub errors_retry_delay_max: Duration,
29    pub config_fingerprint: String,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct RetryPolicy {
34    pub max_retries: i32,
35    pub initial_delay: Duration,
36    pub max_delay: Duration,
37}
38
39impl Default for RetryPolicy {
40    fn default() -> Self {
41        Self {
42            max_retries: 10,
43            initial_delay: Duration::from_millis(300),
44            max_delay: Duration::from_secs(10),
45        }
46    }
47}
48
49impl RuntimeConfig {
50    #[must_use]
51    pub const fn retry_policy(&self) -> RetryPolicy {
52        RetryPolicy {
53            max_retries: self.errors_max_retries,
54            initial_delay: self.errors_retry_delay_initial,
55            max_delay: self.errors_retry_delay_max,
56        }
57    }
58}
59
60impl Default for RuntimeConfig {
61    fn default() -> Self {
62        Self {
63            channel_capacity: 2_048,
64            max_batch_size: 512,
65            flush_interval: Duration::from_millis(100),
66            shutdown_timeout: Duration::from_secs(30),
67            errors_max_retries: 10,
68            errors_retry_delay_initial: Duration::from_millis(300),
69            errors_retry_delay_max: Duration::from_secs(10),
70            config_fingerprint: String::new(),
71        }
72    }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
77pub enum ConnectorState {
78    Created,
79    Starting,
80    Snapshotting,
81    Streaming,
82    Paused,
83    Failed,
84    Stopping,
85    Stopped,
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct StatusSnapshot {
90    pub connector_name: String,
91    pub state: ConnectorState,
92    pub state_since: DateTime<Utc>,
93    pub state_reason: Option<String>,
94    pub last_position: Option<SourcePosition>,
95    pub last_checkpoint_at: Option<DateTime<Utc>>,
96    pub last_source_event_at: Option<DateTime<Utc>>,
97    pub last_event_observed_at: Option<DateTime<Utc>>,
98    pub source_lag_millis: Option<u64>,
99    pub delivered_events: u64,
100    pub failed_events: u64,
101    pub sink_retry_attempts: u64,
102    pub queue_depth: usize,
103}
104
105#[derive(Clone)]
106pub struct RuntimeStatus(Arc<RwLock<StatusSnapshot>>);
107
108impl RuntimeStatus {
109    #[must_use]
110    pub fn new(connector_name: impl Into<String>) -> Self {
111        Self(Arc::new(RwLock::new(StatusSnapshot {
112            connector_name: connector_name.into(),
113            state: ConnectorState::Created,
114            state_since: Utc::now(),
115            state_reason: None,
116            last_position: None,
117            last_checkpoint_at: None,
118            last_source_event_at: None,
119            last_event_observed_at: None,
120            source_lag_millis: None,
121            delivered_events: 0,
122            failed_events: 0,
123            sink_retry_attempts: 0,
124            queue_depth: 0,
125        })))
126    }
127
128    pub async fn snapshot(&self) -> StatusSnapshot {
129        let mut snapshot = self.0.read().await.clone();
130        snapshot.source_lag_millis = snapshot
131            .last_source_event_at
132            .map(|source_time| event_lag_millis(source_time, Utc::now()));
133        snapshot
134    }
135
136    pub async fn transition(&self, state: ConnectorState, reason: Option<String>) {
137        let mut status = self.0.write().await;
138        status.state = state;
139        status.state_since = Utc::now();
140        status.state_reason = reason;
141    }
142
143    async fn set_queue_depth(&self, depth: usize) {
144        self.0.write().await.queue_depth = depth;
145    }
146
147    async fn increment_failed_events(&self, failed: usize) {
148        self.0.write().await.failed_events += failed as u64;
149    }
150
151    async fn increment_sink_retry_attempts(&self) {
152        self.0.write().await.sink_retry_attempts += 1;
153    }
154
155    async fn checkpointed(
156        &self,
157        position: SourcePosition,
158        delivered: usize,
159        event_timing: Option<EventTiming>,
160    ) {
161        let mut status = self.0.write().await;
162        status.last_position = Some(position);
163        status.last_checkpoint_at = Some(Utc::now());
164        status.delivered_events += delivered as u64;
165        if let Some(event_timing) = event_timing {
166            status.last_source_event_at = event_timing.source_time;
167            status.last_event_observed_at = Some(event_timing.observed_time);
168            status.source_lag_millis = event_timing
169                .source_time
170                .map(|source_time| event_lag_millis(source_time, Utc::now()));
171        }
172    }
173}
174
175fn event_lag_millis(source_time: DateTime<Utc>, observed_time: DateTime<Utc>) -> u64 {
176    u64::try_from(
177        observed_time
178            .signed_duration_since(source_time)
179            .num_milliseconds()
180            .max(0),
181    )
182    .unwrap_or(u64::MAX)
183}
184
185pub struct ConnectorRuntime {
186    identity: ConnectorIdentity,
187    source: Option<Box<dyn SourceConnector>>,
188    encoder: Arc<dyn EventEncoder>,
189    sink: Box<dyn Sink>,
190    checkpoint_store: Arc<dyn CheckpointStore>,
191    config: RuntimeConfig,
192    status: RuntimeStatus,
193    signal_sender: SignalSender,
194    signal_receiver: Option<mpsc::Receiver<crate::SignalDelivery>>,
195}
196
197struct PendingBatch {
198    encoded: Vec<EncodedEvent>,
199    highest_position: Option<SourcePosition>,
200    latest_event_timing: Option<EventTiming>,
201    signal_acknowledgements: Vec<crate::SignalAcknowledgement>,
202}
203
204#[derive(Debug, Clone, Copy)]
205struct EventTiming {
206    source_time: Option<DateTime<Utc>>,
207    observed_time: DateTime<Utc>,
208}
209
210struct RetryState {
211    attempts: u64,
212    delay: Duration,
213}
214
215impl RetryState {
216    fn new(initial_delay: Duration) -> Self {
217        Self {
218            attempts: 0,
219            delay: initial_delay,
220        }
221    }
222}
223
224impl PendingBatch {
225    fn new(capacity: usize) -> Self {
226        Self {
227            encoded: Vec::with_capacity(capacity),
228            highest_position: None,
229            latest_event_timing: None,
230            signal_acknowledgements: Vec::new(),
231        }
232    }
233}
234
235impl ConnectorRuntime {
236    #[must_use]
237    pub fn new(
238        identity: ConnectorIdentity,
239        source: Box<dyn SourceConnector>,
240        encoder: Arc<dyn EventEncoder>,
241        sink: Box<dyn Sink>,
242        checkpoint_store: Arc<dyn CheckpointStore>,
243        config: RuntimeConfig,
244        status: RuntimeStatus,
245    ) -> Self {
246        let (signal_sender, signal_receiver) = signal_channel(config.channel_capacity);
247        Self {
248            identity,
249            source: Some(source),
250            encoder,
251            sink,
252            checkpoint_store,
253            config,
254            status,
255            signal_sender,
256            signal_receiver: Some(signal_receiver),
257        }
258    }
259
260    #[must_use]
261    pub fn signal_sender(&self) -> SignalSender {
262        self.signal_sender.clone()
263    }
264
265    pub async fn run(self, cancellation: CancellationToken) -> Result<()> {
266        let status = self.status.clone();
267        let result = self.run_inner(cancellation).await;
268        if let Err(error) = &result
269            && !matches!(error, Error::Cancelled)
270        {
271            status
272                .transition(ConnectorState::Failed, Some(error.to_string()))
273                .await;
274        }
275        result
276    }
277
278    async fn run_inner(mut self, cancellation: CancellationToken) -> Result<()> {
279        self.status.transition(ConnectorState::Starting, None).await;
280        let mut source = self
281            .source
282            .take()
283            .ok_or_else(|| Error::Invariant("source connector already started".into()))?;
284        source.validate().await?;
285        self.validate_sink_with_retry(&cancellation).await?;
286
287        let initial_checkpoint = self.checkpoint_store.load(&self.identity.name).await?;
288        if let Some(checkpoint) = &initial_checkpoint
289            && checkpoint.config_fingerprint != self.config.config_fingerprint
290        {
291            return Err(Error::Configuration(
292                "persisted checkpoint does not match the active configuration".into(),
293            ));
294        }
295
296        let (source_tx, mut source_rx) = mpsc::channel(self.config.channel_capacity);
297        let signals = self
298            .signal_receiver
299            .take()
300            .ok_or_else(|| Error::Invariant("runtime signal channel already started".into()))?;
301        let (ack_tx, ack_rx) = watch::channel(
302            initial_checkpoint
303                .as_ref()
304                .map(|checkpoint| checkpoint.source_position.clone()),
305        );
306
307        let snapshot_completed = initial_checkpoint
308            .as_ref()
309            .is_some_and(|checkpoint| checkpoint.snapshot_completed);
310        let mut connector_state = initial_checkpoint
311            .as_ref()
312            .and_then(|checkpoint| checkpoint.connector_state.clone());
313        let source_cancel = cancellation.child_token();
314        let mut source_handle: JoinHandle<Result<()>> = tokio::spawn(async move {
315            source
316                .run(SourceContext {
317                    output: source_tx,
318                    acknowledged: ack_rx,
319                    initial_checkpoint,
320                    signals,
321                    cancellation: source_cancel,
322                })
323                .await
324        });
325
326        let pipeline_result: Result<()> = async {
327            self.status
328                .transition(ConnectorState::Streaming, None)
329                .await;
330            let mut interval = tokio::time::interval_at(
331                Instant::now() + self.config.flush_interval,
332                self.config.flush_interval,
333            );
334            interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
335
336            let mut pending = PendingBatch::new(self.config.max_batch_size);
337            let mut snapshot_completed = snapshot_completed;
338
339            loop {
340                tokio::select! {
341                    _ = cancellation.cancelled() => break,
342                    _ = interval.tick() => {
343                        self.flush_batch(
344                            &mut pending,
345                            snapshot_completed,
346                            &connector_state,
347                            &ack_tx,
348                            &cancellation,
349                        ).await?;
350                    }
351                    record = source_rx.recv() => {
352                        let Some(record) = record else { break };
353                        let record = record?;
354                        self.status.set_queue_depth(source_rx.len()).await;
355                        self.consume_record(
356                            record,
357                            &mut pending,
358                            &mut snapshot_completed,
359                            &mut connector_state,
360                            &ack_tx,
361                            &cancellation,
362                        ).await?;
363                    }
364                }
365            }
366
367            self.flush_batch(
368                &mut pending,
369                snapshot_completed,
370                &connector_state,
371                &ack_tx,
372                &cancellation,
373            )
374            .await?;
375            self.flush_sink_with_retry(&cancellation).await
376        }
377        .await;
378        let pipeline_result = match pipeline_result {
379            Err(Error::Cancelled) if cancellation.is_cancelled() => Ok(()),
380            result => result,
381        };
382
383        if pipeline_result.is_ok() {
384            self.status.transition(ConnectorState::Stopping, None).await;
385        }
386        cancellation.cancel();
387
388        let source_result =
389            match tokio::time::timeout(self.config.shutdown_timeout, &mut source_handle).await {
390                Ok(Ok(Ok(()))) | Ok(Ok(Err(Error::Cancelled))) => Ok(()),
391                Ok(Ok(Err(error))) => Err(error),
392                Ok(Err(error)) => Err(Error::Source(format!("source task failed: {error}"))),
393                Err(_) => {
394                    source_handle.abort();
395                    let _ = source_handle.await;
396                    Err(Error::Source("source shutdown timed out".into()))
397                }
398            };
399
400        let shutdown_result = self.sink.shutdown().await;
401        pipeline_result?;
402        source_result?;
403        shutdown_result?;
404        self.status.transition(ConnectorState::Stopped, None).await;
405        info!(connector = %self.identity.name, "connector stopped");
406        Ok(())
407    }
408
409    async fn consume_record(
410        &mut self,
411        record: SourceRecord,
412        pending: &mut PendingBatch,
413        snapshot_completed: &mut bool,
414        connector_state: &mut Option<ConnectorStateEnvelope>,
415        ack_tx: &watch::Sender<Option<SourcePosition>>,
416        cancellation: &CancellationToken,
417    ) -> Result<()> {
418        if let Some(previous) = pending.highest_position.as_ref()
419            && !record.position.is_after(previous)
420            && record.position != *previous
421        {
422            return Err(Error::Invariant(format!(
423                "source position moved backwards: {:?} -> {:?}",
424                previous, record.position
425            )));
426        }
427
428        if let Some(event) = &record.event {
429            let incremental_snapshot = event
430                .source
431                .attributes
432                .get("rustium.snapshot.kind")
433                .and_then(serde_json::Value::as_str)
434                == Some("incremental");
435            if event.source.snapshot
436                && !incremental_snapshot
437                && self.status.snapshot().await.state != ConnectorState::Snapshotting
438            {
439                self.status
440                    .transition(ConnectorState::Snapshotting, None)
441                    .await;
442            }
443            match self.encoder.encode_batch(event) {
444                Ok(encoded) => pending.encoded.extend(encoded),
445                Err(error) => {
446                    self.status.increment_failed_events(1).await;
447                    return Err(error);
448                }
449            }
450            pending.latest_event_timing = Some(EventTiming {
451                source_time: event.source_time,
452                observed_time: event.observed_time,
453            });
454        }
455        pending.highest_position = Some(record.position);
456        if let Some(state) = record.connector_state {
457            *connector_state = Some(state);
458        }
459        pending
460            .signal_acknowledgements
461            .extend(record.signal_acknowledgements);
462
463        match record.boundary {
464            RecordBoundary::SnapshotComplete => {
465                *snapshot_completed = true;
466                self.status
467                    .transition(ConnectorState::Streaming, None)
468                    .await;
469                self.flush_batch(
470                    pending,
471                    *snapshot_completed,
472                    connector_state,
473                    ack_tx,
474                    cancellation,
475                )
476                .await?;
477            }
478            RecordBoundary::TransactionCommit => {
479                self.flush_batch(
480                    pending,
481                    *snapshot_completed,
482                    connector_state,
483                    ack_tx,
484                    cancellation,
485                )
486                .await?;
487            }
488            RecordBoundary::Data if pending.encoded.len() >= self.config.max_batch_size => {
489                self.flush_batch(
490                    pending,
491                    *snapshot_completed,
492                    connector_state,
493                    ack_tx,
494                    cancellation,
495                )
496                .await?;
497            }
498            RecordBoundary::Heartbeat if pending.encoded.is_empty() => {
499                self.flush_batch(
500                    pending,
501                    *snapshot_completed,
502                    connector_state,
503                    ack_tx,
504                    cancellation,
505                )
506                .await?;
507            }
508            _ => {}
509        }
510        Ok(())
511    }
512
513    async fn flush_batch(
514        &mut self,
515        pending: &mut PendingBatch,
516        snapshot_completed: bool,
517        connector_state: &Option<ConnectorStateEnvelope>,
518        ack_tx: &watch::Sender<Option<SourcePosition>>,
519        cancellation: &CancellationToken,
520    ) -> Result<()> {
521        let Some(position) = pending.highest_position.take() else {
522            return Ok(());
523        };
524        let delivered = pending.encoded.len();
525
526        if !pending.encoded.is_empty() {
527            let batch = DeliveryBatch {
528                events: std::mem::take(&mut pending.encoded),
529                highest_position: position.clone(),
530            };
531            if let Err(error) = self.write_sink_with_retry(&batch, cancellation).await {
532                if matches!(error, Error::Cancelled) {
533                    return Err(error);
534                }
535                error!(connector = %self.identity.name, %error, "sink delivery failed");
536                self.status.increment_failed_events(delivered).await;
537                return Err(error);
538            }
539        }
540
541        let checkpoint = Checkpoint {
542            schema_version: CHECKPOINT_SCHEMA_VERSION,
543            connector_name: self.identity.name.clone(),
544            generation: self.identity.generation,
545            source_position: position.clone(),
546            snapshot_completed,
547            config_fingerprint: self.config.config_fingerprint.clone(),
548            updated_at: std::time::SystemTime::now(),
549            connector_state: connector_state.clone(),
550        };
551        self.checkpoint_store.save(&checkpoint).await?;
552        ack_tx
553            .send(Some(position.clone()))
554            .map_err(|_| Error::Source("source acknowledgement channel closed".into()))?;
555        for acknowledgement in pending.signal_acknowledgements.drain(..) {
556            acknowledgement.acknowledge();
557        }
558        self.status
559            .checkpointed(position, delivered, pending.latest_event_timing.take())
560            .await;
561        Ok(())
562    }
563
564    async fn validate_sink_with_retry(&mut self, cancellation: &CancellationToken) -> Result<()> {
565        let mut retry = RetryState::new(self.config.errors_retry_delay_initial);
566        loop {
567            match self.sink.validate().await {
568                Ok(()) => return Ok(()),
569                Err(error @ Error::RetryableSink(_)) => {
570                    if !self
571                        .wait_for_sink_retry("validation", &error, &mut retry, cancellation)
572                        .await?
573                    {
574                        return Err(error);
575                    }
576                }
577                Err(error) => return Err(error),
578            }
579        }
580    }
581
582    async fn write_sink_with_retry(
583        &mut self,
584        batch: &DeliveryBatch,
585        cancellation: &CancellationToken,
586    ) -> Result<()> {
587        let mut retry = RetryState::new(self.config.errors_retry_delay_initial);
588        loop {
589            match self.sink.write(batch).await {
590                Ok(()) => return Ok(()),
591                Err(error @ Error::RetryableSink(_)) => {
592                    if !self
593                        .wait_for_sink_retry("delivery", &error, &mut retry, cancellation)
594                        .await?
595                    {
596                        return Err(error);
597                    }
598                }
599                Err(error) => return Err(error),
600            }
601        }
602    }
603
604    async fn flush_sink_with_retry(&mut self, cancellation: &CancellationToken) -> Result<()> {
605        let mut retry = RetryState::new(self.config.errors_retry_delay_initial);
606        loop {
607            match self.sink.flush().await {
608                Ok(()) => return Ok(()),
609                Err(error @ Error::RetryableSink(_)) => {
610                    if !self
611                        .wait_for_sink_retry("flush", &error, &mut retry, cancellation)
612                        .await?
613                    {
614                        return Err(error);
615                    }
616                }
617                Err(error) => return Err(error),
618            }
619        }
620    }
621
622    async fn wait_for_sink_retry(
623        &mut self,
624        operation: &'static str,
625        error: &Error,
626        retry: &mut RetryState,
627        cancellation: &CancellationToken,
628    ) -> Result<bool> {
629        if self.config.errors_max_retries >= 0
630            && retry.attempts >= self.config.errors_max_retries as u64
631        {
632            return Ok(false);
633        }
634        retry.attempts += 1;
635        self.status.increment_sink_retry_attempts().await;
636        warn!(
637            connector = %self.identity.name,
638            sink = self.sink.name(),
639            operation,
640            retry = retry.attempts,
641            max_retries = self.config.errors_max_retries,
642            delay_ms = retry.delay.as_millis(),
643            %error,
644            "retryable Sink operation failed; scheduling retry"
645        );
646        tokio::select! {
647            () = cancellation.cancelled() => return Err(Error::Cancelled),
648            () = tokio::time::sleep(retry.delay) => {}
649        }
650        retry.delay = retry
651            .delay
652            .saturating_mul(2)
653            .min(self.config.errors_retry_delay_max);
654        Ok(true)
655    }
656}
657
658#[cfg(test)]
659mod tests {
660    use std::{
661        collections::BTreeMap,
662        sync::{
663            Arc, Mutex,
664            atomic::{AtomicBool, AtomicUsize, Ordering},
665        },
666    };
667
668    use async_trait::async_trait;
669    use bytes::Bytes;
670    use chrono::Utc;
671    use tokio::sync::Notify;
672
673    use super::*;
674    use crate::{
675        ChangeEvent, ConnectorStateEnvelope, Durability, EventId, EventSchema, MySqlPosition,
676        Operation, RecordBoundary, SourceMetadata,
677    };
678
679    struct StateSource {
680        record: SourceRecord,
681    }
682
683    struct SignalSource {
684        received: Arc<Mutex<Option<crate::SignalRecord>>>,
685    }
686
687    struct CheckpointSignalSource {
688        position: SourcePosition,
689    }
690
691    struct CancellableStateSource {
692        record: SourceRecord,
693        cancelled: Arc<AtomicBool>,
694    }
695
696    struct StuckSource {
697        dropped: Arc<AtomicBool>,
698    }
699
700    struct BurstSource {
701        sent: Arc<AtomicUsize>,
702        total: usize,
703    }
704
705    struct DropFlag(Arc<AtomicBool>);
706
707    impl Drop for DropFlag {
708        fn drop(&mut self) {
709            self.0.store(true, Ordering::SeqCst);
710        }
711    }
712
713    #[async_trait]
714    impl SourceConnector for StateSource {
715        fn source_type(&self) -> &'static str {
716            "test"
717        }
718
719        async fn validate(&mut self) -> Result<()> {
720            Ok(())
721        }
722
723        async fn run(&mut self, mut context: SourceContext) -> Result<()> {
724            context
725                .output
726                .send(Ok(self.record.clone()))
727                .await
728                .map_err(|_| Error::Cancelled)?;
729            context
730                .acknowledged
731                .changed()
732                .await
733                .map_err(|_| Error::Cancelled)?;
734            Ok(())
735        }
736    }
737
738    #[async_trait]
739    impl SourceConnector for SignalSource {
740        fn source_type(&self) -> &'static str {
741            "signal-test"
742        }
743
744        async fn validate(&mut self) -> Result<()> {
745            Ok(())
746        }
747
748        async fn run(&mut self, mut context: SourceContext) -> Result<()> {
749            let signal = context.signals.recv().await.ok_or(Error::Cancelled)?;
750            *self.received.lock().unwrap() = Some(signal.record().clone());
751            signal.acknowledge();
752            Ok(())
753        }
754    }
755
756    #[async_trait]
757    impl SourceConnector for CheckpointSignalSource {
758        fn source_type(&self) -> &'static str {
759            "checkpoint-signal-test"
760        }
761
762        async fn validate(&mut self) -> Result<()> {
763            Ok(())
764        }
765
766        async fn run(&mut self, mut context: SourceContext) -> Result<()> {
767            let signal = context.signals.recv().await.ok_or(Error::Cancelled)?;
768            context
769                .output
770                .send(Ok(SourceRecord {
771                    event: None,
772                    position: self.position.clone(),
773                    boundary: RecordBoundary::TransactionCommit,
774                    connector_state: None,
775                    signal_acknowledgements: signal.into_acknowledgement().into_iter().collect(),
776                }))
777                .await
778                .map_err(|_| Error::Cancelled)?;
779            context
780                .acknowledged
781                .changed()
782                .await
783                .map_err(|_| Error::Cancelled)
784        }
785    }
786
787    #[async_trait]
788    impl SourceConnector for CancellableStateSource {
789        fn source_type(&self) -> &'static str {
790            "cancellable-test"
791        }
792
793        async fn validate(&mut self) -> Result<()> {
794            Ok(())
795        }
796
797        async fn run(&mut self, context: SourceContext) -> Result<()> {
798            context
799                .output
800                .send(Ok(self.record.clone()))
801                .await
802                .map_err(|_| Error::Cancelled)?;
803            context.cancellation.cancelled().await;
804            self.cancelled.store(true, Ordering::SeqCst);
805            Err(Error::Cancelled)
806        }
807    }
808
809    #[async_trait]
810    impl SourceConnector for StuckSource {
811        fn source_type(&self) -> &'static str {
812            "stuck-test"
813        }
814
815        async fn validate(&mut self) -> Result<()> {
816            Ok(())
817        }
818
819        async fn run(&mut self, _context: SourceContext) -> Result<()> {
820            let _drop_flag = DropFlag(self.dropped.clone());
821            std::future::pending().await
822        }
823    }
824
825    #[async_trait]
826    impl SourceConnector for BurstSource {
827        fn source_type(&self) -> &'static str {
828            "burst-test"
829        }
830
831        async fn validate(&mut self) -> Result<()> {
832            Ok(())
833        }
834
835        async fn run(&mut self, mut context: SourceContext) -> Result<()> {
836            let mut last_position = None;
837            for serial in 1..=self.total {
838                let event = test_event(serial as u64);
839                last_position = Some(event.position.clone());
840                context
841                    .output
842                    .send(Ok(SourceRecord::data(event)))
843                    .await
844                    .map_err(|_| Error::Cancelled)?;
845                self.sent.fetch_add(1, Ordering::SeqCst);
846            }
847            while context.acknowledged.borrow().as_ref() != last_position.as_ref() {
848                context
849                    .acknowledged
850                    .changed()
851                    .await
852                    .map_err(|_| Error::Cancelled)?;
853            }
854            Ok(())
855        }
856    }
857
858    struct UnusedEncoder;
859
860    impl EventEncoder for UnusedEncoder {
861        fn content_type(&self) -> &'static str {
862            "application/test"
863        }
864
865        fn encode(&self, _event: &ChangeEvent) -> Result<EncodedEvent> {
866            Err(Error::Invariant(
867                "position-only runtime test unexpectedly encoded an event".into(),
868            ))
869        }
870    }
871
872    struct NoopSink;
873
874    #[async_trait]
875    impl Sink for NoopSink {
876        fn name(&self) -> &'static str {
877            "noop"
878        }
879
880        fn durability(&self) -> Durability {
881            Durability::Durable
882        }
883
884        async fn validate(&mut self) -> Result<()> {
885            Ok(())
886        }
887
888        async fn write(&mut self, _batch: &DeliveryBatch) -> Result<()> {
889            Ok(())
890        }
891
892        async fn flush(&mut self) -> Result<()> {
893            Ok(())
894        }
895    }
896
897    struct BatchEncoder;
898
899    impl EventEncoder for BatchEncoder {
900        fn content_type(&self) -> &'static str {
901            "application/test"
902        }
903
904        fn encode(&self, _event: &ChangeEvent) -> Result<EncodedEvent> {
905            Err(Error::Invariant(
906                "batch encoder must be invoked through encode_batch".into(),
907            ))
908        }
909
910        fn encode_batch(&self, event: &ChangeEvent) -> Result<Vec<EncodedEvent>> {
911            let encoded = |id: EventId, payload| EncodedEvent {
912                id,
913                destination: "orders".into(),
914                key: Some(Bytes::from_static(b"1")),
915                key_schema: None,
916                payload,
917                payload_schema: None,
918                headers: BTreeMap::new(),
919            };
920            Ok(vec![
921                encoded(event.id.clone(), Some(Bytes::from_static(br#"{"op":"d"}"#))),
922                encoded(event.id.derived("tombstone"), None),
923            ])
924        }
925    }
926
927    struct RecordingSink {
928        batch_sizes: Arc<Mutex<Vec<usize>>>,
929    }
930
931    struct FailingSink {
932        shutdown: Arc<AtomicBool>,
933    }
934
935    struct RetryingSink {
936        failures: usize,
937        attempts: Arc<AtomicUsize>,
938    }
939
940    struct BlockingSink {
941        blocked: bool,
942        entered: Arc<Notify>,
943        release: Arc<Notify>,
944    }
945
946    #[async_trait]
947    impl Sink for RecordingSink {
948        fn name(&self) -> &'static str {
949            "recording"
950        }
951
952        fn durability(&self) -> Durability {
953            Durability::Durable
954        }
955
956        async fn validate(&mut self) -> Result<()> {
957            Ok(())
958        }
959
960        async fn write(&mut self, batch: &DeliveryBatch) -> Result<()> {
961            self.batch_sizes.lock().unwrap().push(batch.events.len());
962            assert!(batch.events[0].payload.is_some());
963            assert!(batch.events[1].payload.is_none());
964            Ok(())
965        }
966
967        async fn flush(&mut self) -> Result<()> {
968            Ok(())
969        }
970    }
971
972    #[async_trait]
973    impl Sink for FailingSink {
974        fn name(&self) -> &'static str {
975            "failing"
976        }
977
978        fn durability(&self) -> Durability {
979            Durability::Durable
980        }
981
982        async fn validate(&mut self) -> Result<()> {
983            Ok(())
984        }
985
986        async fn write(&mut self, _batch: &DeliveryBatch) -> Result<()> {
987            Err(Error::Sink("intentional delivery failure".into()))
988        }
989
990        async fn flush(&mut self) -> Result<()> {
991            Ok(())
992        }
993
994        async fn shutdown(&mut self) -> Result<()> {
995            self.shutdown.store(true, Ordering::SeqCst);
996            Ok(())
997        }
998    }
999
1000    #[async_trait]
1001    impl Sink for RetryingSink {
1002        fn name(&self) -> &'static str {
1003            "retrying"
1004        }
1005
1006        fn durability(&self) -> Durability {
1007            Durability::Durable
1008        }
1009
1010        async fn validate(&mut self) -> Result<()> {
1011            Ok(())
1012        }
1013
1014        async fn write(&mut self, _batch: &DeliveryBatch) -> Result<()> {
1015            let attempt = self.attempts.fetch_add(1, Ordering::SeqCst);
1016            if attempt < self.failures {
1017                Err(Error::RetryableSink(format!(
1018                    "intentional retryable failure {}",
1019                    attempt + 1
1020                )))
1021            } else {
1022                Ok(())
1023            }
1024        }
1025
1026        async fn flush(&mut self) -> Result<()> {
1027            Ok(())
1028        }
1029    }
1030
1031    #[async_trait]
1032    impl Sink for BlockingSink {
1033        fn name(&self) -> &'static str {
1034            "blocking"
1035        }
1036
1037        fn durability(&self) -> Durability {
1038            Durability::Durable
1039        }
1040
1041        async fn validate(&mut self) -> Result<()> {
1042            Ok(())
1043        }
1044
1045        async fn write(&mut self, _batch: &DeliveryBatch) -> Result<()> {
1046            if !self.blocked {
1047                self.blocked = true;
1048                self.entered.notify_one();
1049                self.release.notified().await;
1050            }
1051            Ok(())
1052        }
1053
1054        async fn flush(&mut self) -> Result<()> {
1055            Ok(())
1056        }
1057    }
1058
1059    #[derive(Default)]
1060    struct MemoryCheckpointStore {
1061        checkpoint: Mutex<Option<Checkpoint>>,
1062    }
1063
1064    #[async_trait]
1065    impl CheckpointStore for MemoryCheckpointStore {
1066        async fn load(&self, _connector_name: &str) -> Result<Option<Checkpoint>> {
1067            Ok(self.checkpoint.lock().unwrap().clone())
1068        }
1069
1070        async fn save(&self, checkpoint: &Checkpoint) -> Result<()> {
1071            *self.checkpoint.lock().unwrap() = Some(checkpoint.clone());
1072            Ok(())
1073        }
1074
1075        async fn delete(&self, _connector_name: &str) -> Result<()> {
1076            *self.checkpoint.lock().unwrap() = None;
1077            Ok(())
1078        }
1079    }
1080
1081    fn test_event(event_serial: u64) -> ChangeEvent {
1082        let position = SourcePosition::MySql(MySqlPosition {
1083            binlog_filename: "mysql-bin.000001".into(),
1084            binlog_position: 1_000 + event_serial,
1085            gtid_set: None,
1086            server_id: 1,
1087            event_serial,
1088            snapshot: false,
1089        });
1090        ChangeEvent {
1091            id: EventId::deterministic(
1092                "runtime-test",
1093                "mysql",
1094                &position,
1095                "app.orders",
1096                event_serial,
1097            ),
1098            source: SourceMetadata {
1099                connector: "mysql".into(),
1100                connector_name: "runtime-test".into(),
1101                database: "app".into(),
1102                schema: None,
1103                table: Some("orders".into()),
1104                snapshot: false,
1105                version: "test".into(),
1106                attributes: BTreeMap::new(),
1107            },
1108            position,
1109            transaction: None,
1110            operation: Operation::Create,
1111            before: None,
1112            after: None,
1113            schema: EventSchema {
1114                name: "orders".into(),
1115                version: 1,
1116                fields: Vec::new(),
1117            },
1118            source_time: Some(Utc::now()),
1119            observed_time: Utc::now(),
1120        }
1121    }
1122
1123    struct SingleEncoder;
1124
1125    impl EventEncoder for SingleEncoder {
1126        fn content_type(&self) -> &'static str {
1127            "application/test"
1128        }
1129
1130        fn encode(&self, event: &ChangeEvent) -> Result<EncodedEvent> {
1131            Ok(EncodedEvent {
1132                id: event.id.clone(),
1133                destination: "orders".into(),
1134                key: Some(Bytes::from_static(b"1")),
1135                key_schema: None,
1136                payload: Some(Bytes::from_static(b"value")),
1137                payload_schema: None,
1138                headers: BTreeMap::new(),
1139            })
1140        }
1141    }
1142
1143    #[tokio::test]
1144    async fn checkpoints_connector_state_with_its_source_position() {
1145        let position = SourcePosition::MySql(MySqlPosition {
1146            binlog_filename: "mysql-bin.000001".into(),
1147            binlog_position: 128,
1148            gtid_set: None,
1149            server_id: 1,
1150            event_serial: 0,
1151            snapshot: false,
1152        });
1153        let connector_state =
1154            ConnectorStateEnvelope::new("rustium.test", 1, serde_json::json!({"table": "orders"}));
1155        let source = StateSource {
1156            record: SourceRecord {
1157                event: None,
1158                position: position.clone(),
1159                boundary: RecordBoundary::Heartbeat,
1160                connector_state: Some(connector_state.clone()),
1161                signal_acknowledgements: Vec::new(),
1162            },
1163        };
1164        let store = Arc::new(MemoryCheckpointStore::default());
1165        let runtime = ConnectorRuntime::new(
1166            ConnectorIdentity::new("runtime-state-test"),
1167            Box::new(source),
1168            Arc::new(UnusedEncoder),
1169            Box::new(NoopSink),
1170            store.clone(),
1171            RuntimeConfig {
1172                flush_interval: Duration::from_secs(60),
1173                ..RuntimeConfig::default()
1174            },
1175            RuntimeStatus::new("runtime-state-test"),
1176        );
1177
1178        runtime.run(CancellationToken::new()).await.unwrap();
1179
1180        let checkpoint = store.checkpoint.lock().unwrap().clone().unwrap();
1181        assert_eq!(checkpoint.schema_version, CHECKPOINT_SCHEMA_VERSION);
1182        assert_eq!(checkpoint.source_position, position);
1183        assert_eq!(checkpoint.connector_state, Some(connector_state));
1184    }
1185
1186    #[tokio::test]
1187    async fn exposes_a_typed_signal_sender_before_runtime_start() {
1188        let received = Arc::new(Mutex::new(None));
1189        let runtime = ConnectorRuntime::new(
1190            ConnectorIdentity::new("runtime-signal-test"),
1191            Box::new(SignalSource {
1192                received: received.clone(),
1193            }),
1194            Arc::new(UnusedEncoder),
1195            Box::new(NoopSink),
1196            Arc::new(MemoryCheckpointStore::default()),
1197            RuntimeConfig::default(),
1198            RuntimeStatus::new("runtime-signal-test"),
1199        );
1200        let sender = runtime.signal_sender();
1201        let signal = crate::SignalRecord::new(
1202            "snapshot-1",
1203            "execute-snapshot",
1204            serde_json::json!({"type": "incremental"}),
1205        );
1206        sender.send(signal.clone()).await.unwrap();
1207
1208        runtime.run(CancellationToken::new()).await.unwrap();
1209
1210        assert_eq!(*received.lock().unwrap(), Some(signal));
1211    }
1212
1213    #[tokio::test]
1214    async fn acknowledges_a_signal_only_after_its_checkpoint_is_saved() {
1215        let position = SourcePosition::MySql(MySqlPosition {
1216            binlog_filename: "binlog.000001".into(),
1217            binlog_position: 120,
1218            gtid_set: None,
1219            server_id: 1,
1220            event_serial: 0,
1221            snapshot: false,
1222        });
1223        let store = Arc::new(MemoryCheckpointStore::default());
1224        let runtime = ConnectorRuntime::new(
1225            ConnectorIdentity::new("runtime-durable-signal-test"),
1226            Box::new(CheckpointSignalSource {
1227                position: position.clone(),
1228            }),
1229            Arc::new(UnusedEncoder),
1230            Box::new(NoopSink),
1231            store.clone(),
1232            RuntimeConfig::default(),
1233            RuntimeStatus::new("runtime-durable-signal-test"),
1234        );
1235        let sender = runtime.signal_sender();
1236        let send = tokio::spawn(async move {
1237            sender
1238                .send_and_wait(crate::SignalRecord::new(
1239                    "snapshot-2",
1240                    "execute-snapshot",
1241                    serde_json::json!({"type": "incremental"}),
1242                ))
1243                .await
1244        });
1245
1246        runtime.run(CancellationToken::new()).await.unwrap();
1247        send.await.unwrap().unwrap();
1248
1249        assert_eq!(
1250            store
1251                .load("runtime-durable-signal-test")
1252                .await
1253                .unwrap()
1254                .unwrap()
1255                .source_position,
1256            position
1257        );
1258    }
1259
1260    #[tokio::test]
1261    async fn checkpoints_after_all_encoded_records_are_delivered_together() {
1262        let position = SourcePosition::MySql(MySqlPosition {
1263            binlog_filename: "mysql-bin.000001".into(),
1264            binlog_position: 256,
1265            gtid_set: None,
1266            server_id: 1,
1267            event_serial: 1,
1268            snapshot: false,
1269        });
1270        let source_time = Utc::now() - chrono::Duration::seconds(2);
1271        let observed_time = Utc::now();
1272        let event = ChangeEvent {
1273            id: EventId::deterministic("orders", "mysql", &position, "app.orders", 1),
1274            source: SourceMetadata {
1275                connector: "mysql".into(),
1276                connector_name: "orders".into(),
1277                database: "app".into(),
1278                schema: None,
1279                table: Some("orders".into()),
1280                snapshot: false,
1281                version: "test".into(),
1282                attributes: BTreeMap::new(),
1283            },
1284            position: position.clone(),
1285            transaction: None,
1286            operation: Operation::Delete,
1287            before: None,
1288            after: None,
1289            schema: EventSchema {
1290                name: "orders".into(),
1291                version: 1,
1292                fields: Vec::new(),
1293            },
1294            source_time: Some(source_time),
1295            observed_time,
1296        };
1297        let source = StateSource {
1298            record: SourceRecord {
1299                event: Some(event),
1300                position: position.clone(),
1301                boundary: RecordBoundary::TransactionCommit,
1302                connector_state: None,
1303                signal_acknowledgements: Vec::new(),
1304            },
1305        };
1306        let store = Arc::new(MemoryCheckpointStore::default());
1307        let batch_sizes = Arc::new(Mutex::new(Vec::new()));
1308        let status = RuntimeStatus::new("runtime-batch-test");
1309        let runtime = ConnectorRuntime::new(
1310            ConnectorIdentity::new("runtime-batch-test"),
1311            Box::new(source),
1312            Arc::new(BatchEncoder),
1313            Box::new(RecordingSink {
1314                batch_sizes: batch_sizes.clone(),
1315            }),
1316            store.clone(),
1317            RuntimeConfig::default(),
1318            status.clone(),
1319        );
1320
1321        runtime.run(CancellationToken::new()).await.unwrap();
1322
1323        assert_eq!(*batch_sizes.lock().unwrap(), [2]);
1324        assert_eq!(
1325            store
1326                .checkpoint
1327                .lock()
1328                .unwrap()
1329                .as_ref()
1330                .unwrap()
1331                .source_position,
1332            position
1333        );
1334        let status = status.snapshot().await;
1335        assert_eq!(status.delivered_events, 2);
1336        assert_eq!(status.last_source_event_at, Some(source_time));
1337        assert_eq!(status.last_event_observed_at, Some(observed_time));
1338        assert!(status.source_lag_millis.is_some_and(|lag| lag >= 2_000));
1339    }
1340
1341    #[tokio::test]
1342    async fn retries_the_same_sink_batch_before_checkpointing() {
1343        let event = test_event(10);
1344        let position = event.position.clone();
1345        let store = Arc::new(MemoryCheckpointStore::default());
1346        let attempts = Arc::new(AtomicUsize::new(0));
1347        let status = RuntimeStatus::new("runtime-retry-test");
1348        let runtime = ConnectorRuntime::new(
1349            ConnectorIdentity::new("runtime-retry-test"),
1350            Box::new(StateSource {
1351                record: SourceRecord {
1352                    event: Some(event),
1353                    position: position.clone(),
1354                    boundary: RecordBoundary::TransactionCommit,
1355                    connector_state: None,
1356                    signal_acknowledgements: Vec::new(),
1357                },
1358            }),
1359            Arc::new(SingleEncoder),
1360            Box::new(RetryingSink {
1361                failures: 2,
1362                attempts: attempts.clone(),
1363            }),
1364            store.clone(),
1365            RuntimeConfig {
1366                errors_max_retries: 2,
1367                errors_retry_delay_initial: Duration::from_millis(1),
1368                errors_retry_delay_max: Duration::from_millis(2),
1369                ..RuntimeConfig::default()
1370            },
1371            status.clone(),
1372        );
1373
1374        runtime.run(CancellationToken::new()).await.unwrap();
1375
1376        assert_eq!(attempts.load(Ordering::SeqCst), 3);
1377        assert_eq!(
1378            store
1379                .checkpoint
1380                .lock()
1381                .unwrap()
1382                .as_ref()
1383                .unwrap()
1384                .source_position,
1385            position
1386        );
1387        let status = status.snapshot().await;
1388        assert_eq!(status.sink_retry_attempts, 2);
1389        assert_eq!(status.delivered_events, 1);
1390        assert_eq!(status.failed_events, 0);
1391    }
1392
1393    #[tokio::test]
1394    async fn exhausts_sink_retries_without_advancing_the_checkpoint() {
1395        let event = test_event(11);
1396        let position = event.position.clone();
1397        let store = Arc::new(MemoryCheckpointStore::default());
1398        let attempts = Arc::new(AtomicUsize::new(0));
1399        let cancelled = Arc::new(AtomicBool::new(false));
1400        let status = RuntimeStatus::new("runtime-retry-exhaustion-test");
1401        let runtime = ConnectorRuntime::new(
1402            ConnectorIdentity::new("runtime-retry-exhaustion-test"),
1403            Box::new(CancellableStateSource {
1404                record: SourceRecord {
1405                    event: Some(event),
1406                    position,
1407                    boundary: RecordBoundary::TransactionCommit,
1408                    connector_state: None,
1409                    signal_acknowledgements: Vec::new(),
1410                },
1411                cancelled: cancelled.clone(),
1412            }),
1413            Arc::new(SingleEncoder),
1414            Box::new(RetryingSink {
1415                failures: usize::MAX,
1416                attempts: attempts.clone(),
1417            }),
1418            store.clone(),
1419            RuntimeConfig {
1420                errors_max_retries: 2,
1421                errors_retry_delay_initial: Duration::from_millis(1),
1422                errors_retry_delay_max: Duration::from_millis(2),
1423                ..RuntimeConfig::default()
1424            },
1425            status.clone(),
1426        );
1427
1428        let error = runtime.run(CancellationToken::new()).await.unwrap_err();
1429
1430        assert!(
1431            error
1432                .to_string()
1433                .contains("intentional retryable failure 3")
1434        );
1435        assert_eq!(attempts.load(Ordering::SeqCst), 3);
1436        assert!(store.checkpoint.lock().unwrap().is_none());
1437        assert!(cancelled.load(Ordering::SeqCst));
1438        let status = status.snapshot().await;
1439        assert_eq!(status.sink_retry_attempts, 2);
1440        assert_eq!(status.delivered_events, 0);
1441        assert_eq!(status.failed_events, 1);
1442        assert_eq!(status.state, ConnectorState::Failed);
1443    }
1444
1445    #[tokio::test]
1446    async fn applies_bounded_backpressure_while_the_sink_is_blocked() {
1447        let total = 16;
1448        let sent = Arc::new(AtomicUsize::new(0));
1449        let entered = Arc::new(Notify::new());
1450        let release = Arc::new(Notify::new());
1451        let store = Arc::new(MemoryCheckpointStore::default());
1452        let runtime = ConnectorRuntime::new(
1453            ConnectorIdentity::new("runtime-backpressure-test"),
1454            Box::new(BurstSource {
1455                sent: sent.clone(),
1456                total,
1457            }),
1458            Arc::new(SingleEncoder),
1459            Box::new(BlockingSink {
1460                blocked: false,
1461                entered: entered.clone(),
1462                release: release.clone(),
1463            }),
1464            store.clone(),
1465            RuntimeConfig {
1466                channel_capacity: 2,
1467                max_batch_size: 1,
1468                flush_interval: Duration::from_secs(60),
1469                ..RuntimeConfig::default()
1470            },
1471            RuntimeStatus::new("runtime-backpressure-test"),
1472        );
1473        let task = tokio::spawn(runtime.run(CancellationToken::new()));
1474
1475        tokio::time::timeout(Duration::from_secs(1), entered.notified())
1476            .await
1477            .unwrap();
1478        tokio::time::sleep(Duration::from_millis(20)).await;
1479        assert!(sent.load(Ordering::SeqCst) <= 3);
1480        release.notify_one();
1481        tokio::time::timeout(Duration::from_secs(2), task)
1482            .await
1483            .unwrap()
1484            .unwrap()
1485            .unwrap();
1486
1487        assert_eq!(sent.load(Ordering::SeqCst), total);
1488        let checkpoint_position = store
1489            .checkpoint
1490            .lock()
1491            .unwrap()
1492            .as_ref()
1493            .unwrap()
1494            .source_position
1495            .clone();
1496        let SourcePosition::MySql(position) = checkpoint_position else {
1497            panic!("backpressure checkpoint used the wrong source position");
1498        };
1499        assert_eq!(position.event_serial, total as u64);
1500    }
1501
1502    #[tokio::test]
1503    async fn cancels_source_shuts_down_sink_and_counts_failed_batches() {
1504        let position = SourcePosition::MySql(MySqlPosition {
1505            binlog_filename: "mysql-bin.000001".into(),
1506            binlog_position: 512,
1507            gtid_set: None,
1508            server_id: 1,
1509            event_serial: 2,
1510            snapshot: false,
1511        });
1512        let event = ChangeEvent {
1513            id: EventId::deterministic("orders", "mysql", &position, "app.orders", 2),
1514            source: SourceMetadata {
1515                connector: "mysql".into(),
1516                connector_name: "orders".into(),
1517                database: "app".into(),
1518                schema: None,
1519                table: Some("orders".into()),
1520                snapshot: false,
1521                version: "test".into(),
1522                attributes: BTreeMap::new(),
1523            },
1524            position: position.clone(),
1525            transaction: None,
1526            operation: Operation::Delete,
1527            before: None,
1528            after: None,
1529            schema: EventSchema {
1530                name: "orders".into(),
1531                version: 1,
1532                fields: Vec::new(),
1533            },
1534            source_time: Some(Utc::now()),
1535            observed_time: Utc::now(),
1536        };
1537        let cancelled = Arc::new(AtomicBool::new(false));
1538        let shutdown = Arc::new(AtomicBool::new(false));
1539        let status = RuntimeStatus::new("runtime-failure-test");
1540        let runtime = ConnectorRuntime::new(
1541            ConnectorIdentity::new("runtime-failure-test"),
1542            Box::new(CancellableStateSource {
1543                record: SourceRecord {
1544                    event: Some(event),
1545                    position,
1546                    boundary: RecordBoundary::TransactionCommit,
1547                    connector_state: None,
1548                    signal_acknowledgements: Vec::new(),
1549                },
1550                cancelled: cancelled.clone(),
1551            }),
1552            Arc::new(BatchEncoder),
1553            Box::new(FailingSink {
1554                shutdown: shutdown.clone(),
1555            }),
1556            Arc::new(MemoryCheckpointStore::default()),
1557            RuntimeConfig::default(),
1558            status.clone(),
1559        );
1560
1561        let error = runtime.run(CancellationToken::new()).await.unwrap_err();
1562        assert!(error.to_string().contains("intentional delivery failure"));
1563        assert!(cancelled.load(Ordering::SeqCst));
1564        assert!(shutdown.load(Ordering::SeqCst));
1565        let status = status.snapshot().await;
1566        assert_eq!(status.state, ConnectorState::Failed);
1567        assert_eq!(status.failed_events, 2);
1568        assert!(
1569            status
1570                .state_reason
1571                .is_some_and(|reason| reason.contains("intentional delivery failure"))
1572        );
1573    }
1574
1575    #[tokio::test]
1576    async fn aborts_a_source_that_exceeds_the_shutdown_timeout() {
1577        let dropped = Arc::new(AtomicBool::new(false));
1578        let shutdown = Arc::new(AtomicBool::new(false));
1579        let status = RuntimeStatus::new("runtime-timeout-test");
1580        let runtime = ConnectorRuntime::new(
1581            ConnectorIdentity::new("runtime-timeout-test"),
1582            Box::new(StuckSource {
1583                dropped: dropped.clone(),
1584            }),
1585            Arc::new(UnusedEncoder),
1586            Box::new(FailingSink {
1587                shutdown: shutdown.clone(),
1588            }),
1589            Arc::new(MemoryCheckpointStore::default()),
1590            RuntimeConfig {
1591                shutdown_timeout: Duration::from_millis(10),
1592                ..RuntimeConfig::default()
1593            },
1594            status.clone(),
1595        );
1596        let cancellation = CancellationToken::new();
1597        cancellation.cancel();
1598
1599        let error = runtime.run(cancellation).await.unwrap_err();
1600        assert!(error.to_string().contains("source shutdown timed out"));
1601        assert!(dropped.load(Ordering::SeqCst));
1602        assert!(shutdown.load(Ordering::SeqCst));
1603        let status = status.snapshot().await;
1604        assert_eq!(status.state, ConnectorState::Failed);
1605        assert_eq!(status.failed_events, 0);
1606    }
1607}