hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
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
//! Reading a run's output stream: the chunks
//! [`Context::put_stream`](crate::Context::put_stream) publishes.
//!
//! One [`OutputStream`] owns one `SubscribeToWorkflowEvents` subscription and
//! one background task. That is the opposite of the run *result* listener next
//! door, which multiplexes every wait on one client onto a single stream — and
//! the difference is in the wire, not in taste: a result subscription takes a
//! *stream* of run ids, so more runs can be added to one connection, while an
//! event subscription's filter is a single request message, so one filter
//! needs one connection.
//!
//! Like the result listener, the loop here is network-agnostic: [`run`] is
//! handed a function that opens one stream, so the filter, the reconnect
//! policy and the give-up rule can be tested against a scripted stream rather
//! than a socket.

use std::collections::{BTreeMap, HashMap};
use std::pin::Pin;
use std::task::{Context as TaskContext, Poll};
use std::time::Duration;

use hatchet_proto::root::{
    ResourceEventType, SubscribeToWorkflowEventsRequest, WorkflowEvent,
    dispatcher_client::DispatcherClient,
};
use tokio::sync::mpsc;
use tokio_stream::Stream;
use tokio_util::sync::{CancellationToken, DropGuard};
use tonic::{Code, Status};

use crate::Client;
use crate::error::{Error, Result};
use crate::retry::{
    STREAM_MAX_CONSECUTIVE_OTHER_FAILURES, StreamErrorClass, classify_stream_end, full_jitter,
    stream_backoff_cap,
};
use crate::transport::GrpcService;

/// How many chunks are held for a consumer that is not reading.
///
/// Beyond this the background task waits, which stops reading the socket,
/// which is what applies back pressure to the engine — the alternative is an
/// unbounded queue that a slow consumer turns into unbounded memory. Payloads
/// are whatever the handler published (128 KiB arrived intact in testing), so
/// this bounds the memory a stalled consumer costs at that many payloads.
const CHUNK_BUFFER: usize = 64;

/// How long [`open`] waits for the engine to answer the subscribe call before
/// handing back a stream that is still being opened in the background.
///
/// It is a *courtesy*, not a guarantee: a subscription the engine answers
/// straight away is open before the caller triggers anything, which is what
/// makes "subscribe, then trigger" worth recommending. Both supported engines
/// have been observed not sending response headers on a fresh stream until
/// they have something to say — for over a minute when nothing matched the
/// filter — so waiting for them without a bound would hang the caller.
///
/// Running out of it never *abandons* the attempt: the call goes on in the
/// background task and becomes the stream's first connection. The engine has
/// registered the subscription by then, whatever its headers say, so dropping
/// the call would close a subscription that was already receiving.
const OPEN_TIMEOUT: Duration = Duration::from_secs(5);

/// One chunk of a run's output, as
/// [`Context::put_stream`](crate::Context::put_stream) published it.
///
/// The payload is whatever the handler wrote. It goes out as bytes and comes
/// back as a `String`, because that is what the two sides of the wire are
/// (`PutStreamEventRequest.message` is `bytes`, `WorkflowEvent.event_payload`
/// is `string`); see [`put_stream`](crate::Context::put_stream) for what that
/// does to bytes that are not UTF-8.
///
/// ```no_run
/// # async fn example(client: hatchet_client::Client) -> hatchet_client::Result<()> {
/// let mut chunks = client.runs().stream("d627fab0-385f-4eb4-98f9-59a783bc8631").await?;
/// if let Some(Ok(chunk)) = chunks.next().await {
///     println!("run {} task {}: [{:?}] {}", chunk.run_id, chunk.task_run_id, chunk.index, chunk.payload);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamChunk {
    /// The run the chunk belongs to. Worth reading when one subscription
    /// covers several runs — see
    /// [`RunsClient::stream_by_metadata`](crate::RunsClient::stream_by_metadata).
    pub run_id: String,
    /// The *task* run that published it. A workflow run has one sequence of
    /// chunks per task, so this is what tells two interleaved outputs apart.
    pub task_run_id: String,
    /// The chunk's number in its task run's sequence, counted from zero, when
    /// the engine sent one. `None` means the engine did not — the field is
    /// optional on the wire — and such chunks are handed over in arrival order
    /// without any ordering guarantee.
    pub index: Option<i64>,
    /// What the handler published.
    pub payload: String,
}

/// A run's output stream: the chunks its handlers publish, in order.
///
/// Made by [`RunsClient::stream`](crate::RunsClient::stream),
/// [`RunsClient::stream_by_metadata`](crate::RunsClient::stream_by_metadata),
/// [`RunHandle::stream`](crate::RunHandle::stream) and
/// [`WorkflowRunHandle::stream`](crate::WorkflowRunHandle::stream).
///
/// It implements [`futures_core::Stream`](tokio_stream::Stream), so every
/// combinator that takes one works; [`next`](OutputStream::next) is here too
/// so the common case needs no extra crate and no trait import.
///
/// **Dropping it ends the subscription.** The background task that owns the
/// connection is cancelled, and the engine sees the stream close.
///
/// Delivery is not guaranteed: the engine has been observed dropping a chunk
/// silently. A gap in a task run's chunk numbering is reported as one
/// [`Error::StreamGap`] item and the stream carries on.
///
/// ```no_run
/// # async fn example(client: hatchet_client::Client) -> hatchet_client::Result<()> {
/// let mut chunks = client.runs().stream("d627fab0-385f-4eb4-98f9-59a783bc8631").await?;
/// while let Some(chunk) = chunks.next().await {
///     match chunk {
///         Ok(chunk) => print!("{}", chunk.payload),
///         // One hole in the output; the rest still arrives.
///         Err(hatchet_client::Error::StreamGap { .. }) => print!("…"),
///         Err(error) => return Err(error),
///     }
/// }
/// # Ok(())
/// # }
/// ```
#[must_use = "an output stream delivers nothing until it is read"]
#[derive(Debug)]
pub struct OutputStream {
    chunks: mpsc::Receiver<Result<StreamChunk>>,
    /// Cancels the background task when this stream is dropped. Holding the
    /// receiver alone would not: the task would keep the subscription open
    /// until it next tried to send.
    _cancel: DropGuard,
}

impl OutputStream {
    /// The next chunk, or `None` once the stream is over — the engine hung up,
    /// or it failed in a way reconnecting cannot fix (and then the last item
    /// was that error).
    ///
    /// Cancel-safe: dropping the returned future loses nothing.
    ///
    /// ```no_run
    /// # async fn example(client: hatchet_client::Client) -> hatchet_client::Result<()> {
    /// let mut chunks = client.runs().stream("d627fab0-385f-4eb4-98f9-59a783bc8631").await?;
    /// while let Some(chunk) = chunks.next().await {
    ///     print!("{}", chunk?.payload);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn next(&mut self) -> Option<Result<StreamChunk>> {
        self.chunks.recv().await
    }
}

impl Stream for OutputStream {
    type Item = Result<StreamChunk>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
        self.chunks.poll_recv(cx)
    }
}

/// The events one subscription is answered with.
type EventStream = Pin<Box<dyn Stream<Item = std::result::Result<WorkflowEvent, Status>> + Send>>;

/// Opens one subscription with `request` and hands back the stream it feeds.
///
/// The first connection is awaited for at most [`OPEN_TIMEOUT`] so that a
/// subscription the engine answers promptly is really open when this returns;
/// if it is not answered in time, *that same attempt* is handed to the
/// background task, which goes on waiting for it. A first connection that
/// fails in a way reconnecting cannot fix (a rejected token or an unknown run
/// id, most of all) is returned as an error rather than becoming a stream that
/// quietly yields nothing.
pub(crate) async fn open(
    client: &Client,
    request: SubscribeToWorkflowEventsRequest,
) -> Result<OutputStream> {
    // `dispatcher_grpc` already applies the client's gzip setting and the auth
    // header, so nothing about this connection is special.
    let connect = connecting(client.dispatcher_grpc(), request);
    open_with(connect, |attempt| {
        full_jitter(stream_backoff_cap(attempt), &mut rand::rng())
    })
    .await
}

/// [`open`] with the delay before reconnect number `attempt` (0-based) chosen
/// by `backoff` rather than by the SDK's policy.
///
/// The seam exists for the tests, exactly as it does on the result listener:
/// under full jitter the real delay may be any length including zero, so no
/// assertion on elapsed time can tell a backoff that is there from one that
/// was deleted.
async fn open_with<C, Fut, S, B>(mut connect: C, backoff: B) -> Result<OutputStream>
where
    C: FnMut() -> Fut + Send + 'static,
    Fut: Future<Output = std::result::Result<S, Status>> + Send + 'static,
    S: Stream<Item = std::result::Result<WorkflowEvent, Status>> + Send + Unpin + 'static,
    B: FnMut(u32) -> Duration + Send + 'static,
{
    let cancel = CancellationToken::new();
    // Spawned rather than awaited in place: an attempt this call stops waiting
    // for is handed to the background task, and dropping the future instead
    // would reset the HTTP/2 stream and unregister a subscription the engine
    // has already made — losing whatever is published before a replacement
    // lands, with no gap to report it by.
    //
    // Outliving *this call* is not the same as outliving the caller, though:
    // the guard below cancels the attempt if this function is dropped before
    // it hands it over — a `timeout` around `stream()`, a `select!` that loses
    // — rather than leaving a subscription registered with nobody to read it.
    let abandoned = cancel.clone().drop_guard();
    let mut connecting = tokio::spawn({
        let cancel = cancel.clone();
        let attempt = connect();
        async move {
            tokio::select! {
                () = cancel.cancelled() => {
                    Err(Status::cancelled("the subscribe call was abandoned"))
                }
                connected = attempt => connected,
            }
        }
    });
    let first = match tokio::time::timeout(OPEN_TIMEOUT, &mut connecting).await {
        Ok(Ok(Ok(stream))) => First::Open(stream),
        Ok(Ok(Err(status))) if classify_stream_end(Some(&status)) == StreamErrorClass::Fatal => {
            return Err(Error::Grpc(Box::new(status)));
        }
        // Worth another attempt, and the background task is where attempts
        // live.
        Ok(Ok(Err(_))) => First::None,
        // The attempt panicked, which is a bug in this SDK rather than
        // anything the engine did; the loop's own attempts are what is left.
        Ok(Err(_)) => First::None,
        // The engine has not answered yet. Not an error: it may simply have
        // nothing to say about this run so far, which is the normal case —
        // both supported engines hold back response headers until they have
        // an event. The attempt goes on in the background task.
        Err(_) => First::Connecting(connecting),
    };
    let (chunks, received) = mpsc::channel(CHUNK_BUFFER);
    tokio::spawn(run(connect, first, chunks, cancel, backoff));
    Ok(OutputStream {
        chunks: received,
        // The attempt belongs to the background task now, so the guard that
        // watched this call hands its job over to the one the consumer holds.
        _cancel: abandoned.disarm().drop_guard(),
    })
}

/// The connect function for a real engine: opens one
/// `SubscribeToWorkflowEvents` stream with the same request every time.
///
/// No `set_timeout` and no [`retry::unary`](crate::retry::unary), for the same
/// reasons as the other two streams in this SDK: a deadline would cut off a
/// run that is simply taking its time, and reconnecting is this loop's own
/// job.
fn connecting(
    dispatcher: DispatcherClient<GrpcService>,
    request: SubscribeToWorkflowEventsRequest,
) -> impl FnMut() -> Pin<Box<dyn Future<Output = std::result::Result<EventStream, Status>> + Send>>
{
    move || {
        let mut dispatcher = dispatcher.clone();
        let request = request.clone();
        Box::pin(async move {
            let events = dispatcher
                .subscribe_to_workflow_events(request)
                .await?
                .into_inner();
            Ok(Box::pin(events) as EventStream)
        })
    }
}

/// The connection attempt [`open_with`] already made, handed to [`run`] so
/// that one call to `open` never registers two subscriptions.
enum First<S> {
    /// Nothing to take over: the loop opens its own.
    None,
    /// Answered before [`OPEN_TIMEOUT`] was up, and open.
    Open(S),
    /// Still unanswered when [`OPEN_TIMEOUT`] was up. Awaiting the handle is
    /// what takes it over; aborting it is what closes it.
    Connecting(tokio::task::JoinHandle<std::result::Result<S, Status>>),
}

/// Holds one subscription open, reopening it for as long as the engine keeps
/// dropping it, until the engine hangs up, the consumer goes away, or a
/// failure that reconnecting cannot fix.
///
/// `first` is the attempt [`open`] already made — open, or still being
/// answered — so a subscription the engine has already registered is used
/// rather than opened a second time.
async fn run<C, Fut, S, B>(
    mut connect: C,
    first: First<S>,
    chunks: mpsc::Sender<Result<StreamChunk>>,
    cancel: CancellationToken,
    mut backoff: B,
) where
    C: FnMut() -> Fut,
    Fut: Future<Output = std::result::Result<S, Status>>,
    S: Stream<Item = std::result::Result<WorkflowEvent, Status>> + Unpin,
    B: FnMut(u32) -> Duration,
{
    // The backoff exponent and the run of failures that count towards giving
    // up. Both are reset by a single delivered chunk: a stream that delivered
    // output was healthy, whatever it did afterwards.
    let mut attempt: u32 = 0;
    let mut consecutive_other: u32 = 0;
    let mut first = first;
    // Kept across reconnects: a new subscription may replay chunks the old one
    // delivered, and this is what remembers them.
    let mut ordering = Reorder::default();

    loop {
        let connected = match std::mem::replace(&mut first, First::None) {
            First::Open(stream) => Ok(stream),
            // Aborted rather than dropped when the consumer goes away:
            // dropping a `JoinHandle` detaches the task, which would leave the
            // subscribe call running with nobody to read it.
            First::Connecting(mut connecting) => tokio::select! {
                () = cancel.cancelled() => {
                    connecting.abort();
                    return;
                }
                joined = &mut connecting => match joined {
                    Ok(connected) => connected,
                    Err(_) => Err(Status::internal("the subscribe call panicked")),
                },
            },
            First::None => {
                tokio::select! {
                    () = cancel.cancelled() => return,
                    connected = connect() => connected,
                }
            }
        };
        let outcome = match connected {
            Ok(events) => serve(events, &chunks, &cancel, &mut ordering).await,
            // No difference, for what happens next, between "the stream could
            // not be opened" and "it closed immediately".
            Err(status) => Outcome::Ended {
                status: Some(status),
                received: false,
            },
        };
        let (status, received) = match outcome {
            // The consumer dropped the stream, or the engine hung up: either
            // way this subscription is over for good.
            Outcome::Done => return,
            Outcome::Ended { status, received } => (status, received),
        };
        if received {
            attempt = 0;
            consecutive_other = 0;
        }

        let give_up = match classify_stream_end(status.as_ref()) {
            // `Cancelled` is a clean stop for the worker's listener, which
            // shares `classify_stream_end`; here a cancelled subscription the
            // consumer still holds is just one more stream to reopen.
            StreamErrorClass::StopClean => false,
            // `Internal` is transient in general — a restarting engine sends
            // it — but it is also what a chunk the engine cannot marshal ends
            // *every* subscription with (a non-UTF-8 `put_stream` payload;
            // see `Context::put_stream`), and that one does not heal: the
            // chunk is replayed to the next subscription and breaks it the
            // same way. Counting it here, and only when the connection
            // delivered nothing, keeps a restarting engine reconnecting for
            // as long as it takes while a poisoned stream still reaches the
            // consumer as an error instead of silence. The classification
            // table stays as it is: the other two streams in this SDK have
            // their own give-up rules.
            StreamErrorClass::Transient
                if status.as_ref().map(Status::code) == Some(Code::Internal) =>
            {
                consecutive_other += 1;
                consecutive_other >= STREAM_MAX_CONSECUTIVE_OTHER_FAILURES
            }
            StreamErrorClass::Transient => false,
            StreamErrorClass::Fatal => true,
            StreamErrorClass::Other => {
                consecutive_other += 1;
                consecutive_other >= STREAM_MAX_CONSECUTIVE_OTHER_FAILURES
            }
        };
        if give_up {
            // What was held goes out first: giving up is no reason to throw
            // away chunks that did arrive.
            let mut held = Vec::new();
            ordering.flush(&mut held);
            for item in held {
                if chunks.send(item).await.is_err() {
                    return;
                }
            }
            let status = status.unwrap_or_else(|| Status::unknown("the output stream ended"));
            tracing::warn!(
                code = ?status.code(),
                message = status.message(),
                consecutive_other,
                "giving up on a run's output stream",
            );
            // The last thing the consumer is told, so the failure is not
            // indistinguishable from a run that produced nothing.
            let _ = chunks
                .send(Err(Error::ResultStream(Box::new(status))))
                .await;
            return;
        }

        let delay = backoff(attempt);
        attempt = attempt.saturating_add(1);
        log_reconnect(attempt, consecutive_other, delay, status.as_ref());
        tokio::select! {
            () = cancel.cancelled() => return,
            () = tokio::time::sleep(delay) => {}
        }
    }
}

/// How one connection ended.
enum Outcome {
    /// Nothing more will be delivered: the engine hung up, or the consumer
    /// went away.
    Done,
    /// The stream ended; `status` is `None` when it ended cleanly.
    Ended {
        status: Option<Status>,
        /// Whether this connection delivered at least one chunk.
        received: bool,
    },
}

/// Hands every chunk on `events` to the consumer until the stream ends, the
/// engine hangs up, or the consumer goes away.
async fn serve<S>(
    mut events: S,
    chunks: &mpsc::Sender<Result<StreamChunk>>,
    cancel: &CancellationToken,
    ordering: &mut Reorder,
) -> Outcome
where
    S: Stream<Item = std::result::Result<WorkflowEvent, Status>> + Unpin,
{
    use tokio_stream::StreamExt;

    let mut received = false;
    // Reused rather than allocated per event: the ordinary chunk releases
    // exactly one item.
    let mut ready: Vec<Result<StreamChunk>> = Vec::new();
    loop {
        let item = tokio::select! {
            () = cancel.cancelled() => return Outcome::Done,
            item = events.next() => item,
        };
        match item {
            Some(Ok(event)) => {
                // The hang-up flag is read before the event is consumed, and
                // acted on after it is delivered: the engine is allowed to put
                // it on a chunk, and dropping that chunk would lose the last
                // thing the run said.
                let hangup = event.hangup;
                ready.clear();
                if let Some(chunk) = chunk_of(event) {
                    ordering.accept(chunk, &mut ready);
                }
                if hangup {
                    // Everything held goes out before the stream ends — the
                    // hang-up is the last chance to release it.
                    ordering.flush(&mut ready);
                }
                for item in ready.drain(..) {
                    // What resets the backoff is a chunk *delivered*; a
                    // reported gap is not evidence that the stream is healthy.
                    received |= item.is_ok();
                    if chunks.send(item).await.is_err() {
                        return Outcome::Done;
                    }
                }
                if hangup {
                    tracing::debug!("the engine hung up on a run's output stream");
                    return Outcome::Done;
                }
            }
            Some(Err(status)) => {
                return Outcome::Ended {
                    status: Some(status),
                    received,
                };
            }
            None => {
                return Outcome::Ended {
                    status: None,
                    received,
                };
            }
        }
    }
}

/// The chunk in `event`, or `None` for an event that is not one.
///
/// The filter is the event *type* alone, as the official Go SDK's is
/// (`pkg/client/listener.go:422`): the same subscription carries a run's
/// lifecycle events (STARTED, COMPLETED, …) and this is what tells them apart.
/// `resource_type` is deliberately not looked at — the engine decides what it
/// puts there, and a second condition could only ever make chunks disappear.
fn chunk_of(event: WorkflowEvent) -> Option<StreamChunk> {
    if event.event_type != ResourceEventType::Stream as i32 {
        return None;
    }
    Some(StreamChunk {
        run_id: event.workflow_run_id,
        task_run_id: event.resource_id,
        index: event.event_index,
        payload: event.event_payload,
    })
}

/// How many chunks of one task run are held back while an earlier one is
/// missing.
///
/// Measured rather than guessed: against both supported engines, a task run's
/// chunks arrived in index order every time, with no duplicates, including a
/// hundred pushed back to back. Holding chunks costs latency and memory, so
/// the buffer is only as deep as the engine was observed to need — and the gap
/// report below is what makes a shallow buffer safe, because a hole is then
/// *said* rather than waited out.
const REORDER_BUFFER: usize = 1;

/// One task run's chunk sequence.
struct Sequence {
    /// The index to deliver next.
    next: i64,
    /// Chunks that arrived before their turn, by index.
    held: BTreeMap<i64, StreamChunk>,
}

/// Puts the chunks of one subscription back into `event_index` order, per task
/// run.
///
/// It lives across reconnects on purpose: a new subscription may replay chunks
/// this one has already delivered, and remembering where each task run got to
/// is what turns those into duplicates to drop rather than output to hand over
/// twice.
///
/// Three rules, and the reasons they are not the obvious ones:
///
/// * **The first index seen starts the sequence.** A subscription opened after
///   the run started has not "lost" the chunks before it — it was never there
///   for them — and reporting them as a gap would make the ordinary case look
///   broken.
/// * **An index at or below the last one delivered is dropped.** Handing a
///   consumer the same chunk twice is worse than telling it one is missing.
/// * **A hole is waited out only so far.** Past [`REORDER_BUFFER`] chunks
///   behind it, what was held is released in index order and every hole that
///   release steps over — there can be more than one — is reported as its own
///   [`Error::StreamGap`](crate::Error::StreamGap). Nothing waits for ever.
#[derive(Default)]
struct Reorder {
    tasks: HashMap<String, Sequence>,
}

impl Reorder {
    /// Takes one chunk and appends whatever is now ready, in order, to `out`.
    fn accept(&mut self, chunk: StreamChunk, out: &mut Vec<Result<StreamChunk>>) {
        let Some(index) = chunk.index else {
            // Nothing to order it by, and nothing it can be ordered against:
            // an engine that does not fill `event_index` gets arrival order,
            // which is what it gave us.
            out.push(Ok(chunk));
            return;
        };
        let task_run_id = chunk.task_run_id.clone();
        let sequence = self.tasks.entry(task_run_id).or_insert(Sequence {
            next: index,
            held: BTreeMap::new(),
        });
        if index < sequence.next {
            tracing::debug!(
                task_run_id = %chunk.task_run_id,
                index,
                expected = sequence.next,
                "dropping a chunk of a run's output stream that was already delivered",
            );
            return;
        }
        if index == sequence.next {
            out.push(Ok(chunk));
            sequence.next += 1;
            // Whatever was waiting behind it can go now.
            while let Some(next) = sequence.held.remove(&sequence.next) {
                out.push(Ok(next));
                sequence.next += 1;
            }
            return;
        }
        let task_run_id = chunk.task_run_id.clone();
        sequence.held.insert(index, chunk);
        if sequence.held.len() > REORDER_BUFFER {
            release(&task_run_id, sequence, out);
        }
    }

    /// Appends everything still held, in index order, to `out` — what the end
    /// of a subscription releases.
    fn flush(&mut self, out: &mut Vec<Result<StreamChunk>>) {
        for (task_run_id, sequence) in &mut self.tasks {
            release(task_run_id, sequence, out);
        }
    }
}

/// Releases everything `sequence` holds, in index order, reporting every hole
/// it steps over.
///
/// One report per hole rather than one per batch: a batch can have more than
/// one, and a second hole passed over in silence is exactly the loss
/// [`Error::StreamGap`](crate::Error::StreamGap) exists to prevent.
fn release(task_run_id: &str, sequence: &mut Sequence, out: &mut Vec<Result<StreamChunk>>) {
    // `BTreeMap` iterates in key order, which is index order.
    for (index, chunk) in std::mem::take(&mut sequence.held) {
        if index > sequence.next {
            tracing::warn!(
                task_run_id,
                expected = sequence.next,
                got = index,
                "a run's output stream skipped chunks",
            );
            out.push(Err(Error::StreamGap {
                task_run_id: task_run_id.to_string(),
                expected: sequence.next,
                got: index,
            }));
        }
        sequence.next = index + 1;
        out.push(Ok(chunk));
    }
}

/// Reconnecting is normal, so only the first attempt and every fifth one are
/// worth a warning; the rest would drown a long outage in log lines.
fn log_reconnect(attempt: u32, consecutive_other: u32, delay: Duration, status: Option<&Status>) {
    let code = status.map(Status::code);
    let message = status.map(Status::message).unwrap_or_default();
    if attempt == 1 || attempt.is_multiple_of(5) {
        tracing::warn!(
            attempt,
            consecutive_other,
            ?delay,
            ?code,
            message,
            "reconnecting to a run's output stream",
        );
    } else {
        tracing::debug!(
            attempt,
            consecutive_other,
            ?delay,
            ?code,
            message,
            "reconnecting to a run's output stream",
        );
    }
}

#[cfg(test)]
mod tests {
    use std::collections::VecDeque;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};

    use tokio::sync::mpsc;
    use tokio::time::Instant;
    use tokio_stream::wrappers::ReceiverStream;

    use super::*;

    /// Nothing here may block for ever: a regression should fail the test
    /// rather than hang the suite. The clock is paused, so a wait that is
    /// going to be answered costs no real time.
    const NEVER: Duration = Duration::from_secs(10 * 60);

    type ScriptedStream = ReceiverStream<std::result::Result<WorkflowEvent, Status>>;
    type ScriptedSender = mpsc::Sender<std::result::Result<WorkflowEvent, Status>>;

    /// One scripted connection: a stream the test drives, or a failure to
    /// connect at all.
    enum Step {
        Stream(mpsc::Receiver<std::result::Result<WorkflowEvent, Status>>),
        Fail(Status),
    }

    /// A connection the test drives: the script's step, and the sender that
    /// feeds it. Dropping the sender ends that connection cleanly.
    fn connection() -> (ScriptedSender, Step) {
        let (tx, rx) = mpsc::channel(8);
        (tx, Step::Stream(rx))
    }

    /// A `connect` function driven by a script, which also records when each
    /// connection was opened. Once the script runs out it blocks for ever, so
    /// the loop sits waiting rather than spinning.
    #[derive(Clone)]
    struct Script {
        steps: Arc<Mutex<VecDeque<Step>>>,
        calls: Arc<AtomicUsize>,
        opened: mpsc::UnboundedSender<Instant>,
    }

    impl Script {
        fn new(steps: Vec<Step>) -> (Self, mpsc::UnboundedReceiver<Instant>) {
            let (opened, opens) = mpsc::unbounded_channel();
            (
                Self {
                    steps: Arc::new(Mutex::new(steps.into())),
                    calls: Arc::new(AtomicUsize::new(0)),
                    opened,
                },
                opens,
            )
        }

        async fn connect(self) -> std::result::Result<ScriptedStream, Status> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            let _ = self.opened.send(Instant::now());
            let step = self
                .steps
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .pop_front();
            match step {
                Some(Step::Stream(events)) => Ok(ReceiverStream::new(events)),
                Some(Step::Fail(status)) => Err(status),
                None => std::future::pending().await,
            }
        }

        fn calls(&self) -> usize {
            self.calls.load(Ordering::SeqCst)
        }
    }

    /// An output stream over `steps`, whose reconnect delay is
    /// `backoff(attempt)` instead of the policy's jittered one.
    async fn opened(
        steps: Vec<Step>,
        backoff: impl FnMut(u32) -> Duration + Send + 'static,
    ) -> (OutputStream, Script, mpsc::UnboundedReceiver<Instant>) {
        let (script, opens) = Script::new(steps);
        let stream = open_with(
            {
                let script = script.clone();
                move || script.clone().connect()
            },
            backoff,
        )
        .await
        .expect("a scripted first connection is never fatal");
        (stream, script, opens)
    }

    fn chunk(index: i64, payload: &str) -> WorkflowEvent {
        WorkflowEvent {
            workflow_run_id: "run-1".to_string(),
            resource_id: "task-1".to_string(),
            event_type: ResourceEventType::Stream as i32,
            event_payload: payload.to_string(),
            event_index: Some(index),
            ..WorkflowEvent::default()
        }
    }

    /// When the next connection was opened, or a failed test rather than a
    /// hung one.
    async fn next_open(opens: &mut mpsc::UnboundedReceiver<Instant>) -> Instant {
        tokio::time::timeout(NEVER, opens.recv())
            .await
            .expect("timed out waiting for a connection")
            .expect("the loop dropped the recording channel")
    }

    /// The next item, or a failed test rather than a hung one.
    async fn next_item(stream: &mut OutputStream) -> Option<Result<StreamChunk>> {
        tokio::time::timeout(NEVER, stream.next())
            .await
            .expect("timed out waiting for the stream")
    }

    /// The ordering state, and what one call to `accept` released.
    fn accepted(ordering: &mut Reorder, chunk: StreamChunk) -> Vec<Result<StreamChunk>> {
        let mut out = Vec::new();
        ordering.accept(chunk, &mut out);
        out
    }

    /// The payloads of the chunks in `items`, and a `"gap(expected..got)"`
    /// marker for each gap — so a test can assert on one flat sequence.
    fn shape(items: Vec<Result<StreamChunk>>) -> Vec<String> {
        items
            .into_iter()
            .map(|item| match item {
                Ok(chunk) => chunk.payload,
                Err(Error::StreamGap { expected, got, .. }) => format!("gap({expected}..{got})"),
                Err(other) => format!("error({other})"),
            })
            .collect()
    }

    fn numbered(task: &str, index: i64) -> StreamChunk {
        StreamChunk {
            run_id: "run-1".to_string(),
            task_run_id: task.to_string(),
            index: Some(index),
            payload: format!("chunk-{index}"),
        }
    }

    #[test]
    fn chunks_that_arrive_in_order_pass_straight_through() {
        let mut ordering = Reorder::default();
        for n in 0..3 {
            assert_eq!(
                shape(accepted(&mut ordering, numbered("task-1", n))),
                [format!("chunk-{n}")],
            );
        }
    }

    /// Criterion 2, without a socket: 2, 0, 1 comes out 0, 1, 2.
    #[test]
    fn an_early_chunk_waits_for_the_ones_before_it() {
        let mut ordering = Reorder::default();
        // The first index seen is where the sequence starts, so this test
        // begins at 0 on purpose: 2 arriving first would simply *be* the start
        // (see `a_late_subscription_starts_where_it_joined`).
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-1", 0))),
            ["chunk-0"],
        );
        assert!(shape(accepted(&mut ordering, numbered("task-1", 2))).is_empty());
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-1", 1))),
            ["chunk-1", "chunk-2"],
        );
    }

    /// Criterion 3: a chunk that never comes does not block the stream for
    /// ever. Once more than `REORDER_BUFFER` chunks are waiting behind the
    /// hole, the hole is reported and what was held is released in order.
    #[test]
    fn a_hole_is_reported_once_the_buffer_is_over_full_and_the_rest_follows() {
        let mut ordering = Reorder::default();
        accepted(&mut ordering, numbered("task-1", 0));
        // Index 1 never arrives. Everything after it waits…
        let mut released = Vec::new();
        for n in 2..=(2 + REORDER_BUFFER as i64) {
            released.extend(shape(accepted(&mut ordering, numbered("task-1", n))));
        }
        // …until the buffer is over full, and then the gap is reported once
        // and the held chunks follow it in index order.
        let expected: Vec<String> = std::iter::once("gap(1..2)".to_string())
            .chain((2..=(2 + REORDER_BUFFER as i64)).map(|n| format!("chunk-{n}")))
            .collect();
        assert_eq!(released, expected);
        // And the sequence carries on from where the engine is.
        assert_eq!(
            shape(accepted(
                &mut ordering,
                numbered("task-1", 3 + REORDER_BUFFER as i64),
            )),
            [format!("chunk-{}", 3 + REORDER_BUFFER as i64)],
        );
    }

    /// Two holes in one batch are two reports: the consumer is told about
    /// every stretch that is missing, not only the first one. With
    /// `REORDER_BUFFER = 1` the release happens with two chunks held, so
    /// `{3, 7}` behind `next = 1` is exactly the case that reaches it.
    #[test]
    fn every_hole_in_a_released_batch_is_reported() {
        let mut ordering = Reorder::default();
        // The sequence starts at 0, so 1 is what is expected next.
        accepted(&mut ordering, numbered("task-1", 0));
        assert!(shape(accepted(&mut ordering, numbered("task-1", 3))).is_empty());
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-1", 7))),
            ["gap(1..3)", "chunk-3", "gap(4..7)", "chunk-7"],
        );
        // And the sequence carries on from the last index released.
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-1", 8))),
            ["chunk-8"],
        );
    }

    /// A chunk that was already delivered is dropped rather than handed over
    /// twice — reconnecting can replay, and a duplicate is worse for a
    /// consumer than a reported gap.
    #[test]
    fn a_chunk_that_was_already_delivered_is_dropped() {
        let mut ordering = Reorder::default();
        accepted(&mut ordering, numbered("task-1", 0));
        accepted(&mut ordering, numbered("task-1", 1));
        assert!(shape(accepted(&mut ordering, numbered("task-1", 0))).is_empty());
        assert!(shape(accepted(&mut ordering, numbered("task-1", 1))).is_empty());
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-1", 2))),
            ["chunk-2"],
        );
    }

    /// Indexes are per task run, so two tasks streaming at once do not hold
    /// each other up.
    #[test]
    fn each_task_run_has_its_own_sequence() {
        let mut ordering = Reorder::default();
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-1", 0))),
            ["chunk-0"],
        );
        // Task two's 0 is not task one's 1, and does not wait for anything.
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-2", 0))),
            ["chunk-0"],
        );
        assert!(shape(accepted(&mut ordering, numbered("task-1", 2))).is_empty());
        // Task two is unaffected by task one's hole.
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-2", 1))),
            ["chunk-1"],
        );
    }

    /// An engine that does not fill `event_index` still delivers: those chunks
    /// go straight through, and they neither wait for nor disturb a sequence.
    #[test]
    fn a_chunk_without_an_index_goes_straight_through() {
        let mut ordering = Reorder::default();
        accepted(&mut ordering, numbered("task-1", 0));
        assert!(shape(accepted(&mut ordering, numbered("task-1", 2))).is_empty());
        let unnumbered = StreamChunk {
            index: None,
            payload: "no index".to_string(),
            ..numbered("task-1", 0)
        };
        assert_eq!(shape(accepted(&mut ordering, unnumbered)), ["no index"]);
        // The held chunk is still held, and 1 still completes it.
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-1", 1))),
            ["chunk-1", "chunk-2"],
        );
    }

    /// A subscription opened after the run started joins at whatever index it
    /// first sees. Reporting everything before that as a gap would make the
    /// ordinary case — subscribe after trigger — look broken.
    #[test]
    fn a_late_subscription_starts_where_it_joined() {
        let mut ordering = Reorder::default();
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-1", 40))),
            ["chunk-40"],
        );
        assert_eq!(
            shape(accepted(&mut ordering, numbered("task-1", 41))),
            ["chunk-41"],
        );
    }

    /// The end of the stream releases what is still held, gap and all: chunks
    /// that did arrive are not thrown away because one did not.
    #[test]
    fn flushing_releases_what_is_held_and_reports_the_hole() {
        let mut ordering = Reorder::default();
        accepted(&mut ordering, numbered("task-1", 0));
        accepted(&mut ordering, numbered("task-1", 2));
        let mut out = Vec::new();
        ordering.flush(&mut out);
        assert_eq!(shape(out), ["gap(1..2)", "chunk-2"]);
        // Flushing twice releases nothing more.
        let mut out = Vec::new();
        ordering.flush(&mut out);
        assert!(out.is_empty());
    }

    /// Under full jitter the real delay may be any length including zero, so
    /// only a fixed backoff can tell a reconnect delay that is there from one
    /// that was deleted.
    #[tokio::test(start_paused = true)]
    async fn a_reconnect_waits_for_the_backoff() {
        let (first, one) = connection();
        let (second, two) = connection();
        let (mut chunks, _script, mut opens) =
            opened(vec![one, two], |_| Duration::from_secs(7)).await;
        let opened_at = next_open(&mut opens).await;

        // A clean end of stream: worth reconnecting, after the backoff.
        drop(first);

        let reopened_at = next_open(&mut opens).await;
        assert!(
            reopened_at.duration_since(opened_at) >= Duration::from_secs(7),
            "reconnected after {:?}",
            reopened_at.duration_since(opened_at),
        );
        second
            .send(Ok(chunk(0, "after")))
            .await
            .expect("the second connection is open");
        let chunk = next_item(&mut chunks)
            .await
            .expect("a chunk")
            .expect("not an error");
        assert_eq!(chunk.payload, "after");
    }

    /// Ten unclassified failures in a row is the SDK's give-up rule
    /// (`STREAM_MAX_CONSECUTIVE_OTHER_FAILURES`), and giving up is told to the
    /// consumer rather than looking like a run with no output.
    #[tokio::test(start_paused = true)]
    async fn ten_unclassified_failures_in_a_row_give_up() {
        let (first, one) = connection();
        let mut steps = vec![one];
        steps.extend((0..10).map(|_| Step::Fail(Status::unknown("what?"))));
        let (mut chunks, script, _opens) = opened(steps, |_| Duration::ZERO).await;

        // A clean end is transient, so it does not count towards the ten.
        drop(first);

        let error = next_item(&mut chunks)
            .await
            .expect("the give-up is the last item")
            .expect_err("giving up is an error");
        assert!(matches!(error, Error::ResultStream(_)), "{error:?}");
        assert!(next_item(&mut chunks).await.is_none(), "and then it ends");
        assert_eq!(script.calls(), 11, "one good connection and ten failures");
    }

    /// A connection that delivered a chunk was healthy, whatever it did
    /// afterwards: the give-up counter starts again from it.
    #[tokio::test(start_paused = true)]
    async fn a_delivered_chunk_resets_the_give_up_counter() {
        let (first, one) = connection();
        let (middle, two) = connection();
        let (last, three) = connection();
        let mut steps = vec![one];
        steps.extend((0..9).map(|_| Step::Fail(Status::unknown("what?"))));
        steps.push(two);
        steps.extend((0..9).map(|_| Step::Fail(Status::unknown("what?"))));
        steps.push(three);
        let (mut chunks, script, _opens) = opened(steps, |_| Duration::ZERO).await;

        drop(first);
        middle
            .send(Ok(chunk(0, "healthy")))
            .await
            .expect("the middle connection is open");
        assert_eq!(
            next_item(&mut chunks)
                .await
                .expect("a chunk")
                .expect("not an error")
                .payload,
            "healthy",
        );
        drop(middle);

        // Nine more failures after that: still under the limit, so the stream
        // is alive and the last connection delivers.
        last.send(Ok(chunk(1, "still here")))
            .await
            .expect("the last connection is open");
        assert_eq!(
            next_item(&mut chunks)
                .await
                .expect("a chunk")
                .expect("not an error")
                .payload,
            "still here",
        );
        assert_eq!(script.calls(), 21);
    }
}