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
use strum::{Display, EnumString};

use boulder::{BuildableWithPersianRug, GeneratableWithPersianRug};
use boulder::{Cycle, Inc, Pattern, Some as GSome};
use django_query::{
    filtering::FilterableWithPersianRug, row::IntoRowWithPersianRug,
    sorting::SortableWithPersianRug,
};
use persian_rug::{contextual, Context, Proxy};

/// An alias from the LAVA API
#[derive(
    Clone,
    Debug,
    FilterableWithPersianRug,
    SortableWithPersianRug,
    IntoRowWithPersianRug,
    BuildableWithPersianRug,
    GeneratableWithPersianRug,
)]
#[boulder(persian_rug(context = C, access(Alias<C>)))]
#[django(persian_rug(context = C, access(Alias<C>)))]
#[contextual(C)]
pub struct Alias<C: Context + 'static> {
    #[django(exclude)]
    _marker: core::marker::PhantomData<C>,
    #[boulder(default="test-alias", generator=Pattern!("test-alias-{}", Inc(1)))]
    #[django(sort, op(in, contains, icontains, startswith, endswith))]
    pub name: String,
}

/// An architecture from the LAVA API
// FIXME: we implement IntoRowWithPersianRug to get AsForeignKey derived for us
#[derive(
    Clone,
    Debug,
    FilterableWithPersianRug,
    IntoRowWithPersianRug,
    BuildableWithPersianRug,
    GeneratableWithPersianRug,
)]
#[boulder(persian_rug(context = C, access(Architecture<C>)))]
#[django(persian_rug(context = C, access(Architecture<C>)))]
#[contextual(C)]
pub struct Architecture<C: Context + 'static> {
    #[django(exclude)]
    _marker: core::marker::PhantomData<C>,
    #[boulder(default="test-arch", generator=Pattern!("test-arch-{}", Inc(1)))]
    #[django(op(in, contains, icontains, startswith, endswith))]
    pub name: String,
}

/// A bit width from the LAVA API
// FIXME: we implement IntoRowWithPersianRug to get AsForeignKey derived for us
#[derive(
    Clone,
    Debug,
    FilterableWithPersianRug,
    IntoRowWithPersianRug,
    BuildableWithPersianRug,
    GeneratableWithPersianRug,
)]
#[boulder(persian_rug(context = C, access(BitWidth<C>)))]
#[django(persian_rug(context = C, access(BitWidth<C>)))]
#[contextual(C)]
pub struct BitWidth<C: Context + 'static> {
    #[django(exclude)]
    _marker: core::marker::PhantomData<C>,
    #[boulder(default=64u64, generator=Cycle::new(vec![32u64,64u64].into_iter()))]
    #[django(op(in))]
    pub width: u64,
}

/// A core from the LAVA API
// FIXME: we implement IntoRowWithPersianRug to get AsForeignKey derived for us
#[derive(
    Clone,
    Debug,
    FilterableWithPersianRug,
    IntoRowWithPersianRug,
    BuildableWithPersianRug,
    GeneratableWithPersianRug,
)]
#[boulder(persian_rug(context = C, access(Core<C>)))]
#[django(persian_rug(context = C, access(Core<C>)))]
#[contextual(C)]
pub struct Core<C: Context + 'static> {
    #[django(exclude)]
    _marker: core::marker::PhantomData<C>,
    #[boulder(default="test-core", generator=Pattern!("test-core-{}", Inc(1)))]
    #[django(op(in, contains, icontains, startswith, endswith))]
    pub name: String,
}

/// A processor family from the LAVA API
// FIXME: we implement IntoRowWithPersianRug to get AsForeignKey derived for us
#[derive(
    Clone,
    Debug,
    FilterableWithPersianRug,
    IntoRowWithPersianRug,
    BuildableWithPersianRug,
    GeneratableWithPersianRug,
)]
#[boulder(persian_rug(context = C, access(ProcessorFamily<C>)))]
#[django(persian_rug(context = C, access(ProcessorFamily<C>)))]
#[contextual(C)]
pub struct ProcessorFamily<C: Context + 'static> {
    #[django(exclude)]
    _marker: core::marker::PhantomData<C>,
    #[boulder(default="test-processor-family", generator=Pattern!("test-processor-family-{}", Inc(1)))]
    #[django(op(in, contains, icontains, startswith, endswith))]
    pub name: String,
}

/// A device type from the LAVA API
// FIXME: Verify: the docs say this is not sortable
// FIXME: Only implementing sortable so that we can do a nested sort on the name key
#[derive(
    Clone,
    Debug,
    FilterableWithPersianRug,
    SortableWithPersianRug,
    IntoRowWithPersianRug,
    BuildableWithPersianRug,
    GeneratableWithPersianRug,
)]
#[boulder(
    persian_rug(
        context = C,
        access(
            DeviceType<C>,
            Alias<C>,
            Architecture<C>,
            BitWidth<C>,
            Core<C>,
            ProcessorFamily<C>
        )
    )
)]
#[django(
    persian_rug(
        context = C,
        access(
            DeviceType<C>,
            Alias<C>,
            Architecture<C>,
            BitWidth<C>,
            Core<C>,
            ProcessorFamily<C>
        )
    )
)]
#[contextual(C)]
pub struct DeviceType<C: Context + 'static> {
    #[boulder(default="test-device-type", generator=Pattern!("test-device-type-{}", Inc(0)))]
    #[django(sort, op(in, contains, icontains, startswith, endswith))]
    pub name: String,
    #[boulder(buildable_with_persian_rug, generatable_with_persian_rug)]
    #[django(traverse, foreign_key = "name")]
    pub architecture: Option<Proxy<Architecture<C>>>,
    #[boulder(buildable_with_persian_rug, generatable_with_persian_rug)]
    #[django(traverse, foreign_key = "name")]
    pub processor: Option<Proxy<ProcessorFamily<C>>>,
    #[boulder(default=Some("test-cpu-model".to_string()), generator=GSome(Pattern!("test-cpu-model-{}", Inc(0))))]
    #[django(op(in, contains, icontains, startswith, endswith))]
    pub cpu_model: Option<String>,
    #[boulder(generatable_with_persian_rug, sequence = 2usize)]
    #[django(traverse, foreign_key = "name")]
    pub aliases: Vec<Proxy<Alias<C>>>,
    #[boulder(buildable_with_persian_rug, generatable_with_persian_rug)]
    #[django(traverse, foreign_key = "width")]
    pub bits: Option<Proxy<BitWidth<C>>>,
    #[boulder(generatable_with_persian_rug,sequence=4usize,sequence_generator=Cycle::new(vec![4usize,8usize,16usize].into_iter()))]
    #[django(traverse, foreign_key = "name")]
    pub cores: Vec<Proxy<Core<C>>>,
    #[boulder(default=Some(4), generator=GSome(Cycle::new(vec![4,8,16].into_iter())))]
    #[django(op(in))]
    pub core_count: Option<u64>,
    #[boulder(default=Some("Example device type description.".to_string()))]
    #[django(op(in, contains, icontains, startswith, endswith))]
    pub description: Option<String>,
    #[boulder(default = 10)]
    #[django(op(in))]
    pub health_frequency: i64,
    #[boulder(default = false)]
    #[django(op(in))]
    pub disable_health_check: bool,
    #[boulder(default=HealthDenominator::Hours)]
    pub health_denominator: HealthDenominator,
    #[boulder(default = true)]
    #[django(op(in))]
    pub display: bool,
}

/// The units for the [`health_frequency`](Device::health_frequency)
/// field in [`Device`] from the LAVA API
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Display, EnumString)]
#[strum(serialize_all = "snake_case")]
pub enum HealthDenominator {
    Hours,
    Jobs,
}

impl django_query::filtering::ops::Scalar for HealthDenominator {}
impl django_query::row::StringCellValue for HealthDenominator {}

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

    use crate::state::{SharedState, State};

    use boulder::{GeneratorWithPersianRugIterator, Repeat};
    use test_log::test;

    #[test(tokio::test)]
    async fn test_output() {
        let mut p = SharedState::new();
        {
            let m = p.mutate();

            let gen = Proxy::<DeviceType<State>>::generator()
                .architecture(|| None)
                .processor(|| None)
                .cpu_model(Repeat::new([None, Some("".to_string())]))
                .aliases(|| Vec::new())
                .bits(|| None)
                .cores(|| Vec::new())
                .core_count(|| None)
                .description(Repeat::new([None, Some("".to_string())]))
                .health_frequency(|| 10);

            let _ = GeneratorWithPersianRugIterator::new(gen, m)
                .take(5)
                .collect::<Vec<_>>();
        }

        let server = wiremock::MockServer::start().await;

        let ep = p.endpoint::<DeviceType<_>>(Some(&server.uri()), None);

        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/api/v0.2/devicetypes/"))
            .respond_with(ep)
            .mount(&server)
            .await;

        let body: serde_json::Value = reqwest::get(&format!(
            "{}/api/v0.2/devicetypes/?limit=2&offset=2",
            server.uri()
        ))
        .await
        .expect("error getting device types")
        .json()
        .await
        .expect("error parsing device types");

        let next = format!("{}/api/v0.2/devicetypes/?limit=2&offset=4", server.uri());
        let prev = format!("{}/api/v0.2/devicetypes/?limit=2", server.uri());

        assert_eq!(
            body,
            serde_json::json! {
                {
                    "count": 5,
                    "next": next,
                    "previous": prev,
                    "results": [
                        {
                            "name": "test-device-type-2",
                            "architecture": null,
                            "processor": null,
                            "cpu_model": null,
                            "aliases": [],
                            "bits": null,
                            "cores": [],
                            "core_count": null,
                            "description": null,
                            "health_frequency": 10,
                            "disable_health_check": false,
                            "health_denominator": "hours",
                            "display": true
                        },
                        {
                            "name": "test-device-type-3",
                            "architecture": null,
                            "processor": null,
                            "cpu_model": "",
                            "aliases": [],
                            "bits": null,
                            "cores": [],
                            "core_count": null,
                            "description": "",
                            "health_frequency": 10,
                            "disable_health_check": false,
                            "health_denominator": "hours",
                            "display": true
                        }
                    ]
                }
            }
        );
    }
}