bc-envelope 0.43.0

Gordian Envelope for Rust.
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
use bc_components::{ARID, tags};
use dcbor::{Date, prelude::*};

use crate::{
    Envelope, EnvelopeEncodable, Error, Expression, ExpressionBehavior,
    Function, Parameter, Result, known_values,
};

/// A `Request` represents a message requesting execution of a function with
/// parameters.
///
/// Requests are part of the expression system that enables distributed function
/// calls and communication between systems. Each request:
/// - Contains a body (an `Expression`) that represents the function to be
///   executed
/// - Has a unique identifier (ARID) for tracking and correlation
/// - May include optional metadata like a note and timestamp
///
/// Requests are designed to be paired with `Response` objects that contain the
/// results of executing the requested function.
///
/// When serialized to an envelope, requests are tagged with `#6.40010`
/// (TAG_REQUEST).
///
/// # Examples
///
/// ```
/// use bc_components::ARID;
/// use bc_envelope::prelude::*;
///
/// // Create a random request ID
/// let request_id = ARID::new();
///
/// // Create a request to execute a function with parameters
/// let request = Request::new("getBalance", request_id)
///     .with_parameter("account", "alice")
///     .with_parameter("currency", "USD")
///     .with_note("Monthly balance check");
///
/// // Convert to an envelope
/// let envelope = request.into_envelope();
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Request {
    body: Expression,
    id: ARID,
    note: String,
    date: Option<Date>,
}

impl std::fmt::Display for Request {
    /// Formats the request for display, showing its ID and body.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Request({})", self.summary())
    }
}

impl Request {
    /// Returns a human-readable summary of the request.
    pub fn summary(&self) -> String {
        format!(
            "id: {}, body: {}",
            self.id.short_description(),
            self.body.expression_envelope().format_flat()
        )
    }
}

/// Trait that defines the behavior of a request.
///
/// This trait extends `ExpressionBehavior` to add methods specific to requests,
/// including metadata management and access to request properties. Types
/// implementing this trait can be used in contexts that expect request
/// functionality.
pub trait RequestBehavior: ExpressionBehavior {
    //
    // Composition
    //

    /// Adds a note to the request.
    ///
    /// This provides human-readable context about the request's purpose.
    fn with_note(self, note: impl Into<String>) -> Self;

    /// Adds a date to the request.
    ///
    /// This timestamp typically represents when the request was created.
    fn with_date(self, date: Date) -> Self;

    //
    // Parsing
    //

    /// Returns the body of the request, which is the expression to be
    /// evaluated.
    fn body(&self) -> &Expression;

    /// Returns the unique identifier (ARID) of the request.
    fn id(&self) -> ARID;

    /// Returns the note attached to the request, or an empty string if none
    /// exists.
    fn note(&self) -> &str;

    /// Returns the date attached to the request, if any.
    fn date(&self) -> Option<Date>;
}

impl Request {
    /// Creates a new request with the specified expression body and ID.
    ///
    /// # Arguments
    ///
    /// * `body` - The expression to be executed
    /// * `id` - Unique identifier for the request
    pub fn new_with_body(body: Expression, id: ARID) -> Self {
        Self { body, id, note: String::new(), date: None }
    }

    /// Creates a new request with a function and ID.
    ///
    /// This is a convenience method that creates an expression from the
    /// function and then creates a request with that expression.
    ///
    /// # Arguments
    ///
    /// * `function` - The function to be executed
    /// * `id` - Unique identifier for the request
    ///
    /// # Examples
    ///
    /// ```
    /// use bc_components::ARID;
    /// use bc_envelope::prelude::*;
    ///
    /// let request_id = ARID::new();
    /// let request = Request::new("transferFunds", request_id)
    ///     .with_parameter("from", "alice")
    ///     .with_parameter("to", "bob")
    ///     .with_parameter("amount", 100);
    /// ```
    pub fn new(function: impl Into<Function>, id: ARID) -> Self {
        Self::new_with_body(Expression::new(function), id)
    }
}

/// Implementation of `ExpressionBehavior` for `Request`.
///
/// This delegates most operations to the request's body expression.
impl ExpressionBehavior for Request {
    /// Adds a parameter to the request.
    fn with_parameter(
        mut self,
        parameter: impl Into<Parameter>,
        value: impl EnvelopeEncodable,
    ) -> Self {
        self.body = self.body.with_parameter(parameter, value);
        self
    }

    /// Adds an optional parameter to the request.
    fn with_optional_parameter(
        mut self,
        parameter: impl Into<Parameter>,
        value: Option<impl EnvelopeEncodable>,
    ) -> Self {
        self.body = self.body.with_optional_parameter(parameter, value);
        self
    }

    /// Returns the function of the request.
    fn function(&self) -> &Function { self.body.function() }

    /// Returns the expression envelope of the request.
    fn expression_envelope(&self) -> &Envelope {
        self.body.expression_envelope()
    }

    /// Returns the object for a parameter in the request.
    fn object_for_parameter(
        &self,
        param: impl Into<Parameter>,
    ) -> Result<Envelope> {
        self.body.object_for_parameter(param)
    }

    /// Returns all objects for a parameter in the request.
    fn objects_for_parameter(
        &self,
        param: impl Into<Parameter>,
    ) -> Vec<Envelope> {
        self.body.objects_for_parameter(param)
    }

    /// Extracts a typed object for a parameter in the request.
    fn extract_object_for_parameter<T>(
        &self,
        param: impl Into<Parameter>,
    ) -> Result<T>
    where
        T: TryFrom<CBOR, Error = dcbor::Error> + 'static,
    {
        self.body.extract_object_for_parameter(param)
    }

    /// Extracts an optional typed object for a parameter in the request.
    fn extract_optional_object_for_parameter<
        T: TryFrom<CBOR, Error = dcbor::Error> + 'static,
    >(
        &self,
        param: impl Into<Parameter>,
    ) -> Result<Option<T>> {
        self.body.extract_optional_object_for_parameter(param)
    }

    /// Extracts multiple typed objects for a parameter in the request.
    fn extract_objects_for_parameter<T>(
        &self,
        param: impl Into<Parameter>,
    ) -> Result<Vec<T>>
    where
        T: TryFrom<CBOR, Error = dcbor::Error> + 'static,
    {
        self.body.extract_objects_for_parameter(param)
    }
}

/// Implementation of `RequestBehavior` for `Request`.
impl RequestBehavior for Request {
    /// Adds a note to the request.
    fn with_note(mut self, note: impl Into<String>) -> Self {
        self.note = note.into();
        self
    }

    /// Adds a date to the request.
    fn with_date(mut self, date: Date) -> Self {
        self.date = Some(date);
        self
    }

    /// Returns the body of the request.
    fn body(&self) -> &Expression { &self.body }

    /// Returns the ID of the request.
    fn id(&self) -> ARID { self.id }

    /// Returns the note of the request.
    fn note(&self) -> &str { &self.note }

    /// Returns the date of the request.
    fn date(&self) -> Option<Date> { self.date }
}

/// Converts a `Request` to an `Expression`.
///
/// This extracts the request's body expression.
impl From<Request> for Expression {
    fn from(request: Request) -> Self { request.body }
}

/// Converts a `Request` to an `Envelope`.
///
/// The envelope's subject is the request's ID tagged with TAG_REQUEST,
/// and assertions include the request's body, note (if not empty), and date (if
/// present).
impl From<Request> for Envelope {
    fn from(request: Request) -> Self {
        Envelope::new(CBOR::to_tagged_value(tags::TAG_REQUEST, request.id))
            .add_assertion(known_values::BODY, request.body.into_envelope())
            .add_assertion_if(
                !request.note.is_empty(),
                known_values::NOTE,
                request.note,
            )
            .add_optional_assertion(known_values::DATE, request.date)
    }
}

/// Converts an envelope and optional expected function to a `Request`.
///
/// This constructor is used when parsing an envelope that is expected to
/// contain a request. The optional function parameter enables validation of the
/// request's function.
impl TryFrom<(Envelope, Option<&Function>)> for Request {
    type Error = Error;

    fn try_from(
        (envelope, expected_function): (Envelope, Option<&Function>),
    ) -> Result<Self> {
        let body_envelope =
            envelope.object_for_predicate(known_values::BODY)?;
        Ok(Self {
            body: Expression::try_from((body_envelope, expected_function))?,
            id: envelope
                .subject()
                .try_leaf()?
                .try_into_expected_tagged_value(tags::TAG_REQUEST)?
                .try_into()?,
            note: envelope.extract_object_for_predicate_with_default(
                known_values::NOTE,
                "".to_string(),
            )?,
            date: envelope
                .extract_optional_object_for_predicate(known_values::DATE)?,
        })
    }
}

/// Converts an envelope to a `Request`.
///
/// This simplified constructor doesn't validate the request's function.
impl TryFrom<Envelope> for Request {
    type Error = Error;

    fn try_from(envelope: Envelope) -> Result<Self> {
        Self::try_from((envelope, None))
    }
}

#[cfg(test)]
mod tests {
    use hex_literal::hex;
    use indoc::indoc;

    use super::*;

    fn request_id() -> ARID {
        ARID::from_data(hex!(
            "c66be27dbad7cd095ca77647406d07976dc0f35f0d4d654bb0e96dd227a1e9fc"
        ))
    }

    #[test]
    fn test_basic_request() -> Result<()> {
        crate::register_tags();

        let request = Request::new("test", request_id())
            .with_parameter("param1", 42)
            .with_parameter("param2", "hello");

        let envelope: Envelope = request.clone().into();
        #[rustfmt::skip]
        let expected = indoc!{r#"
            request(ARID(c66be27d)) [
                'body': «"test"» [
                    ❰"param1"❱: 42
                    ❰"param2"❱: "hello"
                ]
            ]
        "#}.trim();
        assert_eq!(envelope.format(), expected);

        let parsed_request = Request::try_from(envelope)?;
        assert_eq!(
            parsed_request.extract_object_for_parameter::<i32>("param1")?,
            42
        );
        assert_eq!(
            parsed_request.extract_object_for_parameter::<String>("param2")?,
            "hello"
        );
        assert_eq!(parsed_request.note(), "");
        assert_eq!(parsed_request.date(), None);

        assert_eq!(request, parsed_request);

        Ok(())
    }

    #[test]
    fn test_request_with_metadata() -> Result<()> {
        crate::register_tags();

        let request_date = Date::try_from("2024-07-04T11:11:11Z")?;
        let request = Request::new("test", request_id())
            .with_parameter("param1", 42)
            .with_parameter("param2", "hello")
            .with_note("This is a test")
            .with_date(request_date);

        let envelope: Envelope = request.clone().into();
        // println!("{}", envelope.format());
        #[rustfmt::skip]
        assert_eq!(envelope.format(), indoc!{r#"
            request(ARID(c66be27d)) [
                'body': «"test"» [
                    ❰"param1"❱: 42
                    ❰"param2"❱: "hello"
                ]
                'date': 2024-07-04T11:11:11Z
                'note': "This is a test"
            ]
        "#}.trim());

        let parsed_request = Request::try_from(envelope)?;
        assert_eq!(
            parsed_request.extract_object_for_parameter::<i32>("param1")?,
            42
        );
        assert_eq!(
            parsed_request.extract_object_for_parameter::<String>("param2")?,
            "hello"
        );
        assert_eq!(parsed_request.note(), "This is a test");
        assert_eq!(parsed_request.date(), Some(request_date));

        assert_eq!(request, parsed_request);

        Ok(())
    }

    #[test]
    fn test_parameter_format() {
        crate::register_tags();

        let parameter = Parameter::new_named("testParam");
        let envelope = parameter.into_envelope();
        let expected = r#"❰"testParam"❱"#;
        assert_eq!(envelope.format(), expected);
    }
}