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
//! Options that refine how Hatchet schedules a task.

use std::time::Duration;

use hatchet_proto::root::WorkerLabels;
use hatchet_proto::v1;

/// What happens to runs beyond a concurrency limit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConcurrencyLimitStrategy {
    /// Cancel the oldest running run to make room (the engine default).
    CancelInProgress,
    /// Queue runs and take them round-robin across groups.
    GroupRoundRobin,
    /// Cancel the newly arriving run.
    CancelNewest,
}

/// How a workflow's runs are pinned to the worker that started them.
///
/// Set it with [`Workflow::sticky`](crate::Workflow::sticky), or with
/// [`TaskBuilder::sticky`](crate::TaskBuilder::sticky) for a standalone
/// task. It is also what makes a child run's own sticky pinning
/// meaningful: the engine's own comment on `desired_worker_id` says it
/// "requires the workflow definition to have a sticky strategy".
///
/// ```
/// use hatchet_client::{StickyStrategy, Workflow, TaskBuilder};
///
/// let load = TaskBuilder::<(), ()>::new("load").handler(|_ctx, _input| async { Ok(()) });
/// let index = TaskBuilder::<(), ()>::new("index").handler(|_ctx, _input| async { Ok(()) });
/// // Both tasks want the same machine's warm cache.
/// let build = Workflow::new("build-index")
///     .sticky(StickyStrategy::Soft)
///     .task(&load)
///     .task(&index);
/// # let _ = build;
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StickyStrategy {
    /// Prefer the worker that ran the first task of the run, and fall back
    /// to another when it cannot be used. Observed against `hatchet-lite`
    /// (both supported versions): a run's tasks landed on the same worker
    /// 4/4 times, against 2/4 (v0.107.0) and 0/4 (v0.80.0) for a run with no
    /// sticky strategy.
    Soft,
    /// Only that worker may run the rest of the run. Observed against
    /// `hatchet-lite` (both supported versions): a run's tasks landed on the
    /// same worker 4/4 times, **and when that worker was gone (a graceful
    /// shutdown), the run's remaining tasks never ran** — not even when
    /// another worker was registered and serving the same action. A `HARD`
    /// run whose worker disappears is stranded, not rescheduled.
    Hard,
}

impl StickyStrategy {
    pub(crate) fn to_proto(self) -> i32 {
        let proto = match self {
            Self::Soft => v1::StickyStrategy::Soft,
            Self::Hard => v1::StickyStrategy::Hard,
        };
        proto as i32
    }
}

/// A concurrency limit keyed by a CEL expression over the run's input.
///
/// Set a [`strategy`](Concurrency::strategy) if runs beyond the limit should
/// *wait*: without one the engine applies its own default, and that default
/// does not queue. Observed against `hatchet-lite`, on both supported engine
/// versions: with [`max_runs(1)`](Concurrency::max_runs), no strategy and two
/// runs sharing a key, the run **already under way** was cancelled and the
/// newcomer went through — the cancelled one ending as
/// [`Error::RunCancelled`](crate::Error::RunCancelled) for its waiter, and
/// its handler seeing [`Context::cancelled`](crate::Context::cancelled). With
/// [`ConcurrencyLimitStrategy::GroupRoundRobin`] the second run waits for the
/// first and then runs.
///
/// ```
/// use hatchet_client::{Concurrency, ConcurrencyLimitStrategy, TaskBuilder};
///
/// let sync = TaskBuilder::<(), ()>::new("sync")
///     .workflow_concurrency(
///         Concurrency::expr("input.account_id")
///             .max_runs(1)
///             .strategy(ConcurrencyLimitStrategy::GroupRoundRobin),
///     )
///     .handler(|_ctx, _input| async { Ok(()) });
/// # let _ = sync;
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Concurrency {
    expression: String,
    max_runs: Option<u32>,
    strategy: Option<ConcurrencyLimitStrategy>,
    name: Option<String>,
    is_tenant_scoped: bool,
    max_runs_expression: Option<String>,
}

impl Concurrency {
    /// Groups runs by the value of a CEL expression such as `input.device_id`.
    pub fn expr(expression: impl Into<String>) -> Self {
        Self {
            expression: expression.into(),
            max_runs: None,
            strategy: None,
            name: None,
            is_tenant_scoped: false,
            max_runs_expression: None,
        }
    }

    /// How many runs of one group may execute at once (engine default: 1).
    pub fn max_runs(mut self, max_runs: u32) -> Self {
        self.max_runs = Some(max_runs);
        self
    }

    /// What to do with runs beyond the limit.
    ///
    /// Leaving this unset leaves the choice to the engine, which cancels
    /// rather than queues: observed against `hatchet-lite`, the run that lost
    /// was the one already under way, and it ended as
    /// [`Error::RunCancelled`](crate::Error::RunCancelled) for its waiter.
    /// [`ConcurrencyLimitStrategy::GroupRoundRobin`] is the strategy that
    /// makes a run wait its turn.
    pub fn strategy(mut self, strategy: ConcurrencyLimitStrategy) -> Self {
        self.strategy = Some(strategy);
        self
    }

    /// Names this entry. Required for a tenant-scoped strategy, where the
    /// name is what makes two workflows share one limit. What the engine does
    /// with the name of an entry that is not tenant-scoped was not verified.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Shares this limit with every other workflow declaring a tenant-scoped
    /// entry of the same [`name`](Concurrency::name), rather than keeping it
    /// to this workflow.
    ///
    /// A tenant-scoped entry without a name is an
    /// [`Error::InvalidDeclaration`](crate::Error::InvalidDeclaration) at
    /// registration.
    pub fn tenant_scoped(mut self) -> Self {
        self.is_tenant_scoped = true;
        self
    }

    /// Takes the limit from a CEL expression over the run's input instead of
    /// a fixed number, evaluated per group; the group's effective limit is
    /// the value from its most recently created task. Overrides
    /// [`max_runs`](Concurrency::max_runs) for the groups it applies to; both
    /// may be set, and `max_runs` then stays the static default.
    pub fn max_runs_expression(mut self, expression: impl Into<String>) -> Self {
        self.max_runs_expression = Some(expression.into());
        self
    }

    /// Checks that this concurrency limit can be sent to the engine.
    pub(crate) fn validate(&self) -> Result<(), String> {
        if self.max_runs == Some(0) {
            return Err("concurrency max_runs must be at least 1".to_string());
        }
        if self.is_tenant_scoped && self.name.is_none() {
            return Err(
                "a tenant-scoped concurrency entry needs a name; it is what makes two \
                 workflows share one limit"
                    .to_string(),
            );
        }
        Ok(())
    }

    pub(crate) fn to_proto(&self) -> v1::Concurrency {
        v1::Concurrency {
            expression: self.expression.clone(),
            max_runs: self.max_runs.map(saturating_i32),
            limit_strategy: self.strategy.map(|strategy| {
                let proto = match strategy {
                    ConcurrencyLimitStrategy::CancelInProgress => {
                        v1::ConcurrencyLimitStrategy::CancelInProgress
                    }
                    ConcurrencyLimitStrategy::GroupRoundRobin => {
                        v1::ConcurrencyLimitStrategy::GroupRoundRobin
                    }
                    ConcurrencyLimitStrategy::CancelNewest => {
                        v1::ConcurrencyLimitStrategy::CancelNewest
                    }
                };
                proto as i32
            }),
            name: self.name.clone(),
            is_tenant_scoped: self.is_tenant_scoped.then_some(true),
            max_runs_expression: self.max_runs_expression.clone(),
        }
    }
}

/// The window a rate limit's allowance refills over.
///
/// The engine's own default when nothing is sent was not measured; the
/// official Go SDK leaves it unset too, and the official Python SDK always
/// sends `MINUTE`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RateLimitDuration {
    /// Per second.
    Second,
    /// Per minute.
    Minute,
    /// Per hour.
    Hour,
    /// Per day.
    Day,
    /// Per week.
    Week,
    /// Per month.
    Month,
    /// Per year.
    Year,
}

impl RateLimitDuration {
    pub(crate) fn to_proto(self) -> i32 {
        let proto = match self {
            Self::Second => v1::RateLimitDuration::Second,
            Self::Minute => v1::RateLimitDuration::Minute,
            Self::Hour => v1::RateLimitDuration::Hour,
            Self::Day => v1::RateLimitDuration::Day,
            Self::Week => v1::RateLimitDuration::Week,
            Self::Month => v1::RateLimitDuration::Month,
            Self::Year => v1::RateLimitDuration::Year,
        };
        proto as i32
    }
}

/// How much of a rate limit one run of a task consumes.
///
/// Two kinds, and a task may carry several of either:
///
/// * [`new`](RateLimit::new) names a **static** limit — one the tenant
///   already has, which
///   [`RateLimitsClient::put`](crate::RateLimitsClient::put) creates or
///   raises. Without that upsert, registering a task that uses this key
///   fails with a bare `Internal` error from the engine (observed against
///   both supported engine versions); the SDK cannot detect this ahead of
///   time, so create the key first.
/// * [`dynamic`](RateLimit::dynamic) computes the key from the run's input
///   with CEL, which is how one limit per tenant or per user is expressed.
///   A dynamic limit must also say what the allowance *is*, with
///   [`limit_expr`](RateLimit::limit_expr) — there is no stored limit to
///   look up for a key nobody registered. A dynamic limit without one is an
///   [`Error::InvalidDeclaration`](crate::Error::InvalidDeclaration) at
///   registration, which is the rule the official Python SDK enforces too
///   (`sdks/python/hatchet_sdk/types/rate_limit.py`, `validate_rate_limit`);
///   the official Go SDK does not check it at all. It must also say how many
///   units a run consumes, with [`units_expr`](RateLimit::units_expr):
///   without one, `hatchet-lite` v0.107.0 registered the task and then
///   failed *every* run of it with a CEL syntax error on the empty
///   expression, so a dynamic limit without `units_expr` is rejected here
///   too (an SDK rule; neither official SDK checks it).
///
/// The dynamic wire shape here follows the official Python SDK: the key
/// expression is sent as both `key` and `key_expr`. The official Go SDK
/// instead leaves `key` empty for a dynamic limit, but both supported
/// engine versions reject that with `InvalidArgument` (`Key: required`) —
/// observed against `hatchet-lite` v0.107.0 and v0.80.0.
///
/// ```
/// use hatchet_client::{RateLimit, RateLimitDuration, TaskBuilder};
///
/// let call_api = TaskBuilder::<(), ()>::new("call-api")
///     // Five calls per customer per minute, whoever the customer is.
///     .rate_limit(
///         RateLimit::dynamic("input.customer_id")
///             .units_expr("1")
///             .limit_expr("5")
///             .duration(RateLimitDuration::Minute),
///     )
///     .handler(|_ctx, _input| async { Ok(()) });
/// # let _ = call_api;
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RateLimit {
    key: String,
    key_expr: Option<String>,
    units: Option<u32>,
    units_expr: Option<String>,
    limit_expr: Option<String>,
    duration: Option<RateLimitDuration>,
}

impl RateLimit {
    /// Each run consumes `units` of the rate limit named `key`, which must
    /// already exist on the tenant (see
    /// [`RateLimitsClient::put`](crate::RateLimitsClient::put)).
    pub fn new(key: impl Into<String>, units: u32) -> Self {
        Self {
            key: key.into(),
            key_expr: None,
            units: Some(units),
            units_expr: None,
            limit_expr: None,
            duration: None,
        }
    }

    /// Takes the limit's key from a CEL expression over the run's input,
    /// such as `"input.customer_id"`. Needs
    /// [`limit_expr`](RateLimit::limit_expr).
    pub fn dynamic(key_expr: impl Into<String>) -> Self {
        let key_expr = key_expr.into();
        Self {
            key: key_expr.clone(),
            key_expr: Some(key_expr),
            units: None,
            units_expr: None,
            limit_expr: None,
            duration: None,
        }
    }

    /// Takes the units consumed from a CEL expression instead of a fixed
    /// number. Works on both a static and a dynamic rate limit.
    pub fn units_expr(mut self, expression: impl Into<String>) -> Self {
        self.units_expr = Some(expression.into());
        self
    }

    /// The allowance itself, as a CEL expression — the engine's
    /// `limit_values_expr`. A constant is written as one: `"5"`. Required on
    /// a [`dynamic`](RateLimit::dynamic) limit; optional on a static one.
    pub fn limit_expr(mut self, expression: impl Into<String>) -> Self {
        self.limit_expr = Some(expression.into());
        self
    }

    /// The window the allowance refills over. Works on both a static and a
    /// dynamic rate limit.
    pub fn duration(mut self, duration: RateLimitDuration) -> Self {
        self.duration = Some(duration);
        self
    }

    /// Checks that this rate limit can be sent to the engine.
    pub(crate) fn validate(&self) -> Result<(), String> {
        match &self.key_expr {
            Some(expr) if expr.trim().is_empty() => {
                Err("a dynamic rate limit key expression must not be empty".to_string())
            }
            Some(_) if self.limit_expr.is_none() => Err(
                "a dynamic rate limit needs its allowance too; add `limit_expr(..)`, since \
                 there is no stored limit for a key that is computed per run"
                    .to_string(),
            ),
            Some(_) if self.units_expr.is_none() => Err(
                "a dynamic rate limit needs `units_expr(..)`, the units one run consumes; \
                 without it the engine registers the task and then fails every run of it \
                 with a CEL syntax error"
                    .to_string(),
            ),
            None if self.key.trim().is_empty() => {
                Err("a rate limit key must not be empty".to_string())
            }
            _ => Ok(()),
        }
    }

    pub(crate) fn to_proto(&self) -> v1::CreateTaskRateLimit {
        v1::CreateTaskRateLimit {
            key: self.key.clone(),
            units: self.units.map(saturating_i32),
            key_expr: self.key_expr.clone(),
            units_expr: self.units_expr.clone(),
            limit_values_expr: self.limit_expr.clone(),
            duration: self.duration.map(RateLimitDuration::to_proto),
        }
    }
}

/// A worker label value: a string or an integer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LabelValue {
    /// A string label such as `"macos"`.
    Str(String),
    /// An integer label such as `16`.
    Int(i32),
}

impl From<&str> for LabelValue {
    fn from(value: &str) -> Self {
        Self::Str(value.to_string())
    }
}

impl From<String> for LabelValue {
    fn from(value: String) -> Self {
        Self::Str(value)
    }
}

impl From<i32> for LabelValue {
    fn from(value: i32) -> Self {
        Self::Int(value)
    }
}

impl LabelValue {
    /// The label as the engine takes it, whether it is being registered with
    /// a worker or upserted from a running task.
    pub(crate) fn to_proto(&self) -> WorkerLabels {
        match self {
            Self::Str(value) => WorkerLabels {
                str_value: Some(value.clone()),
                int_value: None,
            },
            Self::Int(value) => WorkerLabels {
                str_value: None,
                int_value: Some(*value),
            },
        }
    }
}

/// A label a task wants its worker to have.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DesiredLabel {
    value: LabelValue,
    comparator: v1::WorkerLabelComparator,
    required: bool,
    weight: Option<i32>,
}

impl DesiredLabel {
    fn new(value: impl Into<LabelValue>, comparator: v1::WorkerLabelComparator) -> Self {
        Self {
            value: value.into(),
            comparator,
            required: false,
            weight: None,
        }
    }

    /// The worker's label equals `value`.
    #[allow(clippy::should_implement_trait)]
    pub fn eq(value: impl Into<LabelValue>) -> Self {
        Self::new(value, v1::WorkerLabelComparator::Equal)
    }

    /// The worker's label differs from `value`.
    #[allow(clippy::should_implement_trait)]
    pub fn ne(value: impl Into<LabelValue>) -> Self {
        Self::new(value, v1::WorkerLabelComparator::NotEqual)
    }

    /// The worker's label is greater than `value`.
    pub fn gt(value: impl Into<LabelValue>) -> Self {
        Self::new(value, v1::WorkerLabelComparator::GreaterThan)
    }

    /// The worker's label is at least `value`.
    pub fn gte(value: impl Into<LabelValue>) -> Self {
        Self::new(value, v1::WorkerLabelComparator::GreaterThanOrEqual)
    }

    /// The worker's label is less than `value`.
    pub fn lt(value: impl Into<LabelValue>) -> Self {
        Self::new(value, v1::WorkerLabelComparator::LessThan)
    }

    /// The worker's label is at most `value`.
    pub fn lte(value: impl Into<LabelValue>) -> Self {
        Self::new(value, v1::WorkerLabelComparator::LessThanOrEqual)
    }

    /// Only workers satisfying this label may take the task.
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    /// How strongly to prefer workers satisfying this label.
    pub fn weight(mut self, weight: i32) -> Self {
        self.weight = Some(weight);
        self
    }

    pub(crate) fn to_proto(&self) -> v1::DesiredWorkerLabels {
        let (str_value, int_value) = match &self.value {
            LabelValue::Str(value) => (Some(value.clone()), None),
            LabelValue::Int(value) => (None, Some(*value)),
        };
        v1::DesiredWorkerLabels {
            str_value,
            int_value,
            required: Some(self.required),
            comparator: Some(self.comparator as i32),
            weight: self.weight,
        }
    }
}

/// Run priority; higher runs are scheduled first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Priority {
    /// Priority 1.
    Low,
    /// Priority 2.
    Medium,
    /// Priority 3.
    High,
}

impl Priority {
    pub(crate) fn to_proto(self) -> i32 {
        match self {
            Self::Low => 1,
            Self::Medium => 2,
            Self::High => 3,
        }
    }
}

/// How the engine buffers concurrent runs of one task into a batch.
///
/// The runs of a batch task are **held by the engine** until the batch fills up
/// ([`max_size`](Self::max_size)) or its interval runs out
/// ([`max_interval`](Self::max_interval)), and the whole group is then given to
/// one worker as a single action. The handler is called once and answers with
/// one output per buffered run.
///
/// **A batch is flushed on time as well as on size, always.** Measured against
/// real engines, a batch with no `max_interval` set was still handed over about
/// a second after the first run arrived — there is a default interval, so a
/// half-full batch never waits indefinitely for the rest.
///
/// Needs an engine of at least
/// [`BATCH_MIN_ENGINE_VERSION`](crate::BATCH_MIN_ENGINE_VERSION); a worker
/// registering a batch task on an older one is refused by
/// [`WorkerBuilder::build`](crate::WorkerBuilder::build).
///
/// ```
/// use std::time::Duration;
///
/// use hatchet_client::{BatchConfig, TaskBuilder};
///
/// let embed = TaskBuilder::<String, usize>::new("embed").batch_handler(
///     BatchConfig::max_size(32)
///         .max_interval(Duration::from_millis(200))
///         .group_key("input.tenant"),
///     |_ctx, batch| async move {
///         Ok(batch.iter().map(|(id, text)| (id.clone(), text.len())).collect())
///     },
/// );
/// # let _ = embed;
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use = "a batch config configures nothing until a task is declared with it"]
pub struct BatchConfig {
    max_size: u32,
    max_interval: Option<Duration>,
    group_key: Option<String>,
    group_max_runs: Option<u32>,
}

impl BatchConfig {
    /// Buffer at most `max_size` runs before handing the batch to a worker.
    /// Required, and at least 1.
    pub fn max_size(max_size: u32) -> Self {
        Self {
            max_size,
            max_interval: None,
            group_key: None,
            group_max_runs: None,
        }
    }

    /// Hand a partly filled batch over after this long rather than waiting for
    /// [`max_size`](Self::max_size) runs to arrive.
    ///
    /// The engine takes whole milliseconds, so anything that rounds down to
    /// zero is an
    /// [`Error::InvalidDeclaration`](crate::Error::InvalidDeclaration) rather
    /// than a silent zero, which the engine reads as "no interval given".
    pub fn max_interval(mut self, interval: Duration) -> Self {
        self.max_interval = Some(interval);
        self
    }

    /// Split the buffered runs into independent batches by the value of a CEL
    /// expression over each run's input, such as `"input.tenant"`, so one
    /// tenant's runs are never mixed into another's
    /// (`pkg/client/types/batch.go:18-20`).
    ///
    /// Measured: four runs of two tenants under `"input.tenant"` arrived as two
    /// batches, each holding only its own tenant's inputs, and each batch's
    /// [`BatchInput::batch_key`](crate::BatchInput::batch_key) held the
    /// **evaluated value** (`"acme"`, `"globex"`) rather than the expression.
    /// Without a group key every run goes into one partition, which engines
    /// name `"default"`.
    pub fn group_key(mut self, expression: impl Into<String>) -> Self {
        self.group_key = Some(expression.into());
        self
    }

    /// How many batches of one group may run at once.
    pub fn group_max_runs(mut self, max_runs: u32) -> Self {
        self.group_max_runs = Some(max_runs);
        self
    }

    /// Why this configuration cannot be registered, if it cannot.
    pub(crate) fn invalid_reason(&self) -> Option<String> {
        if self.max_size == 0 {
            return Some(
                "a batch config needs a max size of at least 1; a size of zero buffers nothing"
                    .to_string(),
            );
        }
        if let Some(interval) = self.max_interval {
            if interval.is_zero() {
                return Some(
                    "a batch max interval of zero is not an interval; leave it unset to let the \
                     engine use its own default"
                        .to_string(),
                );
            }
            if interval.as_millis() == 0 {
                return Some(format!(
                    "a batch max interval of {interval:?} rounds down to zero milliseconds, which \
                     the engine reads as no interval at all; use at least 1ms"
                ));
            }
            if i32::try_from(interval.as_millis()).is_err() {
                return Some(format!(
                    "a batch max interval of {interval:?} is longer than the engine's limit of \
                     about 24 days"
                ));
            }
        }
        if self.group_max_runs == Some(0) {
            return Some(
                "a batch group max runs of zero would let no batch of a group run at all"
                    .to_string(),
            );
        }
        if self
            .group_key
            .as_ref()
            .is_some_and(|key| key.trim().is_empty())
        {
            return Some("a batch group key is a CEL expression and cannot be blank".to_string());
        }
        None
    }

    /// The registration field. `broadcast_output` comes from the handler that
    /// was attached, never from the caller: the flag and the handler's return
    /// type are one decision.
    pub(crate) fn to_proto(&self, broadcast_output: bool) -> v1::TaskBatchConfig {
        v1::TaskBatchConfig {
            batch_max_size: saturating_i32(self.max_size),
            batch_max_interval_ms: self
                .max_interval
                .map(|interval| i32::try_from(interval.as_millis()).unwrap_or(i32::MAX)),
            batch_group_key: self.group_key.clone(),
            batch_group_max_runs: self.group_max_runs.map(saturating_i32),
            broadcast_output: Some(broadcast_output),
        }
    }
}

pub(crate) fn saturating_i32(value: u32) -> i32 {
    i32::try_from(value).unwrap_or(i32::MAX)
}

#[cfg(test)]
mod tests {
    use super::*;
    use hatchet_proto::v1;

    #[test]
    fn a_batch_config_maps_to_the_registration_field() {
        let proto = BatchConfig::max_size(10)
            .max_interval(Duration::from_secs(2))
            .group_key("input.tenant")
            .group_max_runs(3)
            .to_proto(false);
        assert_eq!(
            proto,
            v1::TaskBatchConfig {
                batch_max_size: 10,
                batch_max_interval_ms: Some(2_000),
                batch_group_key: Some("input.tenant".to_string()),
                batch_group_max_runs: Some(3),
                broadcast_output: Some(false),
            }
        );
    }

    #[test]
    fn a_batch_config_sends_only_what_it_was_given() {
        let proto = BatchConfig::max_size(4).to_proto(true);
        assert_eq!(proto.batch_max_size, 4);
        assert_eq!(proto.batch_max_interval_ms, None);
        assert_eq!(proto.batch_group_key, None);
        assert_eq!(proto.batch_group_max_runs, None);
        // Explicitly true rather than absent: the handler that was attached
        // decides it, so the wire says which decision was made.
        assert_eq!(proto.broadcast_output, Some(true));
    }

    #[test]
    fn a_batch_config_rejects_what_the_engine_would_read_as_nothing() {
        for config in [
            BatchConfig::max_size(0),
            BatchConfig::max_size(1).max_interval(Duration::ZERO),
            BatchConfig::max_size(1).max_interval(Duration::from_micros(999)),
            BatchConfig::max_size(1).max_interval(Duration::from_secs(60 * 60 * 24 * 25)),
            BatchConfig::max_size(1).group_max_runs(0),
            BatchConfig::max_size(1).group_key(" "),
        ] {
            assert!(config.invalid_reason().is_some(), "{config:?}");
        }
        assert!(
            BatchConfig::max_size(1)
                .max_interval(Duration::from_millis(1))
                .group_key("input.tenant")
                .group_max_runs(1)
                .invalid_reason()
                .is_none()
        );
    }

    #[test]
    fn a_batch_config_saturates_rather_than_wrapping() {
        let proto = BatchConfig::max_size(u32::MAX)
            .group_max_runs(u32::MAX)
            .to_proto(false);
        assert_eq!(proto.batch_max_size, i32::MAX);
        assert_eq!(proto.batch_group_max_runs, Some(i32::MAX));
    }

    #[test]
    fn concurrency_maps_expression_max_runs_and_strategy() {
        let concurrency = Concurrency::expr("input.device_id")
            .max_runs(1)
            .strategy(ConcurrencyLimitStrategy::GroupRoundRobin);
        assert_eq!(
            concurrency.to_proto(),
            v1::Concurrency {
                expression: "input.device_id".to_string(),
                max_runs: Some(1),
                limit_strategy: Some(v1::ConcurrencyLimitStrategy::GroupRoundRobin as i32),
                ..Default::default()
            }
        );
    }

    #[test]
    fn concurrency_max_runs_zero_is_invalid() {
        let err = Concurrency::expr("input.user")
            .max_runs(0)
            .validate()
            .unwrap_err();
        assert!(err.contains("max_runs"), "{err}");
    }

    #[test]
    fn concurrency_without_max_runs_or_with_a_positive_one_is_valid() {
        assert!(Concurrency::expr("input.user").validate().is_ok());
        assert!(
            Concurrency::expr("input.user")
                .max_runs(1)
                .validate()
                .is_ok()
        );
    }

    #[test]
    fn concurrency_leaves_unset_fields_to_the_engine_defaults() {
        assert_eq!(
            Concurrency::expr("input.user").to_proto(),
            v1::Concurrency {
                expression: "input.user".to_string(),
                ..Default::default()
            }
        );
    }

    #[test]
    fn every_strategy_maps_to_its_proto_value() {
        use ConcurrencyLimitStrategy::*;
        for (ours, theirs) in [
            (
                CancelInProgress,
                v1::ConcurrencyLimitStrategy::CancelInProgress,
            ),
            (
                GroupRoundRobin,
                v1::ConcurrencyLimitStrategy::GroupRoundRobin,
            ),
            (CancelNewest, v1::ConcurrencyLimitStrategy::CancelNewest),
        ] {
            let proto = Concurrency::expr("x").strategy(ours).to_proto();
            assert_eq!(proto.limit_strategy, Some(theirs as i32));
        }
    }

    #[test]
    fn concurrency_maps_the_name_tenant_scope_and_max_runs_expression() {
        let concurrency = Concurrency::expr("input.tenant")
            .name("per-tenant")
            .tenant_scoped()
            .max_runs_expression("input.limit");
        assert_eq!(
            concurrency.to_proto(),
            v1::Concurrency {
                expression: "input.tenant".to_string(),
                name: Some("per-tenant".to_string()),
                is_tenant_scoped: Some(true),
                max_runs_expression: Some("input.limit".to_string()),
                ..Default::default()
            }
        );
    }

    #[test]
    fn a_workflow_scoped_entry_sends_neither_the_tenant_flag_nor_a_name() {
        // The Go SDK sets `Name` only when it is non-empty and
        // `IsTenantScoped` only when true (declaration.go:763-791); an
        // unset optional is how the engine hears "default".
        let proto = Concurrency::expr("input.user").max_runs(2).to_proto();
        assert_eq!(proto.name, None);
        assert_eq!(proto.is_tenant_scoped, None);
        assert_eq!(proto.max_runs_expression, None);
    }

    #[test]
    fn a_tenant_scoped_entry_without_a_name_is_invalid() {
        let err = Concurrency::expr("input.tenant")
            .tenant_scoped()
            .validate()
            .unwrap_err();
        assert!(err.contains("name"), "{err}");
    }

    #[test]
    fn static_rate_limit_maps_key_and_units() {
        assert_eq!(
            RateLimit::new("github-api", 2).to_proto(),
            v1::CreateTaskRateLimit {
                key: "github-api".to_string(),
                units: Some(2),
                ..Default::default()
            }
        );
    }

    #[test]
    fn a_dynamic_rate_limit_maps_every_expression_and_the_window() {
        // The wire shape follows the official Python SDK: `key` carries the
        // key expression too, since both supported engine versions reject
        // the Go SDK's empty `key` with `InvalidArgument` (observed against
        // hatchet-lite v0.107.0 and v0.80.0).
        let limit = RateLimit::dynamic("input.tenant")
            .units_expr("input.cost")
            .limit_expr("5")
            .duration(RateLimitDuration::Minute);
        assert_eq!(
            limit.to_proto(),
            v1::CreateTaskRateLimit {
                key: "input.tenant".to_string(),
                units: None,
                key_expr: Some("input.tenant".to_string()),
                units_expr: Some("input.cost".to_string()),
                limit_values_expr: Some("5".to_string()),
                duration: Some(v1::RateLimitDuration::Minute as i32),
            }
        );
    }

    #[test]
    fn a_static_rate_limit_may_also_take_a_units_expression_and_a_window() {
        let limit = RateLimit::new("github-api", 2)
            .units_expr("input.cost")
            .duration(RateLimitDuration::Hour);
        let proto = limit.to_proto();
        assert_eq!(proto.key, "github-api");
        assert_eq!(proto.units, Some(2));
        assert_eq!(proto.units_expr, Some("input.cost".to_string()));
        assert_eq!(proto.duration, Some(v1::RateLimitDuration::Hour as i32));
        assert_eq!(proto.key_expr, None);
    }

    #[test]
    fn every_rate_limit_duration_maps_to_its_proto_value() {
        use RateLimitDuration::*;
        for (ours, theirs) in [
            (Second, v1::RateLimitDuration::Second),
            (Minute, v1::RateLimitDuration::Minute),
            (Hour, v1::RateLimitDuration::Hour),
            (Day, v1::RateLimitDuration::Day),
            (Week, v1::RateLimitDuration::Week),
            (Month, v1::RateLimitDuration::Month),
            (Year, v1::RateLimitDuration::Year),
        ] {
            assert_eq!(ours.to_proto(), theirs as i32);
        }
    }

    #[test]
    fn a_dynamic_rate_limit_without_a_units_expression_is_invalid() {
        let reason = RateLimit::dynamic("input.tenant")
            .limit_expr("5")
            .validate()
            .unwrap_err();
        assert!(reason.contains("units_expr"), "{reason}");
    }

    #[test]
    fn a_dynamic_rate_limit_without_a_limit_expression_is_invalid() {
        let reason = RateLimit::dynamic("input.tenant").validate().unwrap_err();
        assert!(reason.contains("limit_expr"), "{reason}");
    }

    #[test]
    fn a_static_rate_limit_needs_no_limit_expression() {
        assert!(RateLimit::new("github-api", 1).validate().is_ok());
    }

    #[test]
    fn an_empty_static_key_is_invalid() {
        let reason = RateLimit::new("  ", 1).validate().unwrap_err();
        assert!(reason.contains("key"), "{reason}");
    }

    #[test]
    fn an_empty_dynamic_key_expression_is_invalid() {
        let reason = RateLimit::dynamic("  ")
            .limit_expr("5")
            .units_expr("1")
            .validate()
            .unwrap_err();
        assert!(reason.contains("key"), "{reason}");
    }

    #[test]
    fn required_string_label() {
        assert_eq!(
            DesiredLabel::eq("macos").required().to_proto(),
            v1::DesiredWorkerLabels {
                str_value: Some("macos".to_string()),
                int_value: None,
                required: Some(true),
                comparator: Some(v1::WorkerLabelComparator::Equal as i32),
                weight: None,
            }
        );
    }

    #[test]
    fn weighted_integer_label() {
        assert_eq!(
            DesiredLabel::gte(8).weight(50).to_proto(),
            v1::DesiredWorkerLabels {
                str_value: None,
                int_value: Some(8),
                required: Some(false),
                comparator: Some(v1::WorkerLabelComparator::GreaterThanOrEqual as i32),
                weight: Some(50),
            }
        );
    }

    #[test]
    fn every_comparator_maps_to_its_proto_value() {
        use v1::WorkerLabelComparator as C;
        for (label, comparator) in [
            (DesiredLabel::eq(1), C::Equal),
            (DesiredLabel::ne(1), C::NotEqual),
            (DesiredLabel::gt(1), C::GreaterThan),
            (DesiredLabel::gte(1), C::GreaterThanOrEqual),
            (DesiredLabel::lt(1), C::LessThan),
            (DesiredLabel::lte(1), C::LessThanOrEqual),
        ] {
            assert_eq!(label.to_proto().comparator, Some(comparator as i32));
        }
    }

    #[test]
    fn priorities_are_one_to_three() {
        assert_eq!(Priority::Low.to_proto(), 1);
        assert_eq!(Priority::Medium.to_proto(), 2);
        assert_eq!(Priority::High.to_proto(), 3);
    }

    #[test]
    fn every_sticky_strategy_maps_to_its_proto_value() {
        assert_eq!(
            StickyStrategy::Soft.to_proto(),
            v1::StickyStrategy::Soft as i32
        );
        assert_eq!(
            StickyStrategy::Hard.to_proto(),
            v1::StickyStrategy::Hard as i32
        );
    }
}