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
/*
 * AquaVM Workflow Engine
 *
 * Copyright (C) 2024 Fluence DAO
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use super::*;
use crate::RawValue;

impl ParResult {
    pub fn new(left_size: u32, right_size: u32) -> Self {
        Self {
            left_size,
            right_size,
        }
    }

    /// Returns a size of subtrace that this par describes in execution_step trace.
    pub fn size(&self) -> Option<u32> {
        self.left_size.checked_add(self.right_size)
    }
}

impl CallResult {
    pub fn sent_peer_id(peer_id: Rc<String>) -> CallResult {
        CallResult::RequestSentBy(Sender::PeerId(peer_id))
    }

    pub fn sent_peer_id_with_call_id(peer_id: Rc<String>, call_id: u32) -> CallResult {
        CallResult::RequestSentBy(Sender::PeerIdWithCallId { peer_id, call_id })
    }

    pub fn executed_service_result(value_ref: ValueRef) -> Self {
        Self::Executed(value_ref)
    }

    pub fn executed_scalar(service_result_agg_cid: CID<ServiceResultCidAggregate>) -> Self {
        Self::executed_service_result(ValueRef::Scalar(service_result_agg_cid))
    }

    pub fn executed_stream_stub(cid: CID<ServiceResultCidAggregate>) -> CallResult {
        let generation = GenerationIdx::stub();
        let value = ValueRef::Stream { cid, generation };
        CallResult::Executed(value)
    }

    pub fn executed_unused(value_cid: CID<JValue>) -> CallResult {
        Self::executed_service_result(ValueRef::Unused(value_cid))
    }

    pub fn failed(service_result_agg_cid: CID<ServiceResultCidAggregate>) -> CallResult {
        CallResult::Failed(service_result_agg_cid)
    }

    pub fn get_cid(&self) -> Option<&CID<ServiceResultCidAggregate>> {
        match self {
            CallResult::RequestSentBy(_) => None,
            CallResult::Executed(executed) => executed.get_cid(),
            CallResult::Failed(cid) => Some(cid),
        }
    }
}

impl SubTraceDesc {
    pub fn new(begin_pos: TracePos, subtrace_len: usize) -> Self {
        Self {
            begin_pos,
            subtrace_len: subtrace_len as _,
        }
    }
}

impl ExecutedState {
    pub fn par(left_subgraph_size: usize, right_subgraph_size: usize) -> Self {
        let par_result = ParResult {
            left_size: left_subgraph_size as _,
            right_size: right_subgraph_size as _,
        };

        Self::Par(par_result)
    }
}

impl ApResult {
    pub fn new(res_generation: GenerationIdx) -> Self {
        Self {
            res_generations: vec![res_generation],
        }
    }

    pub fn stub() -> Self {
        Self {
            res_generations: vec![GenerationIdx::stub()],
        }
    }
}

impl CanonResult {
    pub fn executed(cid: CID<CanonResultCidAggregate>) -> Self {
        CanonResult::Executed(cid)
    }

    pub fn request_sent_by(peer_id: Rc<String>) -> Self {
        CanonResult::RequestSentBy(peer_id)
    }
}

impl CanonResultCidAggregate {
    pub fn new(tetraplet: CID<SecurityTetraplet>, values: Vec<CID<CanonCidAggregate>>) -> Self {
        Self { tetraplet, values }
    }
}

impl CanonCidAggregate {
    pub fn new(
        value: CID<RawValue>,
        tetraplet: CID<SecurityTetraplet>,
        provenance: Provenance,
    ) -> Self {
        Self {
            value,
            tetraplet,
            provenance,
        }
    }
}

impl ServiceResultCidAggregate {
    pub fn new(
        value_cid: CID<RawValue>,
        argument_hash: Rc<str>,
        tetraplet_cid: CID<SecurityTetraplet>,
    ) -> Self {
        Self {
            value_cid,
            argument_hash,
            tetraplet_cid,
        }
    }
}

impl Provenance {
    #[inline]
    pub fn literal() -> Self {
        Self::Literal
    }

    #[inline]
    pub fn service_result(cid: CID<ServiceResultCidAggregate>) -> Self {
        Self::ServiceResult { cid }
    }

    #[inline]
    pub fn canon(cid: CID<CanonResultCidAggregate>) -> Self {
        Self::Canon { cid }
    }
}

impl std::fmt::Display for ExecutedState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use CallResult::*;
        use ExecutedState::*;

        match self {
            Par(ParResult {
                left_size: left_subgraph_size,
                right_size: right_subgraph_size,
            }) => write!(f, "par({left_subgraph_size}, {right_subgraph_size})"),
            Call(RequestSentBy(sender)) => write!(f, r"{sender}"),
            Call(Executed(value_ref)) => {
                write!(f, "executed({value_ref:?})")
            }
            Call(Failed(failed_cid)) => {
                write!(f, "failed({failed_cid:?})")
            }
            Fold(FoldResult { lore }) => {
                writeln!(f, "fold(",)?;
                for sublore in lore {
                    writeln!(
                        f,
                        "          {} - [{}, {}], [{}, {}]",
                        sublore.value_pos,
                        sublore.subtraces_desc[0].begin_pos,
                        sublore.subtraces_desc[0].subtrace_len,
                        sublore.subtraces_desc[1].begin_pos,
                        sublore.subtraces_desc[1].subtrace_len
                    )?;
                }
                write!(f, "     )")
            }
            Ap(ap) => {
                write!(f, "ap: _ -> {:?}", ap.res_generations)
            }
            Canon(_) => {
                write!(f, "canon [<object>]")
            }
        }
    }
}

impl ValueRef {
    pub(crate) fn get_cid(&self) -> Option<&CID<ServiceResultCidAggregate>> {
        match self {
            ValueRef::Scalar(cid) => Some(cid),
            ValueRef::Stream { cid, .. } => Some(cid),
            ValueRef::Unused(_) => None,
        }
    }
}

impl std::fmt::Display for ValueRef {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ValueRef::Scalar(cid) => write!(f, "scalar: {cid:?}"),
            ValueRef::Stream { cid, generation } => {
                write!(f, "stream: {cid:?} generation: {generation}")
            }
            ValueRef::Unused(cid) => write!(f, "unused: {cid:?}"),
        }
    }
}

impl std::fmt::Display for Sender {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Sender::PeerId(peer_id) => write!(f, "request_sent_by({peer_id})"),
            Sender::PeerIdWithCallId { peer_id, call_id } => {
                write!(f, "request_sent_by({peer_id}: {call_id})")
            }
        }
    }
}