hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
//! The worker runtime: the pieces that keep a worker connected to the engine
//! and run the actions it hands out.
//!
//! [`WorkerBuilder`] assembles them and owns the startup order; [`Worker::run`]
//! owns what happens while the worker is up and how it comes down.

pub(crate) mod events;
pub(crate) mod heartbeat;
pub(crate) mod listener;
pub(crate) mod runner;

use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use hatchet_proto::prost_types::Timestamp;
use hatchet_proto::root::{
    AssignedAction, BatchActionEvent, HeartbeatRequest, RuntimeInfo, StepActionEvent,
    WorkerListenRequest, WorkerRegisterRequest, WorkerUnsubscribeRequest,
};
use hatchet_proto::v1;
use tokio::sync::mpsc;
use tokio_stream::Stream;
use tokio_util::sync::CancellationToken;
use tonic::{Code, Request, Status};

use crate::declare::{Register, RegisteredAction, WorkflowDef};
use crate::durable::eviction::{self, EvictionBook};
use crate::durable::stream::DurableStream;
use crate::worker::runner::{BatchReporter, DurableSetup, Reporter, Runner};
use crate::{Client, Error, LabelValue, Result, retry, version};

/// How many runs a worker takes on at once unless it says otherwise. The same
/// default as the official Go SDK.
const DEFAULT_SLOTS: u32 = 100;

/// How many durable runs a worker holds at once unless it says otherwise. The
/// same default as the official Go SDK (`sdks/go/client.go:193-196`), and
/// deliberately far above [`DEFAULT_SLOTS`]: a durable run that is waiting on
/// the engine is not doing any work.
const DEFAULT_DURABLE_SLOTS: u32 = 1000;

/// How long a shutting-down worker waits for the runs in flight by default.
const DEFAULT_SHUTDOWN_GRACE: Duration = Duration::from_secs(30);

/// How long a worker whose action stream failed fatally waits for the runs in
/// flight to report, unless it says otherwise.
///
/// The same 30 seconds as [`DEFAULT_SHUTDOWN_GRACE`], for the same reason: it
/// is the drain of a graceful shutdown, reached by another route.
const DEFAULT_STREAM_ERROR_DRAIN: Duration = Duration::from_secs(30);

/// How long the farewell `Unsubscribe` is given, in total.
///
/// It is sent once and never retried: it runs *before* the drain, so every
/// second spent on it is a second taken from the runs in flight — and a worker
/// that is being shut down by a supervisor may be `SIGKILL`ed while it waits.
/// The engine times a worker out on its own, so a lost `Unsubscribe` costs
/// nothing but a little tidiness. The official Python SDK bounds it the same
/// way, at the same five seconds.
const UNSUBSCRIBE_TIMEOUT: Duration = Duration::from_secs(5);

/// The action stream, boxed so the listener loop has one type to work with
/// whatever the transport hands back.
type ActionStream = Pin<Box<dyn Stream<Item = std::result::Result<AssignedAction, Status>> + Send>>;

/// Configures a worker: what it can run, how much of it at once, and how it
/// describes itself to the engine.
///
/// Start one with [`Client::worker`].
///
/// ```no_run
/// # use std::time::Duration;
/// # async fn example(client: hatchet_client::Client) -> hatchet_client::Result<()> {
/// # let agent_run = hatchet_client::TaskBuilder::<(), ()>::new("agent-run")
/// #     .handler(|_ctx, _input| async { Ok(()) });
/// let worker = client
///     .worker("mac-studio-1")
///     .slots(8)
///     .label("os", "macos")
///     .register(&agent_run)
///     .build()
///     .await?;
/// worker.run_until_shutdown().await
/// # }
/// ```
#[must_use = "a worker builder configures nothing until `build` is awaited"]
pub struct WorkerBuilder {
    client: Client,
    name: String,
    slots: u32,
    durable_slots: u32,
    /// Ordered so a registration request is the same from run to run.
    labels: BTreeMap<String, LabelValue>,
    declarations: Vec<WorkflowDef>,
    grace: Duration,
    stream_error_drain: Duration,
}

impl fmt::Debug for WorkerBuilder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WorkerBuilder")
            .field("name", &self.name)
            .field("slots", &self.slots)
            .field("durable_slots", &self.durable_slots)
            .field("labels", &self.labels)
            .field("declarations", &self.declarations.len())
            .field("shutdown_grace", &self.grace)
            .field("stream_error_drain", &self.stream_error_drain)
            .finish_non_exhaustive()
    }
}

impl WorkerBuilder {
    pub(crate) fn new(client: Client, name: impl Into<String>) -> Self {
        Self {
            client,
            name: name.into(),
            slots: DEFAULT_SLOTS,
            durable_slots: DEFAULT_DURABLE_SLOTS,
            labels: BTreeMap::new(),
            declarations: Vec::new(),
            grace: DEFAULT_SHUTDOWN_GRACE,
            stream_error_drain: DEFAULT_STREAM_ERROR_DRAIN,
        }
    }

    /// How many runs this worker executes at once. Defaults to 100; zero is
    /// rejected by [`build`](Self::build).
    #[must_use = "this returns the builder to carry on from"]
    pub fn slots(mut self, slots: u32) -> Self {
        self.slots = slots;
        self
    }

    /// How many **durable** runs this worker may hold at once. Defaults to
    /// 1000; zero is rejected by [`build`](Self::build) when a durable task is
    /// registered.
    ///
    /// A durable run that is waiting on the engine — in
    /// [`DurableContext::sleep_for`](crate::DurableContext::sleep_for), say —
    /// is not doing any work, so this pool is deliberately much larger than
    /// [`slots`](Self::slots), and separate from it: a thousand parked runs
    /// cannot keep the worker from executing an ordinary task. The official Go
    /// SDK uses the same default (`sdks/go/client.go:193-196`). The number
    /// only reaches the engine when a durable task is registered.
    ///
    /// ```no_run
    /// # async fn example(client: hatchet_client::Client) -> hatchet_client::Result<()> {
    /// # let approve = hatchet_client::TaskBuilder::<(), ()>::new("approve")
    /// #     .durable_handler(|_ctx, _input| async { Ok(()) });
    /// let worker = client
    ///     .worker("mac-studio-1")
    ///     .slots(8)
    ///     .durable_slots(5_000)
    ///     .register(&approve)
    ///     .build()
    ///     .await?;
    /// # let _ = worker;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use = "this returns the builder to carry on from"]
    pub fn durable_slots(mut self, slots: u32) -> Self {
        self.durable_slots = slots;
        self
    }

    /// Describes the worker to the engine, so tasks can ask for a worker with
    /// this label. Setting the same key twice keeps the last value.
    #[must_use = "this returns the builder to carry on from"]
    pub fn label(mut self, key: impl Into<String>, value: impl Into<LabelValue>) -> Self {
        self.labels.insert(key.into(), value.into());
        self
    }

    /// Adds a [`Task`](crate::Task) or [`Workflow`](crate::Workflow) this
    /// worker declares and runs.
    #[must_use = "this returns the builder to carry on from"]
    pub fn register(mut self, declaration: &impl Register) -> Self {
        self.declarations.push(declaration.definition());
        self
    }

    /// How long [`Worker::run`] waits for the runs in flight before it asks
    /// them to stop. Defaults to 30 seconds.
    #[must_use = "this returns the builder to carry on from"]
    pub fn shutdown_grace(mut self, grace: Duration) -> Self {
        self.grace = grace;
        self
    }

    /// How long [`Worker::run`] waits for the runs in flight when the engine
    /// ends the action stream in a way reconnecting cannot fix. Defaults to 30
    /// seconds.
    ///
    /// Two cases are deliberately different. When the engine refuses this
    /// worker's credentials (`Unauthenticated` or `PermissionDenied`) nothing
    /// could be reported over that connection anyway, so the runs are dropped
    /// at once and this timeout is not used. For every other fatal end —
    /// `InvalidArgument`, `FailedPrecondition`, `NotFound`, `Unimplemented`,
    /// or too many unclassified failures in a row — the connection still
    /// works: the worker unsubscribes, keeps heartbeating, and gives the runs
    /// in flight up to this long to report before it exits with the error.
    ///
    /// [`Duration::ZERO`] asks the runs to stop straight away, which is close
    /// to what the official Go SDK does (it never drains here).
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # async fn example(client: hatchet_client::Client) -> hatchet_client::Result<()> {
    /// # let task = hatchet_client::TaskBuilder::<(), ()>::new("t")
    /// #     .handler(|_ctx, _input| async { Ok(()) });
    /// let worker = client
    ///     .worker("mac-studio-1")
    ///     .register(&task)
    ///     .stream_error_drain(Duration::from_secs(120))
    ///     .build()
    ///     .await?;
    /// # let _ = worker;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use = "this returns the builder to carry on from"]
    pub fn stream_error_drain(mut self, timeout: Duration) -> Self {
        self.stream_error_drain = timeout;
        self
    }

    /// Declares everything this worker runs and registers it with the engine.
    ///
    /// In order: the engine's version is checked, every declaration is sent to
    /// `PutWorkflow`, and the worker is registered. The worker is known to the
    /// engine when this returns, but takes no work until [`Worker::run`].
    ///
    /// # Errors
    ///
    /// [`Error::Config`] when the worker has no slots,
    /// [`Error::InvalidDeclaration`] when it has nothing to run, when a
    /// declaration is invalid, or when two declarations serve the same action.
    /// All of those are found before the first RPC.
    /// [`Error::UnsupportedEngine`] when the engine is too old,
    /// [`Error::UnsupportedFeature`] when a registered declaration carries
    /// [`idempotency`](crate::Workflow::idempotency) and the engine reports a
    /// version below [`IDEMPOTENCY_MIN_ENGINE_VERSION`](crate::IDEMPOTENCY_MIN_ENGINE_VERSION)
    /// (checked after the version call and before any registration RPC), and
    /// [`Error::Grpc`] when a call fails.
    pub async fn build(self) -> Result<Worker> {
        if self.slots == 0 {
            return Err(Error::Config(format!(
                "worker `{}` was given no slots; it could never run anything",
                self.name
            )));
        }
        if self.declarations.is_empty() {
            return Err(Error::InvalidDeclaration(format!(
                "worker `{}` has nothing to run; register a task or a workflow",
                self.name
            )));
        }
        let serves_durable = self.declarations.iter().any(WorkflowDef::has_durable);
        if serves_durable && self.durable_slots == 0 {
            // The engine would simply never assign the durable tasks, which is
            // a deadlock with nothing to see; an error at registration is
            // cheaper than a worker that looks healthy and runs nothing.
            return Err(Error::Config(format!(
                "worker `{}` registers a durable task but was given no durable slots",
                self.name
            )));
        }

        // Everything that can be decided without the engine is decided here,
        // so a mistake in a declaration cannot leave half of it registered.
        let namespace = self.client.config().namespace().to_string();
        let mut requests = Vec::with_capacity(self.declarations.len());
        let mut handlers: HashMap<String, RegisteredAction> = HashMap::new();
        for declaration in &self.declarations {
            requests.push(declaration.to_request(&namespace)?);
            for (action, handler) in declaration.actions(&namespace)? {
                if handlers.insert(action.clone(), handler).is_some() {
                    return Err(Error::InvalidDeclaration(format!(
                        "more than one registered declaration serves the action `{action}`"
                    )));
                }
            }
        }
        let registration = self.registration(handlers.keys().cloned().collect());

        let engine_version = self.client.engine_version().await?;
        version::ensure_supported(&engine_version)?;
        for declaration in &self.declarations {
            declaration.check_engine_features(&engine_version)?;
        }
        if serves_durable
            && version::ensure_feature(
                crate::durable::SPAWN_FEATURE,
                version::DURABLE_SPAWN_MIN_ENGINE_VERSION,
                &engine_version,
            )
            .is_err()
        {
            // Not an error: whether a durable handler ever spawns is not
            // knowable from its declaration, and refusing the whole worker for
            // a capability it may never use would be worse than a handler that
            // is told when it asks. The official SDKs do not refuse
            // registration either.
            tracing::warn!(
                engine_version,
                required = version::DURABLE_SPAWN_MIN_ENGINE_VERSION,
                "this engine is too old for durable child spawns; \
                 `DurableContext::spawn` will be refused on this worker",
            );
        }
        let engine_version: Arc<str> = Arc::from(engine_version.as_str());
        for request in requests {
            put_workflow(&self.client, &request).await?;
        }
        let worker_id = register(&self.client, &registration).await?;
        tracing::info!(
            worker_id,
            worker_name = %self.name,
            slots = self.slots,
            actions = handlers.len(),
            // Worth its own field: a batch action's runs are buffered by the
            // engine, so "nothing has been assigned yet" is expected of them in
            // a way it is not of the rest.
            batch_actions = handlers
                .values()
                .filter(|action| action.batch.is_some())
                .count(),
            "registered a worker with the engine",
        );

        let report = reporter(self.client.clone());
        let report_batch = batch_reporter(self.client.clone());
        // The stream is built here rather than on the first durable action
        // because the worker id — the first thing it must say — is already
        // known. The official SDKs open it lazily for want of that id.
        let durable_stop = CancellationToken::new();
        let durable = serves_durable.then(|| {
            DurableStream::new(
                worker_id.clone(),
                crate::durable::stream::connect(
                    self.client.grpc_service(),
                    self.client.config().gzip(),
                ),
                durable_stop.clone(),
            )
        });
        // A ledger only when something can act on it: a worker whose durable
        // tasks declare no policy keeps none, and nothing is recorded or
        // counted.
        let evictable: Vec<&str> = handlers
            .iter()
            .filter(|(_, action)| action.durable && action.eviction_policy.is_some())
            .map(|(action_id, _)| action_id.as_str())
            .collect();
        let eviction = if evictable.is_empty() {
            None
        } else if eviction::supported(&engine_version) {
            Some(Arc::new(EvictionBook::default()))
        } else {
            // Unreachable while `EVICTION_MIN_ENGINE_VERSION` is the SDK's own
            // floor, which `ensure_supported` above has already enforced —
            // written out so that the day the floor moves down, the policies
            // are dropped with a word rather than acted on against an engine
            // that cannot honour them. The official SDKs warn here too
            // (`sdks/go/client.go:496-550`).
            tracing::warn!(
                %engine_version,
                required = version::EVICTION_MIN_ENGINE_VERSION,
                tasks = ?evictable,
                "this engine does not support durable eviction; the eviction policies on these \
                 tasks are ignored",
            );
            None
        };
        let durable_setup = durable.clone().map(|stream| DurableSetup {
            slots: self.durable_slots as usize,
            stream,
            engine_version,
            eviction: eviction.clone(),
        });
        let runner = Arc::new(Runner::new(
            worker_id.clone(),
            Some(self.client.clone()),
            handlers,
            self.slots as usize,
            durable_setup,
            report,
            report_batch,
        ));
        if let Some(stream) = &durable {
            // The engine says this invocation is stale: cancel the run the way
            // an engine-sent cancellation does — the handler stops and **no
            // terminal event is reported**, because the run belongs to the
            // engine now.
            // A weak handle: the runner owns the stream, so a strong one here
            // would be a cycle that keeps both alive for ever.
            let runner = Arc::downgrade(&runner);
            stream.on_server_evict(move |task_id, invocation_count| {
                tracing::info!(
                    task_run_external_id = %task_id,
                    invocation_count,
                    "the engine evicted a durable invocation",
                );
                if let Some(runner) = runner.upgrade() {
                    runner.cancel(task_id);
                }
            });
        }
        Ok(Worker {
            client: self.client,
            id: worker_id,
            slots: self.slots,
            durable_slots: self.durable_slots,
            grace: self.grace,
            stream_error_drain: self.stream_error_drain,
            runner,
            durable,
            durable_stop,
            eviction,
            shutdown: CancellationToken::new(),
        })
    }

    /// The registration request for this worker.
    fn registration(&self, mut actions: Vec<String>) -> WorkerRegisterRequest {
        // The engine does not care about the order, but a stable one keeps
        // the request comparable between runs.
        actions.sort();
        WorkerRegisterRequest {
            worker_name: self.name.clone(),
            actions,
            labels: self
                .labels
                .iter()
                .map(|(key, value)| (key.clone(), value.to_proto()))
                .collect(),
            runtime_info: Some(RuntimeInfo {
                sdk_version: Some(env!("CARGO_PKG_VERSION").to_string()),
                // Deliberately absent: the `SDKS` enum has no Rust entry, and
                // the engine rejects `UNKNOWN` outright — hatchet-lite
                // v0.107.0 answers `Dispatcher/Register` with `Internal`
                // ("invalid sdk: UNKNOWN"). The field is `optional`, so
                // absence is a first-class state and registration succeeds;
                // `extra` and `sdk_version` below still identify this SDK.
                language: None,
                // Deliberately absent: the rustc version is not knowable at
                // runtime, and sending the MSRV would be a false claim.
                language_version: None,
                os: Some(std::env::consts::OS.to_string()),
                extra: Some("rust".to_string()),
            }),
            slot_config: self.slot_config(),
            // `slots` is the deprecated spelling of `slot_config`; sending
            // both would let them disagree.
            slots: None,
            ..WorkerRegisterRequest::default()
        }
    }

    /// The slot pools this worker offers, named after what it registered.
    ///
    /// The same rule as the official Go SDK's `resolveWorkerSlotConfig`
    /// (`sdks/go/client.go:439-491`): a pool appears only when something
    /// registered asks for it, so a worker with nothing durable never mentions
    /// durable slots.
    fn slot_config(&self) -> HashMap<String, i32> {
        let mut slot_config = HashMap::new();
        if self.declarations.iter().any(WorkflowDef::has_default) {
            slot_config.insert("default".to_string(), saturating(self.slots));
        }
        if self.declarations.iter().any(WorkflowDef::has_durable) {
            slot_config.insert("durable".to_string(), saturating(self.durable_slots));
        }
        if slot_config.is_empty() {
            // A worker with nothing to run is already rejected, so this only
            // guards a future declaration kind that asks for neither.
            slot_config.insert("default".to_string(), saturating(self.slots));
        }
        slot_config
    }
}

/// The engine takes slot counts as a signed integer.
fn saturating(slots: u32) -> i32 {
    i32::try_from(slots).unwrap_or(i32::MAX)
}

/// A registered worker: it runs the actions the engine assigns until it is
/// asked to stop.
///
/// Build one with [`Client::worker`].
#[must_use = "a worker does nothing until `run` is awaited"]
pub struct Worker {
    client: Client,
    id: String,
    slots: u32,
    /// How many durable runs this worker holds at once — what the eviction
    /// manager measures capacity pressure against.
    durable_slots: u32,
    grace: Duration,
    stream_error_drain: Duration,
    runner: Arc<Runner>,
    /// The `DurableTask` stream, when a durable task is registered.
    durable: Option<DurableStream>,
    /// Ends that stream, and with it the eviction manager. Fired *after* the
    /// drain, because a durable handler that is still winding down wakes up
    /// through it. The manager keeps its ordinary policy during the drain;
    /// nothing is evicted just because the worker is stopping.
    durable_stop: CancellationToken,
    /// The eviction ledger, when a registered durable task carries a policy.
    eviction: Option<Arc<EvictionBook>>,
    shutdown: CancellationToken,
}

impl fmt::Debug for Worker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Worker")
            .field("id", &self.id)
            .field("slots", &self.slots)
            .field("in_flight", &self.runner.in_flight())
            .field("shutdown_grace", &self.grace)
            .field("stream_error_drain", &self.stream_error_drain)
            .field("shutting_down", &self.shutdown.is_cancelled())
            .finish_non_exhaustive()
    }
}

impl Worker {
    /// The id the engine gave this worker when it registered.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// A handle that stops this worker, from anywhere and as often as you
    /// like. Take it before [`run`](Self::run), which consumes the worker.
    pub fn shutdown_handle(&self) -> ShutdownHandle {
        ShutdownHandle {
            token: self.shutdown.clone(),
        }
    }

    /// Runs until [`ShutdownHandle::shutdown`] is called or the engine ends
    /// the action stream in a way reconnecting cannot fix.
    ///
    /// Shutting down is graceful: the worker stops taking work, unsubscribes,
    /// and waits up to [`shutdown_grace`](WorkerBuilder::shutdown_grace) for
    /// the runs in flight — it keeps heartbeating meanwhile, so the engine
    /// does not give the worker up for dead — before it asks the stragglers to
    /// stop.
    ///
    /// A fatal stream error comes down the same way, with one exception. If
    /// the engine refused this worker's credentials (`Unauthenticated` or
    /// `PermissionDenied`), nothing could be reported over that connection, so
    /// the runs in flight are dropped where they stand and no `Unsubscribe` is
    /// attempted. Any other fatal end leaves a working connection, so the
    /// worker unsubscribes and drains for up to
    /// [`stream_error_drain`](WorkerBuilder::stream_error_drain) before
    /// returning the error.
    ///
    /// # Cancellation
    ///
    /// Dropping this future is *not* a shutdown. It stops the heartbeat and
    /// the action stream, but every run already dispatched executes and
    /// reports in a task of its own, and those tasks outlive it — the engine
    /// is never told the worker is going, and no run is waited for. To stop a
    /// worker, take a [`ShutdownHandle`] before `run`, call
    /// [`shutdown`](ShutdownHandle::shutdown), and let this future return.
    ///
    /// # Errors
    ///
    /// [`Error::Grpc`] with the status that ended the action stream.
    pub async fn run(self) -> Result<()> {
        let heartbeat_stop = CancellationToken::new();
        // The heartbeat outlives this future unless it is told not to, so it is
        // told on every way out — including a caller that drops `run` rather
        // than shutting the worker down.
        let _stop_the_heartbeat = heartbeat_stop.clone().drop_guard();
        // The durable stream likewise: a dropped `run` must not leave it
        // announcing waits at 1 Hz for the life of the process. The normal
        // exit still cancels it explicitly, after the drain, below.
        let _stop_the_durable_stream = self.durable_stop.clone().drop_guard();
        let heartbeat = tokio::spawn(heartbeat::run(
            beating(self.client.clone(), self.id.clone()),
            heartbeat_stop.clone(),
        ));

        // Opened before the action stream, so the first durable action never
        // also has to wait for a connection, and so the engine knows this
        // worker is listening for durable completions from the outset.
        if let Some(durable) = &self.durable {
            durable.start();
        }
        // The eviction manager, for as long as the durable stream lives. A
        // weak handle on the runner for the same reason the `server_evict`
        // hook takes one: the runner owns the stream this manager talks on, so
        // a strong one would be a cycle.
        if let (Some(stream), Some(book)) = (&self.durable, &self.eviction) {
            let runner = Arc::downgrade(&self.runner);
            tokio::spawn(eviction::run(
                Arc::clone(book),
                stream.clone(),
                move |task_id| {
                    if let Some(runner) = runner.upgrade() {
                        // The cancellation an engine-sent eviction takes: the
                        // handler stops, no terminal event is reported, and
                        // the durable slot comes back as the run unwinds.
                        runner.cancel(task_id);
                    }
                },
                self.durable_slots as usize,
                eviction::CONFIG,
                self.durable_stop.clone(),
            ));
        }

        let runner = Arc::clone(&self.runner);
        let listening = listener::run(
            connecting(self.client.clone(), self.id.clone()),
            move |action| runner.dispatch(action),
            self.shutdown.clone(),
        );
        // A durable stream that has been given up on is as fatal as an action
        // stream that has: every durable wait has just failed, and every
        // durable task assigned from here on would fail on its first step. It
        // comes down the same way — unsubscribe, drain, return the error.
        let outcome = match &self.durable {
            Some(durable) => {
                let given_up = durable.given_up();
                tokio::pin!(listening);
                tokio::select! {
                    outcome = &mut listening => outcome,
                    error = given_up => {
                        tracing::error!(
                            worker_id = %self.id,
                            %error,
                            "the worker's durable task stream ended for good",
                        );
                        Err(error)
                    }
                }
            }
            None => listening.await,
        };

        let result = match outcome {
            Ok(()) => {
                tracing::info!(worker_id = %self.id, "the worker is shutting down");
                self.unsubscribe().await;
                // Heartbeating right through the drain is deliberate: a worker
                // that goes quiet while it finishes its last runs looks dead
                // to the engine, which would hand those runs to someone else.
                self.runner.drain(self.grace).await;
                Ok(())
            }
            Err(error) => {
                if refuses_this_worker(&error) {
                    // Nothing this worker says will be accepted over that
                    // connection, so there is nothing to drain for.
                    tracing::error!(
                        worker_id = %self.id,
                        %error,
                        runs = self.runner.in_flight(),
                        "the engine refused this worker's credentials; dropping the runs in flight",
                    );
                    self.runner.abort_all().await;
                } else {
                    // The stream is done for, but the connection is not: the
                    // runs in flight can still report, and dropping work that
                    // could have been reported is the more expensive mistake.
                    tracing::error!(
                        worker_id = %self.id,
                        %error,
                        runs = self.runner.in_flight(),
                        drain = ?self.stream_error_drain,
                        "the worker's action stream ended for good; draining the runs in flight",
                    );
                    self.unsubscribe().await;
                    self.runner.drain(self.stream_error_drain).await;
                }
                Err(error)
            }
        };

        // Only now: a durable handler still winding down in the drain wakes up
        // through this stream, so ending it any earlier would fail the very
        // waits the drain is there to let finish.
        self.durable_stop.cancel();
        heartbeat_stop.cancel();
        if let Err(error) = heartbeat.await {
            tracing::warn!(%error, "the heartbeat task did not end cleanly");
        }
        result
    }

    /// [`run`](Self::run), and also stops on `SIGINT` or `SIGTERM` (on unix)
    /// or `Ctrl-C` (elsewhere).
    ///
    /// The first signal starts the graceful shutdown [`run`](Self::run)
    /// describes. The handlers stay installed for the whole of it, so a
    /// *second* signal is heard too, and it does not wait: the runs still in
    /// flight are dropped where they stand and this returns `Ok(())`. An
    /// operator who will not sit out the grace period therefore never has to
    /// reach for `SIGKILL`, which would take the drain's reports with it.
    ///
    /// # Errors
    ///
    /// Whatever [`run`](Self::run) returns. On unix, also [`Error::Config`]
    /// when the `SIGINT` or `SIGTERM` handler cannot be installed. Elsewhere
    /// the `Ctrl-C` handler is installed on first use, so a failure to install
    /// it cannot be returned from here: it is logged, and the worker runs on
    /// until it is stopped another way.
    pub async fn run_until_shutdown(self) -> Result<()> {
        // One in hand is enough: what matters is that a repeat signal is not
        // lost while the first one is being acted on.
        let (sender, receiver) = mpsc::channel(1);
        let forward = shutdown_signals(sender)?;
        // The signal receivers live in this task, so they go on taking signals
        // for as long as the worker is coming down. Dropping them after the
        // first one — as an `await`-once watcher would — is what used to leave
        // `SIGKILL` as the only way to interrupt a long drain.
        let watcher = tokio::spawn(forward);

        let result = self.run_until(receiver).await;
        // Nothing left to stop; the task would otherwise sit on the signals
        // for as long as the process lives.
        watcher.abort();
        result
    }

    /// [`run`](Self::run), with `signals` standing in for the process's
    /// shutdown signals: the first event asks for a graceful shutdown, a
    /// second one gives up on the runs in flight and returns.
    ///
    /// Split out from [`run_until_shutdown`](Self::run_until_shutdown) so the
    /// decision can be tested without sending a process real signals.
    async fn run_until(self, mut signals: mpsc::Receiver<()>) -> Result<()> {
        let handle = self.shutdown_handle();
        let runner = Arc::clone(&self.runner);
        let worker_id = self.id.clone();
        let running = self.run();
        tokio::pin!(running);

        let mut asked_to_stop = false;
        loop {
            let signal = tokio::select! {
                result = &mut running => return result,
                signal = signals.recv() => signal,
            };
            if signal.is_none() {
                // Nobody is left to ask again, so there is nothing to watch
                // for; see the worker out.
                return running.await;
            }
            if asked_to_stop {
                tracing::warn!(
                    worker_id = %worker_id,
                    runs = runner.in_flight(),
                    "a second shutdown signal arrived; dropping the runs still in flight",
                );
                // The runs are dropped rather than left to the dying process,
                // so their slots and handlers are released here and now.
                runner.abort_all().await;
                return Ok(());
            }
            asked_to_stop = true;
            tracing::info!(worker_id = %worker_id, "received a shutdown signal");
            handle.shutdown();
        }
    }

    /// Tells the engine this worker is not listening any more.
    ///
    /// One attempt under a short deadline, never retried: this runs before the
    /// drain, so anything it waits for is taken from the runs in flight. A
    /// failure is worth a warning and nothing more — the shutdown is under way
    /// either way, and the engine times the worker out on its own.
    async fn unsubscribe(&self) {
        let mut request = Request::new(WorkerUnsubscribeRequest {
            worker_id: self.id.clone(),
        });
        // `grpc-timeout` bounds the call once it is on the wire; the timeout
        // around it also bounds getting there — connecting, or waiting behind
        // a stalled connection, is not covered by a deadline header.
        request.set_timeout(UNSUBSCRIBE_TIMEOUT);
        let mut dispatcher = self.client.dispatcher_grpc();
        let sent = tokio::time::timeout(UNSUBSCRIBE_TIMEOUT, dispatcher.unsubscribe(request)).await;
        match sent {
            Ok(Ok(_)) => {}
            Ok(Err(status)) => tracing::warn!(
                worker_id = %self.id,
                code = ?status.code(),
                message = status.message(),
                "could not unsubscribe from the engine",
            ),
            Err(_) => tracing::warn!(
                worker_id = %self.id,
                timeout = ?UNSUBSCRIBE_TIMEOUT,
                "unsubscribing from the engine timed out",
            ),
        }
    }
}

/// Stops a [`Worker`]. Cloning it is cheap, and every clone stops the same
/// worker; calling [`shutdown`](Self::shutdown) more than once is harmless.
#[derive(Clone, Debug)]
pub struct ShutdownHandle {
    token: CancellationToken,
}

impl ShutdownHandle {
    /// Asks the worker to stop. Returns at once — the worker is stopped when
    /// [`Worker::run`] returns.
    pub fn shutdown(&self) {
        self.token.cancel();
    }
}

/// Whether an error that ended the action stream means the engine will not
/// accept anything else from this worker.
///
/// Only the credential codes qualify. Every other fatal end — a bad request,
/// a worker the engine has forgotten, a missing RPC, or a run of unclassified
/// failures — leaves a connection that can still carry the reports of the
/// runs in flight. The *classification* of stream errors is unchanged and
/// still matches the official Go SDK (`pkg/client/retry/stream.go:77-79`);
/// what differs is what happens afterwards.
fn refuses_this_worker(error: &Error) -> bool {
    matches!(
        error,
        Error::Grpc(status)
            if matches!(
                status.code(),
                Code::Unauthenticated | Code::PermissionDenied
            )
    )
}

/// Opens one `ListenV2` stream for `worker_id`.
///
/// Reconnecting re-opens the *stream* and nothing else: the worker keeps the
/// id it registered with, so the engine sees one worker coming back rather
/// than a new one arriving.
fn connecting(
    client: Client,
    worker_id: String,
) -> impl FnMut() -> Pin<Box<dyn Future<Output = std::result::Result<ActionStream, Status>> + Send>>
{
    move || {
        let mut dispatcher = client.dispatcher_grpc();
        let worker_id = worker_id.clone();
        // No `set_timeout` here, and no `retry::unary`: a deadline would cut
        // the stream off mid-flight, and reconnecting is the listener's job.
        Box::pin(async move {
            let actions = dispatcher
                .listen_v2(WorkerListenRequest { worker_id })
                .await?
                .into_inner();
            Ok(Box::pin(actions) as ActionStream)
        })
    }
}

/// Sends one heartbeat for `worker_id`.
///
/// One attempt, not [`retry::unary`]: a retried beat could outlast the
/// interval and delay the next one, and a missed beat matters far less than a
/// late one — the engine allows for several. For the same reason the deadline
/// is [`heartbeat::TIMEOUT`] rather than the unary one.
fn beating(
    client: Client,
    worker_id: String,
) -> impl FnMut() -> Pin<Box<dyn Future<Output = std::result::Result<(), Status>> + Send>> {
    move || {
        let mut dispatcher = client.dispatcher_grpc();
        let worker_id = worker_id.clone();
        Box::pin(async move {
            let mut request = Request::new(HeartbeatRequest {
                worker_id,
                heartbeat_at: Some(Timestamp::from(SystemTime::now())),
            });
            request.set_timeout(heartbeat::TIMEOUT);
            // `grpc-timeout` alone only bounds the call once it is on the
            // wire; this local timeout also bounds getting there — connecting,
            // or waiting behind a stalled connection — which `grpc-timeout`
            // does not cover.
            match tokio::time::timeout(heartbeat::TIMEOUT, dispatcher.heartbeat(request)).await {
                Ok(result) => result.map(|_| ()),
                Err(_) => Err(Status::deadline_exceeded("the heartbeat attempt timed out")),
            }
        })
    }
}

/// Reports a batch's events to the engine, under the unary retry policy.
///
/// Dropped on failure for the same reason [`reporter`] drops one: a run must
/// never be held up by a report. The cost is higher here — every member of the
/// batch is in the report that was lost — which is why the log line names how
/// many runs it was about.
fn batch_reporter(client: Client) -> BatchReporter {
    Arc::new(move |event: BatchActionEvent| {
        let client = client.clone();
        Box::pin(async move {
            let sent = retry::unary(|| {
                let mut dispatcher = client.dispatcher_grpc();
                let request = retry::timed(event.clone());
                async move { dispatcher.send_batch_action_event(request).await }
            })
            .await;
            if let Err(status) = sent {
                tracing::error!(
                    batch_id = ?event.batch_id,
                    action_id = %event.action_id,
                    event_type = event.event_type,
                    items = event.items.len(),
                    code = ?status.code(),
                    message = status.message(),
                    "could not report a batch event to the engine",
                );
            }
        })
    })
}

/// Reports a run's events to the engine, under the unary retry policy.
///
/// A report that will not go through is logged and dropped: a run must never
/// be held up by one, and the engine re-schedules what it never heard about.
fn reporter(client: Client) -> Reporter {
    Arc::new(move |event: StepActionEvent| {
        let client = client.clone();
        Box::pin(async move {
            let sent = retry::unary(|| {
                let mut dispatcher = client.dispatcher_grpc();
                let request = retry::timed(event.clone());
                async move { dispatcher.send_step_action_event(request).await }
            })
            .await;
            if let Err(status) = sent {
                tracing::error!(
                    task_run_external_id = %event.task_run_external_id,
                    event_type = event.event_type,
                    code = ?status.code(),
                    message = status.message(),
                    "could not report a task run event to the engine",
                );
            }
        })
    })
}

async fn put_workflow(client: &Client, request: &v1::CreateWorkflowVersionRequest) -> Result<()> {
    retry::unary(|| {
        let mut admin = client.admin_grpc();
        let request = retry::timed(request.clone());
        async move { admin.put_workflow(request).await }
    })
    .await?;
    Ok(())
}

/// Registers the worker and returns the id the engine gave it.
async fn register(client: &Client, request: &WorkerRegisterRequest) -> Result<String> {
    let response = retry::unary(|| {
        let mut dispatcher = client.dispatcher_grpc();
        let request = retry::timed(request.clone());
        async move { dispatcher.register(request).await }
    })
    .await?;
    Ok(response.into_inner().worker_id)
}

/// Forwards every `SIGINT` and `SIGTERM` to `signals`, one event each, for as
/// long as the returned future is polled.
///
/// The receivers live inside that future rather than being awaited once and
/// dropped, so repeats keep arriving: the second signal during a long drain is
/// the one that matters.
#[cfg(unix)]
fn shutdown_signals(
    signals: mpsc::Sender<()>,
) -> Result<impl Future<Output = ()> + Send + 'static> {
    use tokio::signal::unix::{SignalKind, signal};

    let install = |kind: SignalKind, name: &str| {
        signal(kind).map_err(|error| Error::Config(format!("could not listen for {name}: {error}")))
    };
    let mut interrupt = install(SignalKind::interrupt(), "SIGINT")?;
    let mut terminate = install(SignalKind::terminate(), "SIGTERM")?;
    Ok(async move {
        loop {
            tokio::select! {
                // Only the future of the losing `recv` is dropped, never the
                // receiver itself, so nothing that arrives is missed.
                _ = interrupt.recv() => {}
                _ = terminate.recv() => {}
            }
            if signals.send(()).await.is_err() {
                return;
            }
        }
    })
}

/// [`shutdown_signals`], with `Ctrl-C` as the only signal there is.
#[cfg(not(unix))]
fn shutdown_signals(
    signals: mpsc::Sender<()>,
) -> Result<impl Future<Output = ()> + Send + 'static> {
    // Unlike the unix handlers, this one is only installed when it is awaited,
    // so a failure cannot be reported from here.
    Ok(async move {
        loop {
            if let Err(error) = tokio::signal::ctrl_c().await {
                tracing::error!(
                    %error,
                    "could not listen for Ctrl-C; the worker will not stop on it",
                );
                return;
            }
            if signals.send(()).await.is_err() {
                return;
            }
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{TaskBuilder, TlsStrategy, Workflow};
    use hatchet_proto::root::{ActionType, StepActionEventType};
    use hatchet_testkit::MockEngine;
    use serde_json::{Value, json};
    use tokio::sync::Semaphore;

    const TOKEN: &str = "e30.eyJzdWIiOiJ0Iiwic2VydmVyX3VybCI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODg4OCIsImdycGNfYnJvYWRjYXN0X2FkZHJlc3MiOiJsb2NhbGhvc3Q6NzA3NyJ9.sig";

    /// Nothing here may block forever: a regression should fail the test
    /// rather than hang the suite.
    const NEVER: Duration = Duration::from_secs(30);

    fn client() -> Client {
        Client::builder()
            .token(TOKEN)
            .namespace("dev")
            .tls(TlsStrategy::None)
            .build()
            .expect("the test token is well formed")
    }

    fn client_for(engine: &MockEngine) -> Client {
        Client::builder()
            .token(engine.token())
            .namespace("dev")
            .tls(TlsStrategy::None)
            .build()
            .expect("the mock engine's token is well formed")
    }

    fn echo(name: &str) -> crate::Task<Value, Value> {
        TaskBuilder::new(name).handler(|_ctx, input| async move { Ok(input) })
    }

    fn durable(name: &str) -> crate::Task<Value, Value> {
        TaskBuilder::new(name).durable_handler(|_ctx, input| async move { Ok(input) })
    }

    fn start_action(run_id: &str, action_id: &str) -> AssignedAction {
        AssignedAction {
            task_run_external_id: run_id.to_string(),
            action_id: action_id.to_string(),
            action_type: ActionType::StartStepRun as i32,
            action_payload: json!({ "input": null }).to_string(),
            ..AssignedAction::default()
        }
    }

    fn reported(engine: &MockEngine, run_id: &str, kind: StepActionEventType) -> bool {
        engine
            .requests::<StepActionEvent>()
            .iter()
            .any(|event| event.task_run_external_id == run_id && event.event_type == kind as i32)
    }

    async fn wait_for_event(engine: &MockEngine, run_id: &str, kind: StepActionEventType) {
        let what = format!("{kind:?} for {run_id}");
        engine
            .wait_until(&what, |engine| reported(engine, run_id, kind))
            .await;
    }

    /// What the worker returned, or a failed test rather than a hung suite.
    async fn stopped(running: tokio::task::JoinHandle<Result<()>>) -> Result<()> {
        tokio::time::timeout(NEVER, running)
            .await
            .expect("the worker never stopped")
            .expect("the worker's task panicked")
    }

    /// The whole drain policy turns on this one predicate, so both sides of
    /// it are pinned — including the fatal codes that are *not* about
    /// credentials, and the unclassified ones a run of failures gives up on.
    #[test]
    fn only_the_credential_codes_mean_nothing_can_be_reported() {
        for code in [Code::Unauthenticated, Code::PermissionDenied] {
            let error = Error::from(Status::new(code, "no"));
            assert!(refuses_this_worker(&error), "{code:?}");
        }
        for code in [
            Code::InvalidArgument,
            Code::FailedPrecondition,
            Code::NotFound,
            Code::Unimplemented,
            Code::Unknown,
            Code::Internal,
        ] {
            let error = Error::from(Status::new(code, "no"));
            assert!(!refuses_this_worker(&error), "{code:?}");
        }
        // Not every error that ends `run` is a gRPC status.
        assert!(!refuses_this_worker(&Error::Config("no slots".to_string())));
    }

    /// One shutdown signal is the graceful path: the run in flight finishes
    /// and is reported before `run_until` returns.
    #[tokio::test]
    async fn one_shutdown_signal_waits_for_the_runs_in_flight() {
        let engine = MockEngine::start().await;
        let gate = Arc::new(Semaphore::new(0));
        let gated = TaskBuilder::<Value, Value>::new("gated").handler({
            let gate = Arc::clone(&gate);
            move |_ctx, _input| {
                let gate = Arc::clone(&gate);
                async move {
                    gate.acquire().await.expect("the gate stays open").forget();
                    Ok(json!("done"))
                }
            }
        });
        let worker = client_for(&engine)
            .worker("w")
            .register(&gated)
            .build()
            .await
            .expect("the mock engine registers the worker");
        let (signals, receiver) = mpsc::channel(4);
        let running = tokio::spawn(worker.run_until(receiver));
        engine.wait_for_listeners(1).await;
        engine.push_action(start_action("in-flight", "dev_gated:gated"));
        wait_for_event(
            &engine,
            "in-flight",
            StepActionEventType::StepEventTypeStarted,
        )
        .await;

        signals.send(()).await.expect("the loop is listening");
        engine.wait_for_calls("Unsubscribe", 1).await;
        assert!(
            !running.is_finished(),
            "the first signal must not abandon the run in flight",
        );

        gate.add_permits(1);
        stopped(running)
            .await
            .expect("a graceful stop is not an error");
        assert!(reported(
            &engine,
            "in-flight",
            StepActionEventType::StepEventTypeCompleted
        ));
    }

    /// A second signal does not wait: it drops the runs in flight — even one
    /// whose handler ignores cancellation — and returns.
    #[tokio::test]
    async fn a_second_shutdown_signal_stops_without_waiting() {
        let engine = MockEngine::start().await;
        let (entered, mut has_entered) = mpsc::unbounded_channel();
        let (finished, mut has_finished) = mpsc::unbounded_channel();
        let stubborn = TaskBuilder::<Value, Value>::new("stubborn").handler(move |_ctx, _input| {
            let (entered, finished) = (entered.clone(), finished.clone());
            async move {
                let _ = entered.send(());
                // Never looks at `ctx.cancelled()`: only the kill can end it.
                std::future::pending::<()>().await;
                let _ = finished.send(());
                Ok(json!("never"))
            }
        });
        let worker = client_for(&engine)
            .worker("w")
            // Far longer than this test will wait, so the only way out is the
            // second signal: sitting the drain out is a failure.
            .shutdown_grace(Duration::from_secs(300))
            .register(&stubborn)
            .build()
            .await
            .expect("the mock engine registers the worker");
        let (signals, receiver) = mpsc::channel(4);
        let running = tokio::spawn(worker.run_until(receiver));
        engine.wait_for_listeners(1).await;
        engine.push_action(start_action("stuck", "dev_stubborn:stubborn"));
        wait_for_event(&engine, "stuck", StepActionEventType::StepEventTypeStarted).await;
        has_entered.recv().await.expect("the handler ran");

        signals.send(()).await.expect("the loop is listening");
        engine.wait_for_calls("Unsubscribe", 1).await;
        // The drain is under way, and the handler would sit out its whole
        // grace period.
        assert!(!running.is_finished());

        signals.send(()).await.expect("the loop is still listening");
        stopped(running)
            .await
            .expect("a forced stop is not an error");

        assert!(
            has_finished.try_recv().is_err(),
            "the handler was not still blocked, so nothing was proven",
        );
        for kind in [
            StepActionEventType::StepEventTypeCompleted,
            StepActionEventType::StepEventTypeFailed,
        ] {
            assert!(
                !reported(&engine, "stuck", kind),
                "a dropped run reported {kind:?}",
            );
        }
    }

    #[tokio::test]
    async fn the_registration_request_describes_the_worker() {
        let builder = client()
            .worker("mac-studio-1")
            .slots(4)
            .label("os", "macos")
            .label("cores", 12)
            .register(&echo("agent-run"));

        let request = builder.registration(vec!["dev_agent-run:agent-run".to_string()]);

        assert_eq!(request.worker_name, "mac-studio-1");
        assert_eq!(request.actions, ["dev_agent-run:agent-run"]);
        assert_eq!(request.slot_config["default"], 4);
        assert_eq!(request.slots, None);
        assert_eq!(request.labels["os"].str_value.as_deref(), Some("macos"));
        assert_eq!(request.labels["cores"].int_value, Some(12));
        let runtime = request.runtime_info.expect("runtime info is always sent");
        assert_eq!(
            runtime.language, None,
            "the engine rejects SDKS_UNKNOWN, so no language is sent"
        );
        assert_eq!(runtime.language_version, None);
        assert_eq!(runtime.extra.as_deref(), Some("rust"));
    }

    /// Criterion 1: the registration names only the slot kinds the worker
    /// actually serves, with the numbers the builder was given.
    #[tokio::test]
    async fn the_slot_config_names_only_the_slot_types_the_worker_needs() {
        let only_durable = client()
            .worker("durable-only")
            .durable_slots(9)
            .register(&durable("approve"))
            .registration(Vec::new());
        assert_eq!(
            only_durable.slot_config,
            HashMap::from([("durable".to_string(), 9)])
        );

        let only_default = client()
            .worker("plain")
            .slots(7)
            .register(&echo("fetch"))
            .registration(Vec::new());
        assert_eq!(
            only_default.slot_config,
            HashMap::from([("default".to_string(), 7)])
        );

        let mixed = client()
            .worker("mixed")
            .slots(7)
            .durable_slots(9)
            .register(&durable("approve"))
            .register(&echo("fetch"))
            .registration(Vec::new());
        assert_eq!(
            mixed.slot_config,
            HashMap::from([("default".to_string(), 7), ("durable".to_string(), 9)])
        );

        // The default is the official Go SDK's, and far above `slots`.
        let defaults = client()
            .worker("defaults")
            .register(&durable("approve"))
            .registration(Vec::new());
        assert_eq!(defaults.slot_config["durable"], 1000);
    }

    /// Criterion 1: a durable task with no durable slots would never be
    /// assigned, so it is refused before the first RPC.
    #[tokio::test]
    async fn a_worker_without_durable_slots_is_rejected_before_it_talks_to_the_engine() {
        let error = client()
            .worker("no-durable-slots")
            .durable_slots(0)
            .register(&durable("approve"))
            .build()
            .await
            .expect_err("no durable slots is a configuration mistake");
        assert!(matches!(error, Error::Config(_)), "{error:?}");

        // …and a worker with nothing durable does not care about the number.
        client()
            .worker("plain")
            .durable_slots(0)
            .register(&echo("fetch"))
            .registration(Vec::new());
    }

    #[tokio::test]
    async fn a_label_set_twice_keeps_the_last_value() {
        let builder = client()
            .worker("w")
            .label("os", "linux")
            .label("os", "macos")
            .register(&echo("a"));

        let request = builder.registration(Vec::new());

        assert_eq!(request.labels.len(), 1);
        assert_eq!(request.labels["os"].str_value.as_deref(), Some("macos"));
    }

    #[tokio::test]
    async fn a_worker_without_slots_is_rejected_before_it_talks_to_the_engine() {
        let error = client()
            .worker("w")
            .slots(0)
            .register(&echo("a"))
            .build()
            .await
            .expect_err("no slots is a configuration mistake");

        assert!(matches!(error, Error::Config(_)), "{error:?}");
    }

    #[tokio::test]
    async fn a_worker_with_nothing_to_run_is_rejected() {
        let error = client()
            .worker("w")
            .build()
            .await
            .expect_err("a worker that runs nothing is a mistake");

        let Error::InvalidDeclaration(message) = &error else {
            panic!("{error:?}")
        };
        assert!(message.contains('w'), "{message}");
    }

    #[tokio::test]
    async fn two_declarations_serving_the_same_action_are_rejected_by_name() {
        let error = client()
            .worker("w")
            .register(&Workflow::new("pipeline").task(&echo("build")))
            .register(&Workflow::new("Pipeline").task(&echo("Build")))
            .build()
            .await
            .expect_err("two declarations cannot serve one action");

        let Error::InvalidDeclaration(message) = &error else {
            panic!("{error:?}")
        };
        assert!(message.contains("dev_pipeline:build"), "{message}");
    }

    #[tokio::test]
    async fn an_invalid_declaration_is_rejected() {
        let error = client()
            .worker("w")
            .register(&Workflow::new("empty"))
            .build()
            .await
            .expect_err("a workflow without tasks is invalid");

        assert!(matches!(error, Error::InvalidDeclaration(_)), "{error:?}");
    }

    #[tokio::test]
    async fn debug_output_names_the_worker_without_its_token() {
        let builder = client().worker("mac-studio-1").label("os", "macos");
        let debug = format!("{builder:?}");
        assert!(debug.starts_with("WorkerBuilder"), "{debug}");
        assert!(debug.contains("mac-studio-1"), "{debug}");
        assert!(debug.contains(".."), "{debug}");
        assert!(!debug.contains(TOKEN), "{debug}");

        // A `Worker` needs an engine to be built, so this is one by hand.
        let client = client();
        let worker = Worker {
            id: "worker-1".to_string(),
            slots: 4,
            grace: DEFAULT_SHUTDOWN_GRACE,
            stream_error_drain: DEFAULT_STREAM_ERROR_DRAIN,
            runner: Arc::new(Runner::new(
                "worker-1".to_string(),
                Some(client.clone()),
                HashMap::new(),
                4,
                None,
                reporter(client.clone()),
                batch_reporter(client.clone()),
            )),
            durable: None,
            durable_slots: DEFAULT_DURABLE_SLOTS,
            durable_stop: CancellationToken::new(),
            eviction: None,
            shutdown: CancellationToken::new(),
            client,
        };
        let debug = format!("{worker:?}");
        assert!(debug.starts_with("Worker"), "{debug}");
        assert!(debug.contains("worker-1"), "{debug}");
        assert!(debug.contains("in_flight: 0"), "{debug}");
        assert!(!debug.contains(TOKEN), "{debug}");

        assert!(!format!("{:?}", worker.shutdown_handle()).contains(TOKEN));
    }
}