google-cloud-pubsub 1.0.0

Google Cloud Client Libraries for Rust - Pub/Sub
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::options::BatchingOptions;
use crate::generated::gapic_dataplane::client::Publisher as GapicPublisher;
use crate::publisher::batch::Batch;
use std::collections::{HashMap, VecDeque};
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinSet;
use tokio_util::task::JoinMap;

/// A command sent from the `Publisher` to the background Dispatcher actor.
pub(crate) enum ToDispatcher {
    /// A request to publish a single message.
    Publish(BundledMessage),
    /// A request to flush all outstanding messages.
    Flush(oneshot::Sender<()>),
    /// A request to resume publishing on an ordering key.
    ResumePublish(String),
}

/// A command sent from the Dispatcher to a batch actor.
pub(crate) enum ToBatchActor {
    /// A request to publish a single message.
    Publish(BundledMessage),
    /// A request to flush all outstanding messages.
    Flush(oneshot::Sender<()>),
    /// A request to resume publishing.
    ResumePublish(),
}

/// Object that is passed to the actor tasks over the
/// main channel. This represents a single message and the sender
/// half of the channel to resolve the [PublishFuture].
#[derive(Debug)]
pub(crate) struct BundledMessage {
    pub msg: crate::model::Message,
    pub tx: oneshot::Sender<std::result::Result<String, crate::error::PublishError>>,
}

/// The Dispatcher runs in a background task and handles all Publisher operations
/// by dispatching it to BatchActors.
#[derive(Debug)]
pub(crate) struct Dispatcher {
    topic_name: String,
    client: GapicPublisher,
    batching_options: BatchingOptions,
    rx: mpsc::UnboundedReceiver<ToDispatcher>,
}

impl Dispatcher {
    pub(crate) fn new(
        topic_name: String,
        client: GapicPublisher,
        batching_options: BatchingOptions,
        rx: mpsc::UnboundedReceiver<ToDispatcher>,
    ) -> Self {
        Self {
            topic_name,
            client,
            rx,
            batching_options,
        }
    }

    pub(crate) fn spawn_actor(
        &mut self,
        key: String,
        tasks: &mut JoinMap<String, ()>,
    ) -> BatchActorHandle {
        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
        if key.is_empty() {
            tasks.spawn(
                key,
                ConcurrentBatchActor::new(
                    self.topic_name.clone(),
                    self.client.clone(),
                    self.batching_options.clone(),
                    rx,
                )
                .run(),
            );
        } else {
            tasks.spawn(
                key,
                SequentialBatchActor::new(
                    self.topic_name.clone(),
                    self.client.clone(),
                    self.batching_options.clone(),
                    rx,
                )
                .run(),
            );
        }
        BatchActorHandle { sender: tx }
    }

    /// The main loop of the Dispatcher.
    ///
    /// This method continuously handles the following events:
    ///
    /// 1. A Publish command from the `Publisher` is dispatched to the BatchActor
    ///    for its ordering key.
    /// 2. A Flush command from the `Publisher` causes the Dispatcher to flush
    ///    all BatchActors and awaits its completion.
    /// 3. A ResumePublish command from the `Publisher` is dispatched to the BatchActor
    ///    for its ordering key.
    /// 4. A timer fire causes the Dispatcher to flush all BatchActors.
    ///
    /// The loop terminates when the `rx` channel is closed, which happens when all
    /// `Publisher` clones have been dropped.
    pub(crate) async fn run(mut self) {
        // A dictionary of ordering key to outstanding publish operations.
        // We batch publish operations on the same ordering key together.
        // Publish without ordering keys are treated as having the key "".
        let mut batch_actors: HashMap<String, BatchActorHandle> = HashMap::new();
        let mut actor_tasks: JoinMap<String, ()> = JoinMap::new();
        let delay = self.batching_options.delay_threshold;
        let timer = tokio::time::sleep(delay);
        // Pin the timer to the stack.
        tokio::pin!(timer);
        loop {
            tokio::select! {
                _ = actor_tasks.join_next(), if !actor_tasks.is_empty() => {
                    // TODO(#4012): Remove batch actors when there are no outstanding operations
                    // on the ordering key.
                    continue;
                }
                // Currently, the Dispatcher periodically flushes all batches on a shared timer.
                // If needed, this can be moved into the batch actors such that each are running
                // on a separate timer.
                _ = &mut timer => {
                    for (_, batch_actor) in batch_actors.iter() {
                        let (tx, _) = oneshot::channel();
                        if batch_actor.sender.send(ToBatchActor::Flush(tx)).is_err() {
                            return; // Stop the dispatcher if a batch actor is dropped.
                        }
                    }
                    timer.as_mut().reset(tokio::time::Instant::now() + delay);
                }
                // Handle receiving a message from the channel.
                msg = self.rx.recv() => {
                    match msg {
                        Some(ToDispatcher::Publish(msg)) => {
                            let ordering_key = msg.msg.ordering_key.clone();
                            let batch_actor = batch_actors
                                .entry(ordering_key.clone())
                                .or_insert_with(|| self.spawn_actor(ordering_key.clone(), &mut actor_tasks));
                            if batch_actor.sender.send(ToBatchActor::Publish(msg)).is_err() {
                                return; // Stop the dispatcher if a batch actor is dropped.
                            }
                        },
                        Some(ToDispatcher::Flush(tx)) => {
                            let mut flush_set = JoinSet::new();
                            for (_, batch_actor) in batch_actors.iter() {
                                let (tx, rx) = oneshot::channel();
                                if batch_actor.sender.send(ToBatchActor::Flush(tx)).is_err() {
                                    return; // Stop the dispatcher if a batch actor is dropped.
                                }
                                flush_set.spawn(rx);
                            }
                            tokio::spawn(async move {
                                // Wait on all the flush operations.
                                flush_set.join_all().await;
                                let _ = tx.send(());
                            });
                        },
                        Some(ToDispatcher::ResumePublish(ordering_key)) => {
                            if let Some(batch_actor) = batch_actors.get_mut(&ordering_key) {
                                // Send down the same tx for the BatchActors to directly signal completion
                                // instead of spawning a new task.
                                if batch_actor.sender.send(ToBatchActor::ResumePublish()).is_err() {
                                    return; // Stop the dispatcher if a batch actor is dropped.
                                }
                            }
                        }
                        None => {
                            // Gracefully shutdown since the Publisher has dropped the Sender.
                            // By dropping the BatchActorHandles, they will individually handle the
                            // shutdown procedures.
                            drop(batch_actors);
                            // When we drop actor_tasks, some batch actors may not have started execution
                            // so the batch actor is aborted with messages in its receiving channel.
                            // We wait for the batch actors instead of aborting so that it can
                            // gracefully shutdown.
                            while actor_tasks.join_next().await.is_some() {};
                            break;
                        }
                    }
                }

            }
        }
    }
}

#[derive(Debug)]
pub(crate) struct BatchActorHandle {
    sender: mpsc::UnboundedSender<ToBatchActor>,
}

#[derive(Debug)]
pub(crate) struct BatchActorContext {
    topic: String,
    client: GapicPublisher,
    rx: mpsc::UnboundedReceiver<ToBatchActor>,
    batching_options: BatchingOptions,
}

impl BatchActorContext {
    pub(crate) fn new(
        topic: String,
        client: GapicPublisher,
        batching_options: BatchingOptions,
        rx: mpsc::UnboundedReceiver<ToBatchActor>,
    ) -> Self {
        BatchActorContext {
            topic,
            client,
            rx,
            batching_options,
        }
    }
}

/// A batch actor that sends batches concurrently.
#[derive(Debug)]
pub(crate) struct ConcurrentBatchActor {
    context: BatchActorContext,
}

impl ConcurrentBatchActor {
    pub(crate) fn new(
        topic: String,
        client: GapicPublisher,
        batching_options: BatchingOptions,
        rx: mpsc::UnboundedReceiver<ToBatchActor>,
    ) -> Self {
        ConcurrentBatchActor {
            context: BatchActorContext::new(topic, client, batching_options, rx),
        }
    }

    /// The main loop of the concurrent batch actor.
    ///
    /// This method continuously handles the following events:
    ///
    /// 1. A Publish command from the Dispatcher causes the new message to be
    ///    added a pending message queue. If there is enough message to create
    ///    a full batch, then also flush the batch.
    /// 2. A `Flush` command from the Dispatcher causes all the pending messages
    ///    to be flushed concurrently respecting the configured batch size and message
    ///    ordering.
    /// 3. A ResumePublish command from the Dispatcher causes the actor to resume
    ///    publishing.
    ///
    /// The loop terminates when the `rx` channel is closed, which happens when the
    /// Dispatcher drops the Sender.
    pub(crate) async fn run(mut self) {
        // We have multiple inflight batches concurrently.
        let mut inflight = JoinSet::new();
        let mut batch = Batch::new(
            self.context.topic.len() as u32,
            self.context.batching_options.clone(),
        );
        loop {
            tokio::select! {
                // Remove completed inflight batches.
                _ = inflight.join_next(), if !inflight.is_empty() => {
                    continue;
                }
                msg = self.context.rx.recv() => {
                    match msg {
                        Some(ToBatchActor::Publish(msg)) => {
                            self.add_msg_and_flush(&mut inflight, &mut batch, msg);
                        },
                        Some(ToBatchActor::Flush(tx)) => {
                            self.flush(&mut inflight, &mut batch);
                            inflight.join_all().await;
                            inflight = JoinSet::new();
                            let _ = tx.send(());
                        },
                        Some(ToBatchActor::ResumePublish()) => {
                            // Nothing to resume as we do not pause without ordering key.
                        }
                        None => {
                            // This isn't guaranteed to execute if a user does not .await on the
                            // corresponding PublishFutures.
                            self.flush(&mut inflight, &mut batch);
                            inflight.join_all().await;
                            break;
                        }
                    }
                }
            }
        }
    }

    // Flush the pending batch if it's not empty.
    pub(crate) fn flush(&mut self, inflight: &mut JoinSet<crate::Result<()>>, batch: &mut Batch) {
        if !batch.is_empty() {
            batch.flush(
                self.context.client.clone(),
                self.context.topic.clone(),
                inflight,
            );
        }
    }

    // Move message to the pending batch respecting batch thresholds
    // and flush the batch if it is full.
    pub(crate) fn add_msg_and_flush(
        &mut self,
        inflight: &mut JoinSet<crate::Result<()>>,
        batch: &mut Batch,
        msg: BundledMessage,
    ) {
        if !batch.can_add(&msg) {
            self.flush(inflight, batch);
        }
        batch.push(msg);
        if batch.at_threshold() {
            self.flush(inflight, batch);
        }
    }
}

/// A batch actor that sends batches sequentially by awaiting on the previous batch.
#[derive(Debug)]
pub(crate) struct SequentialBatchActor {
    context: BatchActorContext,
    pending_msgs: VecDeque<BundledMessage>,
    paused: bool,
}

impl SequentialBatchActor {
    pub(crate) fn new(
        topic: String,
        client: GapicPublisher,
        batching_options: BatchingOptions,
        rx: mpsc::UnboundedReceiver<ToBatchActor>,
    ) -> Self {
        SequentialBatchActor {
            context: BatchActorContext::new(topic, client, batching_options, rx),
            pending_msgs: VecDeque::new(),
            paused: false,
        }
    }

    /// The main loop of the sequential batch actor.
    ///
    /// This method continuously handles the following events:
    ///
    /// 1. A Publish command from the Dispatcher causes the new message to be
    ///    added a pending message queue. If there is enough message to create
    ///    a full batch and there are currently no inflight batch, then also flush
    ///    the batch.
    /// 2. A `Flush` command from the Dispatcher causes all the pending messages
    ///    to be flushed sequentially respecting the configured batch size and message
    ///    ordering.
    /// 3. A ResumePublish command from the Dispatcher causes the actor to resume
    ///    publishing.
    /// 4. A `inflight` batch completion causes the next batch to send if it satisfies
    ///    the configured batch threshold.
    ///
    /// The loop terminates when the `rx` channel is closed, which happens when the
    /// Dispatcher drops the Sender.
    pub(crate) async fn run(mut self) {
        // While it is possible to use Some(JoinHandle) here as there is at max
        // a single inflight task at any given time, the use of JoinSet
        // simplify the managing the inflight JoinHandle.
        let mut inflight: JoinSet<crate::Result<()>> = JoinSet::new();
        let mut batch = Batch::new(
            self.context.topic.len() as u32,
            self.context.batching_options.clone(),
        );
        loop {
            if self.paused {
                // When paused, we do not need to check inflight as handle_inflight_join()
                // ensures that there are no inflight batch.
                let msg = self.context.rx.recv().await;
                match msg {
                    Some(ToBatchActor::Publish(msg)) => {
                        let _ = msg
                            .tx
                            .send(Err(crate::error::PublishError::OrderingKeyPaused));
                    }
                    Some(ToBatchActor::Flush(tx)) => {
                        // There should be no pending messages and messages in the pending batch as
                        // it was already handled when this was paused.
                        let _ = tx.send(());
                    }
                    Some(ToBatchActor::ResumePublish()) => {
                        self.paused = false;
                    }
                    None => {
                        // There should be no pending messages and messages in the pending batch as
                        // it was already handled when this was paused.
                        break;
                    }
                }
                continue;
            }
            tokio::select! {
                join = inflight.join_next(), if !inflight.is_empty() => {
                    self.handle_inflight_join(join);
                    self.move_to_batch_and_flush(&mut inflight, &mut batch);
                }
                msg = self.context.rx.recv() => {
                    match msg {
                        Some(ToBatchActor::Publish(msg)) => {
                            self.pending_msgs.push_back(msg);
                            if inflight.is_empty() {
                                self.move_to_batch_and_flush(&mut inflight, &mut batch);
                            }
                        },
                        Some(ToBatchActor::Flush(tx)) => {
                            self.flush(&mut inflight, &mut batch).await;
                            inflight = JoinSet::new();
                            let _ = tx.send(());
                        },
                        Some(ToBatchActor::ResumePublish()) => {
                            // Nothing to resume as we are not paused.
                        },
                        None => {
                            // This isn't guaranteed to execute if a user does not .await on the
                            // corresponding PublishFutures.
                            self.flush(&mut inflight, &mut batch).await;
                            break;
                        }
                    }
                }
            }
        }
    }

    // Flush the pending messages by sending the messages in sequential batches.
    async fn flush(&mut self, inflight: &mut JoinSet<crate::Result<()>>, batch: &mut Batch) {
        self.handle_inflight_join(inflight.join_next().await);
        while !self.pending_msgs.is_empty() {
            self.move_to_batch_and_flush(inflight, batch);
            self.handle_inflight_join(inflight.join_next().await);
        }
        // Flush the pending batch even if it does not fill the batch.
        if !batch.is_empty() {
            batch.flush(
                self.context.client.clone(),
                self.context.topic.clone(),
                inflight,
            );
        }
        self.handle_inflight_join(inflight.join_next().await);
    }

    // Move message to the pending batch respecting batch thresholds
    // and flush the batch if it is full.
    pub(crate) fn move_to_batch_and_flush(
        &mut self,
        inflight: &mut JoinSet<crate::Result<()>>,
        batch: &mut Batch,
    ) {
        let mut should_flush = false;
        while let Some(next) = self.pending_msgs.front() {
            if !batch.can_add(next) && !batch.is_empty() {
                should_flush = true;
                break;
            }
            let publish = self
                .pending_msgs
                .pop_front()
                .expect("front should contain an element");
            batch.push(publish);
            if batch.at_threshold() {
                should_flush = true;
                break;
            }
        }

        if should_flush {
            batch.flush(
                self.context.client.clone(),
                self.context.topic.clone(),
                inflight,
            );
        }
    }

    // Pause publish operations.
    pub(crate) fn pause(&mut self) {
        self.paused = true;
        while let Some(publish) = self.pending_msgs.pop_front() {
            // The user may have dropped the handle, so it is ok if this fails.
            let _ = publish
                .tx
                .send(Err(crate::error::PublishError::OrderingKeyPaused));
        }
    }

    pub(crate) fn handle_inflight_join(
        &mut self,
        join_next_option: Option<Result<crate::Result<()>, tokio::task::JoinError>>,
    ) {
        // If there was a JoinError or non-retryable error:
        // 1. We need to pause publishing and send out errors for pending_msgs.
        // 2. The pending batch should have sent out error for its messages.
        // 3. The messages in rx will be handled when they are received.
        if let Some(Err(_) | Ok(Err(_))) = join_next_option {
            self.pause();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{ConcurrentBatchActor, SequentialBatchActor};
    use crate::error::PublishError;
    use crate::publisher::actor::{BundledMessage, ToBatchActor};
    use crate::publisher::batch::Batch;
    use crate::publisher::constants::{MAX_BYTES, MAX_MESSAGES};
    use crate::publisher::options::BatchingOptions;
    use crate::{
        generated::gapic_dataplane::client::Publisher as GapicPublisher,
        model::{Message, PublishResponse},
    };
    use google_cloud_test_macros::tokio_test_no_panics;
    use mockall::Sequence;
    use rand::{RngExt, distr::Alphanumeric};
    use std::collections::VecDeque;
    use std::time::Duration;
    use tokio::sync::mpsc::{UnboundedSender, unbounded_channel};

    static TOPIC: &str = "my-topic";
    const EXPECTED_BATCHES: usize = 5;
    const TIME_PER_BATCH: Duration = Duration::from_secs(10);

    mockall::mock! {
        #[derive(Debug)]
        GapicPublisher {}
        impl crate::generated::gapic_dataplane::stub::Publisher for GapicPublisher {
            async fn publish(&self, req: crate::model::PublishRequest, _options: google_cloud_gax::options::RequestOptions) -> google_cloud_gax::Result<google_cloud_gax::response::Response<crate::model::PublishResponse>>;
        }
    }

    // Similar to GapicPublisher but returns impl Future instead.
    // This is useful for mocking a response with delays/timeouts.
    // See https://github.com/asomers/mockall/issues/189 for more
    // detail on why this is needed.
    // While this can used inplace of GapicPublisher, it makes the
    // normal usage without async closure much more cumbersome.
    mockall::mock! {
        #[derive(Debug)]
        GapicPublisherWithFuture {}
        impl crate::generated::gapic_dataplane::stub::Publisher for GapicPublisherWithFuture {
            fn publish(&self, req: crate::model::PublishRequest, _options: google_cloud_gax::options::RequestOptions) -> impl Future<Output=google_cloud_gax::Result<google_cloud_gax::response::Response<crate::model::PublishResponse>>> + Send;
        }
    }

    fn publish_ok(
        req: crate::model::PublishRequest,
        _options: crate::RequestOptions,
    ) -> crate::Result<crate::Response<crate::model::PublishResponse>> {
        let ids = req
            .messages
            .iter()
            .map(|m| String::from_utf8(m.data.to_vec()).unwrap());
        Ok(crate::Response::from(
            PublishResponse::new().set_message_ids(ids),
        ))
    }

    fn track_publish_msg_seq(
        req: &crate::model::PublishRequest,
        msg_seq_tx: UnboundedSender<Message>,
    ) {
        req.messages.iter().for_each(|m| {
            msg_seq_tx
                .send(m.clone())
                .expect("sending should always succeed as the test should not close the channel");
        });
    }

    fn publish_err(
        _req: crate::model::PublishRequest,
        _options: crate::RequestOptions,
    ) -> crate::Result<crate::Response<crate::model::PublishResponse>> {
        Err(crate::Error::service(
            google_cloud_gax::error::rpc::Status::default()
                .set_code(google_cloud_gax::error::rpc::Code::Unknown)
                .set_message("unknown error has occurred"),
        ))
    }

    fn generate_random_data() -> String {
        rand::rng()
            .sample_iter(&Alphanumeric)
            .take(16)
            .map(char::from)
            .collect()
    }

    // Send ToBatchActor::Publish with random data n times and track the messages in publish_rxs.
    macro_rules! publish_random_data {
        ($publish_rxs:ident, $actor_tx:ident, $n:expr) => {
            for _ in 0..$n {
                let (publish_tx, publish_rx) = tokio::sync::oneshot::channel();
                let msg = generate_random_data();
                let bundle = BundledMessage {
                    msg: Message::new().set_data(msg.clone()),
                    tx: publish_tx,
                };
                $actor_tx.send(ToBatchActor::Publish(bundle))?;
                $publish_rxs.push_back((msg, publish_rx));
            }
        };
    }

    // Verify that the publish data in publish_rxs matches the resolved message.
    macro_rules! assert_publish_data {
        ($publish_rxs:ident) => {
            for (msg, publish_rx) in $publish_rxs {
                assert_eq!(
                    publish_rx.await??,
                    msg,
                    "unexpected message for given handler"
                );
            }
        };
    }

    // Verify that the publish data in publish_rxs the resolved message and the expected sequence.
    macro_rules! assert_publish_data_with_seq {
        ($publish_rxs:ident, $expected_msg_seq_rx:ident) => {
            for (msg, publish_rx) in $publish_rxs {
                assert_eq!(
                    publish_rx.await??,
                    msg,
                    "unexpected message for given handler"
                );
                // Assert that publish message matches the expected message sequence.
                let expected_msg = $expected_msg_seq_rx.try_recv()?.data;
                assert_eq!(msg, expected_msg, "message published out of order");
            }
        };
    }

    // Send ToBatchActor::Publish with random data n times then await and assert the result.
    macro_rules! assert_publish_is_ok {
        ($actor_tx:ident, $n:expr) => {
            let mut publish_rxs = VecDeque::new();
            publish_random_data!(publish_rxs, $actor_tx, $n);
            assert_publish_data!(publish_rxs);
        };
        ($actor_tx:ident, $expected_msg_seq_rx:ident, $n:expr) => {
            let mut publish_rxs = VecDeque::new();
            publish_random_data!(publish_rxs, $actor_tx, $n);
            assert_publish_data_with_seq!(publish_rxs, $expected_msg_seq_rx);
        };
    }

    // Send ToBatchActor::Publish with random data n times then await and assert that the actor is paused.
    macro_rules! assert_actor_is_paused {
        ($actor_tx:ident, $n:expr) => {
            let mut publish_rxs = Vec::new();
            for _ in 0..$n {
                let (publish_tx, publish_rx) = tokio::sync::oneshot::channel();
                // let msg = generate_random_data();
                let bundle = BundledMessage {
                    msg: Message::new().set_data(generate_random_data()),
                    tx: publish_tx,
                };
                $actor_tx.send(ToBatchActor::Publish(bundle))?;
                publish_rxs.push(publish_rx);
            }
            for v in publish_rxs {
                let res = v.await;
                assert!(
                    matches!(res, Ok(Err(PublishError::OrderingKeyPaused))),
                    "{res:?}"
                );
            }
        };
    }

    macro_rules! assert_flush {
        ($actor_tx:ident) => {
            let (flush_tx, flush_rx) = tokio::sync::oneshot::channel();
            $actor_tx.send(ToBatchActor::Flush(flush_tx))?;
            flush_rx.await?;
        };
    }

    #[tokio::test]
    async fn basic() -> anyhow::Result<()> {
        let client = GapicPublisher::from_stub(MockGapicPublisher::new());
        let batching_options = BatchingOptions::default();

        let (_, rx) = tokio::sync::mpsc::unbounded_channel();
        let _ = ConcurrentBatchActor::new(
            TOPIC.to_string(),
            client.clone(),
            batching_options.clone(),
            rx,
        );

        let (_, rx) = tokio::sync::mpsc::unbounded_channel();
        let _ = SequentialBatchActor::new("topic".to_string(), client, batching_options, rx);
        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn concurrent_actor_publish() -> anyhow::Result<()> {
        let mut mock = MockGapicPublisherWithFuture::new();
        mock.expect_publish()
            .withf(|req, _o| req.topic == TOPIC)
            .times(EXPECTED_BATCHES)
            .returning({
                |r, o| {
                    Box::pin(async move {
                        tokio::time::sleep(TIME_PER_BATCH).await;
                        publish_ok(r, o)
                    })
                }
            });
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            ConcurrentBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default().set_message_count_threshold(2_u32),
                actor_rx,
            )
            .run(),
        );

        let start = tokio::time::Instant::now();
        assert_publish_is_ok!(actor_tx, 10);
        assert_eq!(
            start.elapsed(),
            TIME_PER_BATCH,
            "all batches should have been concurrently sent and completed by {:?}",
            TIME_PER_BATCH
        );
        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn sequential_actor_publish() -> anyhow::Result<()> {
        let (msg_seq_tx, mut msg_seq_rx) = unbounded_channel::<Message>();
        let mut mock = MockGapicPublisherWithFuture::new();
        mock.expect_publish()
            .withf(|req, _o| req.topic == TOPIC)
            .times(EXPECTED_BATCHES)
            .returning({
                move |r, o| {
                    Box::pin({
                        let seq_tx = msg_seq_tx.clone();
                        async move {
                            tokio::time::sleep(TIME_PER_BATCH).await;
                            track_publish_msg_seq(&r, seq_tx);
                            publish_ok(r, o)
                        }
                    })
                }
            });
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            SequentialBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default().set_message_count_threshold(2_u32),
                actor_rx,
            )
            .run(),
        );

        let start = tokio::time::Instant::now();
        assert_publish_is_ok!(actor_tx, msg_seq_rx, 10);
        assert_eq!(
            start.elapsed(),
            EXPECTED_BATCHES as u32 * TIME_PER_BATCH,
            "all batches should have been seqentially sent and takes {:?}",
            EXPECTED_BATCHES as u32 * TIME_PER_BATCH
        );
        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn concurrent_actor_flush() -> anyhow::Result<()> {
        let mut mock = MockGapicPublisherWithFuture::new();
        mock.expect_publish()
            .withf(|req, _o| req.topic == TOPIC)
            .times(EXPECTED_BATCHES)
            .returning({
                |r, o| {
                    Box::pin(async move {
                        tokio::time::sleep(TIME_PER_BATCH).await;
                        publish_ok(r, o)
                    })
                }
            });
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            ConcurrentBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default().set_message_count_threshold(2_u32),
                actor_rx,
            )
            .run(),
        );

        // Flush on empty.
        assert_flush!(actor_tx);

        // Publish 10 messages then Flush.
        let start = tokio::time::Instant::now();
        let mut publish_rxs = VecDeque::new();
        publish_random_data!(publish_rxs, actor_tx, 10);
        assert_flush!(actor_tx);
        assert_publish_data!(publish_rxs);
        assert_eq!(
            start.elapsed(),
            TIME_PER_BATCH,
            "all batches should have been concurrently sent and completed by {:?}",
            TIME_PER_BATCH
        );

        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn sequential_actor_flush() -> anyhow::Result<()> {
        let (msg_seq_tx, mut msg_seq_rx) = unbounded_channel::<Message>();
        let mut mock = MockGapicPublisherWithFuture::new();
        mock.expect_publish()
            .withf(|req, _o| req.topic == TOPIC)
            .times(EXPECTED_BATCHES)
            .returning({
                move |r, o| {
                    Box::pin({
                        let seq_tx = msg_seq_tx.clone();
                        async move {
                            tokio::time::sleep(TIME_PER_BATCH).await;
                            track_publish_msg_seq(&r, seq_tx);
                            publish_ok(r, o)
                        }
                    })
                }
            });
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            SequentialBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default().set_message_count_threshold(2_u32),
                actor_rx,
            )
            .run(),
        );

        // Flush on empty.
        assert_flush!(actor_tx);

        // Publish 10 messages then Flush.
        let start = tokio::time::Instant::now();
        let mut publish_rxs = VecDeque::new();
        publish_random_data!(publish_rxs, actor_tx, 10);
        assert_flush!(actor_tx);
        assert_publish_data_with_seq!(publish_rxs, msg_seq_rx);
        assert_eq!(
            start.elapsed(),
            EXPECTED_BATCHES as u32 * TIME_PER_BATCH,
            "all batches should have been seqentially sent and takes {:?}",
            EXPECTED_BATCHES as u32 * TIME_PER_BATCH
        );

        Ok(())
    }

    #[tokio::test]
    async fn concurrent_actor_resume() -> anyhow::Result<()> {
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            ConcurrentBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(MockGapicPublisher::new()),
                BatchingOptions::default(),
                actor_rx,
            )
            .run(),
        );

        actor_tx.send(ToBatchActor::ResumePublish())?;
        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn sequential_actor_resume() -> anyhow::Result<()> {
        let (msg_seq_tx, mut msg_seq_rx) = unbounded_channel::<Message>();
        let mut mock = MockGapicPublisherWithFuture::new();
        let mut seq = Sequence::new();
        mock.expect_publish()
            .withf(|req, _o| req.topic == TOPIC)
            .times(EXPECTED_BATCHES)
            .in_sequence(&mut seq)
            .returning(move |r, o| Box::pin(async move { publish_ok(r, o) }));
        mock.expect_publish()
            .withf(|req, _o| req.topic == TOPIC)
            .once()
            .in_sequence(&mut seq)
            .returning(move |r, o| Box::pin(async { publish_err(r, o) }));
        mock.expect_publish()
            .withf(|req, _o| req.topic == TOPIC)
            .times(EXPECTED_BATCHES)
            .in_sequence(&mut seq)
            .returning({
                move |r, o| {
                    Box::pin({
                        let seq_tx = msg_seq_tx.clone();
                        async move {
                            track_publish_msg_seq(&r, seq_tx);
                            publish_ok(r, o)
                        }
                    })
                }
            });

        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            SequentialBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default().set_message_count_threshold(1_u32),
                actor_rx,
            )
            .run(),
        );

        // Validate resume when not paused.
        actor_tx.send(ToBatchActor::ResumePublish())?;
        assert_publish_is_ok!(actor_tx, EXPECTED_BATCHES);

        // This message triggers the mock to return publish error and causes the actor to pause.
        let (publish_tx, publish_rx) = tokio::sync::oneshot::channel();
        let bundle = BundledMessage {
            msg: Message::new().set_data(generate_random_data()),
            tx: publish_tx,
        };
        actor_tx.send(ToBatchActor::Publish(bundle))?;
        let got_err = publish_rx.await;
        // TODO(#3689): Validate the error structure when Publisher error structure is better defined.
        assert!(matches!(got_err, Ok(Err(_))), "{got_err:?}");
        assert_actor_is_paused!(actor_tx, 5);

        // Resume then validate that the actor is no longer paused.
        actor_tx.send(ToBatchActor::ResumePublish())?;
        assert_publish_is_ok!(actor_tx, msg_seq_rx, EXPECTED_BATCHES);

        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn concurrent_actor_batch_message_count_threshold() -> anyhow::Result<()> {
        let mut mock = MockGapicPublisher::new();
        mock.expect_publish()
            .withf(|req, _o| req.topic == TOPIC && req.messages.len() == 10)
            .returning(publish_ok);
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            ConcurrentBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default()
                    .set_message_count_threshold(10_u32)
                    .set_byte_threshold(MAX_BYTES)
                    .set_delay_threshold(std::time::Duration::MAX),
                actor_rx,
            )
            .run(),
        );

        assert_publish_is_ok!(actor_tx, 10);

        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn sequential_actor_batch_message_count_threshold() -> anyhow::Result<()> {
        let mut mock = MockGapicPublisher::new();
        mock.expect_publish()
            .withf(|req, _o| req.topic == TOPIC && req.messages.len() == 10)
            .returning(publish_ok);
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            SequentialBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default()
                    .set_message_count_threshold(10_u32)
                    .set_byte_threshold(MAX_BYTES)
                    .set_delay_threshold(std::time::Duration::MAX),
                actor_rx,
            )
            .run(),
        );

        assert_publish_is_ok!(actor_tx, 10);
        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn concurrent_actor_byte_count_threshold() -> anyhow::Result<()> {
        let mut mock = MockGapicPublisher::new();
        mock.expect_publish()
            .withf(|req, _o| {
                // Recreate the batch from req to calculate the batch size.
                let mut batch = Batch::new(req.topic.len() as u32, BatchingOptions::default());
                req.messages.iter().for_each(|msg| {
                    let (tx, _rx) = tokio::sync::oneshot::channel();
                    batch.push(BundledMessage {
                        msg: msg.clone(),
                        tx,
                    });
                });
                req.topic == TOPIC && batch.size() <= 25_u32
            })
            .returning(publish_ok);
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            ConcurrentBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default()
                    .set_message_count_threshold(MAX_MESSAGES)
                    .set_byte_threshold(25_u32), // The current test generates 24 byte single message batches.
                actor_rx,
            )
            .run(),
        );

        let mut publish_rxs = VecDeque::new();
        publish_random_data!(publish_rxs, actor_tx, 10);
        // We flush here otherwise the last message will await forever since it never exceed the byte threshold.
        assert_flush!(actor_tx);
        assert_publish_data!(publish_rxs);

        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn sequential_actor_byte_count_threshold() -> anyhow::Result<()> {
        let mut mock = MockGapicPublisher::new();
        mock.expect_publish()
            .withf(|req, _o| {
                // Recreate the batch from req to calculate the batch size.
                let mut batch = Batch::new(req.topic.len() as u32, BatchingOptions::default());
                req.messages.iter().for_each(|msg| {
                    let (tx, _rx) = tokio::sync::oneshot::channel();
                    batch.push(BundledMessage {
                        msg: msg.clone(),
                        tx,
                    });
                });
                req.topic == TOPIC && batch.size() <= 25_u32
            })
            .returning(publish_ok);
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            SequentialBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default()
                    .set_message_count_threshold(MAX_MESSAGES)
                    .set_byte_threshold(25_u32), // The current test generates 24 byte single message batches.
                actor_rx,
            )
            .run(),
        );

        let mut publish_rxs = VecDeque::new();
        publish_random_data!(publish_rxs, actor_tx, 1);
        // We flush here otherwise the last message will await forever since it never exceed the byte threshold.
        assert_flush!(actor_tx);
        assert_publish_data!(publish_rxs);

        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn sequential_actor_send_large_message() -> anyhow::Result<()> {
        let mut mock = MockGapicPublisher::new();
        mock.expect_publish()
            .withf(|req, _o| {
                // Recreate the batch from req to calculate the batch size.
                let mut batch = Batch::new(req.topic.len() as u32, BatchingOptions::default());
                req.messages.iter().for_each(|msg| {
                    let (tx, _rx) = tokio::sync::oneshot::channel();
                    batch.push(BundledMessage {
                        msg: msg.clone(),
                        tx,
                    });
                });
                req.topic == TOPIC && batch.size() >= 23_u32
            })
            .returning(publish_ok);
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            SequentialBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default()
                    .set_message_count_threshold(MAX_MESSAGES)
                    .set_byte_threshold(1_u32), // The current test generates 24 byte single message batches.
                actor_rx,
            )
            .run(),
        );
        assert_publish_is_ok!(actor_tx, 10);

        Ok(())
    }

    #[tokio_test_no_panics(start_paused = true)]
    async fn concurrent_actor_send_large_message() -> anyhow::Result<()> {
        let mut mock = MockGapicPublisher::new();
        mock.expect_publish()
            .withf(|req, _o| {
                // Recreate the batch from req to calculate the batch size.
                let mut batch = Batch::new(req.topic.len() as u32, BatchingOptions::default());
                req.messages.iter().for_each(|msg| {
                    let (tx, _rx) = tokio::sync::oneshot::channel();
                    batch.push(BundledMessage {
                        msg: msg.clone(),
                        tx,
                    });
                });
                req.topic == TOPIC && batch.size() >= 23_u32
            })
            .returning(publish_ok);
        let (actor_tx, actor_rx) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(
            ConcurrentBatchActor::new(
                TOPIC.to_string(),
                GapicPublisher::from_stub(mock),
                BatchingOptions::default()
                    .set_message_count_threshold(MAX_MESSAGES)
                    .set_byte_threshold(1_u32), // The current test generates 24 byte single message batches.
                actor_rx,
            )
            .run(),
        );
        assert_publish_is_ok!(actor_tx, 10);

        Ok(())
    }
}