xapi-rs 0.1.22

A conformant LRS implementation of xAPI 2.0.0
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
// SPDX-License-Identifier: GPL-3.0-or-later

use crate::{
    MyLanguageTag,
    data::{
        Actor, ActorId, ContextActivities, ContextActivitiesId, ContextAgent, ContextAgentId,
        ContextGroup, ContextGroupId, DataError, Extensions, Fingerprint, Group, GroupId,
        StatementRef, Validate, ValidationError,
    },
    emit_error,
};
use core::fmt;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;
use std::{hash::Hasher, ops::Deref, str::FromStr};
use tracing::error;
use uuid::Uuid;

/// Structure that gives a [Statement][1] more meaning like a team the
/// [Actor][2] is working with, or the _altitude_ at which a scenario was
/// attempted in a flight simulator exercise.
///
/// [1]: crate::Statement
/// [2]: crate::Actor
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "camelCase")]
pub struct Context {
    registration: Option<Uuid>,
    instructor: Option<Actor>,
    team: Option<Group>,
    context_activities: Option<ContextActivities>,
    context_agents: Option<Vec<ContextAgent>>,
    context_groups: Option<Vec<ContextGroup>>,
    revision: Option<String>,
    platform: Option<String>,
    language: Option<MyLanguageTag>,
    statement: Option<StatementRef>,
    extensions: Option<Extensions>,
}

#[skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ContextId {
    registration: Option<Uuid>,
    instructor: Option<ActorId>,
    team: Option<GroupId>,
    context_activities: Option<ContextActivitiesId>,
    context_agents: Option<Vec<ContextAgentId>>,
    context_groups: Option<Vec<ContextGroupId>>,
    revision: Option<String>,
    platform: Option<String>,
    language: Option<MyLanguageTag>,
    statement: Option<StatementRef>,
    extensions: Option<Extensions>,
}

impl From<Context> for ContextId {
    fn from(value: Context) -> Self {
        ContextId {
            registration: value.registration,
            instructor: value.instructor.map(ActorId::from),
            team: value.team.map(GroupId::from),
            context_activities: value.context_activities.map(ContextActivitiesId::from),
            context_agents: value
                .context_agents
                .map(|z_agents| z_agents.into_iter().map(ContextAgentId::from).collect()),
            context_groups: value
                .context_groups
                .map(|z_groups| z_groups.into_iter().map(ContextGroupId::from).collect()),
            revision: value.revision,
            platform: value.platform,
            language: value.language,
            statement: value.statement,
            extensions: value.extensions,
        }
    }
}

impl From<ContextId> for Context {
    fn from(value: ContextId) -> Self {
        Context {
            registration: value.registration,
            instructor: value.instructor.map(Actor::from),
            team: value.team.map(Group::from),
            context_activities: value.context_activities.map(ContextActivities::from),
            context_agents: value
                .context_agents
                .map(|z_agents| z_agents.into_iter().map(ContextAgent::from).collect()),
            context_groups: value
                .context_groups
                .map(|z_groups| z_groups.into_iter().map(ContextGroup::from).collect()),
            revision: value.revision,
            platform: value.platform,
            language: value.language,
            statement: value.statement,
            extensions: value.extensions,
        }
    }
}

impl Context {
    /// Return a [Context] -Builder_.
    pub fn builder() -> ContextBuilder {
        ContextBuilder::default()
    }

    /// Return `registration` (a UUID) if set; `None` otherwise.
    pub fn registration(&self) -> Option<&Uuid> {
        self.registration.as_ref()
    }

    /// Return `instructor` if set; `None` otherwise.
    pub fn instructor(&self) -> Option<&Actor> {
        self.instructor.as_ref()
    }

    /// Return `team` if set; `None` otherwise.
    pub fn team(&self) -> Option<&Group> {
        self.team.as_ref()
    }

    /// Return `context_activities` if set; `None` otherwise.
    pub fn context_activities(&self) -> Option<&ContextActivities> {
        self.context_activities.as_ref()
    }

    /// Return `context_agents` if set; `None` otherwise.
    pub fn context_agents(&self) -> Option<&[ContextAgent]> {
        self.context_agents.as_deref()
    }

    /// Return `context_groups` if set; `None` otherwise.
    pub fn context_groups(&self) -> Option<&[ContextGroup]> {
        self.context_groups.as_deref()
    }

    /// Return `revision` if set; `None` otherwise.
    pub fn revision(&self) -> Option<&str> {
        self.revision.as_deref()
    }

    /// Return `platform` if set; `None` otherwise.
    pub fn platform(&self) -> Option<&str> {
        self.platform.as_deref()
    }

    /// Return `language` if set; `None` otherwise.
    pub fn language(&self) -> Option<&MyLanguageTag> {
        self.language.as_ref()
    }

    /// Return `language` as string reference if set; `None` otherwise.
    pub fn language_as_str(&self) -> Option<&str> {
        match &self.language {
            Some(x) => Some(x.as_str()),
            None => None,
        }
    }

    /// Return `statement` if set; `None` otherwise.
    pub fn statement(&self) -> Option<&StatementRef> {
        self.statement.as_ref()
    }

    /// Return `extensions` if set; `None` otherwise.
    pub fn extensions(&self) -> Option<&Extensions> {
        self.extensions.as_ref()
    }
}

impl Fingerprint for Context {
    fn fingerprint<H: Hasher>(&self, state: &mut H) {
        if self.registration.is_some() {
            state.write(self.registration().unwrap().as_bytes());
        }
        if self.instructor.is_some() {
            self.instructor().unwrap().fingerprint(state)
        }
        if self.team.is_some() {
            self.team().unwrap().fingerprint(state)
        }
        if self.context_activities.is_some() {
            self.context_activities().unwrap().fingerprint(state)
        }
        if self.context_agents.is_some() {
            Fingerprint::fingerprint_slice(self.context_agents().unwrap(), state)
        }
        if self.context_groups.is_some() {
            Fingerprint::fingerprint_slice(self.context_groups().unwrap(), state)
        }
        if self.revision.is_some() {
            state.write(self.revision().unwrap().as_bytes())
        }
        if self.platform.is_some() {
            state.write(self.platform().unwrap().as_bytes())
        }
        if let Some(z_language) = self.language.as_ref() {
            state.write(z_language.as_str().as_bytes())
        }
        if self.statement.is_some() {
            self.statement().unwrap().fingerprint(state)
        }
        if self.extensions.is_some() {
            self.extensions().unwrap().fingerprint(state)
        }
    }
}

impl fmt::Display for Context {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut vec = vec![];

        if let Some(z_registration) = self.registration.as_ref() {
            vec.push(format!(
                "registration: \"{}\"",
                z_registration
                    .hyphenated()
                    .encode_lower(&mut Uuid::encode_buffer())
            ))
        }
        if let Some(z_instructor) = self.instructor.as_ref() {
            vec.push(format!("instructor: {}", z_instructor))
        }
        if let Some(z_team) = self.team.as_ref() {
            vec.push(format!("team: {}", z_team))
        }
        if let Some(z_activities) = self.context_activities.as_ref() {
            vec.push(format!("contextActivities: {}", z_activities));
        }
        if self.context_agents.is_some() {
            let items = self.context_agents.as_deref().unwrap();
            vec.push(format!(
                "contextAgents: [{}]",
                items
                    .iter()
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        if self.context_groups.is_some() {
            let items = self.context_groups.as_deref().unwrap();
            vec.push(format!(
                "contextGroups: [{}]",
                items
                    .iter()
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }
        if let Some(z_revision) = self.revision.as_ref() {
            vec.push(format!("revision: \"{}\"", z_revision))
        }
        if let Some(z_platform) = self.platform.as_ref() {
            vec.push(format!("platform: \"{}\"", z_platform))
        }
        if let Some(z_language) = self.language.as_ref() {
            vec.push(format!("language: \"{}\"", z_language))
        }
        if let Some(z_statement) = self.statement.as_ref() {
            vec.push(format!("statement: {}", z_statement))
        }
        if let Some(z_extensions) = self.extensions.as_ref() {
            vec.push(format!("extensions: {}", z_extensions))
        }

        let res = vec
            .iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(", ");
        write!(f, "Context{{ {res} }}")
    }
}

impl Validate for Context {
    fn validate(&self) -> Vec<ValidationError> {
        let mut vec = vec![];

        if self.registration.is_some()
            && (self.registration.as_ref().unwrap().is_nil()
                || self.registration.as_ref().unwrap().is_max())
        {
            let msg = "UUID must not be all 0's or 1's";
            error!("{}", msg);
            vec.push(ValidationError::ConstraintViolation(msg.into()))
        }
        if let Some(z_instructor) = self.instructor.as_ref() {
            vec.extend(z_instructor.validate())
        }
        if let Some(z_team) = self.team.as_ref() {
            vec.extend(z_team.validate());
        }
        if let Some(z_activities) = self.context_activities.as_ref() {
            vec.extend(z_activities.validate());
        }
        if let Some(z_agents) = self.context_agents.as_ref() {
            for ca in z_agents.iter() {
                vec.extend(ca.validate())
            }
        }
        if let Some(z_groups) = self.context_groups.as_ref() {
            for cg in z_groups.iter() {
                vec.extend(cg.validate())
            }
        }
        if self.revision.is_some() && self.revision.as_ref().unwrap().is_empty() {
            vec.push(ValidationError::Empty("revision".into()))
        }
        if self.platform.is_some() && self.platform.as_ref().unwrap().is_empty() {
            vec.push(ValidationError::Empty("platform".into()))
        }
        if let Some(z_statement) = self.statement.as_ref() {
            vec.extend(z_statement.validate())
        }

        vec
    }
}

/// A Type that knows how to construct a [Context].
#[derive(Debug, Default)]
pub struct ContextBuilder {
    _registration: Option<Uuid>,
    _instructor: Option<Actor>,
    _team: Option<Group>,
    _context_activities: Option<ContextActivities>,
    _context_agents: Option<Vec<ContextAgent>>,
    _context_groups: Option<Vec<ContextGroup>>,
    _revision: Option<String>,
    _platform: Option<String>,
    _language: Option<MyLanguageTag>,
    _statement: Option<StatementRef>,
    _extensions: Option<Extensions>,
}

impl ContextBuilder {
    /// Set the `registration` field from an `&str`.
    ///
    /// Raise [DataError] if the input string is empty.
    pub fn registration(mut self, val: &str) -> Result<Self, DataError> {
        let val = val.trim();
        if val.is_empty() {
            emit_error!(DataError::Validation(ValidationError::Empty(
                "registration".into()
            )))
        } else {
            let uuid = Uuid::parse_str(val)?;
            if uuid.is_nil() || uuid.is_max() {
                emit_error!(DataError::Validation(ValidationError::ConstraintViolation(
                    "UUID should not be all zeroes or ones".into()
                )))
            } else {
                self._registration = Some(uuid);
                Ok(self)
            }
        }
    }

    /// Set the `registration` field from a UUID value.
    ///
    /// Raise [DataError] if the input string is empty.
    pub fn registration_uuid(mut self, uuid: Uuid) -> Result<Self, DataError> {
        if uuid.is_nil() || uuid.is_max() {
            emit_error!(DataError::Validation(ValidationError::ConstraintViolation(
                "UUID should not be all zeroes or ones".into()
            )))
        } else {
            self._registration = Some(uuid);
            Ok(self)
        }
    }

    /// Set the `instructor` field.
    ///
    /// Raise [DataError] if the [Actor] argument is invalid.
    pub fn instructor(mut self, val: Actor) -> Result<Self, DataError> {
        val.check_validity()?;
        self._instructor = Some(val);
        Ok(self)
    }

    /// Set the `team` field.
    ///
    /// Raise [DataError] if the [Group] argument is invalid.
    pub fn team(mut self, val: Group) -> Result<Self, DataError> {
        val.check_validity()?;
        self._team = Some(val);
        Ok(self)
    }

    /// Set the `context_activities` field.
    ///
    /// Raise [DataError] if the [ContextActivities] argument is invalid.
    pub fn context_activities(mut self, val: ContextActivities) -> Result<Self, DataError> {
        val.check_validity()?;
        self._context_activities = Some(val);
        Ok(self)
    }

    /// Add a [ContextAgent] to `context_agents` field.
    ///
    /// Raise [DataError] if the [ContextAgent] argument is invalid.
    pub fn context_agent(mut self, val: ContextAgent) -> Result<Self, DataError> {
        val.check_validity()?;
        if self._context_agents.is_none() {
            self._context_agents = Some(vec![])
        }
        self._context_agents.as_mut().unwrap().push(val);
        Ok(self)
    }

    /// Add a [ContextGroup] to `context_groups` field.
    ///
    /// Raise [DataError] if the [ContextGroup] argument is invalid.
    pub fn context_group(mut self, val: ContextGroup) -> Result<Self, DataError> {
        val.check_validity()?;
        if self._context_groups.is_none() {
            self._context_groups = Some(vec![])
        }
        self._context_groups.as_mut().unwrap().push(val);
        Ok(self)
    }

    /// Set the `revision` field.
    ///
    /// Raise [DataError] if the input string is empty.
    pub fn revision<S: Deref<Target = str>>(mut self, val: S) -> Result<Self, DataError> {
        let val = val.trim();
        if val.is_empty() {
            emit_error!(DataError::Validation(ValidationError::Empty(
                "revision".into()
            )))
        } else {
            self._revision = Some(val.to_owned());
            Ok(self)
        }
    }

    /// Set the `platform` field.
    ///
    /// Raise [DataError] if the input string is empty.
    pub fn platform<S: Deref<Target = str>>(mut self, val: S) -> Result<Self, DataError> {
        let val = val.trim();
        if val.is_empty() {
            emit_error!(DataError::Validation(ValidationError::Empty(
                "platform".into()
            )))
        } else {
            self._platform = Some(val.to_owned());
            Ok(self)
        }
    }

    /// Set the `language` field.
    ///
    /// Raise [DataError] if the input string is empty.
    pub fn language<S: Deref<Target = str>>(mut self, val: S) -> Result<Self, DataError> {
        let val = val.trim();
        if val.is_empty() {
            emit_error!(DataError::Validation(ValidationError::Empty(
                "language".into()
            )))
        } else {
            self._language = Some(MyLanguageTag::from_str(val)?);

            Ok(self)
        }
    }

    /// Set the `statement` field from given [StatementRef] instance.
    ///
    /// Raise [DataError] if the argument is invalid.
    pub fn statement(mut self, val: StatementRef) -> Result<Self, DataError> {
        val.check_validity()?;
        self._statement = Some(val);
        Ok(self)
    }

    /// Set the `statement` field from a Statement's UUID.
    ///
    /// Raise [DataError] if the argument is invalid.
    pub fn statement_uuid(mut self, uuid: Uuid) -> Result<Self, DataError> {
        let val = StatementRef::builder().id_as_uuid(uuid)?.build()?;
        self._statement = Some(val);
        Ok(self)
    }

    /// Add to `extensions` an entry w/ (`key`, `value`) pair.
    ///
    /// Raise [DataError] if the `key` is empty.
    pub fn extension(mut self, key: &str, value: &Value) -> Result<Self, DataError> {
        if self._extensions.is_none() {
            self._extensions = Some(Extensions::new());
        }
        let _ = self._extensions.as_mut().unwrap().add(key, value);
        Ok(self)
    }

    /// Set (as in replace) the `extensions` property of this instance  w/ the
    /// given argument.
    pub fn with_extensions(mut self, map: Extensions) -> Result<Self, DataError> {
        self._extensions = Some(map);
        Ok(self)
    }

    /// Create a [Context] from set field values.
    pub fn build(self) -> Result<Context, DataError> {
        if self._registration.is_none()
            && self._instructor.is_none()
            && self._team.is_none()
            && self._context_activities.is_none()
            && self._context_agents.is_none()
            && self._context_groups.is_none()
            && self._revision.is_none()
            && self._platform.is_none()
            && self._language.is_none()
            && self._statement.is_none()
            && self._extensions.is_none()
        {
            emit_error!(DataError::Validation(ValidationError::ConstraintViolation(
                "At least one of the fields must not be empty".into()
            )))
        } else {
            Ok(Context {
                registration: self._registration,
                instructor: self._instructor,
                team: self._team,
                context_activities: self._context_activities,
                context_agents: self._context_agents,
                context_groups: self._context_groups,
                revision: self._revision,
                platform: self._platform,
                language: self._language,
                statement: self._statement,
                extensions: self._extensions,
            })
        }
    }
}

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

    #[traced_test]
    #[test]
    fn test_simple() {
        const JSON: &str = r#"{
            "registration": "ec531277-b57b-4c15-8d91-d292c5b2b8f7",
            "contextActivities": {
                "parent": [
                    {
                        "id": "http://www.example.com/meetings/series/267",
                        "objectType": "Activity"
                    }
                ],
                "category": [
                    {
                        "id": "http://www.example.com/meetings/categories/teammeeting",
                        "objectType": "Activity",
                        "definition": {
                            "name": {
                                "en": "team meeting"
                            },
                            "description": {
                                "en": "A category of meeting used for regular team meetings."
                            },
                            "type": "http://example.com/expapi/activities/meetingcategory"
                        }
                    }
                ],
                "other": [
                    {
                        "id": "http://www.example.com/meetings/occurances/34257",
                        "objectType": "Activity"
                    },
                    {
                        "id": "http://www.example.com/meetings/occurances/3425567",
                        "objectType": "Activity"
                    }
                ]
            },
            "instructor": {
                "name": "Andrew Downes",
                "account": {
                    "homePage": "http://www.example.com",
                    "name": "13936749"
                },
                "objectType": "Agent"
            },
            "team": {
                "name": "Team PB",
                "mbox": "mailto:teampb@example.com",
                "objectType": "Group"
            },
            "platform": "Example virtual meeting software",
            "language": "tlh",
            "statement": {
                "objectType": "StatementRef",
                "id": "6690e6c9-3ef0-4ed3-8b37-7f3964730bee"
            }
        }"#;
        let de_result = serde_json::from_str::<Context>(JSON);
        assert!(de_result.is_ok());
        let _ctx = de_result.unwrap();
    }
}