rialo-types 0.12.2

Rialo Types
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
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! # Output Module
//!
//! Defines the output format for REX results.
//!
//! This module provides the [`RexOutput`] enum which represents all possible
//! outcomes from a REX execution. The output is designed to be:
//! - Self-describing with status tags
//! - Easily serializable to JSON
//! - Type-safe with exhaustive matching
//!
//! ## Output Types
//!
//! - `Success` - The REX execution completed successfully and returned data
//! - `RexError` - The REX execution encountered an error
//! - `UnserializableResponse` - The REX execution produced output that couldn't be serialized
//!
//! ## Serialization Format
//!
//! All outputs serialize to a consistent JSON structure:
//! ```json
//! {
//!   "status": "success|rex-error|unserializable-response",
//!   "contents": <actual data or error details>
//! }
//! ```

use std::{fmt, fmt::Debug};

use borsh::{BorshDeserialize, BorshSerialize};
use chrono::SecondsFormat;
use rialo_cli_representable::Representable;
use serde::{Deserialize, Serialize};

use crate::RexError;

/// Result for filtering operations.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub enum FilterResult {
    Success(Vec<u8>),
    Error(String),
}

impl FilterResult {
    /// Returns true if the filter result is a success.
    pub fn is_success(&self) -> bool {
        matches!(self, FilterResult::Success(_))
    }

    /// Returns true if the filter result is an error.
    pub fn is_error(&self) -> bool {
        matches!(self, FilterResult::Error(_))
    }

    /// Returns the contained bytes if the filter result is a success, otherwise returns `None`.
    pub fn as_success(&self) -> Option<&Vec<u8>> {
        if let FilterResult::Success(ref bytes) = self {
            Some(bytes)
        } else {
            None
        }
    }

    /// Returns the contained error message if the filter result is an error, otherwise returns `None`.
    pub fn as_error(&self) -> Option<&String> {
        if let FilterResult::Error(ref err) = self {
            Some(err)
        } else {
            None
        }
    }
}

impl fmt::Display for FilterResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FilterResult::Success(bytes) => write!(f, "Success: {:?}", bytes),
            FilterResult::Error(err) => write!(f, "Error: {}", err),
        }
    }
}

impl From<Result<Vec<u8>, String>> for FilterResult {
    fn from(result: Result<Vec<u8>, String>) -> Self {
        match result {
            Ok(bytes) => FilterResult::Success(bytes),
            Err(err) => FilterResult::Error(err),
        }
    }
}

/// Represents the data returned by REX.
/// This is a vector of bytes that can contain any data returned by the REX execution.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
pub enum RexData {
    /// The raw bytes returned by the REX execution.
    Raw(Vec<u8>),
    /// The filtered bytes returned by the REX execution.
    Filtered(Vec<FilterResult>),
}

impl RexData {
    /// Returns true if the REX data is raw.
    pub fn is_raw(&self) -> bool {
        matches!(self, RexData::Raw(_))
    }

    /// Returns true if the REX data is filtered.
    pub fn is_filtered(&self) -> bool {
        matches!(self, RexData::Filtered(_))
    }

    /// Returns the contained raw bytes if the REX data is raw, otherwise returns `None`.
    pub fn as_raw(&self) -> Option<&Vec<u8>> {
        if let RexData::Raw(ref data) = self {
            Some(data)
        } else {
            None
        }
    }

    /// Returns the contained filtered results if the REX data is filtered, otherwise returns `None`.
    pub fn as_filtered(&self) -> Option<&Vec<FilterResult>> {
        if let RexData::Filtered(ref results) = self {
            Some(results)
        } else {
            None
        }
    }

    /// Returns the length of the contained data in bytes.
    pub fn len(&self) -> usize {
        match self {
            RexData::Raw(data) => data.len(),
            RexData::Filtered(results) => results
                .iter()
                .map(|r| match r {
                    FilterResult::Success(bytes) => bytes.len(),
                    FilterResult::Error(err) => err.len(),
                })
                .sum(),
        }
    }

    /// Returns true if the contained data is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// The response received from REX.
///
/// This data structure is used to represent the successful output of a REX request.
#[derive(
    Clone,
    Debug,
    Eq,
    PartialEq,
    Serialize,
    Deserialize,
    BorshSerialize,
    BorshDeserialize,
    Representable,
)]
#[representable(human_readable = "rex_response_human_readable")]
pub struct RexResponse {
    /// The raw response data from the REX execution, encoded as bytes.
    pub response: RexData,
    /// The timestamp when the REX response was generated.
    pub timestamp: String,
}

fn rex_response_human_readable(response: &RexResponse) -> String {
    let mut out = String::new();
    out.push_str(&format!(
        "Response: {:?}, Timestamp (from TEE): {}",
        response.response, response.timestamp
    ));
    out
}

impl RexResponse {
    /// Creates a new `RexResponse` with the given response data and timestamp.
    pub fn new(response: RexData) -> Self {
        Self {
            response,
            // Always uses 'Z' suffix and 6 decimal places (microseconds)
            // Produces exactly 30 bytes: "2025-08-24T10:59:40.123456Z"
            timestamp: chrono::Utc::now().to_rfc3339_opts(SecondsFormat::Micros, true),
        }
    }

    /// Convert to successful response data. In case of `RexData::Raw` returns a vector of one
    /// element containing the raw bytes. In case of `RexData::Filtered` returns a vector of all
    /// successful filtered bytes.
    ///
    /// If there are no successful responses, returns an empty vector.
    pub fn into_successful_responses(self) -> Vec<Vec<u8>> {
        match self.response {
            RexData::Raw(data) => vec![data],
            RexData::Filtered(results) => results
                .into_iter()
                .filter_map(|r| {
                    if let FilterResult::Success(bytes) = r {
                        Some(bytes)
                    } else {
                        None
                    }
                })
                .collect(),
        }
    }
}

/// The output from REX.
///
/// This enum represents the possible outcomes of a REX execution.
#[derive(
    Clone,
    Debug,
    Eq,
    PartialEq,
    Serialize,
    Deserialize,
    BorshSerialize,
    BorshDeserialize,
    Representable,
)]
#[serde(tag = "status", content = "contents")]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
#[representable(human_readable = "rex_output_human_readable")]
pub enum RexOutput {
    /// The response of a successfully handled REX request.
    Success(RexResponse),
    /// The details of an error reported by a REX execution.
    RexError(RexError),
    /// The REX execution produced an unserializable response.
    UnserializableResponse(String),
}

fn rex_output_human_readable(output: &RexOutput) -> String {
    match output {
        RexOutput::Success(resp) => {
            let len = resp.response.len();
            format!("Success: {} bytes @ {}", len, resp.timestamp)
        }
        RexOutput::RexError(err) => format!("RexError: {}", err),
        RexOutput::UnserializableResponse(msg) => {
            format!("UnserializableResponse: {}", msg)
        }
    }
}

impl RexOutput {
    /// Returns true if the output is a success.
    pub fn is_success(&self) -> bool {
        matches!(self, RexOutput::Success(_))
    }

    /// Returns true if the output is a REX error.
    pub fn is_rex_error(&self) -> bool {
        matches!(self, RexOutput::RexError(_))
    }

    /// Returns true if the output is an unserializable response.
    pub fn is_unserializable_response(&self) -> bool {
        matches!(self, RexOutput::UnserializableResponse(_))
    }

    /// Returns the contained `RexResponse` if the output is a success, otherwise returns `None`.
    pub fn as_success(&self) -> Option<&RexResponse> {
        if let RexOutput::Success(ref response) = self {
            Some(response)
        } else {
            None
        }
    }

    /// Returns the contained `RexError` if the output is a REX error, otherwise returns `None`.
    pub fn as_rex_error(&self) -> Option<&RexError> {
        if let RexOutput::RexError(ref error) = self {
            Some(error)
        } else {
            None
        }
    }

    /// Converts to successful response data if the output is a success, and we have successful `RexData`.
    /// Otherwise, returns `None`.
    pub fn into_success_payload(self) -> Option<Vec<Vec<u8>>> {
        match self {
            RexOutput::Success(response) => Some(response.into_successful_responses()),
            _ => None,
        }
    }
}

impl From<Result<RexResponse, RexError>> for RexOutput {
    fn from(result: Result<RexResponse, RexError>) -> Self {
        match result {
            Ok(response) => RexOutput::Success(response),
            Err(error) => RexOutput::RexError(error),
        }
    }
}

impl From<RexError> for RexOutput {
    fn from(error: RexError) -> Self {
        RexOutput::RexError(error)
    }
}

#[cfg(test)]
mod test {
    use serde_json::json;

    use super::*;

    #[test]
    fn test_rex_result_success_serialization() {
        let rex_data = RexResponse::new(RexData::Raw(
            serde_json::to_vec(&json!({"data": 42, "message": "test"})).unwrap(),
        ));
        let result = RexOutput::Success(rex_data.clone());
        let json = serde_json::to_value(&result).unwrap();

        assert_eq!(
            json,
            json!({
                "status": "success",
                "contents": rex_data
            })
        );
    }

    #[test]
    fn test_rex_result_error_serialization() {
        let error = RexError::HttpStatusError {
            status: 404,
            reason: String::from("HTTP Status Code 404 Not Found"),
        };

        let result = RexOutput::RexError(error.clone());
        let json = serde_json::to_value(&result).unwrap();

        assert_eq!(
            json,
            json!({
                "status": "rex-error",
                "contents": error
            })
        );
    }

    #[test]
    fn test_rex_result_unserializable_serialization() {
        let result = RexOutput::UnserializableResponse("Failed to parse response".to_string());
        let json = serde_json::to_value(&result).unwrap();

        assert_eq!(
            json,
            json!({
                "status": "unserializable-response",
                "contents": "Failed to parse response"
            })
        );
    }

    #[test]
    fn test_rex_result_deserialization() {
        // Test deserializing success
        let expected = RexResponse::new(RexData::Raw(
            serde_json::to_vec(&json!({"data": 123 })).unwrap(),
        ));
        let expected_clone = expected.clone();
        let json = json!({
            "status": "success",
            "contents": expected_clone
        });
        let result: RexOutput = serde_json::from_value(json).unwrap();
        assert_eq!(result, RexOutput::Success(expected_clone));

        // Test deserializing error
        let error = RexError::HttpStatusError {
            status: 500,
            reason: "Internal Server Error".to_string(),
        };
        let json = json!({
            "status": "rex-error",
            "contents": error.clone()
        });
        let result: RexOutput = serde_json::from_value(json).unwrap();
        assert_eq!(result, RexOutput::RexError(error));

        // Test deserializing unserializable response
        let json = json!({
            "status": "unserializable-response",
            "contents": "Parse error"
        });
        let result: RexOutput = serde_json::from_value(json).unwrap();
        assert_eq!(
            result,
            RexOutput::UnserializableResponse("Parse error".to_string())
        );
    }

    #[test]
    fn test_rex_result_roundtrip() {
        let rex_response = RexResponse::new(RexData::Raw(
            serde_json::to_vec(&json!({"key": "value", "number": 42})).unwrap(),
        ));
        let error = RexError::HttpStatusError {
            status: 403,
            reason: "Forbidden".to_string(),
        };
        let test_cases = vec![
            RexOutput::Success(rex_response),
            RexOutput::RexError(error),
            RexOutput::UnserializableResponse("Invalid JSON".to_string()),
        ];

        for original in test_cases {
            let serialized = serde_json::to_string(&original).unwrap();
            let deserialized: RexOutput = serde_json::from_str(&serialized).unwrap();
            assert_eq!(original, deserialized);
        }
    }

    #[test]
    fn test_rex_result_complex_nested_values() {
        let complex_value = json!({
            "nested": {
                "array": [1, 2, 3],
                "object": {"key": "value"},
                "null": null,
                "bool": true
            }
        });
        let rex_response =
            RexResponse::new(RexData::Raw(serde_json::to_vec(&complex_value).unwrap()));

        let result = RexOutput::Success(rex_response.clone());
        let json = serde_json::to_value(&result).unwrap();

        assert_eq!(json["status"], "success");
        assert_eq!(json["contents"], json!(rex_response));
    }

    #[test]
    fn test_rex_result_empty_values() {
        // Test with empty object
        let rex_response = RexResponse::new(RexData::Raw(serde_json::to_vec(&json!({})).unwrap()));
        let result = RexOutput::Success(rex_response.clone());
        let json = serde_json::to_value(&result).unwrap();
        assert_eq!(
            json,
            json!({
                "status": "success",
                "contents": rex_response
            })
        );

        // Test with empty string
        let result = RexOutput::UnserializableResponse("".to_string());
        let json = serde_json::to_value(&result).unwrap();
        assert_eq!(
            json,
            json!({
                "status": "unserializable-response",
                "contents": ""
            })
        );
    }
}