-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathmod.rs
3935 lines (3485 loc) · 124 KB
/
mod.rs
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Data structures and related facilities for representing resources in the API
//!
//! This includes all representations over the wire for both the external and
//! internal APIs. The contents here are all HTTP-agnostic.
mod error;
pub mod http_pagination;
pub use crate::api::internal::shared::AllowedSourceIps;
pub use crate::api::internal::shared::SwitchLocation;
use crate::update::ArtifactHash;
use crate::update::ArtifactId;
use anyhow::Context;
use api_identity::ObjectIdentity;
use chrono::DateTime;
use chrono::Utc;
use daft::Diffable;
use dropshot::HttpError;
pub use dropshot::PaginationOrder;
pub use error::*;
use futures::stream::BoxStream;
use omicron_uuid_kinds::AffinityGroupUuid;
use omicron_uuid_kinds::GenericUuid;
use omicron_uuid_kinds::InstanceUuid;
use oxnet::IpNet;
use oxnet::Ipv4Net;
use parse_display::Display;
use parse_display::FromStr;
use rand::thread_rng;
use rand::Rng;
use schemars::JsonSchema;
use semver::Version;
use serde::Deserialize;
use serde::Serialize;
use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FormatResult;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::num::{NonZeroU16, NonZeroU32};
use std::str::FromStr;
use uuid::Uuid;
// The type aliases below exist primarily to ensure consistency among return
// types for functions in the `nexus::Nexus` and `nexus::DataStore`. The
// type argument `T` generally implements `Object`.
/// Result of a create operation for the specified type
pub type CreateResult<T> = Result<T, Error>;
/// Result of a delete operation for the specified type
pub type DeleteResult = Result<(), Error>;
/// Result of a list operation that returns an ObjectStream
pub type ListResult<T> = Result<ObjectStream<T>, Error>;
/// Result of a list operation that returns a vector
pub type ListResultVec<T> = Result<Vec<T>, Error>;
/// Result of a lookup operation for the specified type
pub type LookupResult<T> = Result<T, Error>;
/// Result of an update operation for the specified type
pub type UpdateResult<T> = Result<T, Error>;
/// Result of an optional lookup operation for the specified type
pub type OptionalLookupResult<T> = Result<Option<T>, Error>;
/// A stream of Results, each potentially representing an object in the API
pub type ObjectStream<T> = BoxStream<'static, Result<T, Error>>;
// General-purpose types used for client request parameters and return values.
/// Describes an `Object` that has its own identity metadata. This is
/// currently used only for pagination.
pub trait ObjectIdentity {
fn identity(&self) -> &IdentityMetadata;
}
/// Exists for types that don't properly implement `ObjectIdentity` but
/// still need to be paginated by id.
pub trait SimpleIdentity {
fn id(&self) -> Uuid;
}
impl<T: ObjectIdentity> SimpleIdentity for T {
fn id(&self) -> Uuid {
self.identity().id
}
}
/// Exists for types that don't properly implement `ObjectIdentity` but
/// still need to be paginated by name or id.
pub trait SimpleIdentityOrName {
fn id(&self) -> Uuid;
fn name(&self) -> &Name;
}
impl<T: ObjectIdentity> SimpleIdentityOrName for T {
fn id(&self) -> Uuid {
self.identity().id
}
fn name(&self) -> &Name {
&self.identity().name
}
}
/// Parameters used to request a specific page of results when listing a
/// collection of objects
///
/// This is logically analogous to Dropshot's `PageSelector` (plus the limit from
/// Dropshot's `PaginationParams). However, this type is HTTP-agnostic. More
/// importantly, by the time this struct is generated, we know the type of the
/// sort field and we can specialize `DataPageParams` to that type. This makes
/// it considerably simpler to implement the backend for most of our paginated
/// APIs.
///
/// `NameType` is the type of the field used to sort the returned values and it's
/// usually `Name`.
#[derive(Clone, Debug)]
pub struct DataPageParams<'a, NameType> {
/// If present, this is the value of the sort field for the last object seen
pub marker: Option<&'a NameType>,
/// Whether the sort is in ascending order
pub direction: PaginationOrder,
/// This identifies how many results should be returned on this page.
/// Backend implementations must provide this many results unless we're at
/// the end of the scan. Dropshot assumes that if we provide fewer results
/// than this number, then we're done with the scan.
pub limit: NonZeroU32,
}
impl<'a, NameType> DataPageParams<'a, NameType> {
pub fn max_page() -> Self {
Self {
marker: None,
direction: dropshot::PaginationOrder::Ascending,
limit: NonZeroU32::new(u32::MAX).unwrap(),
}
}
/// Maps the marker type to a new type.
///
/// Equivalent to [std::option::Option::map], because that's what it calls.
pub fn map_name<OtherName, F>(&self, f: F) -> DataPageParams<'a, OtherName>
where
F: FnOnce(&'a NameType) -> &'a OtherName,
{
DataPageParams {
marker: self.marker.map(f),
direction: self.direction,
limit: self.limit,
}
}
}
impl<'a> TryFrom<&DataPageParams<'a, NameOrId>> for DataPageParams<'a, Name> {
type Error = HttpError;
fn try_from(
value: &DataPageParams<'a, NameOrId>,
) -> Result<Self, Self::Error> {
match value.marker {
Some(NameOrId::Name(name)) => Ok(DataPageParams {
marker: Some(name),
direction: value.direction,
limit: value.limit,
}),
None => Ok(DataPageParams {
marker: None,
direction: value.direction,
limit: value.limit,
}),
_ => Err(HttpError::for_bad_request(
None,
String::from("invalid pagination marker"),
)),
}
}
}
impl<'a> TryFrom<&DataPageParams<'a, NameOrId>> for DataPageParams<'a, Uuid> {
type Error = HttpError;
fn try_from(
value: &DataPageParams<'a, NameOrId>,
) -> Result<Self, Self::Error> {
match value.marker {
Some(NameOrId::Id(id)) => Ok(DataPageParams {
marker: Some(id),
direction: value.direction,
limit: value.limit,
}),
None => Ok(DataPageParams {
marker: None,
direction: value.direction,
limit: value.limit,
}),
_ => Err(HttpError::for_bad_request(
None,
String::from("invalid pagination marker"),
)),
}
}
}
/// A name used in the API
///
/// Names are generally user-provided unique identifiers, highly constrained as
/// described in RFD 4. An `Name` can only be constructed with a string
/// that's valid as a name.
#[derive(
Clone,
Debug,
Deserialize,
Display,
Eq,
Hash,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
#[display("{0}")]
#[serde(try_from = "String")]
#[derive(Diffable)]
pub struct Name(String);
/// `Name::try_from(String)` is the primary method for constructing an Name
/// from an input string. This validates the string according to our
/// requirements for a name.
/// TODO-cleanup why shouldn't callers use TryFrom<&str>?
impl TryFrom<String> for Name {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
if value.len() > 63 {
return Err(String::from("name may contain at most 63 characters"));
}
let mut iter = value.chars();
let first = iter.next().ok_or_else(|| {
String::from("name requires at least one character")
})?;
if !first.is_ascii_lowercase() {
return Err(String::from(
"name must begin with an ASCII lowercase character",
));
}
let mut last = first;
for c in iter {
last = c;
if !c.is_ascii_lowercase() && !c.is_digit(10) && c != '-' {
return Err(format!(
"name contains invalid character: \"{}\" (allowed \
characters are lowercase ASCII, digits, and \"-\")",
c
));
}
}
if last == '-' {
return Err(String::from("name cannot end with \"-\""));
}
if Uuid::parse_str(&value).is_ok() {
return Err(String::from(
"name cannot be a UUID to avoid ambiguity with IDs",
));
}
Ok(Name(value))
}
}
impl FromStr for Name {
// TODO: We should have better error types here.
// See https://github.com/oxidecomputer/omicron/issues/347
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Name::try_from(String::from(value))
}
}
impl<'a> From<&'a Name> for &'a str {
fn from(n: &'a Name) -> Self {
n.as_str()
}
}
impl From<Name> for String {
fn from(name: Name) -> Self {
name.0
}
}
/// `Name` instances are comparable like Strings, primarily so that they can
/// be used as keys in trees.
impl<S> PartialEq<S> for Name
where
S: AsRef<str>,
{
fn eq(&self, other: &S) -> bool {
self.0 == other.as_ref()
}
}
/// Custom JsonSchema implementation to encode the constraints on Name.
impl JsonSchema for Name {
fn schema_name() -> String {
"Name".to_string()
}
fn json_schema(
_: &mut schemars::gen::SchemaGenerator,
) -> schemars::schema::Schema {
name_schema(schemars::schema::Metadata {
title: Some(
"A name unique within the parent collection".to_string(),
),
description: Some(
"Names must begin with a lower case ASCII letter, be \
composed exclusively of lowercase ASCII, uppercase \
ASCII, numbers, and '-', and may not end with a '-'. \
Names cannot be a UUID, but they may contain a UUID. \
They can be at most 63 characters long."
.to_string(),
),
..Default::default()
})
}
}
impl Name {
/// Parse an `Name`. This is a convenience wrapper around
/// `Name::try_from(String)` that marshals any error into an appropriate
/// `Error`.
pub fn from_param(value: String, label: &str) -> Result<Name, Error> {
value.parse().map_err(|e| Error::invalid_value(label, e))
}
/// Return the `&str` representing the actual name.
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
#[derive(Debug, Serialize, Deserialize, Display, Clone, PartialEq)]
#[display("{0}")]
#[serde(untagged)]
pub enum NameOrId {
Id(Uuid),
Name(Name),
}
impl TryFrom<String> for NameOrId {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
if let Ok(id) = Uuid::parse_str(&value) {
Ok(NameOrId::Id(id))
} else {
Ok(NameOrId::Name(Name::try_from(value)?))
}
}
}
impl FromStr for NameOrId {
// TODO: We should have better error types here.
// See https://github.com/oxidecomputer/omicron/issues/347
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
NameOrId::try_from(String::from(value))
}
}
impl From<Name> for NameOrId {
fn from(name: Name) -> Self {
NameOrId::Name(name)
}
}
impl From<Uuid> for NameOrId {
fn from(id: Uuid) -> Self {
NameOrId::Id(id)
}
}
impl JsonSchema for NameOrId {
fn schema_name() -> String {
"NameOrId".to_string()
}
fn json_schema(
gen: &mut schemars::gen::SchemaGenerator,
) -> schemars::schema::Schema {
schemars::schema::SchemaObject {
subschemas: Some(Box::new(schemars::schema::SubschemaValidation {
one_of: Some(vec![
label_schema("id", gen.subschema_for::<Uuid>()),
label_schema("name", gen.subschema_for::<Name>()),
]),
..Default::default()
})),
..Default::default()
}
.into()
}
}
/// A username for a local-only user.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(try_from = "String")]
pub struct UserId(String);
impl AsRef<str> for UserId {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
impl FromStr for UserId {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
UserId::try_from(String::from(value))
}
}
/// Used to impl `Deserialize`
impl TryFrom<String> for UserId {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
// Mostly, this validation exists to cap the input size. The specific
// length is not critical here. For convenience and consistency, we use
// the same rules as `Name`.
let _ = Name::try_from(value.clone())?;
Ok(UserId(value))
}
}
impl JsonSchema for UserId {
fn schema_name() -> String {
"UserId".to_string()
}
fn json_schema(
_: &mut schemars::gen::SchemaGenerator,
) -> schemars::schema::Schema {
name_schema(schemars::schema::Metadata {
title: Some("A username for a local-only user".to_string()),
description: Some(
"Usernames must begin with a lower case ASCII letter, be \
composed exclusively of lowercase ASCII, uppercase ASCII, \
numbers, and '-', and may not end with a '-'. Usernames \
cannot be a UUID, but they may contain a UUID. They can be at \
most 63 characters long."
.to_string(),
),
..Default::default()
})
}
}
fn name_schema(
metadata: schemars::schema::Metadata,
) -> schemars::schema::Schema {
schemars::schema::SchemaObject {
metadata: Some(Box::new(metadata)),
instance_type: Some(schemars::schema::InstanceType::String.into()),
string: Some(Box::new(schemars::schema::StringValidation {
max_length: Some(63),
min_length: Some(1),
pattern: Some(
concat!(
r#"^"#,
// Cannot match a UUID
concat!(
r#"(?![0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}"#,
r#"-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$)"#,
),
r#"^[a-z]([a-zA-Z0-9-]*[a-zA-Z0-9]+)?"#,
r#"$"#,
)
.to_string(),
),
})),
..Default::default()
}
.into()
}
/// Name for a built-in role
#[derive(
Clone,
Debug,
DeserializeFromStr,
Display,
Eq,
FromStr,
Ord,
PartialEq,
PartialOrd,
SerializeDisplay,
)]
#[display("{resource_type}.{role_name}")]
pub struct RoleName {
// "resource_type" is generally the String value of one of the
// `ResourceType` variants. We could store the parsed `ResourceType`
// instead, but it's useful to be able to represent RoleNames for resource
// types that we don't know about. That could happen if we happen to find
// them in the database, for example.
#[from_str(regex = "[a-z-]+")]
resource_type: String,
#[from_str(regex = "[a-z-]+")]
role_name: String,
}
impl RoleName {
pub fn new(resource_type: &str, role_name: &str) -> RoleName {
RoleName {
resource_type: String::from(resource_type),
role_name: String::from(role_name),
}
}
}
/// Custom JsonSchema implementation to encode the constraints on RoleName
impl JsonSchema for RoleName {
fn schema_name() -> String {
"RoleName".to_string()
}
fn json_schema(
_: &mut schemars::gen::SchemaGenerator,
) -> schemars::schema::Schema {
schemars::schema::Schema::Object(schemars::schema::SchemaObject {
metadata: Some(Box::new(schemars::schema::Metadata {
title: Some("A name for a built-in role".to_string()),
description: Some(
"Role names consist of two string components \
separated by dot (\".\")."
.to_string(),
),
..Default::default()
})),
instance_type: Some(schemars::schema::SingleOrVec::Single(
Box::new(schemars::schema::InstanceType::String),
)),
string: Some(Box::new(schemars::schema::StringValidation {
max_length: Some(63),
min_length: None,
pattern: Some("[a-z-]+\\.[a-z-]+".to_string()),
})),
..Default::default()
})
}
}
/// Byte count to express memory or storage capacity.
//
// The maximum supported byte count is [`i64::MAX`]. This makes it somewhat
// inconvenient to define constructors: a u32 constructor can be infallible,
// but an i64 constructor can fail (if the value is negative) and a u64
// constructor can fail (if the value is larger than i64::MAX). We provide
// all of these for consumers' convenience.
//
// The maximum byte count of i64::MAX comes from the fact that this is stored
// in the database as an i64. Constraining it here ensures that we can't fail
// to serialize the value.
//
// TODO: custom JsonSchema impl to describe i64::MAX limit; this is blocked by
// https://github.com/oxidecomputer/typify/issues/589
#[derive(
Copy,
Clone,
Debug,
Serialize,
JsonSchema,
Hash,
PartialEq,
Eq,
PartialOrd,
Ord,
Diffable,
)]
pub struct ByteCount(u64);
impl<'de> Deserialize<'de> for ByteCount {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let bytes = u64::deserialize(deserializer)?;
ByteCount::try_from(bytes).map_err(serde::de::Error::custom)
}
}
#[allow(non_upper_case_globals)]
const KiB: u64 = 1024;
#[allow(non_upper_case_globals)]
const MiB: u64 = KiB * 1024;
#[allow(non_upper_case_globals)]
const GiB: u64 = MiB * 1024;
#[allow(non_upper_case_globals)]
const TiB: u64 = GiB * 1024;
impl ByteCount {
// None of these three constructors can create a value larger than
// `i64::MAX`. (Note that a `from_tebibytes_u32` could overflow u64.)
pub const fn from_kibibytes_u32(kibibytes: u32) -> ByteCount {
ByteCount(KiB * kibibytes as u64)
}
pub const fn from_mebibytes_u32(mebibytes: u32) -> ByteCount {
ByteCount(MiB * mebibytes as u64)
}
pub const fn from_gibibytes_u32(gibibytes: u32) -> ByteCount {
ByteCount(GiB * gibibytes as u64)
}
pub const fn to_bytes(&self) -> u64 {
self.0
}
pub const fn to_whole_kibibytes(&self) -> u64 {
self.to_bytes() / KiB
}
pub const fn to_whole_mebibytes(&self) -> u64 {
self.to_bytes() / MiB
}
pub const fn to_whole_gibibytes(&self) -> u64 {
self.to_bytes() / GiB
}
pub const fn to_whole_tebibytes(&self) -> u64 {
self.to_bytes() / TiB
}
}
impl Display for ByteCount {
fn fmt(&self, f: &mut Formatter<'_>) -> FormatResult {
if self.to_bytes() >= TiB && self.to_bytes() % TiB == 0 {
write!(f, "{} TiB", self.to_whole_tebibytes())
} else if self.to_bytes() >= GiB && self.to_bytes() % GiB == 0 {
write!(f, "{} GiB", self.to_whole_gibibytes())
} else if self.to_bytes() >= MiB && self.to_bytes() % MiB == 0 {
write!(f, "{} MiB", self.to_whole_mebibytes())
} else if self.to_bytes() >= KiB && self.to_bytes() % KiB == 0 {
write!(f, "{} KiB", self.to_whole_kibibytes())
} else {
write!(f, "{} B", self.to_bytes())
}
}
}
// TODO-cleanup This could use the experimental std::num::IntErrorKind.
#[derive(Debug, Eq, thiserror::Error, Ord, PartialEq, PartialOrd)]
pub enum ByteCountRangeError {
#[error("value is too small for a byte count")]
TooSmall,
#[error("value is too large for a byte count")]
TooLarge,
}
impl TryFrom<u64> for ByteCount {
type Error = ByteCountRangeError;
fn try_from(bytes: u64) -> Result<Self, Self::Error> {
if i64::try_from(bytes).is_err() {
Err(ByteCountRangeError::TooLarge)
} else {
Ok(ByteCount(bytes))
}
}
}
impl TryFrom<i64> for ByteCount {
type Error = ByteCountRangeError;
fn try_from(bytes: i64) -> Result<Self, Self::Error> {
Ok(ByteCount(
u64::try_from(bytes).map_err(|_| ByteCountRangeError::TooSmall)?,
))
}
}
impl From<u32> for ByteCount {
fn from(value: u32) -> Self {
ByteCount(u64::from(value))
}
}
impl From<ByteCount> for i64 {
fn from(b: ByteCount) -> Self {
// We have already validated that this value is in range.
i64::try_from(b.0).unwrap()
}
}
/// Generation numbers stored in the database, used for optimistic concurrency
/// control
//
// A generation is a value between 0 and 2**63-1, i.e. equivalent to a u63.
// The reason is that we store it as an i64 in the database, and we want to
// disallow negative values. (We could potentially use two's complement to
// store values greater than that as negative values, but surely 2**63 is
// enough.)
#[derive(
Copy,
Clone,
Debug,
Eq,
Hash,
JsonSchema,
Ord,
PartialEq,
PartialOrd,
Serialize,
Diffable,
)]
#[daft(leaf)]
pub struct Generation(u64);
impl Generation {
// `as` is a little distasteful because it allows lossy conversion, but we
// know converting `i64::MAX` to `u64` will always succeed losslessly.
const MAX: Generation = Generation(i64::MAX as u64);
pub const fn new() -> Generation {
Generation(1)
}
pub const fn from_u32(value: u32) -> Generation {
// `as` is a little distasteful because it allows lossy conversion, but
// (a) we know converting `u32` to `u64` will always succeed
// losslessly, and (b) it allows to make this function `const`, unlike
// if we were to use `u64::from(value)`.
Generation(value as u64)
}
pub const fn next(&self) -> Generation {
// It should technically be an operational error if this wraps or even
// exceeds the value allowed by an i64. But it seems unlikely enough to
// happen in practice that we can probably feel safe with this.
let next_gen = self.0 + 1;
assert!(
next_gen <= Generation::MAX.0,
"attempt to overflow generation number"
);
Generation(next_gen)
}
}
impl<'de> Deserialize<'de> for Generation {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = u64::deserialize(deserializer)?;
Generation::try_from(value).map_err(|GenerationOverflowError(_)| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Unsigned(value),
&"an integer between 0 and 9223372036854775807",
)
})
}
}
impl Display for Generation {
fn fmt(&self, f: &mut Formatter<'_>) -> FormatResult {
f.write_str(&self.0.to_string())
}
}
impl From<&Generation> for i64 {
fn from(g: &Generation) -> Self {
// We have already validated that the value is within range.
i64::try_from(g.0).unwrap()
}
}
impl From<Generation> for u64 {
fn from(g: Generation) -> Self {
g.0
}
}
impl From<u32> for Generation {
fn from(value: u32) -> Self {
Generation(u64::from(value))
}
}
impl TryFrom<i64> for Generation {
type Error = GenerationNegativeError;
fn try_from(value: i64) -> Result<Self, Self::Error> {
Ok(Generation(
u64::try_from(value).map_err(|_| GenerationNegativeError(()))?,
))
}
}
impl TryFrom<u64> for Generation {
type Error = GenerationOverflowError;
fn try_from(value: u64) -> Result<Self, Self::Error> {
i64::try_from(value).map_err(|_| GenerationOverflowError(()))?;
Ok(Generation(value))
}
}
impl FromStr for Generation {
type Err = std::num::ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Try to parse `s` as both an i64 and u64, returning the error from
// either.
let _ = i64::from_str(s)?;
Ok(Generation(u64::from_str(s)?))
}
}
#[derive(Debug, thiserror::Error)]
#[error("negative generation number")]
pub struct GenerationNegativeError(());
#[derive(Debug, thiserror::Error)]
#[error("generation number too large")]
pub struct GenerationOverflowError(());
/// An RFC-1035-compliant hostname.
#[derive(
Clone, Debug, Deserialize, Display, Eq, PartialEq, SerializeDisplay,
)]
#[display("{0}")]
#[serde(try_from = "String", into = "String")]
pub struct Hostname(String);
impl Hostname {
/// Return the hostname as a string slice.
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
// Regular expression for hostnames.
//
// Each name is a dot-separated sequence of labels. Each label is supposed to
// be an "LDH": letter, dash, or hyphen. Hostnames can consist of one label, or
// many, separated by a `.`. While _domain_ names are allowed to end in a `.`,
// making them fully-qualified, hostnames are not.
//
// Note that labels are allowed to contain a hyphen, but may not start or end
// with one. See RFC 952, "Lexical grammar" section.
//
// Note that we need to use a regex engine capable of lookbehind to support
// this, since we need to check that labels don't end with a `-`.
const HOSTNAME_REGEX: &str = r#"^([a-zA-Z0-9]+[a-zA-Z0-9\-]*(?<!-))(\.[a-zA-Z0-9]+[a-zA-Z0-9\-]*(?<!-))*$"#;
// Labels need to be encoded on the wire, and prefixed with a signel length
// octet. They also need to end with a length octet of 0 when encoded. So the
// longest name is a single label of 253 characters, which will be encoded as
// `\xfd<the label>\x00`.
const HOSTNAME_MAX_LEN: u32 = 253;
impl FromStr for Hostname {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
anyhow::ensure!(
s.len() <= HOSTNAME_MAX_LEN as usize,
"Max hostname length is {HOSTNAME_MAX_LEN}"
);
let re = regress::Regex::new(HOSTNAME_REGEX).unwrap();
if re.find(s).is_some() {
Ok(Hostname(s.to_string()))
} else {
anyhow::bail!("Hostnames must comply with RFC 1035")
}
}
}
impl TryFrom<&str> for Hostname {
type Error = <Hostname as FromStr>::Err;
fn try_from(s: &str) -> Result<Self, Self::Error> {
s.parse()
}
}
impl TryFrom<String> for Hostname {
type Error = <Hostname as FromStr>::Err;
fn try_from(s: String) -> Result<Self, Self::Error> {
s.as_str().parse()
}
}
// Custom implementation of JsonSchema for Hostname to ensure RFC-1035-style
// validation
impl JsonSchema for Hostname {
fn schema_name() -> String {
"Hostname".to_string()
}
fn json_schema(
_: &mut schemars::gen::SchemaGenerator,
) -> schemars::schema::Schema {
schemars::schema::Schema::Object(schemars::schema::SchemaObject {
metadata: Some(Box::new(schemars::schema::Metadata {
title: Some("An RFC-1035-compliant hostname".to_string()),
description: Some(
"A hostname identifies a host on a network, and \
is usually a dot-delimited sequence of labels, \
where each label contains only letters, digits, \
or the hyphen. See RFCs 1035 and 952 for more details."
.to_string(),
),
..Default::default()
})),
instance_type: Some(schemars::schema::SingleOrVec::Single(
Box::new(schemars::schema::InstanceType::String),
)),
string: Some(Box::new(schemars::schema::StringValidation {
max_length: Some(HOSTNAME_MAX_LEN),
min_length: Some(1),
pattern: Some(HOSTNAME_REGEX.to_string()),
})),
..Default::default()
})
}
}
// General types used to implement API resources
/// Identifies a type of API resource
#[derive(
Clone,
Copy,
Debug,
DeserializeFromStr,
Display,
Eq,
FromStr,
Ord,
PartialEq,
PartialOrd,
SerializeDisplay,
)]
#[display(style = "kebab-case")]
pub enum ResourceType {
AddressLot,
AddressLotBlock,
AffinityGroup,
AffinityGroupMember,
AntiAffinityGroup,
AntiAffinityGroupMember,
AllowList,
BackgroundTask,
BgpConfig,
BgpAnnounceSet,
Blueprint,
Fleet,
Silo,
SiloUser,
SiloGroup,
SiloQuotas,
IdentityProvider,
SamlIdentityProvider,
SshKey,
Certificate,
ConsoleSession,
DeviceAuthRequest,
DeviceAccessToken,
Project,
Dataset,
Disk,
Image,
SiloImage,
ProjectImage,
Instance,
LoopbackAddress,
SwitchPortSettings,
SupportBundle,
IpPool,
IpPoolResource,
InstanceNetworkInterface,
InternetGateway,
InternetGatewayIpPool,
InternetGatewayIpAddress,
PhysicalDisk,
Rack,
Service,
ServiceNetworkInterface,
Sled,
SledInstance,
SledLedger,
Switch,