scaleset 0.2.0

Autoscale GitHub Actions self-hosted runners: a client for the Runner Scale Set APIs.
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
//! Data types exchanged with the scale set APIs.

use std::fmt;

use jiff::Timestamp;
use secrecy::SecretString;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

macro_rules! id_type {
    ($(#[$meta:meta])* $name:ident) => {
        $(#[$meta])*
        #[derive(
            Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
        )]
        #[serde(transparent)]
        pub struct $name(pub i64);

        impl $name {
            /// Returns the raw value.
            pub const fn get(self) -> i64 {
                self.0
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Display::fmt(&self.0, f)
            }
        }

        impl std::str::FromStr for $name {
            type Err = std::num::ParseIntError;

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                s.parse().map(Self)
            }
        }

        impl From<i64> for $name {
            fn from(value: i64) -> Self {
                Self(value)
            }
        }

        impl From<$name> for i64 {
            fn from(value: $name) -> Self {
                value.0
            }
        }
    };
}

id_type!(
    /// Identifies a runner scale set.
    ScaleSetId
);
id_type!(
    /// Identifies a runner group.
    RunnerGroupId
);
id_type!(
    /// Identifies a registered runner.
    RunnerId
);
id_type!(
    /// Identifies a message in a session's message queue.
    MessageId
);
id_type!(
    /// Identifies a job request (`runnerRequestId`), as passed to
    /// [`MessageSession::acquire_jobs`](crate::MessageSession::acquire_jobs).
    JobRequestId
);

impl RunnerGroupId {
    /// The ID of the `Default` runner group.
    pub const DEFAULT: Self = Self(1);
}

/// Identifies a message session.
///
/// It is opaque: the service issues it and the client passes it back as is,
/// so it is kept as text rather than parsed. Today's values are UUIDs.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SessionId(String);

impl SessionId {
    #[cfg(feature = "testing")]
    pub(crate) fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// The ID as text.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for SessionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for SessionId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Name of the default runner group.
pub const DEFAULT_RUNNER_GROUP: &str = "default";

/// Label type the service assigns to labels created through this API.
pub const LABEL_TYPE_SYSTEM: &str = "System";

/// A label workflows use in `runs-on` to target a scale set.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Label {
    /// The label text.
    pub name: String,
    /// The label type. Empty values are sent as [`LABEL_TYPE_SYSTEM`].
    #[serde(rename = "type", default)]
    pub label_type: String,
}

impl Label {
    /// A label of type [`LABEL_TYPE_SYSTEM`].
    pub fn new(name: impl Into<String>) -> Self {
        Self::with_type(name, LABEL_TYPE_SYSTEM)
    }

    /// A label of the given type.
    pub fn with_type(name: impl Into<String>, label_type: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            label_type: label_type.into(),
        }
    }
}

impl From<&str> for Label {
    fn from(name: &str) -> Self {
        Self::new(name)
    }
}

impl From<String> for Label {
    fn from(name: String) -> Self {
        Self::new(name)
    }
}

/// A runner group.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct RunnerGroup {
    /// Runner group ID.
    pub id: RunnerGroupId,
    /// Runner group name.
    pub name: String,
    /// Number of runners in the group.
    pub size: i64,
    /// Whether this is the default group.
    #[serde(rename = "isDefaultGroup")]
    pub is_default: bool,
}

/// Runner settings of a scale set.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct RunnerSetting {
    /// Stops runners from updating themselves.
    pub disable_update: bool,
}

/// Job and runner counts of a scale set.
///
/// Scale on [`total_assigned_jobs`](Self::total_assigned_jobs): it is the
/// number of jobs assigned to the scale set, waiting or running, and is always
/// current. Do not count job messages instead; batches are capped at 50
/// messages and jobs can be reassigned.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct ScaleSetStatistics {
    /// Jobs available to the scale set.
    #[serde(deserialize_with = "count")]
    pub total_available_jobs: u32,
    /// Jobs acquired by the scale set.
    #[serde(deserialize_with = "count")]
    pub total_acquired_jobs: u32,
    /// Jobs assigned to the scale set, including running ones. This is the
    /// number of runners the scale set needs.
    #[serde(deserialize_with = "count")]
    pub total_assigned_jobs: u32,
    /// Jobs running on the scale set's runners.
    #[serde(deserialize_with = "count")]
    pub total_running_jobs: u32,
    /// Runners registered with the scale set.
    #[serde(deserialize_with = "count")]
    pub total_registered_runners: u32,
    /// Runners running a job.
    #[serde(deserialize_with = "count")]
    pub total_busy_runners: u32,
    /// Runners waiting for a job.
    #[serde(deserialize_with = "count")]
    pub total_idle_runners: u32,
}

/// A runner scale set as returned by the service.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct RunnerScaleSet {
    /// Scale set ID.
    pub id: ScaleSetId,
    /// Scale set name.
    pub name: String,
    /// ID of the runner group the scale set belongs to.
    pub runner_group_id: RunnerGroupId,
    /// Name of the runner group the scale set belongs to.
    pub runner_group_name: String,
    /// Labels workflows can target.
    pub labels: Vec<Label>,
    /// Runner settings.
    #[serde(rename = "RunnerSetting")]
    pub runner_setting: RunnerSetting,
    /// When the scale set was created.
    #[serde(deserialize_with = "optional_time")]
    pub created_on: Option<Timestamp>,
    /// URL for generating JIT runner configs.
    pub runner_jit_config_url: Option<String>,
    /// Current statistics, when included.
    pub statistics: Option<ScaleSetStatistics>,
}

/// The desired state of a scale set, for
/// [`Client::create_runner_scale_set`](crate::Client::create_runner_scale_set)
/// and [`Client::update_runner_scale_set`](crate::Client::update_runner_scale_set).
///
/// ```
/// use scaleset::{RunnerGroupId, RunnerScaleSetSpec};
///
/// let spec = RunnerScaleSetSpec::new("my-scale-set")
///     .runner_group_id(RunnerGroupId::DEFAULT)
///     .labels(["linux", "x64"]);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct RunnerScaleSetSpec {
    /// Scale set name. Required on create.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Runner group to place the scale set in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub runner_group_id: Option<RunnerGroupId>,
    /// Runner group name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub runner_group_name: Option<String>,
    /// Labels. On create, an empty list means "use the name as the label".
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<Label>,
    /// Runner settings. On update, `None` leaves them unchanged.
    #[serde(rename = "RunnerSetting", skip_serializing_if = "Option::is_none")]
    pub runner_setting: Option<RunnerSetting>,
}

impl RunnerScaleSetSpec {
    /// A spec with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            ..Self::default()
        }
    }

    /// Sets the name.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the runner group ID.
    #[must_use]
    pub fn runner_group_id(mut self, id: RunnerGroupId) -> Self {
        self.runner_group_id = Some(id);
        self
    }

    /// Sets the runner group name.
    #[must_use]
    pub fn runner_group_name(mut self, name: impl Into<String>) -> Self {
        self.runner_group_name = Some(name.into());
        self
    }

    /// Adds a label.
    #[must_use]
    pub fn label(mut self, label: impl Into<Label>) -> Self {
        self.labels.push(label.into());
        self
    }

    /// Adds labels.
    ///
    /// Multiple labels on GitHub Enterprise Server need 3.18 or later with
    /// the `DistributedTask.AllowRunnerScaleSetCustomLabels` feature flag.
    #[must_use]
    pub fn labels<I, L>(mut self, labels: I) -> Self
    where
        I: IntoIterator<Item = L>,
        L: Into<Label>,
    {
        self.labels.extend(labels.into_iter().map(Into::into));
        self
    }

    /// Stops runners from updating themselves.
    #[must_use]
    pub fn disable_update(mut self) -> Self {
        self.runner_setting = Some(RunnerSetting {
            disable_update: true,
        });
        self
    }

    /// Lets runners update themselves. This is the default on create; on
    /// update it turns updates back on.
    #[must_use]
    pub fn enable_update(mut self) -> Self {
        self.runner_setting = Some(RunnerSetting {
            disable_update: false,
        });
        self
    }

    /// The spec as sent on create: a name is required, and it becomes the
    /// only label when there are none.
    pub(crate) fn for_create(&self) -> Result<Self, String> {
        let name = match self.name.as_deref() {
            Some(name) if !name.trim().is_empty() => name,
            _ => return Err("runner scale set name is required".into()),
        };
        let mut spec = self.for_update();
        if spec.labels.is_empty() {
            spec.labels.push(Label::new(name));
        }
        spec.runner_setting.get_or_insert_default();
        Ok(spec)
    }

    /// The spec as sent on update: labels without a type get type `System`.
    pub(crate) fn for_update(&self) -> Self {
        let mut spec = self.clone();
        for label in &mut spec.labels {
            if label.label_type.is_empty() {
                LABEL_TYPE_SYSTEM.clone_into(&mut label.label_type);
            }
        }
        spec
    }
}

/// Settings for a just-in-time runner.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct JitRunnerSetting {
    /// Runner name. Must be unique within the scale set.
    pub name: String,
    /// Runner work folder. Empty uses the runner's default.
    pub work_folder: String,
}

impl JitRunnerSetting {
    /// Settings for a runner with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            work_folder: String::new(),
        }
    }

    /// Settings for a runner named `prefix-` plus 12 random hex digits, so
    /// names do not collide across restarts.
    pub fn unique(prefix: &str) -> Self {
        Self::new(format!("{prefix}-{:012x}", fastrand::u64(..) >> 16))
    }

    /// Sets the work folder.
    #[must_use]
    pub fn work_folder(mut self, folder: impl Into<String>) -> Self {
        self.work_folder = folder.into();
        self
    }
}

/// A registered runner.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct RunnerReference {
    /// Runner ID.
    pub id: RunnerId,
    /// Runner name.
    pub name: String,
    /// Scale set the runner belongs to.
    pub runner_scale_set_id: ScaleSetId,
}

/// A just-in-time runner configuration.
///
/// [`encoded_jit_config`](Self::encoded_jit_config) is a secret until the
/// runner has used it; it is kept in a [`SecretString`], which is redacted
/// from `Debug` output and wiped from memory on drop.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
#[non_exhaustive]
pub struct JitRunnerConfig {
    /// The runner registered for this config.
    pub runner: Option<RunnerReference>,
    /// Pass to the runner as `ACTIONS_RUNNER_INPUT_JITCONFIG`, or as
    /// `run.sh --jitconfig <value>`. Read it with
    /// [`ExposeSecret::expose_secret`](secrecy::ExposeSecret::expose_secret).
    #[serde(rename = "encodedJITConfig")]
    pub encoded_jit_config: SecretString,
}

/// A message session, as created or refreshed by the service.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct SessionInfo {
    /// Session ID.
    pub session_id: SessionId,
    /// Owner name given when the session was created.
    pub owner_name: String,
    /// The scale set the session belongs to.
    pub runner_scale_set: Option<RunnerScaleSet>,
    /// URL of the message queue.
    pub message_queue_url: String,
    /// Token for the message queue.
    pub message_queue_access_token: SecretString,
    /// Statistics when the session was created.
    pub statistics: Option<ScaleSetStatistics>,
}

/// A batch of job messages from the message queue.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScaleSetMessage {
    /// Message ID. Acknowledge it with
    /// [`MessageSession::delete_message`](crate::MessageSession::delete_message)
    /// and pass it as `last_message_id` on the next poll.
    pub id: MessageId,
    /// Current statistics. Scale on these.
    pub statistics: Option<ScaleSetStatistics>,
    /// Job messages, in delivery order. At most 50 per batch.
    pub jobs: Vec<JobMessage>,
}

impl ScaleSetMessage {
    /// `JobAvailable` messages. Acquire the ones you want with
    /// [`MessageSession::acquire_jobs`](crate::MessageSession::acquire_jobs).
    pub fn jobs_available(&self) -> impl Iterator<Item = &JobAvailable> {
        self.jobs.iter().filter_map(|m| match m {
            JobMessage::Available(j) => Some(j),
            _ => None,
        })
    }

    /// `JobAssigned` messages.
    pub fn jobs_assigned(&self) -> impl Iterator<Item = &JobAssigned> {
        self.jobs.iter().filter_map(|m| match m {
            JobMessage::Assigned(j) => Some(j),
            _ => None,
        })
    }

    /// `JobStarted` messages.
    pub fn jobs_started(&self) -> impl Iterator<Item = &JobStarted> {
        self.jobs.iter().filter_map(|m| match m {
            JobMessage::Started(j) => Some(j),
            _ => None,
        })
    }

    /// `JobCompleted` messages.
    pub fn jobs_completed(&self) -> impl Iterator<Item = &JobCompleted> {
        self.jobs.iter().filter_map(|m| match m {
            JobMessage::Completed(j) => Some(j),
            _ => None,
        })
    }
}

/// One job message in a [`ScaleSetMessage`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "messageType")]
#[non_exhaustive]
pub enum JobMessage {
    /// A job is available to the scale set.
    #[serde(rename = "JobAvailable")]
    Available(JobAvailable),
    /// A job was assigned to the scale set.
    #[serde(rename = "JobAssigned")]
    Assigned(JobAssigned),
    /// A runner started a job.
    #[serde(rename = "JobStarted")]
    Started(JobStarted),
    /// A job finished, or its assignment was canceled.
    #[serde(rename = "JobCompleted")]
    Completed(JobCompleted),
    /// A message type this crate does not know.
    #[serde(other)]
    Unknown,
}

impl JobMessage {
    /// The job details, unless the message type is unknown.
    pub fn job(&self) -> Option<&JobInfo> {
        match self {
            Self::Available(m) => Some(&m.job),
            Self::Assigned(m) => Some(&m.job),
            Self::Started(m) => Some(&m.job),
            Self::Completed(m) => Some(&m.job),
            Self::Unknown => None,
        }
    }
}

/// Details shared by all job messages.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct JobInfo {
    /// Job request ID, for [`MessageSession::acquire_jobs`](crate::MessageSession::acquire_jobs).
    pub runner_request_id: JobRequestId,
    /// Repository name.
    pub repository_name: String,
    /// Repository owner.
    pub owner_name: String,
    /// Job ID.
    pub job_id: String,
    /// Workflow reference.
    pub job_workflow_ref: String,
    /// Job display name.
    pub job_display_name: String,
    /// Workflow run ID.
    pub workflow_run_id: i64,
    /// Event that triggered the workflow.
    pub event_name: String,
    /// Labels the job requested.
    pub request_labels: Vec<String>,
    /// When the job was queued.
    #[serde(deserialize_with = "optional_time")]
    pub queue_time: Option<Timestamp>,
    /// When the job was assigned to the scale set.
    #[serde(deserialize_with = "optional_time")]
    pub scale_set_assign_time: Option<Timestamp>,
    /// When the job was assigned to a runner.
    #[serde(deserialize_with = "optional_time")]
    pub runner_assign_time: Option<Timestamp>,
    /// When the job finished.
    #[serde(deserialize_with = "optional_time")]
    pub finish_time: Option<Timestamp>,
}

/// A job is available to the scale set.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct JobAvailable {
    /// URL for acquiring the job.
    #[serde(default)]
    pub acquire_job_url: String,
    /// Job details.
    #[serde(flatten)]
    pub job: JobInfo,
}

/// A job was assigned to the scale set.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct JobAssigned {
    /// Job details.
    #[serde(flatten)]
    pub job: JobInfo,
}

/// A runner started a job.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct JobStarted {
    /// The runner's ID.
    #[serde(default)]
    pub runner_id: RunnerId,
    /// The runner's name.
    #[serde(default)]
    pub runner_name: String,
    /// Job details.
    #[serde(flatten)]
    pub job: JobInfo,
}

/// A job finished, or its assignment was canceled before a runner took it.
///
/// A job can be assigned and canceled up to three times before it runs; each
/// attempt produces its own messages.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct JobCompleted {
    /// Result, such as `succeeded`, `failed` or `canceled`.
    #[serde(default)]
    pub result: String,
    /// The runner's ID, or `None` if no runner took the job.
    #[serde(
        default,
        deserialize_with = "optional_id",
        serialize_with = "id_or_zero"
    )]
    pub runner_id: Option<RunnerId>,
    /// The runner's name, or `None` if no runner took the job.
    #[serde(
        default,
        deserialize_with = "optional_name",
        serialize_with = "name_or_empty"
    )]
    pub runner_name: Option<String>,
    /// Job details.
    #[serde(flatten)]
    pub job: JobInfo,
}

/// Wire shape of a message queue response.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct RawMessage {
    #[serde(default, deserialize_with = "null_as_default")]
    pub message_id: MessageId,
    #[serde(default, deserialize_with = "null_as_default")]
    pub message_type: String,
    #[serde(default, deserialize_with = "null_as_default")]
    pub body: String,
    #[serde(default)]
    pub statistics: Option<ScaleSetStatistics>,
}

pub(crate) const MESSAGE_TYPE_JOB_MESSAGES: &str = "RunnerScaleSetJobMessages";

impl ScaleSetMessage {
    /// Decodes a queue message. Anything it cannot read becomes a message
    /// with no jobs, so it can still be acknowledged and its statistics
    /// used. Failing instead would redeliver the same message forever.
    pub(crate) fn from_raw(raw: &RawMessage) -> Self {
        let id = raw.message_id;
        let entries: Vec<serde_json::Value> = if raw.message_type != MESSAGE_TYPE_JOB_MESSAGES {
            tracing::warn!(message_id = %id, message_type = %raw.message_type, "skipping a message of an unknown type");
            Vec::new()
        } else if raw.body.is_empty() {
            Vec::new()
        } else {
            serde_json::from_str(&raw.body).unwrap_or_else(|e| {
                tracing::warn!(error = %e, message_id = %id, "skipping a message body that could not be decoded");
                Vec::new()
            })
        };
        // One malformed entry must not make the rest of the batch undeliverable.
        let jobs = entries
            .into_iter()
            .map(|entry| {
                JobMessage::deserialize(&entry).unwrap_or_else(|e| {
                    tracing::warn!(error = %e, message_id = %id, "skipping a job message that could not be decoded");
                    JobMessage::Unknown
                })
            })
            .collect();
        Self {
            id,
            statistics: raw.statistics,
            jobs,
        }
    }
}

/// `{ "count": n, "value": [...] }`
#[derive(Debug, Deserialize)]
pub(crate) struct ListResponse<T> {
    #[serde(default)]
    pub count: usize,
    #[serde(default = "Vec::new")]
    pub value: Vec<T>,
}

/// Deserializes an optional timestamp, mapping Go's zero time to `None`.
fn optional_time<'de, D>(deserializer: D) -> Result<Option<Timestamp>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Timestamp>::deserialize(deserializer)?;
    Ok(value.filter(|t| t.as_second() > GO_ZERO_TIME_SECS))
}

/// Deserializes a count, reading `null` as 0 and a negative or oversized
/// value as the nearest `u32`, rather than failing the whole message.
fn count<'de, D>(deserializer: D) -> Result<u32, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<i64>::deserialize(deserializer)?.unwrap_or(0);
    Ok(u32::try_from(value.max(0)).unwrap_or(u32::MAX))
}

/// Deserializes a runner ID, mapping Go's zero value to `None`.
fn optional_id<'de, D>(deserializer: D) -> Result<Option<RunnerId>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<RunnerId>::deserialize(deserializer)?;
    Ok(value.filter(|id| id.0 != 0))
}

/// Deserializes a runner name, mapping Go's zero value to `None`.
fn optional_name<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<String>::deserialize(deserializer)?;
    Ok(value.filter(|name| !name.is_empty()))
}

/// Serializes a missing runner ID as Go's zero value, as the service does.
#[expect(clippy::ref_option, reason = "serde passes fields by reference")]
fn id_or_zero<S: Serializer>(id: &Option<RunnerId>, serializer: S) -> Result<S::Ok, S::Error> {
    id.unwrap_or_default().serialize(serializer)
}

/// Serializes a missing runner name as Go's zero value, as the service does.
#[expect(clippy::ref_option, reason = "serde passes fields by reference")]
fn name_or_empty<S: Serializer>(name: &Option<String>, serializer: S) -> Result<S::Ok, S::Error> {
    name.as_deref().unwrap_or_default().serialize(serializer)
}

/// Deserializes `null` as the default value, as Go does.
fn null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de> + Default,
{
    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
}

/// `0001-01-01T00:00:00Z` as a Unix timestamp.
const GO_ZERO_TIME_SECS: i64 = -62_135_596_800;

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

    #[test]
    fn decodes_job_messages_in_order() {
        let body = serde_json::json!([
            {"messageType": "JobAvailable", "acquireJobUrl": "u", "runnerRequestId": 1,
             "queueTime": "2024-01-01T00:00:00Z", "finishTime": "0001-01-01T00:00:00Z"},
            {"messageType": "JobStarted", "runnerRequestId": 2, "runnerId": 7, "runnerName": "r"},
            {"messageType": "SomethingNew", "x": 1},
            {"messageType": "JobCompleted", "runnerRequestId": 3, "result": "canceled",
             "runnerId": 0, "runnerName": ""},
            {"messageType": "JobAssigned", "runnerRequestId": 4, "requestLabels": ["a"]},
        ]);
        let raw = RawMessage {
            message_id: MessageId(5),
            message_type: MESSAGE_TYPE_JOB_MESSAGES.into(),
            body: body.to_string(),
            statistics: Some(ScaleSetStatistics {
                total_assigned_jobs: 3,
                ..Default::default()
            }),
        };
        let msg = ScaleSetMessage::from_raw(&raw);
        assert_eq!(msg.id, MessageId(5));
        assert_eq!(msg.jobs.len(), 5);
        assert!(matches!(msg.jobs[2], JobMessage::Unknown));

        let available: Vec<_> = msg.jobs_available().collect();
        assert_eq!(available[0].acquire_job_url, "u");
        assert_eq!(available[0].job.runner_request_id, JobRequestId(1));
        assert!(available[0].job.queue_time.is_some());
        assert_eq!(available[0].job.finish_time, None);

        let started: Vec<_> = msg.jobs_started().collect();
        assert_eq!(started[0].runner_id, RunnerId(7));
        let completed = msg.jobs_completed().next().unwrap();
        assert_eq!(completed.result, "canceled");
        assert_eq!(
            (completed.runner_id, completed.runner_name.as_deref()),
            (None, None)
        );
        assert_eq!(
            msg.jobs_assigned().next().unwrap().job.request_labels,
            vec!["a"]
        );
    }

    #[test]
    fn tolerates_a_malformed_job_message() {
        let body = serde_json::json!([
            {"messageType": "JobStarted", "runnerId": "not a number"},
            {"messageType": "JobAssigned", "runnerRequestId": 4},
        ]);
        let raw = RawMessage {
            message_id: MessageId(1),
            message_type: MESSAGE_TYPE_JOB_MESSAGES.into(),
            body: body.to_string(),
            statistics: None,
        };
        let msg = ScaleSetMessage::from_raw(&raw);
        assert!(matches!(msg.jobs[0], JobMessage::Unknown));
        assert_eq!(msg.jobs_assigned().count(), 1);
    }

    #[test]
    fn skips_what_it_cannot_read() {
        for (message_type, body) in [("Other", "[]"), (MESSAGE_TYPE_JOB_MESSAGES, "not json")] {
            let raw = RawMessage {
                message_id: MessageId(9),
                message_type: message_type.into(),
                body: body.into(),
                statistics: Some(ScaleSetStatistics::default()),
            };
            let msg = ScaleSetMessage::from_raw(&raw);
            assert_eq!(msg.id, MessageId(9));
            assert!(msg.jobs.is_empty());
            assert!(msg.statistics.is_some());
        }
    }

    #[test]
    fn spec_defaults_label_to_name() {
        let spec = RunnerScaleSetSpec::new("set").for_create().unwrap();
        assert_eq!(spec.labels, vec![Label::new("set")]);

        let spec = RunnerScaleSetSpec::default()
            .label(Label {
                name: "x".into(),
                label_type: String::new(),
            })
            .for_update();
        assert_eq!(spec.labels[0].label_type, LABEL_TYPE_SYSTEM);

        assert!(RunnerScaleSetSpec::default().for_create().is_err());
        // A name is required on create even with labels.
        assert!(
            RunnerScaleSetSpec::default()
                .label(Label::new("x"))
                .for_create()
                .is_err()
        );
    }

    #[test]
    fn spec_serialization() {
        let spec = RunnerScaleSetSpec::new("set")
            .runner_group_id(RunnerGroupId(3))
            .for_create()
            .unwrap();
        assert_eq!(
            serde_json::to_value(&spec).unwrap(),
            serde_json::json!({
                "name": "set",
                "runnerGroupId": 3,
                "labels": [{"name": "set", "type": "System"}],
                "RunnerSetting": {"disableUpdate": false}
            })
        );
    }

    #[test]
    fn update_sends_only_what_was_set() {
        let unchanged = RunnerScaleSetSpec::default().for_update();
        assert_eq!(
            serde_json::to_value(&unchanged).unwrap(),
            serde_json::json!({})
        );

        // An explicit `false` is sent, so updates can be turned back on.
        let enable = RunnerScaleSetSpec::default().enable_update().for_update();
        assert_eq!(
            serde_json::to_value(&enable).unwrap(),
            serde_json::json!({"RunnerSetting": {"disableUpdate": false}})
        );
    }

    #[test]
    fn secrets_are_redacted() {
        let jit: JitRunnerConfig =
            serde_json::from_str(r#"{"encodedJITConfig": "secret"}"#).unwrap();
        assert!(!format!("{jit:?}").contains("secret"));

        let session: SessionInfo =
            serde_json::from_str(r#"{"messageQueueAccessToken": "secret"}"#).unwrap();
        assert!(!format!("{session:?}").contains("secret"));
    }

    #[test]
    fn session_ids_are_opaque() {
        // Whatever the service sends is kept and passed back unchanged.
        let session: SessionInfo = serde_json::from_str(r#"{"sessionId": "not-a-uuid"}"#).unwrap();
        assert_eq!(session.session_id.as_str(), "not-a-uuid");
        assert_eq!(session.session_id.to_string(), "not-a-uuid");
    }

    #[test]
    fn counts_tolerate_out_of_range_values() {
        let stats: ScaleSetStatistics =
            serde_json::from_str(r#"{"totalAssignedJobs": -1, "totalRunningJobs": 99999999999}"#)
                .unwrap();
        assert_eq!(stats.total_assigned_jobs, 0);
        assert_eq!(stats.total_running_jobs, u32::MAX);
    }
    #[test]
    fn job_without_runner_uses_go_zero_values() {
        let job = JobCompleted {
            result: "canceled".into(),
            ..JobCompleted::default()
        };
        let wire = serde_json::to_value(&job).unwrap();
        assert_eq!(wire["runnerId"], 0, "{wire}");
        assert_eq!(wire["runnerName"], "", "{wire}");
        assert_eq!(serde_json::from_value::<JobCompleted>(wire).unwrap(), job);
    }

    #[test]
    fn ids_parse_from_text() {
        assert_eq!("42".parse::<RunnerId>(), Ok(RunnerId(42)));
        assert!("x".parse::<ScaleSetId>().is_err());
    }

    #[test]
    fn nulls_read_as_empty() {
        let stats: ScaleSetStatistics =
            serde_json::from_str(r#"{"totalAssignedJobs": null, "totalRunningJobs": 2}"#).unwrap();
        assert_eq!(stats.total_assigned_jobs, 0);
        assert_eq!(stats.total_running_jobs, 2);

        let raw: RawMessage = serde_json::from_str(
            r#"{"messageId": 3, "messageType": null, "body": null, "statistics": {"totalAssignedJobs": null}}"#,
        )
        .unwrap();
        let msg = ScaleSetMessage::from_raw(&raw);
        assert_eq!(msg.id, MessageId(3));
        assert!(msg.jobs.is_empty());
        assert_eq!(msg.statistics, Some(ScaleSetStatistics::default()));
    }
}