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
use heapless::{String, Vec};
use serde::{Deserialize, Serialize};

use super::{StatusDetails, MAX_JOB_ID_LEN, MAX_PENDING_JOBS, MAX_RUNNING_JOBS};

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum JobStatus {
    #[serde(rename = "QUEUED")]
    Queued,
    #[serde(rename = "IN_PROGRESS")]
    InProgress,
    #[serde(rename = "FAILED")]
    Failed,
    #[serde(rename = "SUCCEEDED")]
    Succeeded,
    #[serde(rename = "CANCELED")]
    Canceled,
    #[serde(rename = "REJECTED")]
    Rejected,
    #[serde(rename = "REMOVED")]
    Removed,
}

#[derive(Debug, Clone, PartialEq, Deserialize)]
pub enum ErrorCode {
    /// The request was sent to a topic in the AWS IoT Jobs namespace that does
    /// not map to any API.
    InvalidTopic,
    /// The contents of the request could not be interpreted as valid
    /// UTF-8-encoded JSON.
    InvalidJson,
    /// The contents of the request were invalid. For example, this code is
    /// returned when an UpdateJobExecution request contains invalid status
    /// details. The message contains details about the error.
    InvalidRequest,
    /// An update attempted to change the job execution to a state that is
    /// invalid because of the job execution's current state (for example, an
    /// attempt to change a request in state SUCCEEDED to state IN_PROGRESS). In
    /// this case, the body of the error message also contains the
    /// executionState field.
    InvalidStateTransition,
    /// The JobExecution specified by the request topic does not exist.
    ResourceNotFound,
    /// The expected version specified in the request does not match the version
    /// of the job execution in the AWS IoT Jobs service. In this case, the body
    /// of the error message also contains the executionState field.
    VersionMismatch,
    /// There was an internal error during the processing of the request.
    InternalError,
    /// The request was throttled.
    RequestThrottled,
    /// Occurs when a command to describe a job is performed on a job that is in
    /// a terminal state.
    TerminalStateReached,
}

/// Topic (accepted): $aws/things/{thingName}/jobs/{jobId}/get/accepted \
/// Topic (rejected): $aws/things/{thingName}/jobs/{jobId}/get/rejected
#[derive(Debug, PartialEq, Deserialize)]
pub struct DescribeJobExecutionResponse<'a, J> {
    /// Contains data about a job execution.
    #[serde(rename = "execution")]
    pub execution: Option<JobExecution<'a, J>>,
    /// The time, in seconds since the epoch, when the message was sent.
    #[serde(rename = "timestamp")]
    pub timestamp: i64,
    /// A client token used to correlate requests and responses. Enter an
    /// arbitrary value here and it is reflected in the response.
    #[serde(rename = "clientToken")]
    pub client_token: Option<&'a str>,
}

/// Topic (accepted): $aws/things/{thingName}/jobs/get/accepted \
/// Topic (rejected): $aws/things/{thingName}/jobs/get/rejected
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct GetPendingJobExecutionsResponse<'a> {
    /// A list of JobExecutionSummary objects with status IN_PROGRESS.
    #[serde(rename = "inProgressJobs")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub in_progress_jobs: Option<Vec<JobExecutionSummary, MAX_RUNNING_JOBS>>,
    /// A list of JobExecutionSummary objects with status QUEUED.
    #[serde(rename = "queuedJobs")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queued_jobs: Option<Vec<JobExecutionSummary, MAX_PENDING_JOBS>>,
    /// The time, in seconds since the epoch, when the message was sent.
    #[serde(rename = "timestamp")]
    pub timestamp: i64,
    /// A client token used to correlate requests and responses. Enter an
    /// arbitrary value here and it is reflected in the response.
    #[serde(rename = "clientToken")]
    pub client_token: &'a str,
}

/// Contains data about a job execution.
#[derive(Debug, PartialEq, Deserialize)]
pub struct JobExecution<'a, J> {
    /// The estimated number of seconds that remain before the job execution
    /// status will be changed to <code>TIMED_OUT</code>.
    #[serde(rename = "approximateSecondsBeforeTimedOut")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approximate_seconds_before_timed_out: Option<i64>,
    /// A number that identifies a particular job execution on a particular
    /// device. It can be used later in commands that return or update job
    /// execution information.
    #[serde(rename = "executionNumber")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_number: Option<i64>,
    /// The content of the job document.
    #[serde(rename = "jobDocument")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_document: Option<J>,
    /// The unique identifier you assigned to this job when it was created.
    #[serde(rename = "jobId")]
    pub job_id: &'a str,
    /// The time, in seconds since the epoch, when the job execution was last
    /// updated.
    #[serde(rename = "lastUpdatedAt")]
    pub last_updated_at: i64,
    /// The time, in seconds since the epoch, when the job execution was
    /// enqueued.
    #[serde(rename = "queuedAt")]
    pub queued_at: i64,
    /// The time, in seconds since the epoch, when the job execution was
    /// started.
    #[serde(rename = "startedAt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub started_at: Option<i64>,
    /// The status of the job execution. Can be one of: "QUEUED", "IN_PROGRESS",
    /// "FAILED", "SUCCESS", "CANCELED", "REJECTED", or "REMOVED".
    #[serde(rename = "status")]
    pub status: JobStatus,
    // / A collection of name/value pairs that describe the status of the job
    // execution.
    #[serde(rename = "statusDetails")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_details: Option<StatusDetails<'a>>,
    // The name of the thing that is executing the job.
    #[serde(rename = "thingName")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thing_name: Option<&'a str>,
    /// The version of the job execution. Job execution versions are incremented
    /// each time they are updated by a device.
    #[serde(rename = "versionNumber")]
    pub version_number: i64,
}

/// Contains data about the state of a job execution.
#[derive(Debug, PartialEq, Deserialize)]
pub struct JobExecutionState<'a> {
    /// The status of the job execution. Can be one of: "QUEUED", "IN_PROGRESS",
    /// "FAILED", "SUCCESS", "CANCELED", "REJECTED", or "REMOVED".
    #[serde(rename = "status")]
    pub status: JobStatus,
    /// A collection of name/value pairs that describe the status of the job
    /// execution.
    #[serde(rename = "statusDetails")]
    #[serde(borrow)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_details: Option<StatusDetails<'a>>,
    // The version of the job execution. Job execution versions are incremented
    // each time they are updated by a device.
    #[serde(rename = "versionNumber")]
    pub version_number: i64,
}

/// Contains a subset of information about a job execution.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct JobExecutionSummary {
    /// A number that identifies a particular job execution on a particular
    /// device.
    #[serde(rename = "executionNumber")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_number: Option<i64>,
    /// The unique identifier you assigned to this job when it was created.
    #[serde(rename = "jobId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_id: Option<String<MAX_JOB_ID_LEN>>,
    /// The time, in seconds since the epoch, when the job execution was last
    /// updated.
    #[serde(rename = "lastUpdatedAt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_updated_at: Option<i64>,
    /// The time, in seconds since the epoch, when the job execution was
    /// enqueued.
    #[serde(rename = "queuedAt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queued_at: Option<i64>,
    /// The time, in seconds since the epoch, when the job execution started.
    #[serde(rename = "startedAt")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub started_at: Option<i64>,
    /// The version of the job execution. Job execution versions are incremented
    /// each time AWS IoT Jobs receives an update from a device.
    #[serde(rename = "versionNumber")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version_number: Option<i64>,
}

/// Topic (accepted): $aws/things/{thingName}/jobs/start-next/accepted \
/// Topic (rejected): $aws/things/{thingName}/jobs/start-next/rejected
#[derive(Debug, PartialEq, Deserialize)]
pub struct StartNextPendingJobExecutionResponse<'a, J> {
    /// A JobExecution object.
    #[serde(rename = "execution")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution: Option<JobExecution<'a, J>>,
    /// The time, in seconds since the epoch, when the message was sent.
    #[serde(rename = "timestamp")]
    pub timestamp: i64,
    /// A client token used to correlate requests and responses. Enter an
    /// arbitrary value here and it is reflected in the response.
    #[serde(rename = "clientToken")]
    pub client_token: &'a str,
}

/// Topic (accepted): $aws/things/{thingName}/jobs/{jobId}/update/accepted \
/// Topic (rejected): $aws/things/{thingName}/jobs/{jobId}/update/rejected
#[derive(Debug, PartialEq, Deserialize)]
pub struct UpdateJobExecutionResponse<'a, J> {
    /// A JobExecutionState object.
    #[serde(rename = "executionState")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_state: Option<JobExecutionState<'a>>,
    /// The contents of the Job Documents.
    #[serde(rename = "jobDocument")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub job_document: Option<J>,
    /// The time, in seconds since the epoch, when the message was sent.
    #[serde(rename = "timestamp")]
    pub timestamp: i64,
    /// A client token used to correlate requests and responses. Enter an
    /// arbitrary value here and it is reflected in the response.
    #[serde(rename = "clientToken")]
    pub client_token: &'a str,
}

/// Sent whenever a job execution is added to or removed from the list of
/// pending job executions for a thing.
///
/// Topic: $aws/things/{thingName}/jobs/notify
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct JobExecutionsChanged {
    /// A list of JobExecutionSummary objects with status IN_PROGRESS.
    #[serde(rename = "jobs")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jobs: Option<Jobs>,
    /// The time, in seconds since the epoch, when the message was sent.
    #[serde(rename = "timestamp")]
    pub timestamp: i64,
}

/// Sent whenever there is a change to which job execution is next on the list
/// of pending job executions for a thing, as defined for DescribeJobExecution
/// with jobId $next. This message is not sent when the next job's execution
/// details change, only when the next job that would be returned by
/// DescribeJobExecution with jobId $next has changed. Consider job executions
/// J1 and J2 with state QUEUED. J1 is next on the list of pending job
/// executions. If the state of J2 is changed to IN_PROGRESS while the state of
/// J1 remains unchanged, then this notification is sent and contains details of
/// J2.
///
/// Topic: $aws/things/{thingName}/jobs/notify-next
#[derive(Debug, PartialEq, Deserialize)]
pub struct NextJobExecutionChanged<'a, J> {
    /// Contains data about a job execution.
    #[serde(rename = "execution")]
    #[serde(borrow)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution: Option<JobExecution<'a, J>>,
    /// The time, in seconds since the epoch, when the message was sent.
    #[serde(rename = "timestamp")]
    pub timestamp: i64,
}

#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct Jobs {
    /// Queued jobs.
    #[serde(rename = "QUEUED")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub queued: Option<Vec<JobExecutionSummary, MAX_RUNNING_JOBS>>,
    /// In-progress jobs.
    #[serde(rename = "IN_PROGRESS")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub in_progress: Option<Vec<JobExecutionSummary, MAX_RUNNING_JOBS>>,
}

/// Contains information about an error that occurred during an AWS IoT Jobs
/// service operation.
#[derive(Debug, PartialEq, Deserialize)]
pub struct ErrorResponse<'a> {
    code: ErrorCode,
    /// An error message string.
    message: &'a str,
    /// A client token used to correlate requests and responses. Enter an
    /// arbitrary value here and it is reflected in the response.
    #[serde(rename = "clientToken")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_token: Option<&'a str>,
    /// The time, in seconds since the epoch, when the message was sent.
    #[serde(rename = "timestamp")]
    pub timestamp: i64,
    /// A JobExecutionState object.
    #[serde(rename = "executionState")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_state: Option<JobExecutionState<'a>>,
}

#[cfg(test)]
mod test {
    use super::*;
    use heapless::Vec;
    use serde_json_core::from_slice;

    /// Job document used while developing the module
    #[derive(Debug, Clone, PartialEq, Deserialize)]
    pub struct TestJob<'a> {
        operation: &'a str,
        somerandomkey: &'a str,
    }

    /// All known job document that the device knows how to process.
    #[derive(Debug, PartialEq, Deserialize)]
    pub enum JobDetails<'a> {
        #[serde(rename = "test_job")]
        #[serde(borrow)]
        TestJob(TestJob<'a>),

        #[serde(other)]
        Unknown,
    }

    #[test]
    fn deserialize_next_job_execution_changed() {
        let payload = br#"
        {
            "timestamp": 1587471560,
            "execution": {
                "jobId": "mini",
                "status": "QUEUED",
                "queuedAt": 1587471559,
                "lastUpdatedAt": 1587471559,
                "versionNumber": 1,
                "executionNumber": 1,
                "jobDocument": {
                    "test_job": {
                        "operation": "test",
                        "somerandomkey": "random_value"
                    }
                }
            }
        }
        "#;

        let (response, _) = from_slice::<NextJobExecutionChanged<JobDetails>>(payload).unwrap();

        assert_eq!(
            response,
            NextJobExecutionChanged {
                execution: Some(JobExecution {
                    execution_number: Some(1),
                    job_document: Some(JobDetails::TestJob(TestJob {
                        operation: "test",
                        somerandomkey: "random_value"
                    })),
                    job_id: "mini",
                    last_updated_at: 1587471559,
                    queued_at: 1587471559,
                    status: JobStatus::Queued,
                    version_number: 1,
                    approximate_seconds_before_timed_out: None,
                    status_details: None,
                    started_at: None,
                    thing_name: None,
                }),
                timestamp: 1587471560,
            }
        );
    }

    #[test]
    fn deserialize_get_pending_job_executions_response() {
        let payload = br#"{
                "clientToken": "0:client_name",
                "timestamp": 1587381778,
                "inProgressJobs": []
            }"#;

        let (response, _) = from_slice::<GetPendingJobExecutionsResponse>(payload).unwrap();

        assert_eq!(
            response,
            GetPendingJobExecutionsResponse {
                in_progress_jobs: Some(Vec::<JobExecutionSummary, MAX_RUNNING_JOBS>::new()),
                queued_jobs: None,
                timestamp: 1587381778,
                client_token: "0:client_name",
            }
        );

        let payload = br#"{
                "clientToken": "0:client_name",
                "timestamp": 1587381778,
                "inProgressJobs": [],
                "queuedJobs": [
                    {
                        "executionNumber": 1,
                        "jobId": "test",
                        "lastUpdatedAt": 1587036256,
                        "queuedAt": 1587036256,
                        "versionNumber": 1
                    }
                ]
            }"#;

        let mut queued_jobs: Vec<JobExecutionSummary, MAX_PENDING_JOBS> = Vec::new();
        queued_jobs
            .push(JobExecutionSummary {
                execution_number: Some(1),
                job_id: Some(String::from("test")),
                last_updated_at: Some(1587036256),
                queued_at: Some(1587036256),
                started_at: None,
                version_number: Some(1),
            })
            .unwrap();

        let (response, _) = from_slice::<GetPendingJobExecutionsResponse>(payload).unwrap();

        assert_eq!(
            response,
            GetPendingJobExecutionsResponse {
                in_progress_jobs: Some(Vec::<JobExecutionSummary, MAX_RUNNING_JOBS>::new()),
                queued_jobs: Some(queued_jobs),
                timestamp: 1587381778,
                client_token: "0:client_name",
            }
        );
    }

    #[test]
    fn deserialize_describe_job_execution_response() {
        let payload = br#"{
                "clientToken": "0:client_name",
                "timestamp": 1587381778,
                "execution": {
                    "jobId": "test",
                    "status": "QUEUED",
                    "queuedAt": 1587036256,
                    "lastUpdatedAt": 1587036256,
                    "versionNumber": 1,
                    "executionNumber": 1,
                    "jobDocument": {
                        "test_job": {
                            "operation": "test",
                            "somerandomkey": "random_value"
                        }
                    }
                }
            }"#;

        let (response, _) =
            from_slice::<DescribeJobExecutionResponse<JobDetails>>(payload).unwrap();

        assert_eq!(
            response,
            DescribeJobExecutionResponse {
                execution: Some(JobExecution {
                    execution_number: Some(1),
                    job_document: Some(JobDetails::TestJob(TestJob {
                        operation: "test",
                        somerandomkey: "random_value"
                    })),
                    job_id: "test",
                    last_updated_at: 1587036256,
                    queued_at: 1587036256,
                    status_details: None,
                    status: JobStatus::Queued,
                    version_number: 1,
                    approximate_seconds_before_timed_out: None,
                    started_at: None,
                    thing_name: None,
                }),
                timestamp: 1587381778,
                client_token: Some("0:client_name"),
            }
        );
    }
}