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
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
//! Triggering runs and waiting for their results.
//!
//! Triggering comes first and subscribing second, on purpose: the engine
//! answers a subscription for a run that has already finished straight away,
//! so there is no window to lose a result in — whereas subscribing to a run id
//! that does not exist yet is not possible at all. The official SDKs order it
//! the same way.

use std::fmt;
use std::marker::PhantomData;

use hatchet_proto::root::{StepRunResult, WorkflowRunEvent};
use serde::Serialize;
use serde::de::DeserializeOwned;
use tracing::{Instrument, Span};

use crate::error::{Error, Result, TaskFailure};
use crate::{Client, RunOpts, Task, Workflow, otel, retry, trigger};

pub(crate) mod bulk;
pub(crate) mod client;
pub(crate) mod details;
pub(crate) mod filter;
pub(crate) mod listener;
pub(crate) mod stream;

pub use client::RunsClient;
pub use details::{RunDetails, TaskRunDetail};
pub use filter::{RunStatus, TasksFilter};
pub use stream::{OutputStream, StreamChunk};

impl<I, O> Task<I, O> {
    /// Triggers a run of this task and hands back a handle to it, without
    /// waiting for it to finish.
    ///
    /// What is triggered is the workflow named after the task, which is the
    /// right thing for a task registered on its own — a standalone task *is* a
    /// one-task workflow of the same name. A task declared inside a
    /// [`Workflow`] is not addressable by itself; trigger its workflow with
    /// [`Workflow::run_no_wait`] instead.
    ///
    /// Nothing here checks that the engine is a version this SDK supports; a
    /// client that only triggers runs makes no other call. Call
    /// [`Client::check_engine_version`] once at startup if you want that
    /// checked.
    ///
    /// # Retries
    ///
    /// A `TriggerWorkflow` call the engine received but could not answer in
    /// time is sent again under the SDK's retry policy, so a run can be
    /// started twice — the handle then names only the second one. This is the
    /// same exposure as the official Go SDK. A top-level run has no
    /// deduplication key to hand the engine (the engine's own is for child
    /// runs, see [`RunOpts::child_key`](crate::RunOpts::child_key)), so a task
    /// that must not happen twice needs [`Workflow::idempotency`].
    ///
    /// # Errors
    ///
    /// [`Error::Json`] when `input` or a metadata value cannot be
    /// serialized; [`Error::IdempotencyCollision`] when the workflow
    /// declares [`idempotency`](crate::Workflow::idempotency) and the
    /// computed key is already claimed by another run;
    /// [`Error::InvalidArgument`] when `opts` asks for
    /// [`RunOpts::sticky`](crate::RunOpts::sticky) outside a task handler
    /// (there is no parent run to inherit a worker from); and
    /// [`Error::Grpc`] when the call fails for any other reason.
    pub async fn run_no_wait(
        &self,
        client: &Client,
        input: &I,
        opts: RunOpts,
    ) -> Result<RunHandle<O>>
    where
        I: Serialize,
    {
        let span = otel::run_workflow(self.name());
        let run_id = trigger(client, self.name(), input, &opts, &span)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &run_id);
        Ok(self.handle(client, run_id?))
    }

    /// Triggers a run of this task and waits for its output.
    ///
    /// Equivalent to [`run_no_wait`](Task::run_no_wait) followed by
    /// [`RunHandle::result`], and waits just as long: for ever, if the run
    /// never finishes. Wrap the call in [`tokio::time::timeout`] if that is
    /// not acceptable.
    ///
    /// ```no_run
    /// # use hatchet_client::{Client, RunOpts, TaskBuilder};
    /// # use serde::{Deserialize, Serialize};
    /// # #[derive(Deserialize, Serialize)]
    /// # struct Review { repo: String }
    /// # #[derive(Deserialize, Serialize)]
    /// # struct Verdict { approved: bool }
    /// # async fn example(client: &Client) -> hatchet_client::Result<()> {
    /// // The same declaration the worker registers; triggering only needs
    /// // its name and its types.
    /// let review = TaskBuilder::<Review, Verdict>::new("review")
    ///     .handler(|_ctx, input: Review| async move {
    ///         Ok(Verdict { approved: input.repo == "hatchet-rs" })
    ///     });
    ///
    /// let verdict = review
    ///     .run(
    ///         client,
    ///         &Review { repo: "hatchet-rs".to_string() },
    ///         RunOpts::default().metadata("customer", "acme"),
    ///     )
    ///     .await?;
    /// println!("approved: {}", verdict.approved);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Those of [`run_no_wait`](Task::run_no_wait), plus those of
    /// [`RunHandle::result`].
    pub async fn run(&self, client: &Client, input: &I, opts: RunOpts) -> Result<O>
    where
        I: Serialize,
        O: DeserializeOwned,
    {
        // One span from the trigger to the result, the way the official Go
        // SDK's `Run` holds its `hatchet.run_workflow` open while it waits
        // (`sdks/go/workflow.go:932-963`).
        let span = otel::run_workflow(self.name());
        let output = async {
            let run_id = trigger(client, self.name(), input, &opts, &span).await?;
            self.handle(client, run_id).result().await
        }
        .instrument(span.clone())
        .await;
        otel::record_result(&span, &output);
        output
    }

    /// Triggers a run of this task for every `(input, opts)` pair, in as few
    /// `BulkTriggerWorkflow` calls as the engine's own limits allow (1000
    /// requests or 3 MiB of encoded requests per call, whichever comes
    /// first), and hands back handles in the same order as `inputs`.
    ///
    /// What is triggered is the workflow named after the task, exactly as in
    /// [`run_no_wait`](Task::run_no_wait): right for a standalone task, and
    /// not possible for a task declared inside a [`Workflow`], which is not
    /// addressable on its own — use [`Workflow::run_many`] for those.
    ///
    /// Every request is built and serialized *before* the first call goes
    /// out, so a bad input aborts the whole batch rather than starting some
    /// runs and then failing on a later one. An empty `inputs` makes no call
    /// at all.
    ///
    /// One [`RunOpts`] for the whole batch is a `map` over the inputs, since
    /// the pairs are what this takes:
    ///
    /// ```no_run
    /// # use hatchet_client::{Client, RunOpts, TaskBuilder};
    /// # async fn example(client: &Client, inputs: Vec<u32>) -> hatchet_client::Result<()> {
    /// # let task = TaskBuilder::<u32, u32>::new("double")
    /// #     .handler(|_ctx, input: u32| async move { Ok(input * 2) });
    /// let opts = RunOpts::default().metadata("batch", "nightly");
    /// let handles = task
    ///     .run_many(client, inputs.into_iter().map(|input| (input, opts.clone())))
    ///     .await?;
    /// # let _ = handles;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Retries
    ///
    /// A `BulkTriggerWorkflow` call the engine received but could not answer
    /// in time is sent again under the SDK's retry policy, so a chunk of up to
    /// 1000 runs can be started twice — the handles then name only the second
    /// set. This is the same exposure as the official Go SDK; tasks that must
    /// not happen twice need [`Workflow::idempotency`].
    ///
    /// # Errors
    ///
    /// [`Error::Json`] when an input or a metadata value cannot be
    /// serialized (before anything is sent); [`Error::InvalidArgument`] when
    /// any pair's `opts` asks for [`RunOpts::sticky`](crate::RunOpts::sticky)
    /// (there is no parent run at this level to inherit a worker from), also
    /// checked before anything is sent; [`Error::Grpc`] or
    /// [`Error::IdempotencyCollision`]/[`Error::BulkIdempotencyCollision`]
    /// when the first chunk fails outright; and [`Error::PartialBulkTrigger`]
    /// when a later chunk fails (for any of those same reasons) after
    /// earlier ones already started runs — its `run_ids` are the runs that
    /// really were started, so they are not lost.
    pub async fn run_many(
        &self,
        client: &Client,
        inputs: impl IntoIterator<Item = (I, RunOpts)>,
    ) -> Result<Vec<RunHandle<O>>>
    where
        I: Serialize,
    {
        let inputs: Vec<(I, RunOpts)> = inputs.into_iter().collect();
        let span = otel::run_workflows(self.name(), inputs.len());
        let run_ids = trigger_all(client, self.name(), &inputs, &span)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &run_ids);
        Ok(run_ids?
            .into_iter()
            .map(|run_id| self.handle(client, run_id))
            .collect())
    }

    /// A handle on this task's run `run_id`.
    fn handle(&self, client: &Client, run_id: String) -> RunHandle<O> {
        RunHandle {
            run_id,
            task_name: self.name().to_string(),
            client: client.clone(),
            _output: PhantomData,
        }
    }
}

impl Workflow {
    /// Triggers a run of this workflow and hands back a handle to it, without
    /// waiting for it to finish. The input is the workflow's own, which every
    /// task in it receives.
    ///
    /// # Errors
    ///
    /// The same as [`Task::run_no_wait`].
    pub async fn run_no_wait<I: Serialize>(
        &self,
        client: &Client,
        input: &I,
        opts: RunOpts,
    ) -> Result<WorkflowRunHandle> {
        let span = otel::run_workflow(self.name());
        let run_id = trigger(client, self.name(), input, &opts, &span)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &run_id);
        Ok(self.handle(client, run_id?))
    }

    /// Triggers a run of this workflow and waits for every task in it to
    /// finish.
    ///
    /// Waits without a time limit, exactly like [`Task::run`].
    ///
    /// # Errors
    ///
    /// Those of [`run_no_wait`](Workflow::run_no_wait), plus those of
    /// [`WorkflowRunHandle::result`].
    pub async fn run<I: Serialize>(
        &self,
        client: &Client,
        input: &I,
        opts: RunOpts,
    ) -> Result<WorkflowResult> {
        // One span from the trigger to the result, as in `Task::run`.
        let span = otel::run_workflow(self.name());
        let result = async {
            let run_id = trigger(client, self.name(), input, &opts, &span).await?;
            self.handle(client, run_id).result().await
        }
        .instrument(span.clone())
        .await;
        otel::record_result(&span, &result);
        result
    }

    /// Triggers a run of this workflow for every `(input, opts)` pair, the
    /// same way as [`Task::run_many`], and hands back handles in the same
    /// order as `inputs`.
    ///
    /// This is also the way to start many runs of a task that is *declared
    /// inside* a workflow: such a task is not addressable on its own, so it is
    /// its workflow that is triggered, with the workflow's own input.
    ///
    /// One [`RunOpts`] for the whole batch is a `map` over the inputs —
    /// `inputs.into_iter().map(|input| (input, opts.clone()))` — as shown on
    /// [`Task::run_many`].
    ///
    /// # Retries
    ///
    /// The same as [`Task::run_many`]: a chunk the engine received but could
    /// not answer in time is re-sent, so up to 1000 runs may be started twice.
    ///
    /// # Errors
    ///
    /// The same as [`Task::run_many`].
    pub async fn run_many<I: Serialize>(
        &self,
        client: &Client,
        inputs: impl IntoIterator<Item = (I, RunOpts)>,
    ) -> Result<Vec<WorkflowRunHandle>> {
        let inputs: Vec<(I, RunOpts)> = inputs.into_iter().collect();
        let span = otel::run_workflows(self.name(), inputs.len());
        let run_ids = trigger_all(client, self.name(), &inputs, &span)
            .instrument(span.clone())
            .await;
        otel::record_result(&span, &run_ids);
        Ok(run_ids?
            .into_iter()
            .map(|run_id| self.handle(client, run_id))
            .collect())
    }

    /// A handle on this workflow's run `run_id`.
    fn handle(&self, client: &Client, run_id: String) -> WorkflowRunHandle {
        WorkflowRunHandle {
            run_id,
            client: client.clone(),
        }
    }
}

/// A started run of a single task, and its output type.
///
/// Holding one does not hold a subscription open: the stream is opened when
/// [`result`](RunHandle::result) is awaited, and closed again once nothing is
/// waiting for anything.
///
/// It does keep a clone of the [`Client`] it was started from, which is what
/// lets it wait ([`result`](RunHandle::result)) and cancel
/// ([`cancel`](RunHandle::cancel)) on its own. A `Client` is one `Arc`, so
/// that costs a reference — and it means a handle stays usable after the
/// client it came from goes out of scope. There is no reference cycle: the
/// client's result listener never holds a `Client` (see `client.rs`).
#[must_use = "a run handle waits for nothing until `result` is awaited"]
pub struct RunHandle<O> {
    run_id: String,
    task_name: String,
    client: Client,
    _output: PhantomData<fn() -> O>,
}

/// Cloning a handle costs two strings and a reference; both clones wait on the
/// same run.
impl<O> Clone for RunHandle<O> {
    fn clone(&self) -> Self {
        Self {
            run_id: self.run_id.clone(),
            task_name: self.task_name.clone(),
            client: self.client.clone(),
            _output: PhantomData,
        }
    }
}

impl<O> fmt::Debug for RunHandle<O> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RunHandle")
            .field("run_id", &self.run_id)
            .field("task", &self.task_name)
            .finish_non_exhaustive()
    }
}

impl<O> RunHandle<O> {
    /// The engine's id for this run. Runs are addressed by it in the
    /// dashboard and in the REST API.
    pub fn id(&self) -> &str {
        &self.run_id
    }

    /// Stops this run.
    ///
    /// One `CancelTasks` call naming this run. Measured on both supported
    /// engine versions: a workflow run id cancels every task of that run that
    /// exists when the call arrives — a task the engine has not created yet
    /// is *not* covered and will still run, so a run that fans out over time
    /// may need cancelling more than once.
    ///
    /// Cancelling a run that is already over is not an error, and neither is
    /// cancelling one the engine has never heard of: the engine answers both
    /// by echoing the id back. There is therefore nothing to check — the
    /// answer is not proof of effect — and this hands back nothing.
    ///
    /// The run's own handler sees the cancellation as
    /// [`Context::cancelled`](crate::Context::cancelled); a waiter on
    /// [`result`](RunHandle::result) sees [`Error::RunCancelled`].
    ///
    /// ```no_run
    /// # use hatchet_client::{Client, RunOpts, TaskBuilder};
    /// # async fn example(client: &Client) -> hatchet_client::Result<()> {
    /// # let task = TaskBuilder::<(), u32>::new("count")
    /// #     .handler(|_ctx, _input| async { Ok(1) });
    /// let run = task.run_no_wait(client, &(), RunOpts::default()).await?;
    /// run.cancel().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error::Grpc`] when the call fails.
    pub async fn cancel(&self) -> Result<()> {
        cancel_run(&self.client, &self.run_id).await
    }

    /// The output stream of this run: the chunks its handler publishes with
    /// [`Context::put_stream`](crate::Context::put_stream).
    ///
    /// Exactly [`RunsClient::stream`] for this run's id, which documents what
    /// a subscription opened after the trigger can miss, what ends the stream,
    /// and the five seconds this can spend waiting for the engine to answer
    /// before handing back a stream that is still being opened. Nothing can be
    /// subscribed to before the trigger, so a handler that starts publishing
    /// at once may be a chunk ahead of this; the race-free pattern is
    /// [`RunsClient::stream_by_metadata`], opened *before* the run is
    /// triggered.
    ///
    /// ```no_run
    /// # use hatchet_client::{Client, RunOpts, TaskBuilder};
    /// # async fn example(client: &Client) -> hatchet_client::Result<()> {
    /// # let task = TaskBuilder::<(), u32>::new("count")
    /// #     .handler(|_ctx, _input| async { Ok(1) });
    /// let run = task.run_no_wait(client, &(), RunOpts::default()).await?;
    /// let mut chunks = run.stream().await?;
    /// while let Some(chunk) = chunks.next().await {
    ///     println!("{}", chunk?.payload);
    /// }
    /// // The output is separate from the result: this still waits for it.
    /// let count = run.result().await?;
    /// # let _ = count;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Those of [`RunsClient::stream`].
    pub async fn stream(&self) -> Result<OutputStream> {
        self.client.runs().stream(&self.run_id).await
    }
}

impl<O: DeserializeOwned> RunHandle<O> {
    /// Waits for the run to finish and deserializes its output.
    ///
    /// **There is no time limit.** A run that never finishes is waited for for
    /// ever, which is what the official SDKs do; wrap the call in
    /// [`tokio::time::timeout`] if that is not what you want. The wait costs
    /// nothing while it lasts — every wait on one client shares a single
    /// subscription — and dropping the future stops waiting without affecting
    /// the run.
    ///
    /// Awaiting it more than once waits again, and a run that has already
    /// finished is answered straight away.
    ///
    /// The subscription is the client's, and a handle holds a clone of that
    /// client, so this goes on working after the `Client` the run was started
    /// from goes out of scope.
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # use hatchet_client::{Client, RunOpts, TaskBuilder};
    /// # async fn example(client: &Client) -> hatchet_client::Result<()> {
    /// # let task = TaskBuilder::<(), u32>::new("count")
    /// #     .handler(|_ctx, _input| async { Ok(1) });
    /// let run = task.run_no_wait(client, &(), RunOpts::default()).await?;
    /// println!("started {}", run.id());
    ///
    /// // An hour is this caller's own limit, not the SDK's.
    /// let count = tokio::time::timeout(Duration::from_secs(3600), run.result())
    ///     .await
    ///     .expect("the run took more than an hour")?;
    /// # let _ = count;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error::RunFailed`] when a task of the run reported an error,
    /// [`Error::RunCancelled`] when the run was cancelled before it finished
    /// — by [`cancel`](RunHandle::cancel), by
    /// [`RunsClient::cancel`], by a [`Concurrency`](crate::Concurrency) limit
    /// that cancels rather than queues, or from the dashboard —
    /// [`Error::RunOutput`] when the run produced no output for this task or
    /// its output is not an `O`, and [`Error::ResultStream`] when the
    /// subscription was given up on — the run itself is unaffected by that
    /// last one, and waiting again opens a new subscription.
    pub async fn result(&self) -> Result<O> {
        let event = self.client.run_listener().wait(self.run_id.clone()).await?;
        output_of(&event, &self.task_name)
    }
}

/// A started run of a whole workflow.
///
/// Its tasks have their own output types, so the result is handed back
/// untyped and each output is deserialized on the way out; see
/// [`WorkflowResult`].
///
/// Like [`RunHandle`], it holds a clone of the [`Client`] it was started
/// from, so it can wait and cancel after that client goes out of scope.
#[must_use = "a run handle waits for nothing until `result` is awaited"]
#[derive(Clone)]
pub struct WorkflowRunHandle {
    run_id: String,
    client: Client,
}

impl fmt::Debug for WorkflowRunHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WorkflowRunHandle")
            .field("run_id", &self.run_id)
            .finish_non_exhaustive()
    }
}

impl WorkflowRunHandle {
    /// The engine's id for this run.
    pub fn id(&self) -> &str {
        &self.run_id
    }

    /// Stops this run.
    ///
    /// Exactly [`RunHandle::cancel`], which documents what a run id does and
    /// does not reach.
    ///
    /// ```no_run
    /// # use hatchet_client::{Client, RunOpts, Workflow};
    /// # async fn example(client: &Client) -> hatchet_client::Result<()> {
    /// # let task = hatchet_client::TaskBuilder::<(), ()>::new("t")
    /// #     .handler(|_ctx, _input| async { Ok(()) });
    /// # let workflow = Workflow::new("pipeline").task(&task);
    /// let run = workflow.run_no_wait(client, &(), RunOpts::default()).await?;
    /// run.cancel().await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error::Grpc`] when the call fails.
    pub async fn cancel(&self) -> Result<()> {
        cancel_run(&self.client, &self.run_id).await
    }

    /// The output stream of this run: the chunks its tasks publish with
    /// [`Context::put_stream`](crate::Context::put_stream).
    ///
    /// Exactly [`RunsClient::stream`] for this run's id, which documents what
    /// a subscription opened after the trigger can miss, what ends the stream,
    /// and the five seconds this can spend waiting for the engine to answer
    /// before handing back a stream that is still being opened. The race-free
    /// pattern is [`RunsClient::stream_by_metadata`], opened *before* the run
    /// is triggered.
    ///
    /// A workflow run has one chunk sequence per task, so
    /// [`StreamChunk::task_run_id`](crate::StreamChunk::task_run_id) is what
    /// tells two tasks' outputs apart when they stream at once.
    ///
    /// ```no_run
    /// # use hatchet_client::{Client, RunOpts, TaskBuilder, Workflow};
    /// # async fn example(client: &Client) -> hatchet_client::Result<()> {
    /// # let emit = TaskBuilder::<(), ()>::new("emit")
    /// #     .handler(|_ctx, _input| async { Ok(()) });
    /// # let workflow = Workflow::new("pipeline").task(&emit);
    /// let run = workflow.run_no_wait(client, &(), RunOpts::default()).await?;
    /// let mut chunks = run.stream().await?;
    /// while let Some(chunk) = chunks.next().await {
    ///     let chunk = chunk?;
    ///     println!("{}: {}", chunk.task_run_id, chunk.payload);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Those of [`RunsClient::stream`].
    pub async fn stream(&self) -> Result<OutputStream> {
        self.client.runs().stream(&self.run_id).await
    }

    /// Waits for every task of the run to finish.
    ///
    /// Waits without a time limit, exactly like [`RunHandle::result`], and
    /// like it goes on working after the [`Client`] the run was started from
    /// goes out of scope.
    ///
    /// # Errors
    ///
    /// [`Error::RunFailed`] when any task of the run reported an error,
    /// [`Error::RunCancelled`] when the run was cancelled before it finished
    /// (the same sources as for [`RunHandle::result`]), and
    /// [`Error::ResultStream`] when the subscription was given up on. Reading
    /// an output is what can fail with [`Error::RunOutput`], and that happens
    /// in [`WorkflowResult::output`] rather than here.
    pub async fn result(&self) -> Result<WorkflowResult> {
        let event = self.client.run_listener().wait(self.run_id.clone()).await?;
        succeeded(&event)?;
        Ok(WorkflowResult {
            run_id: event.workflow_run_id,
            results: event.results,
        })
    }
}

/// What a finished workflow run produced: one output per task that ran.
#[derive(Clone, Debug)]
pub struct WorkflowResult {
    run_id: String,
    results: Vec<StepRunResult>,
}

impl WorkflowResult {
    /// The engine's id for the run these outputs came from.
    pub fn run_id(&self) -> &str {
        &self.run_id
    }

    /// The output of `task`, deserialized into the type it was declared with.
    ///
    /// # Errors
    ///
    /// [`Error::RunOutput`] when the run has no output under that task's name,
    /// or the output is not an `O`.
    pub fn output<PI, O: DeserializeOwned>(&self, task: &Task<PI, O>) -> Result<O> {
        self.output_by_name(task.name())
    }

    /// The output of the task called `name`, deserialized into `T`.
    ///
    /// The name is matched as declared first and without regard to case
    /// afterwards, because the engine knows a task by the lowercased name it
    /// was registered under.
    ///
    /// # Errors
    ///
    /// [`Error::RunOutput`] when the run has no output under that name, or
    /// the output is not a `T`.
    pub fn output_by_name<T: DeserializeOwned>(&self, name: &str) -> Result<T> {
        let result = named(&self.results, name).ok_or_else(|| Error::RunOutput {
            run_id: self.run_id.clone(),
            reason: format!(
                "the run produced no output for task {name:?}; it ran {}",
                listed(&self.results)
            ),
        })?;
        decode(&self.run_id, result)
    }

    /// Whether `task` was skipped by its
    /// [`skip_if`](crate::TaskBuilder::skip_if) conditions rather than run.
    ///
    /// A skipped task does not fail the run; it simply produced nothing, so
    /// [`output`](WorkflowResult::output) for it is an [`Error::RunOutput`]
    /// that says it was skipped.
    pub fn was_skipped<PI, O>(&self, task: &Task<PI, O>) -> bool {
        self.was_skipped_by_name(task.name())
    }

    /// Like [`WorkflowResult::was_skipped`], but by name — matched the same
    /// way [`output_by_name`](WorkflowResult::output_by_name) matches: as
    /// declared first, then without regard to case.
    pub fn was_skipped_by_name(&self, name: &str) -> bool {
        named(&self.results, name).is_some_and(was_skipped)
    }
}

/// The result `name` produced, matched as declared and then without regard to
/// case: the engine knows a task by the lowercased name it was registered
/// under.
fn named<'a>(results: &'a [StepRunResult], name: &str) -> Option<&'a StepRunResult> {
    results
        .iter()
        .find(|result| result.task_name == name)
        .or_else(|| {
            results
                .iter()
                .find(|result| result.task_name.eq_ignore_ascii_case(name))
        })
}

/// The task names a run produced results for, for an error message.
fn listed(results: &[StepRunResult]) -> String {
    if results.is_empty() {
        return "nothing".to_string();
    }
    results
        .iter()
        .map(|result| format!("{:?}", result.task_name))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Cancels the run called `run_id`, whatever kind of handle asked.
///
/// One call, and the answer is discarded: the engine echoes back the ids it
/// was given — a run that is already over, and even an id that names nothing
/// at all, come back as "cancelled" (measured on v0.107.0) — so there is
/// nothing in it a handle could report. Kept in one place so both handles
/// cancel the same way.
async fn cancel_run(client: &Client, run_id: &str) -> Result<()> {
    client.runs().cancel([run_id]).await?;
    Ok(())
}

/// Fails if any task of the run reported an error, and tells a cancellation
/// apart from a failure.
///
/// One failed task fails the whole run, whatever the others did: a workflow
/// whose last step could not run has not done what it was asked. A run with
/// both a real failure and a cancelled task is reported as the failure — the
/// cancellation is usually a consequence of it, and the failure is the part
/// someone has to fix.
fn succeeded(event: &WorkflowRunEvent) -> Result<()> {
    let mut errors: Vec<TaskFailure> = Vec::new();
    let mut cancelled: Vec<String> = Vec::new();
    for result in &event.results {
        match result.error.as_deref() {
            // A message the engine did fill in is a failure, whatever else
            // the row holds.
            Some(message) if !message.trim().is_empty() => errors.push(TaskFailure {
                task_name: result.task_name.clone(),
                message: message.to_string(),
            }),
            _ if cancelled_shape(result) => cancelled.push(result.task_name.clone()),
            // An empty error next to an output is neither: the engine fills
            // `error` in with the empty string on rows that succeeded too.
            _ => {}
        }
    }
    if !errors.is_empty() {
        return Err(Error::RunFailed {
            run_id: event.workflow_run_id.clone(),
            errors,
        });
    }
    if !cancelled.is_empty() {
        return Err(Error::RunCancelled {
            run_id: event.workflow_run_id.clone(),
            tasks: cancelled,
        });
    }
    Ok(())
}

/// Whether one result records a task the engine **cancelled** rather than one
/// that failed or succeeded.
///
/// The result stream gives nothing else to go on: `WorkflowRunEventType` has
/// a single value (`FINISHED` —
/// `api-contracts/dispatcher/dispatcher.proto:419-421`) and `StepRunResult`
/// carries no status (`:434-444`). What is left is the shape of the row, and
/// a cancelled task is recorded with an `error` the engine never filled in
/// *and* no output — measured on both supported engine versions, for an
/// explicit `CancelTasks` (by workflow run id and by task run id) and for a
/// concurrency limit that cancels rather than queues.
///
/// Both halves are needed. Cancelling by workflow run id adds a blank-error
/// row for a task that had already *succeeded*, next to that task's real
/// success row, so "the error is blank" alone would report a finished run as
/// cancelled; the success row carries its output, and the cancel row carries
/// none.
///
/// This SDK's own worker cannot produce this shape by failing: it sends a
/// failure message as a JSON string (`worker::events::failed`), so even an
/// empty one goes out as `"\"\""` — two characters, not none.
fn cancelled_shape(result: &StepRunResult) -> bool {
    result.output.is_none()
        && result
            .error
            .as_deref()
            .is_some_and(|message| message.trim().is_empty())
}

/// The output a single-task run produced, as `O`.
///
/// The result is the one recorded under the task's name; a run that reported
/// exactly one result reports it under whatever name the engine chose, so that
/// one is taken as well.
pub(crate) fn output_of<O: DeserializeOwned>(
    event: &WorkflowRunEvent,
    task_name: &str,
) -> Result<O> {
    succeeded(event)?;
    let lone = match event.results.as_slice() {
        [only] => Some(only),
        _ => None,
    };
    let result = named(&event.results, task_name)
        .or(lone)
        .ok_or_else(|| Error::RunOutput {
            run_id: event.workflow_run_id.clone(),
            reason: format!(
                "the run produced no output for task {task_name:?}; it ran {}",
                listed(&event.results)
            ),
        })?;
    decode(&event.workflow_run_id, result)
}

/// Whether one result records a task the engine skipped rather than ran: its
/// output is the engine's `{"skipped": true}` marker, the same marker a
/// child sees in its `parents` map (see `Context::was_skipped`).
fn was_skipped(result: &StepRunResult) -> bool {
    result.output.as_deref().is_some_and(|output| {
        serde_json::from_str::<serde_json::Value>(output)
            .ok()
            .and_then(|value| value.get("skipped").cloned())
            == Some(serde_json::Value::Bool(true))
    })
}

/// Reads one task's output as a `T`.
fn decode<T: DeserializeOwned>(run_id: &str, result: &StepRunResult) -> Result<T> {
    if was_skipped(result) {
        return Err(Error::RunOutput {
            run_id: run_id.to_string(),
            reason: format!(
                "task {:?} was skipped, so it produced no output",
                result.task_name
            ),
        });
    }
    // An output the engine did not record at all is not the same as a task
    // that returned `null`, and only the first is a mistake worth reporting.
    let output = result.output.as_deref().ok_or_else(|| Error::RunOutput {
        run_id: run_id.to_string(),
        reason: format!("task {:?} recorded no output", result.task_name),
    })?;
    serde_json::from_str(output).map_err(|error| Error::RunOutput {
        run_id: run_id.to_string(),
        reason: format!("task {:?}: {error}", result.task_name),
    })
}

/// Triggers a run of the workflow declared as `name`, with no parent, under
/// `span` — whose traceparent the request carries (with the `otel` feature)
/// and on which the run's id is recorded — and hands back its run id.
async fn trigger<I: Serialize>(
    client: &Client,
    name: &str,
    input: &I,
    opts: &RunOpts,
    span: &Span,
) -> Result<String> {
    let mut request = trigger::request(client.config().namespace(), name, input, opts, None)?;
    otel::inject(span, &mut request.additional_metadata);
    let response = retry::unary(|| {
        let mut workflows = client.workflows_grpc();
        let request = retry::timed(request.clone());
        async move { workflows.trigger_workflow(request).await }
    })
    .await
    .map_err(|status| crate::collision::from_trigger(Error::from(status)))?;
    let run_id = response.into_inner().workflow_run_id;
    span.record("hatchet.child_workflow_run_id", run_id.as_str());
    Ok(run_id)
}

/// Builds the request for every `(input, opts)` pair — each carrying
/// `span`'s traceparent, as Go's `RunMany` puts its one
/// `hatchet.run_workflows` span into every item (`sdks/go/workflow.go:1151`)
/// — and sends them in as few `BulkTriggerWorkflow` calls as the engine
/// allows. Every request is built before the first call.
async fn trigger_all<I: Serialize>(
    client: &Client,
    name: &str,
    inputs: &[(I, RunOpts)],
    span: &Span,
) -> Result<Vec<String>> {
    let requests = inputs
        .iter()
        .map(|(input, opts)| {
            let mut request =
                trigger::request(client.config().namespace(), name, input, opts, None)?;
            otel::inject(span, &mut request.additional_metadata);
            Ok(request)
        })
        .collect::<Result<Vec<_>>>()?;
    bulk::trigger_many(client, requests).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use hatchet_proto::root::WorkflowRunEventType;
    use serde::Deserialize;
    use serde_json::json;

    #[derive(Debug, Deserialize, PartialEq)]
    struct Out {
        pr: Option<String>,
    }

    fn result(task_name: &str, output: Option<&str>, error: Option<&str>) -> StepRunResult {
        StepRunResult {
            task_name: task_name.to_string(),
            output: output.map(str::to_string),
            error: error.map(str::to_string),
            ..StepRunResult::default()
        }
    }

    fn event(results: Vec<StepRunResult>) -> WorkflowRunEvent {
        WorkflowRunEvent {
            workflow_run_id: "run-1".to_string(),
            event_type: WorkflowRunEventType::Finished as i32,
            results,
            ..WorkflowRunEvent::default()
        }
    }

    #[test]
    fn the_output_of_the_named_task_is_the_one_that_is_read() {
        let event = event(vec![
            result("fetch", Some(r#"{"pr":"other"}"#), None),
            result("agent-run", Some(r#"{"pr":null}"#), None),
        ]);
        let out: Out = output_of(&event, "agent-run").unwrap();
        assert_eq!(out, Out { pr: None });
    }

    /// The engine knows a task by the lowercased name it was registered under,
    /// so a declaration that was not written in lower case still finds it.
    #[test]
    fn a_name_is_matched_without_regard_to_case() {
        let event = event(vec![result("agent-run", Some(r#"{"pr":null}"#), None)]);
        let out: Out = output_of(&event, "Agent-Run").unwrap();
        assert_eq!(out, Out { pr: None });
    }

    #[test]
    fn a_skipped_task_is_reported_as_skipped_rather_than_as_a_missing_output() {
        let event = event(vec![
            result("fetch", Some(r#"{"pr":"ok"}"#), None),
            result("maybe", Some(r#"{"skipped":true}"#), None),
        ]);
        let result = WorkflowResult {
            run_id: event.workflow_run_id.clone(),
            results: event.results.clone(),
        };

        assert!(result.was_skipped_by_name("maybe"));
        assert!(!result.was_skipped_by_name("fetch"));
        assert!(!result.was_skipped_by_name("never-ran"));

        let error = result.output_by_name::<Out>("maybe").unwrap_err();
        let Error::RunOutput { reason, .. } = &error else {
            panic!("expected RunOutput: {error:?}");
        };
        assert!(reason.contains("skipped"), "{reason}");

        // A skipped task is not a failed one.
        assert!(succeeded(&event).is_ok());
    }

    #[test]
    fn a_lone_result_is_the_output_whatever_it_is_called() {
        let event = event(vec![result("step-one", Some(r#"{"pr":"x"}"#), None)]);
        let out: Out = output_of(&event, "agent-run").unwrap();
        assert_eq!(
            out,
            Out {
                pr: Some("x".to_string())
            }
        );
    }

    #[test]
    fn a_result_that_is_neither_named_nor_alone_is_a_run_output_error() {
        let event = event(vec![
            result("fetch", Some("1"), None),
            result("report", Some("2"), None),
        ]);
        let error = output_of::<Out>(&event, "agent-run").unwrap_err();
        let Error::RunOutput { run_id, reason } = &error else {
            panic!("{error:?}")
        };
        assert_eq!(run_id, "run-1");
        assert!(reason.contains("\"fetch\", \"report\""), "{reason}");
    }

    #[test]
    fn an_output_of_the_wrong_shape_is_a_run_output_error() {
        let event = event(vec![result("agent-run", Some(r#"{"pr":42}"#), None)]);
        let error = output_of::<Out>(&event, "agent-run").unwrap_err();
        assert!(matches!(error, Error::RunOutput { .. }), "{error:?}");
    }

    #[test]
    fn a_missing_output_is_a_run_output_error() {
        let event = event(vec![result("agent-run", None, None)]);
        let error = output_of::<Out>(&event, "agent-run").unwrap_err();
        let Error::RunOutput { reason, .. } = &error else {
            panic!("{error:?}")
        };
        assert!(reason.contains("recorded no output"), "{reason}");
    }

    #[test]
    fn a_reported_error_fails_the_run_before_any_output_is_read() {
        let event = event(vec![
            result("fetch", Some("1"), None),
            result("agent-run", None, Some("boom")),
        ]);
        let error = output_of::<Out>(&event, "agent-run").unwrap_err();
        let Error::RunFailed { run_id, errors } = &error else {
            panic!("{error:?}")
        };
        assert_eq!(run_id, "run-1");
        assert_eq!(
            errors,
            &[TaskFailure {
                task_name: "agent-run".to_string(),
                message: "boom".to_string(),
            }]
        );
    }

    /// The shape a cancelled run arrives in, verbatim from what a real engine
    /// sent when a run was cancelled by its task run id.
    #[test]
    fn a_blank_error_with_no_output_is_a_cancellation() {
        let event = event(vec![
            result("lead", Some(r#"{"ok":true}"#), None),
            result("hold", None, Some("")),
        ]);
        let error = succeeded(&event).unwrap_err();
        let Error::RunCancelled { run_id, tasks } = &error else {
            panic!("expected a cancellation: {error:?}")
        };
        assert_eq!(run_id, "run-1");
        assert_eq!(tasks, &["hold".to_string()]);
    }

    /// Cancelling by *workflow* run id adds a blank-error row for a task that
    /// had already succeeded, next to that task's own success row. The run is
    /// still a cancellation, and the task that really finished is not named
    /// twice for it.
    #[test]
    fn a_success_row_and_a_cancel_row_for_one_task_is_still_a_cancellation() {
        let event = event(vec![
            result("lead", Some(r#"{"ok":true}"#), None),
            result("lead", None, Some("")),
            result("hold", None, Some("")),
        ]);
        let error = succeeded(&event).unwrap_err();
        let Error::RunCancelled { tasks, .. } = &error else {
            panic!("expected a cancellation: {error:?}")
        };
        assert_eq!(tasks, &["lead".to_string(), "hold".to_string()]);
    }

    /// A real failure outranks a cancellation: the run is reported as the
    /// failure, and only the task that really failed is named.
    #[test]
    fn a_real_failure_next_to_a_cancelled_task_is_a_failure() {
        let event = event(vec![
            result("fetch", None, Some("boom")),
            result("report", None, Some("")),
        ]);
        let error = succeeded(&event).unwrap_err();
        let Error::RunFailed { errors, .. } = &error else {
            panic!("expected a failure: {error:?}")
        };
        assert_eq!(
            errors,
            &[TaskFailure {
                task_name: "fetch".to_string(),
                message: "boom".to_string(),
            }]
        );
    }

    /// What this SDK's own worker sends for a failure with nothing to say: an
    /// empty JSON string, which is not empty. A blank-message failure must not
    /// be reported to waiters as someone's decision to stop the run.
    #[test]
    fn a_json_encoded_empty_failure_message_is_a_failure_not_a_cancellation() {
        let event = event(vec![result("agent-run", None, Some("\"\""))]);
        let error = succeeded(&event).unwrap_err();
        let Error::RunFailed { errors, .. } = &error else {
            panic!("expected a failure: {error:?}")
        };
        assert_eq!(errors[0].message, "\"\"");
    }

    /// The engine fills `error` in with the empty string on rows that
    /// succeeded, too — it is the missing output that makes a row a
    /// cancellation.
    #[test]
    fn a_blank_error_next_to_an_output_is_neither_a_failure_nor_a_cancellation() {
        let event = event(vec![result("agent-run", Some(r#"{"pr":null}"#), Some(""))]);
        succeeded(&event).expect("a row with an output is not a cancellation");
        let out: Out = output_of(&event, "agent-run").unwrap();
        assert_eq!(out, Out { pr: None });
    }

    /// A single-task run's cancellation reaches the same waiter that would
    /// have read its output.
    #[test]
    fn a_cancelled_run_is_reported_before_any_output_is_read() {
        let event = event(vec![result("agent-run", None, Some(""))]);
        let error = output_of::<Out>(&event, "agent-run").unwrap_err();
        assert!(matches!(error, Error::RunCancelled { .. }), "{error:?}");
    }

    #[test]
    fn a_workflow_result_reads_each_task_by_name() {
        let event = event(vec![
            result("fetch", Some(r#"{"n":1}"#), None),
            result("report", Some(r#""done""#), None),
        ]);
        succeeded(&event).unwrap();
        let workflow_result = WorkflowResult {
            run_id: event.workflow_run_id.clone(),
            results: event.results.clone(),
        };
        assert_eq!(workflow_result.run_id(), "run-1");
        assert_eq!(
            workflow_result
                .output_by_name::<serde_json::Value>("fetch")
                .unwrap(),
            json!({"n": 1})
        );
        assert_eq!(
            workflow_result.output_by_name::<String>("report").unwrap(),
            "done"
        );
        let error = workflow_result
            .output_by_name::<serde_json::Value>("missing")
            .unwrap_err();
        assert!(matches!(error, Error::RunOutput { .. }), "{error:?}");
    }

    /// A single result is a *standalone task's* output whatever the engine
    /// called it; inside a workflow, names are how outputs are told apart, so
    /// asking for one that did not run is an error even when only one did.
    #[test]
    fn a_workflow_result_does_not_fall_back_to_a_lone_result() {
        let workflow_result = WorkflowResult {
            run_id: "run-1".to_string(),
            results: vec![result("fetch", Some("1"), None)],
        };
        let error = workflow_result.output_by_name::<u32>("report").unwrap_err();
        assert!(matches!(error, Error::RunOutput { .. }), "{error:?}");
    }
}