etcdrs 0.1.2

An async etcd v3 client built on tonic and tokio, with composable operation builders and type-safe responses
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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
use std::{
    backtrace::Backtrace,
    borrow::Cow,
    collections::{HashSet, VecDeque},
    fmt,
    num::NonZeroI64,
    ops::{Deref, DerefMut},
    pin::Pin,
    sync::{
        Arc, Weak,
        atomic::{AtomicI64, Ordering},
    },
    task::{Context, Poll},
};

use bytes::Bytes;
use futures_core::Stream;

use crate::{
    AsRange, LeaseId, Prefix, ResponseHeader, Revision, Version,
    client::{Client, ClientInner, record_from_pb},
    pb::{
        etcdserverpb::{
            self, watch_create_request::FilterType as PbFilterType, watch_request::RequestUnion as PbRequestUnion,
        },
        mvccpb::{self, event::EventType as PbEventType},
    },
    record::{AsKey, KeyWithMetadata, Metadata, Record},
};

/// # Watching
impl Client {
    /// Create a [`WatchBuilder`] for establishing a watch stream.
    ///
    /// Chain [`.key()`][WatchBuilder::key], [`.prefix()`][WatchBuilder::prefix], or
    /// [`.range()`][WatchBuilder::range] to specify targets, then call
    /// [`.start()`][Watch::start] to open the gRPC stream.
    ///
    /// ```no_run
    /// use futures::StreamExt;
    /// use etcdrs::client::WatchEvent;
    /// # async {
    /// # let client: etcdrs::Client = todo!();
    /// let mut watcher = client.watch()
    ///     .key("leader").get_previous()
    ///     .prefix("services/")
    ///     .start();
    /// while let Some(event) = watcher.next().await {
    ///     match event.unwrap() {
    ///         WatchEvent::Put { record, .. } => println!("put: {record:?}"),
    ///         WatchEvent::Delete { key, .. } => println!("delete: {key:?}"),
    ///         WatchEvent::Progress { revision, .. } => println!("progress: {revision:?}"),
    ///     }
    /// }
    /// # };
    /// ```
    pub fn watch(&self) -> WatchBuilder<Self> {
        WatchBuilder {
            client: self.clone(),
            specs: Vec::new(),
        }
    }

    /// Create a [`Watcher`] from a collection of [`Watch`] specs.
    ///
    /// This is a shortcut for building a [`WatchBuilder`], adding each watch, and calling
    /// [`start`][WatchBuilder::start]:
    ///
    /// ```no_run
    /// # use etcdrs::{client::{Watch, Client}, Prefix};
    /// # let client: Client = todo!();
    /// let watcher = client.watcher([
    ///     Watch::new("foo").get_previous(),
    ///     Watch::new(Prefix("bar/")),
    /// ]);
    /// ```
    pub fn watcher(&self, watches: impl IntoIterator<Item = Watch>) -> Watcher {
        let mut builder = self.watch();
        for watch in watches {
            builder = builder.add(watch);
        }
        builder.start()
    }
}

/// Identifier for an individual watch within a [`Watcher`].
///
/// Watch IDs are assigned by the client when a watch is created — either as part of the initial
/// [`Watch`] builder chain or via [`Watcher::add`]. Every [`WatchEvent`] carries the ID of the
/// watch that produced it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct WatchId(NonZeroI64);

impl WatchId {
    pub const fn new(source: i64) -> Option<Self> {
        if let Some(non_zero) = NonZeroI64::new(source) {
            Some(WatchId(non_zero))
        } else {
            None
        }
    }

    pub fn get(&self) -> i64 {
        self.0.get()
    }
}

/// An event delivered by a [`WatchStream`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WatchEvent {
    /// A key was created or updated.
    Put {
        /// The header of the response that carried the event. While a watch catches up on past
        /// revisions, etcd gives its responses the store's current revision, which can be later
        /// than the event's own, the record's [`modified_revision`][Metadata::modified_revision].
        /// Resume a watch after the event's revision, not the header's.
        header: ResponseHeader,
        watch_id: WatchId,
        record: Record,
        /// The record as it existed before the event's mutation. This will always be `None` if
        /// [`get_previous`][Watch::get_previous] was not called on the watch.
        prev_record: Option<Record>,
        /// `true` if the key was newly created (as opposed to updated).
        created: bool,
    },
    /// A key was deleted.
    Delete {
        /// The header of the response that carried the event. As for a
        /// [`Put`][WatchEvent::Put], its revision can be later than the event's own, which is
        /// `key`'s [`modified_revision`][Metadata::modified_revision].
        header: ResponseHeader,
        watch_id: WatchId,
        key: KeyWithMetadata,
        /// The record as it existed before it was deleted. This will always be `None` if
        /// [`get_previous`][Watch::get_previous] was not called on the watch.
        prev_record: Option<Record>,
    },
    /// A progress notification from the server.
    ///
    /// Contains the current store revision. A notification enabled via [`Watch::progress_notify`]
    /// carries the ID of its watch in `watch_id`. A response to a global
    /// [`Watcher::request_progress`] call is not about one watch: etcd sends it with watch ID -1,
    /// so `watch_id` is `WatchId::new(-1)`, not `None`.
    Progress {
        header: ResponseHeader,
        watch_id: Option<WatchId>,
        revision: Revision,
    },
}

/// A [`Client::watch`] operation builder.
///
/// A `WatchBuilder` collects watch targets — call [`.key()`][Self::key],
/// [`.prefix()`][Self::prefix], or [`.range()`][Self::range] to specify what to watch. Each call
/// transitions to a [`Watch`] builder where per-target options can be set, and additional targets
/// can be chained.
#[must_use = "WatchBuilder does nothing unless you add targets and call `start`"]
pub struct WatchBuilder<C = ()> {
    client: C,
    specs: Vec<etcdserverpb::WatchCreateRequest>,
}

impl WatchBuilder<()> {
    /// Create a new `WatchBuilder` with no client attached.
    ///
    /// Use [`with_client`][Self::with_client] to attach a client before calling `start`, or
    /// use [`Client::watch`] instead.
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            client: (),
            specs: Vec::new(),
        }
    }
}

impl<C> WatchBuilder<C> {
    /// Attach a `client` to this builder.
    pub fn with_client<C2>(self, client: C2) -> WatchBuilder<C2> {
        WatchBuilder {
            client,
            specs: self.specs,
        }
    }

    pub(crate) fn into_parts(self) -> (C, WatchBuilder<()>) {
        (
            self.client,
            WatchBuilder {
                client: (),
                specs: self.specs,
            },
        )
    }

    /// Add a pre-built [`Watch`] to this builder.
    #[allow(clippy::should_implement_trait)]
    pub fn add<W>(mut self, watch: Watch<W>) -> Self {
        self.specs.push(watch.current);
        self
    }

    fn _new_watch(self, lower: Bytes, upper: Bytes) -> Watch<Self> {
        Watch {
            watcher: self,
            current: etcdserverpb::WatchCreateRequest {
                key: lower,
                range_end: upper,
                fragment: true,
                ..Default::default()
            },
        }
    }

    /// Watch a single key.
    pub fn key(self, key: impl AsKey) -> Watch<Self> {
        let key = Bytes::copy_from_slice(key.as_key());
        self._new_watch(key, Bytes::new())
    }

    /// Watch all keys with a given prefix.
    pub fn prefix(self, prefix: impl AsKey) -> Watch<Self> {
        self.range(Prefix(prefix))
    }

    /// Watch a range of keys.
    pub fn range(self, range: impl AsRange) -> Watch<Self> {
        let (lower, upper) = range.as_boundaries();
        self._new_watch(lower, upper)
    }
}

impl<C: crate::driver::WatchDriver> WatchBuilder<C> {
    /// Create a watcher and begin watching for events.
    pub fn start(self) -> C::Watcher {
        let (client, builder) = self.into_parts();
        client.start_watch(builder)
    }
}

/// A per-target watch specification for [`Client::watch`] or [`Client::watcher`].
///
/// The type parameter `W` determines what operations are available:
///
/// - **`Watch<()>`** — a standalone single-target spec, created via [`Watch::new`]. Can be
///   configured with per-target options and passed to [`Watcher::add`].
/// - **`Watch<WatchBuilder<C>>`** — part of a builder chain. Additional targets can be chained via
///   [`.key()`][Watch::key], and [`start()`][Watch::start] is available when
///   `C = Client`.
#[must_use = "Watch does nothing unless you call `start` or pass it to `Watcher::add`"]
pub struct Watch<W = ()> {
    watcher: W,
    current: etcdserverpb::WatchCreateRequest,
}

/// Standalone constructor — creates a `Watch<()>` for use with [`Watcher::add`].
impl Watch {
    /// Create a standalone watch spec.
    ///
    /// ```
    /// # use etcdrs::client::Watch;
    /// let watch = Watch::new("my-key");
    /// let watch = Watch::new("a".."z");
    /// let watch = Watch::new(etcdrs::Prefix("config/"));
    /// ```
    pub fn new(query: impl AsRange) -> Self {
        let (lower, upper) = query.as_boundaries();
        Watch {
            watcher: (),
            current: etcdserverpb::WatchCreateRequest {
                key: lower,
                range_end: upper,
                fragment: true,
                ..Default::default()
            },
        }
    }
}

/// Per-target options available for all `W`.
impl<W> Watch<W> {
    /// Start watching from a specific revision.
    ///
    /// Events that occurred at or after this revision will be delivered. If unset, the watch starts
    /// from the current store revision.
    pub fn start_revision(mut self, revision: Revision) -> Self {
        self.current.start_revision = revision.get();
        self
    }

    /// Include the previous key-value in each event.
    ///
    /// When enabled, [`WatchEvent::Put::prev_record`] and [`WatchEvent::Delete::prev_record`] will
    /// contain the record as it existed before the event's mutation.
    pub fn get_previous(mut self) -> Self {
        self.current.prev_kv = true;
        self
    }

    /// Request periodic progress notifications from the server for this watch.
    ///
    /// When enabled, the server sends progress notifications when no events have occurred recently.
    /// The stream yields each one as a [`WatchEvent::Progress`] carrying this watch's ID.
    pub fn progress_notify(mut self) -> Self {
        self.current.progress_notify = true;
        self
    }

    /// Enable or disable put events for this watch.
    ///
    /// When `enabled` is `false`, put events are filtered out (only deletes are delivered).
    /// Calling `.puts(true)` restores the default behavior.
    pub fn puts(mut self, enabled: bool) -> Self {
        let filter = PbFilterType::Noput as i32;
        if enabled {
            self.current.filters.retain(|&f| f != filter);
        } else if !self.current.filters.contains(&filter) {
            self.current.filters.push(filter);
        }
        self
    }

    /// Enable or disable delete events for this watch.
    ///
    /// When `enabled` is `false`, delete events are filtered out (only puts are delivered).
    /// Calling `.deletes(true)` restores the default behavior.
    pub fn deletes(mut self, enabled: bool) -> Self {
        let filter = PbFilterType::Nodelete as i32;
        if enabled {
            self.current.filters.retain(|&f| f != filter);
        } else if !self.current.filters.contains(&filter) {
            self.current.filters.push(filter);
        }
        self
    }
}

/// Chaining methods — only available when `W` is a `WatchBuilder<C>`.
impl<C> Watch<WatchBuilder<C>> {
    fn _finalize_and_new(self, lower: Bytes, upper: Bytes) -> Self {
        let Watch { mut watcher, current } = self;
        watcher.specs.push(current);
        Watch {
            watcher,
            current: etcdserverpb::WatchCreateRequest {
                key: lower,
                range_end: upper,
                fragment: true,
                ..Default::default()
            },
        }
    }

    /// Finalize the current target and add another watch for a single key.
    pub fn key(self, key: impl AsKey) -> Self {
        let key = Bytes::copy_from_slice(key.as_key());
        self._finalize_and_new(key, Bytes::new())
    }

    /// Finalize the current target and add another watch for a prefix.
    pub fn prefix(self, prefix: impl AsKey) -> Self {
        self.range(Prefix(prefix))
    }

    /// Finalize the current target and add another watch for a range.
    pub fn range(self, range: impl AsRange) -> Self {
        let (lower, upper) = range.as_boundaries();
        self._finalize_and_new(lower, upper)
    }
}

/// Attach a client to a clientless watch chain.
impl Watch<WatchBuilder<()>> {
    pub fn with_client(self, client: Client) -> Watch<WatchBuilder<Client>> {
        Watch {
            watcher: self.watcher.with_client(client),
            current: self.current,
        }
    }
}

impl WatchBuilder<Client> {
    /// Create a [`Watcher`] and begin watching for events.
    ///
    /// The gRPC stream is established lazily on the first poll of the returned [`Watcher`]. All
    /// targets accumulated through the builder are sent as `WatchCreateRequest` messages at that
    /// time, followed by any requests already made through the [`Watcher`]. Successful creation
    /// confirmations are consumed internally by the stream; a refusal is yielded as an error (see
    /// [`Watcher::add`]).
    ///
    /// The builder may have zero targets — the resulting [`Watcher`] simply waits for watches to
    /// be added via [`Watcher::add`].
    ///
    /// Because a watch is not active until the stream is first polled, events that occur between
    /// calling `start` and the first poll may be missed. Use
    /// [`start_revision`][Watch::start_revision] to watch from a known point in history if you need
    /// to guarantee delivery.
    ///
    /// The stream carries the client's auth token. See [`Watcher::add`] for what happens when etcd
    /// stops accepting it.
    pub(crate) fn start_client_watch(self) -> Watcher {
        let client = self.client.inner;
        let requests = Arc::new(std::sync::Mutex::new(Requests {
            attempt: None,
            replay: Some(Vec::new()),
        }));
        let sender = WatchSender {
            requests: Arc::downgrade(&requests),
            next_id: AtomicI64::new(1),
        };
        // Watches given to the builder are numbered 1..=N, in order.
        for spec in self.specs {
            sender.add(Watch {
                watcher: (),
                current: spec,
            });
        }

        let inner = async_stream::stream! {
            // Whether this attempt replaced one whose token etcd refused. A second refusal is
            // final.
            let mut refreshed = false;
            'open: loop {
                // Establish the gRPC stream, retrying on Unavailable (the server may not be
                // reachable yet when the channel was created with `connect_lazy`).
                let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
                let (mut response_stream, unanswered_creates, generation) = loop {
                    let receiver = requests.lock().unwrap().new_attempt();
                    let unanswered_creates = Arc::new(std::sync::Mutex::new(VecDeque::new()));
                    let mut request = tonic::Request::new(ReceiverStream {
                        inner: receiver,
                        unanswered_creates: unanswered_creates.clone(),
                    });
                    let generation = client.attach_stream_token(&mut request, deadline).await;
                    let mut watch_client = client.service_client(etcdserverpb::watch_client::WatchClient::new);
                    match watch_client.watch(request).await {
                        Ok(resp) => break (resp.into_inner(), unanswered_creates, generation),
                        Err(status)
                            if status.code() == tonic::Code::Unavailable
                                && std::time::Instant::now() <= deadline =>
                        {
                            continue;
                        }
                        Err(status) => {
                            // A consumer may stop polling at this error, so drop `requests` now
                            // rather than at the return.
                            drop(requests);
                            yield Err(WatchError::from_status(status));
                            return;
                        }
                    }
                };

                // The fragments of a response received so far, combined. All but the last fragment
                // have `fragment` set, and etcd sends nothing else between them.
                let mut fragments: Option<etcdserverpb::WatchResponse> = None;
                // The compacted watches the stream canceled, until etcd confirms each cancellation.
                let mut canceled_compacted = HashSet::new();
                loop {
                    match response_stream.message().await {
                        Ok(Some(mut resp)) => {
                            if resp.created {
                                // Creates are answered in the order they were sent, and a refusal
                                // carries watch ID -1 instead of the ID it refuses.
                                resp.watch_id = unanswered_creates.lock().unwrap().pop_front().unwrap_or(resp.watch_id);
                                if !refreshed
                                    && ClientInner::is_stale_token_refusal(&resp.cancel_reason)
                                    && requests.lock().unwrap().replay.is_some()
                                    && client
                                        .refresh_auth_token_unserialized(
                                            generation,
                                            Some(std::time::Instant::now() + std::time::Duration::from_secs(5)),
                                        )
                                        .await
                                        .is_ok()
                                {
                                    refreshed = true;
                                    continue 'open;
                                }
                                requests.lock().unwrap().replay = None;
                                if !resp.canceled {
                                    continue;
                                }
                            }
                            if let Some(mut held) = fragments.take() {
                                if held.watch_id == resp.watch_id && !resp.canceled {
                                    held.events.append(&mut resp.events);
                                    resp.events = held.events;
                                } else {
                                    yield Err(WatchError::invalid_response("incomplete fragmented watch response"));
                                }
                            }
                            if resp.fragment {
                                fragments = Some(resp);
                                continue;
                            }
                            if resp.canceled {
                                if resp.compact_revision != 0 {
                                    // etcd keeps a compacted watch until it is canceled, and
                                    // answers no stream-wide progress request while it does, so
                                    // cancel it before a consumer can react to the error.
                                    requests.lock().unwrap().send(cancel_request(resp.watch_id));
                                    canceled_compacted.insert(resp.watch_id);
                                } else if canceled_compacted.remove(&resp.watch_id) {
                                    continue;
                                }
                            }
                            // etcd holds back a watch's events until it has answered the watch's
                            // create, but sends a stream-wide progress notification at once.
                            if resp.watch_id == -1 && !resp.canceled && !unanswered_creates.lock().unwrap().is_empty() {
                                continue;
                            }
                            for item in convert_response(resp) {
                                yield item;
                            }
                        }
                        Ok(None) => return,
                        Err(status) => {
                            drop(requests);
                            yield Err(WatchError::from_status(status));
                            return;
                        }
                    }
                }
            }
        };

        Watcher {
            sender,
            stream: WatchStream { inner: Box::new(inner) },
        }
    }
}

/// `start` on a `Watch` chain forwards to the underlying [`WatchBuilder`].
impl<C: crate::driver::WatchDriver> Watch<WatchBuilder<C>> {
    /// Finalize the current target and create a [`Watcher`].
    ///
    /// See [`WatchBuilder::start`] for details.
    pub fn start(self) -> C::Watcher {
        let Watch { mut watcher, current } = self;
        watcher.specs.push(current);
        watcher.start()
    }
}

/// An active watcher over one or more etcd keys.
///
/// Created by [`Watch::start`]. A `Watcher` combines a [`WatchStream`] (for receiving
/// events) and a [`WatchSender`] (for adding/canceling watches and requesting progress).
///
/// `Watcher` dereferences to [`WatchStream`], so it can be used directly as a [`Stream`]:
///
/// ```no_run
/// use futures::StreamExt;
/// use etcdrs::client::WatchEvent;
/// # async {
/// # let client: etcdrs::Client = todo!();
/// let mut watcher = client.watch()
///     .key("foo")
///     .start();
/// while let Some(event) = watcher.next().await {
///     match event.unwrap() {
///         WatchEvent::Put { record, .. } => println!("put: {record:?}"),
///         WatchEvent::Delete { key, .. } => println!("delete: {key:?}"),
///         WatchEvent::Progress { revision, .. } => println!("progress: {revision:?}"),
///     }
/// }
/// # };
/// ```
///
/// Use [`into_parts`][Self::into_parts] to split the watcher when you need to send control messages
/// concurrently with consuming the stream (e.g. from separate tasks).
///
/// Control messages sent before the stream is first polled are sent once it is established. A watch
/// starts when etcd receives its request, so set [`start_revision`][Watch::start_revision] on a
/// watch that must not miss earlier events.
///
/// etcd splits a response too large for one message into fragments. A `Watcher` yields the events
/// of such a response back to back once its last fragment arrives, so a stream that fails does so
/// between revisions, and a watch restarted just after the last event's revision misses nothing.
///
/// ## Cleanup
///
/// Dropping a `Watcher` closes the underlying gRPC stream, which causes the server to cancel
/// all watches associated with it.
pub struct Watcher {
    sender: WatchSender,
    stream: WatchStream,
}

impl Watcher {
    /// Split the `Watcher` into its sender and stream halves.
    ///
    /// This is useful when you need to send control messages (add, cancel, progress) from a
    /// different context than the one consuming events.
    pub fn into_parts(self) -> (WatchSender, WatchStream) {
        (self.sender, self.stream)
    }

    /// Add a watch to this watcher. Returns the assigned [`WatchId`].
    ///
    /// The watch becomes active once the server processes the creation request. Events may not
    /// appear immediately -- the server confirms creation with a response that the stream silently
    /// consumes, then begins delivering events for the new watch.
    ///
    /// If the server refuses to create the watch, the stream yields an error with
    /// [`WatchErrorKind::Canceled`] instead, carrying this [`WatchId`] and the server's
    /// [`cancel_reason`][WatchError::cancel_reason]. etcd refuses a watch whose range is empty or
    /// inverted, whose [`start_revision`][Watch::start_revision] is negative, or whose range the
    /// client may not read. Other watches on this watcher are unaffected.
    ///
    /// etcd also refuses a watch once it stops accepting the auth token the watcher's stream
    /// opened with, for example after the token went unused for five minutes (etcd's default) or
    /// its user's password changed. Until etcd has answered one of the watcher's watches, the
    /// watcher replaces its stream with one that carries a refreshed token, and yields nothing.
    /// After that, replacing the stream would drop the watches etcd created, so the refusal is
    /// yielded like any other, with a reason such as
    /// `rpc error: code = Unauthenticated desc = etcdserver: invalid auth token`, and the watches
    /// already created keep delivering events. To add the watch, start a new [`Watcher`]: it
    /// replaces a stale token as described.
    ///
    /// Construct the [`Watch`] with [`Watch::new`]:
    ///
    /// ```no_run
    /// # use etcdrs::client::{Watch, Watcher};
    /// # let watcher: Watcher = todo!();
    /// let id = watcher.add(Watch::new("key").get_previous());
    /// ```
    pub fn add(&self, watch: Watch) -> WatchId {
        self.sender.add(watch)
    }

    /// Request cancellation of the watch with the given `watch_id`.
    ///
    /// This sends a cancellation request to the server. Because the server processes requests
    /// asynchronously, events for this watch may still arrive after `cancel` returns -- these are
    /// events that were already in-flight before the server processed the cancellation. The stream
    /// will eventually yield an error with [`WatchErrorKind::Canceled`] for this watch, confirming the
    /// cancellation. Other watches on this watcher are unaffected.
    ///
    /// Canceling a watch that already ended with an error yields nothing more: the server ignores a
    /// cancellation of a watch it refused to create (see [`add`][Self::add]), and the stream
    /// cancels a [`WatchErrorKind::Compacted`] watch itself.
    pub fn cancel(&self, watch_id: WatchId) {
        self.sender.cancel(watch_id);
    }

    /// Request a progress notification from the server.
    ///
    /// The server will respond with a [`WatchEvent::Progress`] containing the current store
    /// revision. This is useful for heartbeat/liveness checks and for learning the current
    /// revision when no events have occurred recently.
    ///
    /// No response arrives in three cases, so request progress again if one is overdue. etcd
    /// ignores the request while a watch is catching up on past revisions or starts at a revision
    /// the store has not reached, and answers none on a watcher without watches. The stream drops a
    /// response that arrives while etcd has yet to confirm a watch's creation: etcd sends the
    /// response at once, but holds back that watch's events until it confirms it.
    pub fn request_progress(&self) {
        self.sender.request_progress();
    }
}

impl Deref for Watcher {
    type Target = WatchStream;

    fn deref(&self) -> &Self::Target {
        &self.stream
    }
}

impl DerefMut for Watcher {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.stream
    }
}

impl Stream for Watcher {
    type Item = Result<WatchEvent, WatchError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Pin::new(&mut self.stream).poll_next(cx)
    }
}

#[cfg(feature = "nightly-async-iterator")]
impl std::async_iter::AsyncIterator for Watcher {
    type Item = Result<WatchEvent, WatchError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Stream::poll_next(Pin::new(&mut self.stream), cx)
    }
}

/// The control half of a [`Watcher`], used to add/cancel watches and request progress.
///
/// Obtained via [`Watcher::into_parts`]. All methods send requests through the shared gRPC stream.
/// Because the server processes these asynchronously, there is a window between calling a control
/// method and the server acting on it.
pub struct WatchSender {
    /// `Weak`, so that requests sent after the stream is dropped are not kept.
    requests: Weak<std::sync::Mutex<Requests>>,
    next_id: AtomicI64,
}

impl WatchSender {
    fn send(&self, request: etcdserverpb::WatchRequest) {
        if let Some(requests) = self.requests.upgrade() {
            requests.lock().unwrap().send(request);
        }
    }

    /// Add a watch. Returns the assigned [`WatchId`].
    ///
    /// See [`Watcher::add`] for details.
    pub fn add(&self, watch: Watch) -> WatchId {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        let mut request = watch.current;
        request.watch_id = id;
        self.send(etcdserverpb::WatchRequest {
            request_union: Some(PbRequestUnion::CreateRequest(request)),
        });
        WatchId::new(id).expect("watch ID counter overflowed to 0")
    }

    /// Request cancellation of a watch.
    ///
    /// See [`Watcher::cancel`] for details.
    pub fn cancel(&self, watch_id: WatchId) {
        self.send(cancel_request(watch_id.get()));
    }

    /// Request a progress notification.
    ///
    /// See [`Watcher::request_progress`] for details.
    pub fn request_progress(&self) {
        self.send(etcdserverpb::WatchRequest {
            request_union: Some(PbRequestUnion::ProgressRequest(etcdserverpb::WatchProgressRequest {})),
        });
    }
}

fn cancel_request(watch_id: i64) -> etcdserverpb::WatchRequest {
    etcdserverpb::WatchRequest {
        request_union: Some(PbRequestUnion::CancelRequest(etcdserverpb::WatchCancelRequest {
            watch_id,
        })),
    }
}

/// The event stream half of a [`Watcher`].
///
/// Obtained via [`Watcher::into_parts`]. Implements [`Stream`] — use
/// [`StreamExt::next`][futures_core::Stream] or `for await` to consume events.
pub struct WatchStream {
    inner: Box<dyn Stream<Item = Result<WatchEvent, WatchError>> + Send>,
}

impl WatchStream {
    fn poll_next_impl(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<Option<WatchEvent>, WatchError>> {
        let inner = unsafe { self.map_unchecked_mut(|s| s.inner.as_mut()) };
        inner.poll_next(cx).map(|item| match item {
            None => Ok(None),
            Some(Ok(event)) => Ok(Some(event)),
            Some(Err(err)) => Err(err),
        })
    }
}

impl Stream for WatchStream {
    type Item = Result<WatchEvent, WatchError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.poll_next_impl(cx).map(Result::transpose)
    }
}

#[cfg(feature = "nightly-async-iterator")]
impl std::async_iter::AsyncIterator for WatchStream {
    type Item = Result<WatchEvent, WatchError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.poll_next_impl(cx).map(Result::transpose)
    }
}

/// Where a [`WatchSender`] sends requests, shared with the stream.
///
/// Each attempt to establish the stream gets its own channel, because the transport of a failed
/// attempt can keep taking requests from its channel until the server resets the stream.
struct Requests {
    /// The current attempt's channel, or `None` before the first attempt.
    attempt: Option<tokio::sync::mpsc::UnboundedSender<etcdserverpb::WatchRequest>>,
    /// Every request sent so far, oldest first, while the stream may still be replaced: until etcd
    /// accepts a create on it, or refuses one with a refusal the stream yields. A replaced attempt
    /// loses whatever its transport took, so each attempt's channel starts with all of them.
    replay: Option<Vec<etcdserverpb::WatchRequest>>,
}

impl Requests {
    fn send(&mut self, request: etcdserverpb::WatchRequest) {
        if let Some(replay) = &mut self.replay {
            replay.push(request.clone());
        }
        if let Some(attempt) = &self.attempt {
            let _ = attempt.send(request);
        }
    }

    /// Start a channel for a new attempt with every request sent so far, and send later ones to it.
    fn new_attempt(&mut self) -> tokio::sync::mpsc::UnboundedReceiver<etcdserverpb::WatchRequest> {
        let (attempt, receiver) = tokio::sync::mpsc::unbounded_channel();
        for request in self.replay.iter().flatten() {
            let _ = attempt.send(request.clone());
        }
        self.attempt = Some(attempt);
        receiver
    }
}

/// Wraps a [`tokio::sync::mpsc::UnboundedReceiver`] as a [`Stream`], recording the watch ID of each
/// create request as the transport takes it.
struct ReceiverStream {
    inner: tokio::sync::mpsc::UnboundedReceiver<etcdserverpb::WatchRequest>,
    /// The watch IDs of the create requests taken so far that etcd has not answered, oldest first.
    unanswered_creates: Arc<std::sync::Mutex<VecDeque<i64>>>,
}

impl Stream for ReceiverStream {
    type Item = etcdserverpb::WatchRequest;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let polled = self.inner.poll_recv(cx);
        if let Poll::Ready(Some(request)) = &polled
            && let Some(PbRequestUnion::CreateRequest(create)) = &request.request_union
        {
            self.unanswered_creates.lock().unwrap().push_back(create.watch_id);
        }
        polled
    }
}

/// What went wrong with a watch operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WatchErrorKind {
    /// The watch was compacted — the requested revision is older than the server's compacted
    /// revision. The stream cancels the watch on the server and yields nothing more for it.
    Compacted,
    /// The watch was canceled by [`Watcher::cancel`], or the server refused to create it.
    /// [`WatchError::cancel_reason`] carries the server's reason for a refusal.
    Canceled,
    /// The server returned an invalid or unexpected response.
    InvalidResponse,
    /// A gRPC transport or unexpected error.
    Unknown,
}

/// An error from a watch operation.
pub struct WatchError(Box<WatchErrorRepr>);

struct WatchErrorRepr {
    kind: WatchErrorKind,
    watch_id: Option<WatchId>,
    compact_revision: Option<i64>,
    message: Cow<'static, str>,
    status: Option<tonic::Status>,
    backtrace: Backtrace,
}

impl WatchError {
    /// The operation-specific error kind.
    pub fn kind(&self) -> WatchErrorKind {
        self.0.kind
    }

    /// The watch ID associated with this error, if applicable.
    pub fn watch_id(&self) -> Option<WatchId> {
        self.0.watch_id
    }

    /// The compact revision, if this is a [`WatchErrorKind::Compacted`] error.
    pub fn compact_revision(&self) -> Option<i64> {
        self.0.compact_revision
    }

    /// The cancellation reason, if this is a [`WatchErrorKind::Canceled`] error.
    pub fn cancel_reason(&self) -> Option<&str> {
        if self.0.kind == WatchErrorKind::Canceled {
            Some(&self.0.message)
        } else {
            None
        }
    }

    /// The original gRPC status, if this error originated from a gRPC call.
    pub fn grpc_status(&self) -> Option<&tonic::Status> {
        self.0.status.as_ref()
    }

    /// Take ownership of the original gRPC status, if present.
    pub fn take_grpc_status(self) -> Option<tonic::Status> {
        self.0.status
    }

    /// The backtrace captured when this error was created.
    pub fn backtrace(&self) -> &Backtrace {
        &self.0.backtrace
    }

    pub(crate) fn from_status(status: tonic::Status) -> Self {
        Self(Box::new(WatchErrorRepr {
            kind: WatchErrorKind::Unknown,
            watch_id: None,
            compact_revision: None,
            message: Cow::Borrowed(""),
            status: Some(status),
            backtrace: Backtrace::capture(),
        }))
    }

    fn compacted(watch_id: i64, compact_revision: i64) -> Self {
        Self(Box::new(WatchErrorRepr {
            kind: WatchErrorKind::Compacted,
            watch_id: WatchId::new(watch_id),
            compact_revision: Some(compact_revision),
            message: Cow::Owned(format!("watch {watch_id} compacted at revision {compact_revision}")),
            status: None,
            backtrace: Backtrace::capture(),
        }))
    }

    fn canceled(watch_id: i64, reason: String) -> Self {
        Self(Box::new(WatchErrorRepr {
            kind: WatchErrorKind::Canceled,
            watch_id: WatchId::new(watch_id),
            compact_revision: None,
            message: if reason.is_empty() {
                Cow::Borrowed("canceled")
            } else {
                Cow::Owned(reason)
            },
            status: None,
            backtrace: Backtrace::capture(),
        }))
    }

    fn invalid_response(message: &'static str) -> Self {
        Self(Box::new(WatchErrorRepr {
            kind: WatchErrorKind::InvalidResponse,
            watch_id: None,
            compact_revision: None,
            message: Cow::Borrowed(message),
            status: None,
            backtrace: Backtrace::capture(),
        }))
    }
}

impl WatchError {
    fn display_message(&self) -> &str {
        if !self.0.message.is_empty() {
            &self.0.message
        } else if let Some(status) = &self.0.status {
            status.message()
        } else {
            ""
        }
    }
}

impl fmt::Debug for WatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WatchError")
            .field("kind", &self.0.kind)
            .field("message", &self.display_message())
            .field("watch_id", &self.0.watch_id)
            .finish()
    }
}

impl fmt::Display for WatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}: {}", self.0.kind, self.display_message())
    }
}

impl std::error::Error for WatchError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.0.status.as_ref().map(|s| s as _)
    }
}

impl crate::error::OperationError for WatchError {
    fn grpc_status(&self) -> Option<&tonic::Status> {
        self.0.status.as_ref()
    }

    fn backtrace(&self) -> &Backtrace {
        &self.0.backtrace
    }
}

// -------------------------------------------------------------------------------------------------
// Conversion helpers
// -------------------------------------------------------------------------------------------------

/// Build [`Metadata`] from a protobuf [`KeyValue`], tolerating `create_revision = 0` which etcd
/// sends for DELETE tombstones. In that case, `create_revision` is set equal to `mod_revision`.
fn watch_metadata_from_pb(kv: &mvccpb::KeyValue) -> Metadata {
    let create_revision = Revision::new(kv.create_revision)
        .unwrap_or_else(|| Revision::new(kv.mod_revision).expect("mod_revision should be non-zero"));
    Metadata {
        create_revision,
        modified_revision: Revision::new(kv.mod_revision).expect("mod_revision should be non-zero"),
        version: Version::new(kv.version as u64),
        lease: LeaseId::new(kv.lease),
    }
}

/// Like [`record_from_pb`], but tolerates `create_revision = 0` which etcd sends for DELETE
/// tombstones.
fn watch_record_from_pb(kv: mvccpb::KeyValue) -> Record {
    let metadata = watch_metadata_from_pb(&kv);
    Record::new(kv.key, kv.value, metadata)
}

/// Convert a [`WatchResponse`] into an iterator of stream items.
fn convert_response(resp: etcdserverpb::WatchResponse) -> Vec<Result<WatchEvent, WatchError>> {
    if resp.canceled {
        let err = if resp.compact_revision != 0 {
            WatchError::compacted(resp.watch_id, resp.compact_revision)
        } else {
            WatchError::canceled(resp.watch_id, resp.cancel_reason)
        };
        return vec![Err(err)];
    }

    let header = resp.header.map(ResponseHeader::from_pb);

    // Progress notification: no events, not created, not canceled.
    if resp.events.is_empty() {
        if let Some(header) = header {
            return vec![Ok(WatchEvent::Progress {
                revision: header.revision(),
                header,
                watch_id: WatchId::new(resp.watch_id),
            })];
        }
        return vec![];
    }

    let header = header.expect("WatchResponse with events should have a valid header");
    let watch_id = WatchId::new(resp.watch_id).expect("server returned watch_id 0");
    resp.events
        .into_iter()
        .map(|event| {
            let kv = event
                .kv
                .ok_or_else(|| WatchError::invalid_response("watch event missing kv field"))?;

            let prev_record = event.prev_kv.map(record_from_pb);

            if event.r#type == PbEventType::Delete as i32 {
                let metadata = watch_metadata_from_pb(&kv);
                Ok(WatchEvent::Delete {
                    header,
                    watch_id,
                    key: KeyWithMetadata::new(kv.key, metadata),
                    prev_record,
                })
            } else {
                let created = kv.create_revision == kv.mod_revision;
                let record = watch_record_from_pb(kv);
                Ok(WatchEvent::Put {
                    header,
                    watch_id,
                    record,
                    prev_record,
                    created,
                })
            }
        })
        .collect()
}

#[cfg(test)]
mod test {
    use std::time::Duration;

    use futures::{FutureExt as _, StreamExt as _};

    use super::*;
    use crate::pb::etcdserverpb::watch_server::{Watch as WatchService, WatchServer};

    /// A watch service that sends, on the one stream a client opens, the responses a test gives it,
    /// and ends the stream when the test drops their sender. It passes the requests it receives to
    /// the test.
    struct Scripted {
        responses: std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedReceiver<etcdserverpb::WatchResponse>>>,
        requests: tokio::sync::mpsc::UnboundedSender<etcdserverpb::WatchRequest>,
    }

    #[tonic::async_trait]
    impl WatchService for Scripted {
        async fn watch(
            self: Arc<Self>,
            request: tonic::Request<tonic::Streaming<etcdserverpb::WatchRequest>>,
        ) -> Result<tonic::Response<tonic::codegen::BoxStream<etcdserverpb::WatchResponse>>, tonic::Status> {
            let mut responses = self.responses.lock().unwrap().take().expect("one stream");
            let mut incoming = request.into_inner();
            let requests = self.requests.clone();
            tokio::spawn(async move {
                while let Ok(Some(request)) = incoming.message().await {
                    let _ = requests.send(request);
                }
            });
            Ok(tonic::Response::new(Box::pin(futures::stream::poll_fn(move |cx| {
                responses.poll_recv(cx).map(|response| response.map(Ok))
            }))))
        }
    }

    /// Start a watcher against a [`Scripted`] service, returning it, the sender of the service's
    /// responses, and the receiver of the requests the service receives.
    async fn scripted_watcher() -> (
        Watcher,
        tokio::sync::mpsc::UnboundedSender<etcdserverpb::WatchResponse>,
        tokio::sync::mpsc::UnboundedReceiver<etcdserverpb::WatchRequest>,
    ) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let (responses, receiver) = tokio::sync::mpsc::unbounded_channel();
        let (sender, requests) = tokio::sync::mpsc::unbounded_channel();
        tokio::spawn(tonic::transport::Server::builder().serve_with_incoming(
            WatchServer::new(Scripted {
                responses: std::sync::Mutex::new(Some(receiver)),
                requests: sender,
            }),
            tonic::transport::server::TcpIncoming::from(listener),
        ));
        let client = Client::new(&format!("http://{address}")).unwrap();
        (client.watch().prefix("k/").start(), responses, requests)
    }

    /// The header etcd gives a response at `revision`.
    fn header(revision: i64) -> etcdserverpb::ResponseHeader {
        etcdserverpb::ResponseHeader {
            cluster_id: 1,
            member_id: 1,
            revision,
            raft_term: 1,
        }
    }

    /// etcd's reply that it created watch 1.
    fn created() -> etcdserverpb::WatchResponse {
        etcdserverpb::WatchResponse {
            header: Some(header(1)),
            watch_id: 1,
            created: true,
            ..Default::default()
        }
    }

    /// A stream-wide progress notification at `revision`, which etcd sends with watch ID -1.
    fn progress(revision: i64) -> etcdserverpb::WatchResponse {
        etcdserverpb::WatchResponse {
            header: Some(header(revision)),
            watch_id: -1,
            ..Default::default()
        }
    }

    /// A response on watch 1 that puts each of `keys` at revision 2, marked as a fragment that
    /// more follow if `fragment`.
    fn puts(keys: &[&str], fragment: bool) -> etcdserverpb::WatchResponse {
        etcdserverpb::WatchResponse {
            header: Some(header(2)),
            watch_id: 1,
            fragment,
            events: keys
                .iter()
                .map(|key| mvccpb::Event {
                    r#type: PbEventType::Put as i32,
                    kv: Some(mvccpb::KeyValue {
                        key: Bytes::copy_from_slice(key.as_bytes()),
                        create_revision: 2,
                        mod_revision: 2,
                        version: 1,
                        ..Default::default()
                    }),
                    prev_kv: None,
                })
                .collect(),
            ..Default::default()
        }
    }

    /// The record of the put a watcher yielded.
    fn put_record(item: Option<Result<WatchEvent, WatchError>>) -> Record {
        match item {
            Some(Ok(WatchEvent::Put { record, .. })) => record,
            other => panic!("expected a put, got {other:?}"),
        }
    }

    /// The key of the put a watcher yielded.
    fn put_key(item: Option<Result<WatchEvent, WatchError>>) -> String {
        String::from_utf8(put_record(item).key().to_vec()).unwrap()
    }

    /// The events of a response etcd splits into fragments used to be yielded as each fragment
    /// arrived, so a consumer could take part of a revision for all of it.
    #[tokio::test]
    async fn fragmented_response_is_yielded_once_whole() {
        let (mut watcher, responses, _) = scripted_watcher().await;
        responses.send(puts(&["k/0"], false)).unwrap();
        assert_eq!(put_key(watcher.next().await), "k/0");

        responses.send(puts(&["k/1", "k/2"], true)).unwrap();
        assert!(
            tokio::time::timeout(Duration::from_millis(200), watcher.next())
                .await
                .is_err()
        );

        responses.send(puts(&["k/3"], false)).unwrap();
        let mut keys = vec![put_key(watcher.next().await)];
        while let Some(item) = watcher.next().now_or_never() {
            keys.push(put_key(item));
        }
        assert_eq!(keys, ["k/1", "k/2", "k/3"]);
    }

    /// A stream that ends between the fragments of a response yields none of its events. It used
    /// to yield those of the fragments that arrived, and a consumer that resumed after them lost
    /// the rest of their revision.
    #[tokio::test]
    async fn stream_ending_between_fragments_yields_none_of_them() {
        let (mut watcher, responses, _) = scripted_watcher().await;
        responses.send(puts(&["k/0"], false)).unwrap();
        assert_eq!(put_key(watcher.next().await), "k/0");

        responses.send(puts(&["k/1", "k/2"], true)).unwrap();
        drop(responses);
        assert!(watcher.next().await.is_none());
    }

    /// etcd never sends another response between the fragments of one, so one that does leaves
    /// the fragments before it without their last.
    #[tokio::test]
    async fn interrupted_fragments_are_an_invalid_response() {
        let (mut watcher, responses, _) = scripted_watcher().await;
        responses.send(puts(&["k/1"], true)).unwrap();
        responses
            .send(etcdserverpb::WatchResponse {
                watch_id: 2,
                ..puts(&["k/2"], false)
            })
            .unwrap();

        let error = watcher.next().await.unwrap().unwrap_err();
        assert_eq!(error.kind(), WatchErrorKind::InvalidResponse);
        assert_eq!(put_key(watcher.next().await), "k/2");
    }

    /// etcd holds back a watch's events until it has sent the watch's `created` reply, but sends a
    /// stream-wide progress notification at once. The stream used to yield such a notification
    /// ahead of the events up to its revision.
    #[tokio::test]
    async fn stream_wide_progress_before_a_created_reply_is_dropped() {
        let (mut watcher, responses, mut requests) = scripted_watcher().await;
        // Once the service has the create, the stream counts it as unanswered.
        tokio::select! {
            item = watcher.next() => panic!("expected nothing, got {item:?}"),
            request = requests.recv() => assert!(
                matches!(request.unwrap().request_union, Some(PbRequestUnion::CreateRequest(_)))
            ),
        }

        responses.send(progress(2)).unwrap();
        responses.send(created()).unwrap();
        responses.send(puts(&["k/0"], false)).unwrap();
        responses.send(progress(3)).unwrap();

        assert_eq!(put_key(watcher.next().await), "k/0");
        let item = watcher.next().await;
        assert!(
            matches!(&item, Some(Ok(WatchEvent::Progress { revision, .. })) if revision.get() == 3),
            "expected progress at 3, got {item:?}"
        );
    }

    /// etcd sends the events it held back for a watch it had not yet announced whole, however
    /// large, and tonic refuses a message over 4 MiB unless the client raises its limit.
    #[tokio::test]
    async fn response_over_4_mib_is_yielded() {
        let (mut watcher, responses, _) = scripted_watcher().await;
        let keys = (0..50).map(|i| format!("k/{i:02}")).collect::<Vec<_>>();
        let mut response = puts(&keys.iter().map(String::as_str).collect::<Vec<_>>(), false);
        for (i, event) in response.events.iter_mut().enumerate() {
            event.kv.as_mut().unwrap().value = Bytes::from(vec![i as u8; 100 * 1024]);
        }
        responses.send(response).unwrap();

        for (i, key) in keys.iter().enumerate() {
            let record = put_record(watcher.next().await);
            assert_eq!(record.key(), key.as_bytes());
            assert_eq!(record.value().len(), 100 * 1024);
            assert!(record.value().iter().all(|&byte| byte == i as u8), "{key}");
        }
    }
}