air_interpreter_interface/
call_service_result.rs

1/*
2 * Copyright 2021 Fluence Labs Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use air_interpreter_sede::define_simple_representation;
18use air_interpreter_sede::derive_serialized_type;
19use air_interpreter_sede::MsgPackMultiformat;
20use air_interpreter_sede::Representation;
21use serde::Deserialize;
22use serde::Serialize;
23use serde_json::Value as JValue;
24use std::collections::HashMap;
25
26/// This is a map from a String to a service result for compatibility with JavaScript.
27/// Binary format implementations like `rmp-serde` do not convert keys from strings, unlike `serde_json`.
28pub type CallResults = HashMap<String, CallServiceResult>;
29pub const CALL_SERVICE_SUCCESS: i32 = 0;
30
31pub type CallResultsFormat = MsgPackMultiformat;
32
33derive_serialized_type!(SerializedCallResults);
34
35define_simple_representation! {
36    CallResultsRepr,
37    CallResults,
38    CallResultsFormat,
39    SerializedCallResults
40}
41
42pub type CallResultsDeserializeError = <CallResultsRepr as Representation>::DeserializeError;
43pub type CallResultsSerializeError = <CallResultsRepr as Representation>::SerializeError;
44
45/// Represents an executed host function result.
46#[derive(Debug, Default, Clone, Serialize, Deserialize)]
47pub struct CallServiceResult {
48    /// A error code service or builtin returned, where CALL_SERVICE_SUCCESS represents success.
49    pub ret_code: i32,
50
51    /// Resulted JValue serialized to a string. It's impossible to wrap it with the marine macro,
52    /// inasmuch as it's a enum uses HashMap inside.
53    pub result: String,
54}
55
56impl CallServiceResult {
57    pub fn ok(result: &JValue) -> Self {
58        Self {
59            ret_code: CALL_SERVICE_SUCCESS,
60            // for compatiblity with JavaScript with binary formats, string IDs are used
61            result: result.to_string(),
62        }
63    }
64
65    pub fn err(err_code: i32, result: &JValue) -> Self {
66        Self {
67            ret_code: err_code,
68            result: result.to_string(),
69        }
70    }
71}
72
73use std::fmt;
74
75impl fmt::Display for CallServiceResult {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        write!(f, "ret_code: {}, result: '{}'", self.ret_code, self.result)
78    }
79}