footing 0.4.3

Feature-gated foundations for Rust backend services
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
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::time;

use crate::result::{ClassifyError, ErrorKind};
use crate::settings::{SettingsIssues, SettingsValidationError};

use super::{MAX_WORKER_LEASE_OWNER_LENGTH, MAX_WORKER_NAME_LENGTH};

/// Validated worker loop configuration.
///
/// Defaults enable the worker with no startup delay, 10-second polling, a
/// 10-millisecond queue interval and a 30-second graceful shutdown budget.
/// Ticks have no deadline unless configured. Failures back off from one second
/// to one minute, doubling each time; jitter and leasing are disabled.
/// Customize through [`WorkerSettings::build`]. Clocks, stores and metrics are
/// supplied separately through [`super::WorkerRunOptions`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WorkerConfig {
    pub(super) enabled: bool,
    pub(super) poll_interval: Duration,
    pub(super) min_queue_interval: Duration,
    pub(super) startup_delay: Duration,
    pub(super) tick_timeout: Option<Duration>,
    pub(super) shutdown_timeout: Duration,
    pub(super) failure_backoff: BackoffConfig,
    pub(super) failure_backoff_jitter: bool,
    pub(super) lease: Option<WorkerLeaseConfig>,
}

impl Default for WorkerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            poll_interval: Duration::from_secs(10),
            min_queue_interval: Duration::from_millis(10),
            startup_delay: Duration::ZERO,
            tick_timeout: None,
            shutdown_timeout: Duration::from_secs(30),
            failure_backoff: BackoffConfig::default(),
            failure_backoff_jitter: false,
            lease: None,
        }
    }
}

impl WorkerConfig {
    /// Returns a disabled worker configuration.
    #[must_use]
    pub fn disabled() -> Self {
        Self {
            enabled: false,
            ..Self::default()
        }
    }

    /// Returns whether the worker is enabled.
    #[must_use]
    pub const fn enabled(&self) -> bool {
        self.enabled
    }

    /// Returns the normal polling interval.
    #[must_use]
    pub const fn poll_interval(&self) -> Duration {
        self.poll_interval
    }

    /// Minimum spacing between queue tick starts, capped at `poll_interval`.
    ///
    /// Applies only to `Continue` and `WaitForWork`. Time spent running the
    /// previous tick counts toward this interval. Defaults to 10 milliseconds.
    #[must_use]
    pub const fn min_queue_interval(&self) -> Duration {
        self.min_queue_interval
    }

    /// Returns the startup delay.
    #[must_use]
    pub const fn startup_delay(&self) -> Duration {
        self.startup_delay
    }

    /// Returns the optional maximum duration of one tick, excluding lease acquisition.
    #[must_use]
    pub const fn tick_timeout(&self) -> Option<Duration> {
        self.tick_timeout
    }

    /// Returns the shutdown timeout.
    #[must_use]
    pub const fn shutdown_timeout(&self) -> Duration {
        self.shutdown_timeout
    }

    /// Returns the failure backoff config.
    #[must_use]
    pub const fn failure_backoff(&self) -> BackoffConfig {
        self.failure_backoff
    }

    /// Returns whether worker failure delays are randomized.
    #[must_use]
    pub const fn failure_backoff_jitter(&self) -> bool {
        self.failure_backoff_jitter
    }

    /// Returns optional lease settings.
    #[must_use]
    pub const fn lease(&self) -> Option<WorkerLeaseConfig> {
        self.lease
    }
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable worker settings, starting with [`WorkerConfig`]'s defaults.
///
/// Call [`Self::build`] to validate intervals, deadlines and lease renewal
/// margins before starting the worker. Unknown serialized fields are rejected.
pub struct WorkerSettings {
    /// Whether the worker runs.
    pub enabled: bool,
    #[serde(with = "crate::settings::human_duration")]
    /// Delay for ordinary polling and maximum idle wait for queue schedules.
    pub poll_interval: Duration,
    #[serde(with = "crate::settings::human_duration")]
    /// Minimum queue tick spacing, capped at `poll_interval`; defaults to 10 ms.
    pub min_queue_interval: Duration,
    #[serde(with = "crate::settings::human_duration")]
    /// Delay before the first polling iteration.
    pub startup_delay: Duration,
    #[serde(with = "crate::settings::human_duration::option")]
    /// Optional maximum duration of one tick; disabled by default.
    ///
    /// A deadline drops the tick future and records a failed attempt before the
    /// ordinary failure backoff. It does not terminate blocking work or undo
    /// external effects. Lease acquisition and idle waits are outside this budget.
    /// During shutdown, the earlier tick or shutdown deadline applies.
    pub tick_timeout: Option<Duration>,
    #[serde(with = "crate::settings::human_duration")]
    /// Maximum time allowed for graceful worker shutdown.
    pub shutdown_timeout: Duration,
    /// Delay policy used after worker-level failures.
    pub failure_backoff: BackoffSettings,
    /// Randomizes only worker-level failure delays; disabled by default.
    ///
    /// For the capped exponential delay `d`, samples uniformly between
    /// `max(ceil(d / 2), min(1 ms, d))` and `d`, inclusive. This never exceeds
    /// `failure_backoff.max_delay` or turns a positive delay into zero.
    /// Successful tick schedules, task retry due times, and lease waits are unchanged.
    pub failure_backoff_jitter: bool,
    /// Optional distributed lease configuration.
    pub lease: Option<WorkerLeaseSettings>,
}

impl Default for WorkerSettings {
    fn default() -> Self {
        Self::from(WorkerConfig::default())
    }
}

impl From<WorkerConfig> for WorkerSettings {
    fn from(value: WorkerConfig) -> Self {
        Self {
            enabled: value.enabled,
            poll_interval: value.poll_interval,
            min_queue_interval: value.min_queue_interval,
            startup_delay: value.startup_delay,
            tick_timeout: value.tick_timeout,
            shutdown_timeout: value.shutdown_timeout,
            failure_backoff: BackoffSettings::from(value.failure_backoff),
            failure_backoff_jitter: value.failure_backoff_jitter,
            lease: value.lease.map(WorkerLeaseSettings::from),
        }
    }
}

impl WorkerSettings {
    #[must_use]
    /// Configures enabled and returns the updated value.
    pub const fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    #[must_use]
    /// Configures poll interval and returns the updated value.
    pub const fn with_poll_interval(mut self, poll_interval: Duration) -> Self {
        self.poll_interval = poll_interval;
        self
    }

    /// Sets the minimum spacing for queue schedules; must be greater than zero.
    #[must_use]
    pub const fn with_min_queue_interval(mut self, interval: Duration) -> Self {
        self.min_queue_interval = interval;
        self
    }

    #[must_use]
    /// Configures startup delay and returns the updated value.
    pub const fn with_startup_delay(mut self, startup_delay: Duration) -> Self {
        self.startup_delay = startup_delay;
        self
    }

    /// Sets the optional tick deadline; `Some` must be nonzero and fit the timer range.
    #[must_use]
    pub const fn with_tick_timeout(mut self, tick_timeout: Option<Duration>) -> Self {
        self.tick_timeout = tick_timeout;
        self
    }

    #[must_use]
    /// Configures shutdown timeout and returns the updated value.
    pub const fn with_shutdown_timeout(mut self, shutdown_timeout: Duration) -> Self {
        self.shutdown_timeout = shutdown_timeout;
        self
    }

    #[must_use]
    /// Configures failure backoff and returns the updated value.
    pub const fn with_failure_backoff(mut self, failure_backoff: BackoffSettings) -> Self {
        self.failure_backoff = failure_backoff;
        self
    }

    /// Enables bounded jitter for worker-level failure delays only.
    /// See [`Self::failure_backoff_jitter`] for the sampling interval.
    #[must_use]
    pub const fn with_failure_backoff_jitter(mut self, enabled: bool) -> Self {
        self.failure_backoff_jitter = enabled;
        self
    }

    #[must_use]
    /// Configures lease and returns the updated value.
    pub const fn with_lease(mut self, lease: Option<WorkerLeaseSettings>) -> Self {
        self.lease = lease;
        self
    }

    /// Builds validated worker configuration.
    pub fn build(self) -> Result<WorkerConfig, SettingsValidationError> {
        self.validate()?;
        Ok(WorkerConfig {
            enabled: self.enabled,
            poll_interval: self.poll_interval,
            min_queue_interval: self.min_queue_interval,
            startup_delay: self.startup_delay,
            tick_timeout: self.tick_timeout,
            shutdown_timeout: self.shutdown_timeout,
            failure_backoff: self.failure_backoff.into_config(),
            failure_backoff_jitter: self.failure_backoff_jitter,
            lease: self.lease.map(WorkerLeaseSettings::into_config),
        })
    }

    /// Validates all worker settings.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("worker")
    }

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        issues.require(
            (!self.enabled || !self.poll_interval.is_zero())
                && time::Instant::now()
                    .checked_add(self.poll_interval)
                    .is_some(),
            format!("{path}.poll_interval"),
            "must fit the runtime timer range and be greater than zero when worker is enabled",
        );
        issues.require(
            time::Instant::now()
                .checked_add(self.startup_delay)
                .is_some(),
            format!("{path}.startup_delay"),
            "must fit the runtime timer range",
        );
        issues.require(
            !self.min_queue_interval.is_zero()
                && time::Instant::now()
                    .checked_add(self.min_queue_interval)
                    .is_some(),
            format!("{path}.min_queue_interval"),
            "must be greater than zero and fit the runtime timer range",
        );
        issues.require(
            !self.shutdown_timeout.is_zero()
                && time::Instant::now()
                    .checked_add(self.shutdown_timeout)
                    .is_some(),
            format!("{path}.shutdown_timeout"),
            "must be greater than zero and fit the runtime timer range",
        );
        if let Some(timeout) = self.tick_timeout {
            issues.require(
                !timeout.is_zero() && time::Instant::now().checked_add(timeout).is_some(),
                format!("{path}.tick_timeout"),
                "must be greater than zero and fit the runtime timer range",
            );
        }
        issues.extend_result(
            self.failure_backoff
                .validate_at(&format!("{path}.failure_backoff")),
        );
        if let Some(lease) = &self.lease {
            issues.extend_result(lease.validate_at(&format!("{path}.lease")));
        }
        issues.into_result()
    }
}

/// Exponential retry backoff settings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BackoffConfig {
    pub(super) initial_delay: Duration,
    pub(super) max_delay: Duration,
    pub(super) multiplier: u32,
}

impl Default for BackoffConfig {
    fn default() -> Self {
        Self {
            initial_delay: Duration::from_secs(1),
            max_delay: Duration::from_secs(60),
            multiplier: 2,
        }
    }
}

impl BackoffConfig {
    /// Creates validated exponential backoff configuration.
    pub fn new(
        initial_delay: Duration,
        max_delay: Duration,
        multiplier: u32,
    ) -> Result<Self, SettingsValidationError> {
        BackoffSettings::new(initial_delay, max_delay, multiplier).build()
    }

    /// Returns the first retry delay.
    #[must_use]
    pub const fn initial_delay(&self) -> Duration {
        self.initial_delay
    }

    /// Returns the maximum retry delay.
    #[must_use]
    pub const fn max_delay(&self) -> Duration {
        self.max_delay
    }

    /// Returns the multiplier applied after each failure.
    #[must_use]
    pub const fn multiplier(&self) -> u32 {
        self.multiplier
    }
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for backoff.
pub struct BackoffSettings {
    #[serde(with = "crate::settings::human_duration")]
    /// Delay after the first failure.
    pub initial_delay: Duration,
    #[serde(with = "crate::settings::human_duration")]
    /// Upper bound for a computed delay.
    pub max_delay: Duration,
    /// Integer growth factor applied after each failure.
    pub multiplier: u32,
}

impl Default for BackoffSettings {
    fn default() -> Self {
        Self::from(BackoffConfig::default())
    }
}

impl From<BackoffConfig> for BackoffSettings {
    fn from(value: BackoffConfig) -> Self {
        Self {
            initial_delay: value.initial_delay,
            max_delay: value.max_delay,
            multiplier: value.multiplier,
        }
    }
}

impl BackoffSettings {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(initial_delay: Duration, max_delay: Duration, multiplier: u32) -> Self {
        Self {
            initial_delay,
            max_delay,
            multiplier,
        }
    }

    #[must_use]
    /// Configures initial delay and returns the updated value.
    pub const fn with_initial_delay(mut self, initial_delay: Duration) -> Self {
        self.initial_delay = initial_delay;
        self
    }

    #[must_use]
    /// Configures maximum delay and returns the updated value.
    pub const fn with_max_delay(mut self, max_delay: Duration) -> Self {
        self.max_delay = max_delay;
        self
    }

    #[must_use]
    /// Configures multiplier and returns the updated value.
    pub const fn with_multiplier(mut self, multiplier: u32) -> Self {
        self.multiplier = multiplier;
        self
    }

    /// Builds validated backoff configuration.
    pub fn build(self) -> Result<BackoffConfig, SettingsValidationError> {
        self.validate()?;
        Ok(self.into_config())
    }

    pub(super) fn into_config(self) -> BackoffConfig {
        BackoffConfig {
            initial_delay: self.initial_delay,
            max_delay: self.max_delay,
            multiplier: self.multiplier,
        }
    }

    /// Validates all backoff settings.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("worker.failure_backoff")
    }

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        issues.require(
            !self.initial_delay.is_zero()
                && time::Instant::now()
                    .checked_add(self.initial_delay)
                    .is_some(),
            format!("{path}.initial_delay"),
            "must be greater than zero and fit the runtime timer range",
        );
        issues.require(
            self.max_delay >= self.initial_delay
                && time::Instant::now().checked_add(self.max_delay).is_some(),
            format!("{path}.max_delay"),
            "must fit the runtime timer range and be greater than or equal to initial_delay",
        );
        issues.require(
            self.multiplier >= 1,
            format!("{path}.multiplier"),
            "must be greater than or equal to one",
        );
        issues.into_result()
    }
}

/// Deterministic exponential retry backoff state.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RetryBackoff {
    config: BackoffConfig,
    next_delay: Duration,
}

impl RetryBackoff {
    /// Creates a new backoff state.
    #[must_use]
    pub fn new(config: BackoffConfig) -> Self {
        Self {
            config,
            next_delay: config.initial_delay,
        }
    }

    /// Records a failed attempt and returns the delay to use now.
    pub fn record_failure(&mut self) -> Duration {
        let current = self.next_delay;
        self.next_delay = current
            .saturating_mul(self.config.multiplier)
            .min(self.config.max_delay);
        current
    }

    /// Resets the backoff to the initial delay.
    pub fn reset(&mut self) {
        self.next_delay = self.config.initial_delay;
    }
}

/// Optional lease settings for workers coordinated by application storage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct WorkerLeaseConfig {
    pub(super) lease_duration: Duration,
    pub(super) renew_before: Duration,
    pub(super) operation_timeout: Duration,
}

impl WorkerLeaseConfig {
    /// Creates validated worker lease configuration.
    pub fn new(
        lease_duration: Duration,
        renew_before: Duration,
        operation_timeout: Duration,
    ) -> Result<Self, SettingsValidationError> {
        WorkerLeaseSettings::new(lease_duration, renew_before, operation_timeout).build()
    }

    /// Returns how long a lease is valid.
    #[must_use]
    pub const fn lease_duration(&self) -> Duration {
        self.lease_duration
    }

    /// Returns how long before expiry a holder starts renewal.
    #[must_use]
    pub const fn renew_before(&self) -> Duration {
        self.renew_before
    }

    /// Returns the acquire/renew operation deadline.
    #[must_use]
    pub const fn operation_timeout(&self) -> Duration {
        self.operation_timeout
    }
}

#[cfg_attr(feature = "tier", derive(tier::TierConfig))]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
/// Serializable settings for worker lease.
pub struct WorkerLeaseSettings {
    #[serde(with = "crate::settings::human_duration")]
    /// Duration for which a lease remains valid.
    pub lease_duration: Duration,
    #[serde(with = "crate::settings::human_duration")]
    /// Safety margin before lease expiry at which renewal starts.
    pub renew_before: Duration,
    #[serde(with = "crate::settings::human_duration")]
    /// Deadline for one acquire or renew storage operation.
    pub operation_timeout: Duration,
}

impl From<WorkerLeaseConfig> for WorkerLeaseSettings {
    fn from(value: WorkerLeaseConfig) -> Self {
        Self {
            lease_duration: value.lease_duration,
            renew_before: value.renew_before,
            operation_timeout: value.operation_timeout,
        }
    }
}

impl WorkerLeaseSettings {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(
        lease_duration: Duration,
        renew_before: Duration,
        operation_timeout: Duration,
    ) -> Self {
        Self {
            lease_duration,
            renew_before,
            operation_timeout,
        }
    }

    #[must_use]
    /// Configures lease duration and returns the updated value.
    pub const fn with_lease_duration(mut self, lease_duration: Duration) -> Self {
        self.lease_duration = lease_duration;
        self
    }

    #[must_use]
    /// Configures the renewal safety margin and returns the updated value.
    pub const fn with_renew_before(mut self, renew_before: Duration) -> Self {
        self.renew_before = renew_before;
        self
    }

    #[must_use]
    /// Configures the acquire/renew deadline and returns the updated value.
    pub const fn with_operation_timeout(mut self, operation_timeout: Duration) -> Self {
        self.operation_timeout = operation_timeout;
        self
    }

    /// Builds validated worker lease configuration.
    pub fn build(self) -> Result<WorkerLeaseConfig, SettingsValidationError> {
        self.validate()?;
        Ok(self.into_config())
    }

    fn into_config(self) -> WorkerLeaseConfig {
        WorkerLeaseConfig {
            lease_duration: self.lease_duration,
            renew_before: self.renew_before,
            operation_timeout: self.operation_timeout,
        }
    }

    /// Validates all worker lease settings.
    pub fn validate(&self) -> Result<(), SettingsValidationError> {
        self.validate_at("worker.lease")
    }

    pub(crate) fn validate_at(&self, path: &str) -> Result<(), SettingsValidationError> {
        let mut issues = SettingsIssues::new();
        issues.require(
            !self.lease_duration.is_zero()
                && Instant::now().checked_add(self.lease_duration).is_some(),
            format!("{path}.lease_duration"),
            "must be greater than zero and fit the monotonic clock range",
        );
        issues.require(
            !self.renew_before.is_zero() && self.renew_before < self.lease_duration,
            format!("{path}.renew_before"),
            "must be greater than zero and less than lease_duration",
        );
        issues.require(
            !self.operation_timeout.is_zero()
                && self.operation_timeout < self.renew_before
                && time::Instant::now()
                    .checked_add(self.operation_timeout)
                    .is_some(),
            format!("{path}.operation_timeout"),
            "must be greater than zero, fit the runtime timer range, and be less than renew_before",
        );
        issues.into_result()
    }
}

/// Worker configuration errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum WorkerConfigError {
    #[error("worker lease_duration must be greater than zero")]
    /// The lease duration is invalid.
    InvalidLeaseDuration,
    #[error("worker name must be non-empty and less than or equal to {max} bytes")]
    /// The worker name is invalid.
    InvalidWorkerName {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("worker lease owner must be non-empty and less than or equal to {max} bytes")]
    /// The lease owner is invalid.
    InvalidLeaseOwner {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    #[error("outbox max_attempts must be greater than zero")]
    /// The outbox maximum attempts is invalid.
    InvalidOutboxMaxAttempts,
}

impl ClassifyError for WorkerConfigError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::InvalidLeaseDuration => "worker_invalid_lease_duration",
            Self::InvalidWorkerName { .. } => "worker_invalid_name",
            Self::InvalidLeaseOwner { .. } => "worker_invalid_lease_owner",
            Self::InvalidOutboxMaxAttempts => "outbox_invalid_max_attempts",
        })
    }
}

pub(super) fn normalize_worker_identifier(value: impl Into<String>) -> String {
    value.into().trim().to_owned()
}

pub(super) fn validate_worker_name(value: &str) -> Result<(), WorkerConfigError> {
    validate_worker_identifier(value, MAX_WORKER_NAME_LENGTH).map_err(|()| {
        WorkerConfigError::InvalidWorkerName {
            max: MAX_WORKER_NAME_LENGTH,
        }
    })
}

pub(super) fn validate_lease_owner(value: &str) -> Result<(), WorkerConfigError> {
    validate_worker_identifier(value, MAX_WORKER_LEASE_OWNER_LENGTH).map_err(|()| {
        WorkerConfigError::InvalidLeaseOwner {
            max: MAX_WORKER_LEASE_OWNER_LENGTH,
        }
    })
}

fn validate_worker_identifier(value: &str, max_len: usize) -> Result<(), ()> {
    if value.is_empty()
        || value.len() > max_len
        || value != value.trim()
        || value.chars().any(char::is_control)
    {
        return Err(());
    }
    Ok(())
}