legit-streams 0.1.3

A Redis Streams work contract for task and result envelopes, with a worker loop that leases, reclaims and replies, a producer and a result reader
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
//! The fast lane: a request-and-reply path for work done while a caller waits.
//!
//! A caller adds a task to a fast task stream with two more fields: `reply_to`, a reply key of its
//! own, `results:{app}:{kind}:rpc:{task_id}`, and `deadline_ms`, the Unix time in milliseconds after
//! which it no longer waits. A fast worker reads the stream with a consumer group, deletes what it
//! can't or needn't answer, and adds one result to each reply key, which then expires. The caller
//! blocks on its reply key, deletes it, and falls back when nothing came in time.

use std::collections::HashMap;
use std::fmt;
use std::panic::{self, AssertUnwindSafe};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread;
use std::time::Duration;

use crate::clock::Clock;
use crate::entry::{Entry, EntryId};
use crate::error::{Error, Result};
use crate::fields::{self, Limits};
use crate::result::{ResultBuilder, Status, TaskResult};
use crate::streams::Streams;
use crate::task::{self, APP_MAX_LEN, REPLY_TO_MAX_LEN, Task};
use crate::worker::{
    self, ACTIVE, Context, Control, FINISHING, Flight, Handler, INTERNAL, Origin, Report, Running, Stopper,
};

/// The field naming a fast task's reply key.
const REPLY_TO: &str = "reply_to";
/// The field holding a fast task's deadline.
const DEADLINE_MS: &str = "deadline_ms";
/// How long the read loop waits after a failed read before it tries again.
const READ_RETRY: Duration = Duration::from_millis(500);

/// The longest kind of a fast lane, the `{kind}` of its reply keys, in bytes.
///
/// ```
/// assert_eq!(legit_streams::KIND_MAX_LEN, 16);
/// ```
pub const KIND_MAX_LEN: usize = 16;

/// Whether `kind` can name a fast lane: 1 to [`KIND_MAX_LEN`] lowercase ASCII letters, digits, `_`
/// and `-`, such as `hash` or `image`. A [`FastWorker`] and a [`FastCaller`] each serve one kind,
/// and a worker answers only reply keys of its own.
///
/// ```
/// use legit_streams::is_valid_kind;
///
/// assert!(is_valid_kind("hash"));
/// assert!(!is_valid_kind("Text"));
/// assert!(!is_valid_kind(""));
/// assert!(!is_valid_kind("a-kind-of-17-byte"));
/// ```
#[must_use]
pub fn is_valid_kind(kind: &str) -> bool {
    task::is_name(kind, KIND_MAX_LEN, false)
}

/// The reply key of a fast task, `results:{app}:{kind}:rpc:{task_id}`: a stream of its own, which
/// only that task's result is added to. `kind` names the lane, such as `hash`.
///
/// ```
/// assert_eq!(legit_streams::rpc_reply_to("app", "hash", "app_1"), "results:app:hash:rpc:app_1");
/// ```
#[must_use]
pub fn rpc_reply_to(app: &str, kind: &str, task_id: &str) -> String {
    format!("results:{app}:{kind}:rpc:{task_id}")
}

/// Whether a fast worker of this `kind` answers a task with this `reply_to` and `task_id`: the key
/// must be exactly [`rpc_reply_to`]`(app, kind, task_id)` for this task's id and this kind, with
/// `app` passing [`is_valid_app`](crate::is_valid_app), `task_id` passing
/// [`is_valid_task_id`](crate::is_valid_task_id), and at most [`REPLY_TO_MAX_LEN`] bytes. Another
/// task's id, another kind, a bulk reply stream and trailing bytes all fail. A worker deletes a
/// task whose key fails without answering it: a reply key comes off a queue and names a Redis key,
/// so it's checked rather than trusted.
///
/// ```
/// use legit_streams::is_valid_rpc_reply_to;
///
/// assert!(is_valid_rpc_reply_to("results:app:hash:rpc:app_1", "hash", "app_1"));
/// assert!(!is_valid_rpc_reply_to("results:app:hash:rpc:app_2", "hash", "app_1"));
/// assert!(!is_valid_rpc_reply_to("results:app:hash", "hash", "app_1"));
/// assert!(!is_valid_rpc_reply_to("results:App:hash:rpc:app_1", "hash", "app_1"));
/// assert!(!is_valid_rpc_reply_to("results:app:image:rpc:app_1", "hash", "app_1"));
/// assert!(is_valid_rpc_reply_to("results:app:image:rpc:app_1", "image", "app_1"));
/// ```
#[must_use]
pub fn is_valid_rpc_reply_to(reply_to: &str, kind: &str, task_id: &str) -> bool {
    if !is_valid_kind(kind) || !task::is_valid_task_id(task_id) || reply_to.len() > REPLY_TO_MAX_LEN {
        return false;
    }
    reply_to
        .strip_suffix(task_id)
        .and_then(|head| head.strip_prefix("results:"))
        .and_then(|head| head.strip_suffix(":rpc:"))
        .and_then(|head| head.strip_suffix(kind))
        .and_then(|head| head.strip_suffix(':'))
        .is_some_and(|app| task::is_name(app, APP_MAX_LEN, false))
}

/// A consumer name for a fast worker, `<prefix>-fast_<pid>`, with no `-` when the prefix already
/// ends in `-` or `_`. This is the crate's helper, not a rule of the contract: any name unique
/// within the group works. Sharing a host's prefix keeps a host's consumers together in a listing,
/// and `fast` keeps it apart from a bulk consumer named `<prefix>_<pid>`.
///
/// ```
/// use legit_streams::fast_consumer_name;
///
/// assert_eq!(fast_consumer_name("hash-worker-host1", 4123), "hash-worker-host1-fast_4123");
/// assert_eq!(fast_consumer_name("hash-worker-", 4123), "hash-worker-fast_4123");
/// ```
#[must_use]
pub fn fast_consumer_name(prefix: &str, pid: u32) -> String {
    let separator = if prefix.ends_with(['_', '-']) { "" } else { "-" };
    format!("{prefix}{separator}fast_{pid}")
}

/// The settings of a [`FastWorker`].
///
/// ```
/// use std::time::Duration;
/// use legit_streams::FastWorkerConfig;
///
/// let config = FastWorkerConfig {
///     concurrency: 4,
///     ..FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "hash-worker-host1-fast_4123", "hash")
/// };
/// assert_eq!(config.reply_ttl, Duration::from_secs(60));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FastWorkerConfig {
    /// The fast task stream, such as `hash_tasks:fast`. It can't begin with `results:` or `dead:`.
    pub stream: String,
    /// The consumer group the worker reads it with, created when missing.
    pub group: String,
    /// This worker's consumer name, unique within the group, and the `worker_id` of its results;
    /// see [`fast_consumer_name`].
    pub consumer: String,
    /// The lane's kind, the `{kind}` of the reply keys it answers, such as `hash`; see
    /// [`is_valid_kind`]. A task whose reply key names another kind is deleted unanswered.
    pub kind: String,
    /// How many tasks run at once, each on a thread of its own; also the most one read takes. 1
    /// by default.
    pub concurrency: usize,
    /// How long one read waits for a task; also the longest a stop waits for a read in progress.
    /// 1 s by default.
    pub read_block: Duration,
    /// How long a reply key lives after each reply is added to it, so a reply whose caller gave up
    /// doesn't stay. Whole seconds, at least 1; 60 s by default, the contract's reference value.
    pub reply_ttl: Duration,
    /// The bounds on a task the worker reads and a result it writes.
    pub limits: Limits,
}

impl FastWorkerConfig {
    /// The default settings for reading `stream` with `group` as `consumer`, answering reply keys
    /// of `kind`. The kind has no default: it's checked when the worker is made.
    ///
    /// ```
    /// use legit_streams::FastWorkerConfig;
    ///
    /// let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
    /// assert_eq!(config.concurrency, 1);
    /// ```
    #[must_use]
    pub fn new(
        stream: impl Into<String>,
        group: impl Into<String>,
        consumer: impl Into<String>,
        kind: impl Into<String>,
    ) -> Self {
        Self {
            stream: stream.into(),
            group: group.into(),
            consumer: consumer.into(),
            kind: kind.into(),
            concurrency: 1,
            read_block: Duration::from_secs(1),
            reply_ttl: Duration::from_secs(60),
            limits: Limits::default(),
        }
    }

    fn validate(&self) -> Result<()> {
        let invalid = |message: &str| Err(Error::InvalidConfig(message.to_owned()));
        for (name, value) in [
            ("stream", &self.stream),
            ("group", &self.group),
            ("consumer", &self.consumer),
        ] {
            if value.is_empty() {
                return Err(Error::InvalidConfig(format!("`{name}` is empty")));
            }
        }
        worker::check_task_stream(&self.stream)?;
        if !is_valid_kind(&self.kind) {
            return invalid("`kind` must be 1 to 16 lowercase ASCII letters, digits, `_` and `-`");
        }
        if self.concurrency == 0 {
            return invalid("`concurrency` is 0; a worker runs at least one task at once");
        }
        if self.read_block.is_zero() {
            return invalid("`read_block` is 0; Redis reads `BLOCK 0` as forever");
        }
        if self.reply_ttl < Duration::from_secs(1) || self.reply_ttl.subsec_nanos() != 0 {
            return invalid("`reply_ttl` must be whole seconds, at least 1; `EXPIRE` takes seconds");
        }
        Ok(())
    }
}

/// The worker side of the fast lane. It reads a fast task stream with a consumer group and answers
/// each task on the task's own reply key, while its caller waits:
///
/// - It creates the group when missing, and again when it goes.
/// - A task whose `reply_to` fails [`is_valid_rpc_reply_to`] for its `task_id` and the worker's
///   [`FastWorkerConfig::kind`] is acknowledged and deleted unanswered.
/// - Then a task whose `deadline_ms`, a plain decimal integer of Unix milliseconds, is before the
///   worker's clock when it's read is acknowledged and deleted unanswered: its caller has given up.
///   A clock that reads exactly the deadline still answers. A missing, empty or unreadable deadline
///   (a sign, a point, an exponent, a blank) is no deadline. The deadline isn't checked again after the work, so a
///   task that ran past it is still answered.
/// - Every other entry gets exactly one result, as a [`Worker`](crate::Worker) would write it: the
///   handler's reply, its error, an `internal` error for a panic, or an error for an entry that
///   isn't a valid task. The result is added to the reply key, the key's expiry set to
///   [`FastWorkerConfig::reply_ttl`], and the task acknowledged and deleted, in that order. A write
///   that fails is logged, not retried: the caller won't wait for a retry.
/// - A task the worker can't serve gets an error result, not silence: a handler that abandons it
///   ([`Failure::abandon`](crate::Failure::abandon), or [`Context::checkpoint`] once stopping),
///   and a task no thread could be started for, are answered with an `internal` error, so the
///   caller falls back at once.
/// - Nothing is reclaimed, leased or retried. An entry a dead worker left pending is never run
///   again; an operator deletes old fast entries, and their callers have timed out.
/// - On [`Stopper::stop`] it reads no more and answers every task it has read, however long that
///   takes: a caller may still be waiting. A handler that should stop sooner checks
///   [`Context::checkpoint`], and its task is answered with an `internal` error. Then the worker
///   removes its consumer when it owns nothing.
///
/// A fast worker runs on threads of its own, so it can run in the same process as a bulk
/// [`Worker`](crate::Worker), on the same [`Streams`], without waiting for it: a bulk task holds a
/// bulk slot, never a fast one. Share one handler between them by cloning an `Arc` into each
/// closure.
///
/// ```
/// use std::time::Duration;
/// use legit_streams::{Clock, Failure, FastCaller, FastWorker, FastWorkerConfig, MemoryStreams, Reply, Task};
///
/// let clock = Clock::manual(1_700_000_000_000);
/// let streams = MemoryStreams::with_clock(clock.clone());
/// let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
/// let running = FastWorker::new(config, streams.clone(), |task: &Task, _: &_| {
///     let text = task.get("text_data").ok_or_else(|| Failure::new("invalid_task", "no `text_data`"))?;
///     Ok(Reply::new().field("result", text.len().to_string()))
/// })?
/// .clock(clock.clone())
/// .spawn()?;
///
/// let caller = FastCaller::new(streams.clone(), "hash_tasks:fast", "hash").clock(clock.clone());
/// let task = Task::builder("app", "query", "0").field("text_data", "hello").build()?;
/// let result = caller.call(&task, Duration::from_secs(3))?;
/// assert_eq!(result.get("result"), Some("5"));
///
/// running.stop();
/// clock.advance(Duration::from_secs(1));
/// assert_eq!(running.join()?.results, 1);
/// # Ok::<(), legit_streams::Error>(())
/// ```
pub struct FastWorker {
    config: Arc<FastWorkerConfig>,
    streams: Arc<dyn Streams>,
    handler: Arc<dyn Handler>,
    clock: Clock,
    control: Arc<Control>,
}

impl FastWorker {
    /// A fast worker with these settings, on the system clock.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidConfig`] for settings that can't work, such as an empty stream name, a task
    /// stream beginning with `results:` or `dead:`, a concurrency of 0, or a reply expiry under a
    /// second.
    ///
    /// ```
    /// use std::time::Duration;
    /// use legit_streams::{Error, FastWorker, FastWorkerConfig, MemoryStreams, Reply};
    ///
    /// let config = FastWorkerConfig { reply_ttl: Duration::ZERO, ..FastWorkerConfig::new("s", "g", "c", "hash") };
    /// let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()));
    /// assert!(matches!(worker, Err(Error::InvalidConfig(_))));
    /// ```
    pub fn new(config: FastWorkerConfig, streams: impl Streams + 'static, handler: impl Handler) -> Result<Self> {
        config.validate()?;
        let clock = Clock::system();
        Ok(Self {
            config: Arc::new(config),
            streams: Arc::new(streams),
            handler: Arc::new(handler),
            control: Control::new(&clock),
            clock,
        })
    }

    /// Run on `clock` rather than the system clock, such as a manual clock in tests: deadlines are
    /// checked against its time. Take [`FastWorker::stopper`] after this.
    ///
    /// ```
    /// use legit_streams::{Clock, FastWorker, FastWorkerConfig, MemoryStreams, Reply};
    ///
    /// let config = FastWorkerConfig::new("s", "g", "c", "hash");
    /// let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?.clock(Clock::manual(0));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn clock(mut self, clock: Clock) -> Self {
        self.control = Control::new(&clock);
        self.clock = clock;
        self
    }

    /// The handle that stops this worker.
    ///
    /// ```
    /// use legit_streams::{FastWorker, FastWorkerConfig, MemoryStreams, Reply};
    ///
    /// let config = FastWorkerConfig::new("s", "g", "c", "hash");
    /// let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
    /// assert!(!worker.stopper().is_stopped());
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn stopper(&self) -> Stopper {
        Stopper::new(Arc::clone(&self.control))
    }

    /// The worker's settings.
    ///
    /// ```
    /// use legit_streams::{FastWorker, FastWorkerConfig, MemoryStreams, Reply};
    ///
    /// let config = FastWorkerConfig::new("s", "g", "c", "hash");
    /// let worker = FastWorker::new(config, MemoryStreams::new(), |_: &_, _: &_| Ok(Reply::new()))?;
    /// assert_eq!(worker.config().consumer, "c");
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    #[must_use]
    pub fn config(&self) -> &FastWorkerConfig {
        &self.config
    }

    /// Run the worker on a thread of its own.
    ///
    /// # Errors
    ///
    /// [`Error::Thread`] when the thread can't be started.
    ///
    /// ```no_run
    /// use legit_streams::{FastWorker, FastWorkerConfig, RedisStreams, Reply};
    ///
    /// let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
    /// let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
    /// let running = FastWorker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?.spawn()?;
    /// running.stop();
    /// running.join()?;
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn spawn(self) -> Result<Running> {
        let stopper = self.stopper();
        let thread = thread::Builder::new()
            .name("legit-streams-fast".to_owned())
            .spawn(move || self.run())
            .map_err(|error| Error::Thread(error.to_string()))?;
        Ok(Running::new(stopper, thread))
    }

    /// Run the worker on this thread until [`Stopper::stop`].
    ///
    /// # Errors
    ///
    /// [`Error::Redis`] when the group can't be created at the start. Once running, a failed
    /// command is logged and the loop goes on, never returned.
    ///
    /// ```no_run
    /// use legit_streams::{FastWorker, FastWorkerConfig, RedisStreams, Reply};
    ///
    /// let config = FastWorkerConfig::new("hash_tasks:fast", "hash_workers", "host1-fast_1", "hash");
    /// let streams = RedisStreams::open("redis://127.0.0.1:6379")?;
    /// let report = FastWorker::new(config, streams, |_: &_, _: &_| Ok(Reply::new()))?.run()?;
    /// println!("{} answered, {} expired", report.results, report.expired);
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn run(&self) -> Result<Report> {
        let party = self.clock.party();
        party.bind();
        let config = &self.config;
        self.streams.xgroup_create(&config.stream, &config.group)?;
        let run = Arc::new(FastRun {
            config: Arc::clone(config),
            streams: Arc::clone(&self.streams),
            handler: Arc::clone(&self.handler),
            clock: self.clock.clone(),
            control: Arc::clone(&self.control),
            flights: Mutex::new(HashMap::new()),
            results: AtomicU64::new(0),
            expired: AtomicU64::new(0),
            invalid: AtomicU64::new(0),
            abandoned: AtomicU64::new(0),
        });
        tracing::info!(stream = %config.stream, group = %config.group, consumer = %config.consumer, "Fast worker started");
        run.read_loop();
        run.shut_down();
        run.remove_consumer();
        let report = Report {
            results: run.results.load(Ordering::SeqCst),
            expired: run.expired.load(Ordering::SeqCst),
            invalid: run.invalid.load(Ordering::SeqCst),
            abandoned: run.abandoned.load(Ordering::SeqCst),
            ..Report::default()
        };
        tracing::info!(
            results = report.results,
            expired = report.expired,
            invalid = report.invalid,
            abandoned = report.abandoned,
            "Fast worker stopped"
        );
        Ok(report)
    }
}

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

/// One run of a fast worker: what the read loop and the task threads share.
struct FastRun {
    config: Arc<FastWorkerConfig>,
    streams: Arc<dyn Streams>,
    handler: Arc<dyn Handler>,
    clock: Clock,
    control: Arc<Control>,
    flights: Mutex<HashMap<EntryId, Arc<Flight>>>,
    results: AtomicU64,
    expired: AtomicU64,
    invalid: AtomicU64,
    abandoned: AtomicU64,
}

impl FastRun {
    fn stopping(&self) -> bool {
        self.control.stopping.load(Ordering::SeqCst)
    }

    fn lock_flights(&self) -> MutexGuard<'_, HashMap<EntryId, Arc<Flight>>> {
        self.flights.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn read_loop(self: &Arc<Self>) {
        let config = &self.config;
        while !self.stopping() {
            let seen = self.control.wake.seen();
            let free = config.concurrency.saturating_sub(self.lock_flights().len());
            if free == 0 {
                self.clock.wait(Some((&self.control.wake, seen)), None);
                continue;
            }
            match self.streams.xreadgroup(
                &config.stream,
                &config.group,
                &config.consumer,
                free,
                Some(config.read_block),
            ) {
                // A worker asked to stop answers what it has read...
                Ok(entries) => {
                    for entry in entries {
                        self.admit(entry);
                    }
                }
                Err(error) => {
                    tracing::error!(%error, "Couldn't read fast tasks");
                    if matches!(error, Error::NoGroup { .. })
                        && let Err(error) = self.streams.xgroup_create(&config.stream, &config.group)
                    {
                        tracing::error!(%error, "Couldn't create the consumer group again");
                    }
                    let deadline = self.clock.monotonic().saturating_add(READ_RETRY);
                    self.clock.wait(Some((&self.control.wake, seen)), Some(deadline));
                }
            }
        }
    }

    /// Check an entry's reply key and deadline, then run it or delete it.
    fn admit(self: &Arc<Self>, entry: Entry) {
        let Some(reply_key) = reply_key_of(&entry.fields, &self.config.kind) else {
            tracing::warn!(entry = %entry.id, "The entry's `reply_to` isn't the reply key of its `task_id`; deleted unanswered");
            self.invalid.fetch_add(1, Ordering::SeqCst);
            self.delete(entry.id);
            return;
        };
        match deadline_of(&entry.fields) {
            Deadline::At(deadline) if is_past(self.clock.now_ms(), deadline) => {
                tracing::debug!(entry = %entry.id, "The entry is past its deadline; deleted unanswered");
                self.expired.fetch_add(1, Ordering::SeqCst);
                self.delete(entry.id);
                return;
            }
            Deadline::Unreadable => {
                tracing::warn!(entry = %entry.id, "The entry's `deadline_ms` isn't a decimal integer; it's taken as no deadline");
            }
            Deadline::At(_) | Deadline::None => {}
        }
        self.dispatch(entry, reply_key);
    }

    fn dispatch(self: &Arc<Self>, entry: Entry, reply_key: String) {
        let id = entry.id;
        let entry = Arc::new(entry);
        let reply_key = Arc::new(reply_key);
        let flight = Arc::new(Flight::default());
        self.lock_flights().insert(id, Arc::clone(&flight));
        let run = Arc::clone(self);
        let running = Arc::clone(&flight);
        let (task, key) = (Arc::clone(&entry), Arc::clone(&reply_key));
        let spawned = thread::Builder::new()
            .name("legit-streams-fast-task".to_owned())
            .spawn(move || {
                run.process(&task, &key, &running);
                run.remove_flight(task.id, &running);
                run.control.wake.raise();
            });
        if let Err(error) = spawned {
            tracing::error!(entry = %id, %error, "Couldn't start a thread for a fast task");
            self.unstarted(&entry, &reply_key, &flight);
            self.remove_flight(id, &flight);
        }
    }

    /// Answer a task no thread could be started for with an `internal` error, so its caller falls
    /// back at once rather than at its timeout.
    fn unstarted(&self, entry: &Entry, reply_key: &str, flight: &Flight) {
        let message = "the worker couldn't start a thread to run the task".to_owned();
        let result = ResultBuilder::for_raw(
            &entry.fields,
            worker::answerable_task_id(&entry.fields),
            Status::Error,
            message,
        )
        .error_type(INTERNAL);
        self.abandoned.fetch_add(1, Ordering::SeqCst);
        self.reply(
            entry.id,
            flight,
            result,
            Origin::Refusal,
            reply_key,
            self.clock.monotonic(),
        );
    }

    fn remove_flight(&self, id: EntryId, flight: &Arc<Flight>) {
        let mut flights = self.lock_flights();
        if flights.get(&id).is_some_and(|current| Arc::ptr_eq(current, flight)) {
            flights.remove(&id);
        }
    }

    fn process(&self, entry: &Entry, reply_key: &str, flight: &Arc<Flight>) {
        let started = self.clock.monotonic();
        let task = match Task::from_raw(&entry.fields, &self.config.limits) {
            Ok(task) => task,
            Err(error) => {
                tracing::warn!(entry = %entry.id, %error, "The entry isn't a valid task");
                let error_type = if matches!(error, Error::UnsupportedVersion(_)) {
                    worker::UNSUPPORTED_VERSION
                } else {
                    worker::INVALID_TASK
                };
                let task_id = worker::answerable_task_id(&entry.fields);
                let result = ResultBuilder::for_raw(&entry.fields, task_id, Status::Error, error.to_string())
                    .error_type(error_type);
                self.reply(entry.id, flight, result, Origin::Refusal, reply_key, started);
                return;
            }
        };
        // Read with `>` and never claimed, so this is always the first delivery...
        let context = Context::new(
            entry.id,
            1,
            false,
            Arc::clone(flight),
            Arc::clone(&self.control),
            self.clock.clone(),
            started,
        );
        tracing::debug!(task_id = task.task_id(), entry = %entry.id, "Running a fast task");
        let outcome = panic::catch_unwind(AssertUnwindSafe(|| self.handler.handle(&task, &context)));
        let result = worker::answer(&task, outcome).unwrap_or_else(|| {
            // A fast task gets one result, even one its handler abandoned...
            let message = if self.stopping() {
                "the worker stopped before the task finished"
            } else {
                "the handler abandoned the task before it finished"
            };
            tracing::info!(
                task_id = task.task_id(),
                "The handler abandoned a fast task; it's answered with an `internal` error"
            );
            self.abandoned.fetch_add(1, Ordering::SeqCst);
            TaskResult::failure(task.task_id(), message)
                .echo(&task)
                .error_type(INTERNAL)
        });
        self.reply(entry.id, flight, result, Origin::Handler, reply_key, started);
    }

    /// Add the result to the reply key and set its expiry, then acknowledge and delete the task.
    fn reply(
        &self,
        id: EntryId,
        flight: &Flight,
        result: ResultBuilder,
        origin: Origin,
        reply_key: &str,
        started: Duration,
    ) {
        if !flight.moves(ACTIVE, FINISHING) {
            return;
        }
        let config = &self.config;
        let elapsed = self.clock.monotonic().saturating_sub(started);
        let result = result
            .worker_id(&config.consumer)
            .processing_ms(u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX));
        let fields = worker::result_fields(&config.limits, result, origin);
        match self
            .streams
            .xadd_expire(reply_key, &fields::as_bytes(&fields), config.reply_ttl)
        {
            Ok(_) => {
                self.results.fetch_add(1, Ordering::SeqCst);
            }
            Err(error) => tracing::error!(entry = %id, %error, "Couldn't write a fast reply; its caller times out"),
        }
        // Acknowledged either way: no one would ever answer it...
        self.delete(id);
    }

    /// Acknowledge and delete an entry; nothing reclaims a fast entry, so it's never left pending.
    fn delete(&self, id: EntryId) {
        let config = &self.config;
        if let Err(error) = self.streams.xack_xdel(&config.stream, &config.group, &[id]) {
            tracing::error!(entry = %id, %error, "Couldn't acknowledge a fast task; it stays pending until it's expired");
        }
    }

    /// Wait for every task the worker has read to finish and be answered, however long it takes:
    /// a worker asked to stop answers what it has read, since a caller may still be waiting.
    fn shut_down(&self) {
        loop {
            let seen = self.control.wake.seen();
            if self.lock_flights().is_empty() {
                return;
            }
            self.clock.wait(Some((&self.control.wake, seen)), None);
        }
    }

    /// Remove this worker's consumer from the group, unless it still owns entries.
    fn remove_consumer(&self) {
        let config = &self.config;
        match self
            .streams
            .xpending_consumer(&config.stream, &config.group, &config.consumer, 1)
        {
            Ok(owned) if owned.is_empty() => {
                if let Err(error) = self
                    .streams
                    .xgroup_delconsumer(&config.stream, &config.group, &config.consumer)
                {
                    tracing::debug!(%error, "Couldn't remove the consumer");
                }
            }
            Ok(_) => {}
            Err(error) => tracing::debug!(%error, "Couldn't check what the consumer owns"),
        }
    }
}

/// The entry's reply key, when it's the valid one for its task id and this lane's kind.
fn reply_key_of(raw: &[(Vec<u8>, Vec<u8>)], kind: &str) -> Option<String> {
    let reply_to = fields::last(raw, REPLY_TO)?;
    let task_id = fields::last(raw, "task_id")?;
    is_valid_rpc_reply_to(reply_to, kind, task_id).then(|| reply_to.to_owned())
}

/// A fast task's deadline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Deadline {
    /// No `deadline_ms`, or an empty one.
    None,
    /// A `deadline_ms` that isn't a plain decimal integer, which counts as none.
    Unreadable,
    /// Unix time in milliseconds.
    At(u64),
}

fn deadline_of(raw: &[(Vec<u8>, Vec<u8>)]) -> Deadline {
    let Some((_, value)) = raw.iter().rev().find(|(key, _)| key == DEADLINE_MS.as_bytes()) else {
        return Deadline::None;
    };
    if value.is_empty() {
        return Deadline::None;
    }
    // A plain decimal integer: digits only, no sign, blank, point or exponent...
    if !value.iter().all(u8::is_ascii_digit) {
        return Deadline::Unreadable;
    }
    std::str::from_utf8(value)
        .ok()
        .and_then(|text| text.parse().ok())
        .map_or(Deadline::Unreadable, Deadline::At)
}

/// Whether `now_ms` is past a deadline: strictly after it, so a worker whose clock reads exactly
/// the deadline still answers. There is no tolerance either way.
const fn is_past(now_ms: u64, deadline: u64) -> bool {
    now_ms > deadline
}

/// Sends fast-lane tasks and waits for their replies.
///
/// [`FastCaller::call`] adds the task to the fast task stream with a reply key of its own and a
/// deadline, blocks on the reply key, deletes it, and returns the result, or
/// [`Error::Timeout`] when none came in time. See [`FastWorker`] for a full exchange.
///
/// ```
/// use std::time::Duration;
/// use legit_streams::{Error, FastCaller, MemoryStreams, Task};
///
/// // No worker serves this stream, so the call times out...
/// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "hash");
/// let task = Task::builder("app", "query", "0").field("text_data", "hello").build()?;
/// match caller.call(&task, Duration::from_millis(5)) {
///     Err(Error::Timeout { .. }) => { /* fall back */ }
///     other => panic!("{other:?}"),
/// }
/// # Ok::<(), legit_streams::Error>(())
/// ```
#[derive(Clone)]
pub struct FastCaller {
    streams: Arc<dyn Streams>,
    stream: String,
    kind: String,
    clock: Clock,
    limits: Limits,
}

impl FastCaller {
    /// A caller sending to the fast task stream `stream`, for the fast lane of `kind`, the
    /// `{kind}` of its reply keys, on the system clock. The kind has no default: a call checks it
    /// with [`is_valid_kind`].
    ///
    /// ```
    /// use legit_streams::{FastCaller, MemoryStreams};
    ///
    /// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "hash");
    /// # let _ = caller;
    /// ```
    #[must_use]
    pub fn new(streams: impl Streams + 'static, stream: impl Into<String>, kind: impl Into<String>) -> Self {
        Self {
            streams: Arc::new(streams),
            stream: stream.into(),
            kind: kind.into(),
            clock: Clock::system(),
            limits: Limits::default(),
        }
    }

    /// Take deadlines from `clock` rather than the system clock, such as a manual clock in tests.
    ///
    /// ```
    /// use legit_streams::{Clock, FastCaller, MemoryStreams};
    ///
    /// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "hash").clock(Clock::manual(0));
    /// # let _ = caller;
    /// ```
    #[must_use]
    pub fn clock(mut self, clock: Clock) -> Self {
        self.clock = clock;
        self
    }

    /// Set the bounds on a reply entry.
    ///
    /// ```
    /// use legit_streams::{FastCaller, Limits, MemoryStreams};
    ///
    /// let limits = Limits { max_entry_bytes: 1024 * 1024, ..Limits::default() };
    /// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "hash").limits(limits);
    /// # let _ = caller;
    /// ```
    #[must_use]
    pub const fn limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Send `task` and wait up to `timeout` for its result.
    ///
    /// The task goes to the fast task stream with two fields set, replacing any it has:
    /// `reply_to`, its reply key [`rpc_reply_to`]`(source, kind, task_id)`, right after `v`, and
    /// `deadline_ms`, the caller's clock plus `timeout` in Unix milliseconds, last. The call then
    /// reads the reply key from its start, `XREAD … BLOCK <ms> STREAMS <key> 0`: the key is this
    /// call's alone, so a reply that arrived before the read began is the first entry there, and
    /// none is missed. Once a reply is read, or the wait ends, the key is deleted. A timeout under
    /// a millisecond waits a millisecond.
    ///
    /// A reply counts only when it's a result whose `task_id` is the task's own and whose `status`
    /// is exactly `success` or `error`. Anything else on the key isn't a reply: the call logs it,
    /// skips it and goes on reading the key until the deadline, so a stray entry ends as a timeout,
    /// never as a result.
    ///
    /// The result comes back as it was written, success or error: check
    /// [`TaskResult::is_success`].
    ///
    /// The task's id must carry at least 64 random bits, as the `{app}_{ULID}` id the builder
    /// generates does: the reply key is named after it, and an id another party can guess is a
    /// key it can answer. A caller that sets its own id with
    /// [`TaskBuilder::task_id`](crate::TaskBuilder::task_id) owns that.
    ///
    /// # Errors
    ///
    /// - [`Error::Timeout`] when no reply came within `timeout`. The call has deleted its task
    ///   from the stream, so no worker starts it, and its reply key, and a reply that comes later
    ///   expires with the key. Fall back.
    /// - [`Error::InvalidConfig`] when the caller's stream begins with `results:` or `dead:`, and
    ///   [`Error::InvalidValue`] when the reply key wouldn't pass [`is_valid_rpc_reply_to`], such
    ///   as for a caller whose kind fails [`is_valid_kind`]; nothing is sent.
    /// - [`Error::TooLarge`] when the request, the task with `reply_to`, `deadline_ms` and, for a
    ///   task read without one, `v` added, is over the default [`Limits`]; nothing is sent.
    /// - [`Error::Redis`] when the task can't be sent or the key can't be read; after a failed
    ///   read the task and key are deleted as on a timeout.
    ///
    /// ```
    /// use std::time::Duration;
    /// use legit_streams::{Error, FastCaller, MemoryStreams, Task};
    ///
    /// let caller = FastCaller::new(MemoryStreams::new(), "hash_tasks:fast", "Text");
    /// let task = Task::builder("app", "query", "0").build()?;
    /// assert!(matches!(caller.call(&task, Duration::from_secs(1)), Err(Error::InvalidValue { .. })));
    ///
    /// let caller = FastCaller::new(MemoryStreams::new(), "results:app:hash", "hash");
    /// assert!(matches!(caller.call(&task, Duration::from_secs(1)), Err(Error::InvalidConfig(_))));
    /// # Ok::<(), legit_streams::Error>(())
    /// ```
    pub fn call(&self, task: &Task, timeout: Duration) -> Result<TaskResult> {
        worker::check_task_stream(&self.stream)?;
        let timeout = timeout.max(Duration::from_millis(1));
        let task_id = task.task_id();
        let reply_key = rpc_reply_to(task.source(), &self.kind, task_id);
        if !is_valid_rpc_reply_to(&reply_key, &self.kind, task_id) {
            return Err(Error::InvalidValue {
                field: REPLY_TO.to_owned(),
                expected: "`results:<source>:<kind>:rpc:<task_id>`, with a `source` of 1 to 32 and a kind of 1 to 16 \
                           lowercase ASCII letters, digits, `_` and `-`",
            });
        }
        let timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
        let deadline_ms = self.clock.now_ms().saturating_add(timeout_ms);
        let fields = request_fields(task, &reply_key, deadline_ms);
        // The added fields can take a task at a bound over it, and a worker would refuse it...
        fields::check_strings(&fields, &Limits::default())?;
        let deadline = self.clock.monotonic().saturating_add(timeout);
        let id = self.streams.xadd(&self.stream, &fields::as_bytes(&fields))?;
        let mut after = EntryId::ZERO;
        loop {
            let left = deadline.saturating_sub(self.clock.monotonic());
            if left.is_zero() {
                self.abandon(id, &reply_key);
                return Err(Error::Timeout {
                    task_id: task_id.to_owned(),
                    timeout,
                });
            }
            let entry = match self.streams.xread(&reply_key, after, 1, Some(left)) {
                Ok(entries) => entries.into_iter().next(),
                Err(error) => {
                    self.abandon(id, &reply_key);
                    return Err(error);
                }
            };
            let Some(entry) = entry else {
                continue;
            };
            after = entry.id;
            match TaskResult::from_raw(&entry.fields, &self.limits) {
                Ok(result) if result.task_id() == task_id => {
                    self.forget(&reply_key);
                    return Ok(result);
                }
                Ok(_) => {
                    tracing::warn!(entry = %entry.id, "An entry on a reply key names another task; it isn't a reply");
                }
                Err(error) => {
                    tracing::warn!(entry = %entry.id, %error, "An entry on a reply key isn't a result; it isn't a reply");
                }
            }
        }
    }

    /// Take the task back, so no worker starts it, and delete the reply key. Best effort: a
    /// worker skips the task once its deadline passes, and a late reply expires.
    fn abandon(&self, id: EntryId, reply_key: &str) {
        if let Err(error) = self.streams.xdel(&self.stream, &[id]) {
            tracing::debug!(%error, "Couldn't take back a fast task; its deadline stops it");
        }
        self.forget(reply_key);
    }

    fn forget(&self, reply_key: &str) {
        if let Err(error) = self.streams.del(&[reply_key]) {
            tracing::debug!(%error, "Couldn't delete a reply key; it expires");
        }
    }
}

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

/// The fields of a fast request: the task's, with `v` = `1` (added after `source` when a task
/// read from an older producer had none), `reply_to` after `v` and `deadline_ms` last.
fn request_fields(task: &Task, reply_key: &str, deadline_ms: u64) -> Vec<(String, String)> {
    let wire = task.wire_fields();
    let mut fields = Vec::with_capacity(wire.len() + 2);
    for (name, value) in wire {
        if name == REPLY_TO || name == DEADLINE_MS {
            continue;
        }
        let version = name == "v";
        fields.push((name, value));
        if version {
            fields.push((REPLY_TO.to_owned(), reply_key.to_owned()));
        }
    }
    fields.push((DEADLINE_MS.to_owned(), deadline_ms.to_string()));
    fields
}

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

    use super::{Deadline, FastRun, FastWorkerConfig, deadline_of, is_past, rpc_reply_to};
    use crate::clock::Clock;
    use crate::memory::MemoryStreams;
    use crate::result::TaskResult;
    use crate::streams::Streams;
    use crate::task::Task;
    use crate::worker::{Control, Flight, Reply};

    #[test]
    fn a_task_no_thread_could_be_started_for_is_answered_with_an_internal_error() {
        let clock = Clock::manual(1_700_000_000_000);
        let streams = MemoryStreams::with_clock(clock.clone());
        let config = FastWorkerConfig::new("tasks:fast", "workers", "fast-1", "text");
        streams.xgroup_create(&config.stream, &config.group).expect("group");
        let key = rpc_reply_to("app", "text", "app_1");
        let mut fields = Task::builder("app", "query", "0")
            .task_id("app_1")
            .build()
            .expect("task")
            .into_fields();
        fields.push(("reply_to".to_owned(), key.clone()));
        let pairs: Vec<(&[u8], &[u8])> = fields.iter().map(|(k, v)| (k.as_bytes(), v.as_bytes())).collect();
        streams.xadd(&config.stream, &pairs).expect("the request");
        let entry = streams
            .xreadgroup(&config.stream, &config.group, &config.consumer, 1, None)
            .expect("read")
            .remove(0);
        let run = FastRun {
            config: Arc::new(config),
            streams: Arc::new(streams.clone()),
            handler: Arc::new(|_: &Task, _: &_| Ok(Reply::new())),
            control: Control::new(&clock),
            clock,
            flights: Mutex::new(HashMap::new()),
            results: AtomicU64::new(0),
            expired: AtomicU64::new(0),
            invalid: AtomicU64::new(0),
            abandoned: AtomicU64::new(0),
        };
        run.unstarted(&entry, &key, &Flight::default());

        let reply = TaskResult::from_entry(&streams.entries(&key)[0]).expect("one reply");
        assert_eq!(reply.task_id(), "app_1");
        assert_eq!(reply.error_type(), Some("internal"));
        assert_eq!(reply.model_type(), Some("query"));
        assert_eq!(streams.xlen("tasks:fast"), Ok(0), "the request is removed");
        assert_eq!(
            (run.results.load(Ordering::SeqCst), run.abandoned.load(Ordering::SeqCst)),
            (1, 1)
        );
    }

    fn raw(value: &[u8]) -> Vec<(Vec<u8>, Vec<u8>)> {
        vec![(b"deadline_ms".to_vec(), value.to_vec())]
    }

    #[test]
    fn a_deadline_is_a_plain_decimal_integer() {
        assert_eq!(deadline_of(&[]), Deadline::None);
        assert_eq!(deadline_of(&raw(b"")), Deadline::None);
        assert_eq!(deadline_of(&raw(b"1700000000000")), Deadline::At(1_700_000_000_000));
        assert_eq!(deadline_of(&raw(b"0001")), Deadline::At(1));
        for unreadable in [
            &b"   "[..],
            b" 1700000000000 ",
            b"1.7e12",
            b"1700000000000.0",
            b"1_700_000_000_000",
            b"-5",
            b"+5",
            b"soon",
            b"inf",
            b"NaN",
            b"0x10",
            b"99999999999999999999999",
            &[0xff, 0x31],
        ] {
            assert_eq!(
                deadline_of(&raw(unreadable)),
                Deadline::Unreadable,
                "{}",
                String::from_utf8_lossy(unreadable)
            );
        }
        // A later field replaces an earlier one, as a reader of repeated names takes the last...
        let twice = vec![
            (b"deadline_ms".to_vec(), b"1".to_vec()),
            (b"deadline_ms".to_vec(), b"2".to_vec()),
        ];
        assert_eq!(deadline_of(&twice), Deadline::At(2));
    }

    #[test]
    fn a_deadline_passes_strictly_after_its_millisecond() {
        assert!(!is_past(1_000, 1_000));
        assert!(is_past(1_001, 1_000));
        assert!(!is_past(999, 1_000));
    }
}