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
/*
 * 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/>.
 */

pub mod values;

pub(crate) use self::values::CanonResultAggregate;
pub(crate) use self::values::LiteralAggregate;
pub(crate) use self::values::ServiceResultAggregate;

use super::JValuable;
use crate::execution_step::FoldState;
use crate::execution_step::RcSecurityTetraplet;
use crate::execution_step::PEEK_ALLOWED_ON_NON_EMPTY;
use crate::JValue;

use air_interpreter_cid::CID;
use air_interpreter_data::CanonResultCidAggregate;
use air_interpreter_data::Provenance;
use air_interpreter_data::ServiceResultCidAggregate;
use air_interpreter_data::TracePos;
use serde::Deserialize;
use serde::Serialize;

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ValueAggregate {
    Literal(LiteralAggregate),
    ServiceResult {
        #[serde(flatten)]
        result: ServiceResultAggregate,
        // the original call result CID; not changed on lambda application
        #[serde(rename = "cid")]
        provenance_cid: CID<ServiceResultCidAggregate>,
    },
    Canon {
        #[serde(flatten)]
        result: CanonResultAggregate,
        // the original canon CID; not changed on lambda application
        #[serde(rename = "cid")]
        provenance_cid: CID<CanonResultCidAggregate>,
    },
}

pub(crate) enum ScalarRef<'i> {
    Value(&'i ValueAggregate),
    IterableValue(&'i FoldState<'i>),
}

impl<'i> ScalarRef<'i> {
    pub(crate) fn into_jvaluable(self) -> (Box<dyn JValuable + 'i>, Provenance) {
        match self {
            ScalarRef::Value(value) => (Box::new(value.clone()), value.get_provenance()),
            ScalarRef::IterableValue(fold_state) => {
                let peeked_value = fold_state.iterable.peek().expect(PEEK_ALLOWED_ON_NON_EMPTY);
                let provenance = peeked_value.provenance();
                (Box::new(peeked_value), provenance)
            }
        }
    }
}

impl ValueAggregate {
    pub(crate) fn new(
        result: JValue,
        tetraplet: RcSecurityTetraplet,
        trace_pos: TracePos,
        provenance: Provenance,
    ) -> Self {
        match provenance {
            Provenance::Literal => ValueAggregate::Literal(LiteralAggregate::new(
                result,
                tetraplet.peer_pk.as_str().into(),
                trace_pos,
            )),
            Provenance::ServiceResult { cid } => ValueAggregate::ServiceResult {
                result: ServiceResultAggregate::new(result, tetraplet, trace_pos),
                provenance_cid: cid,
            },
            Provenance::Canon { cid } => ValueAggregate::Canon {
                result: CanonResultAggregate::new(
                    result,
                    tetraplet.peer_pk.as_str().into(),
                    &tetraplet.lens,
                    trace_pos,
                ),
                provenance_cid: cid,
            },
        }
    }

    pub(crate) fn from_literal_result(literal: LiteralAggregate) -> Self {
        Self::Literal(literal)
    }

    pub(crate) fn from_service_result(
        service_result: ServiceResultAggregate,
        service_result_agg_cid: CID<ServiceResultCidAggregate>,
    ) -> Self {
        Self::ServiceResult {
            result: service_result,
            provenance_cid: service_result_agg_cid,
        }
    }

    pub(crate) fn from_canon_result(
        canon_result: CanonResultAggregate,
        canon_result_agg_cid: CID<CanonResultCidAggregate>,
    ) -> Self {
        Self::Canon {
            result: canon_result,
            provenance_cid: canon_result_agg_cid,
        }
    }

    pub(crate) fn as_inner_parts(&self) -> (&JValue, RcSecurityTetraplet, TracePos) {
        match self {
            ValueAggregate::Literal(ref literal) => (&literal.result, literal.get_tetraplet(), literal.trace_pos),
            ValueAggregate::ServiceResult {
                result: ref service_result,
                provenance_cid: _,
            } => (
                &service_result.result,
                service_result.tetraplet.clone(),
                service_result.trace_pos,
            ),
            ValueAggregate::Canon {
                result: ref canon_result,
                provenance_cid: _,
            } => (
                &canon_result.result,
                canon_result.get_tetraplet(),
                canon_result.trace_pos,
            ),
        }
    }

    pub fn get_result(&self) -> &JValue {
        match self {
            ValueAggregate::Literal(literal) => &literal.result,
            ValueAggregate::ServiceResult {
                result: service_result,
                provenance_cid: _,
            } => &service_result.result,
            ValueAggregate::Canon {
                result: canon_result,
                provenance_cid: _,
            } => &canon_result.result,
        }
    }

    pub fn get_tetraplet(&self) -> RcSecurityTetraplet {
        match self {
            ValueAggregate::Literal(literal) => literal.get_tetraplet(),
            ValueAggregate::ServiceResult {
                result: service_result,
                provenance_cid: _,
            } => service_result.tetraplet.clone(),
            ValueAggregate::Canon {
                result: canon_result,
                provenance_cid: _,
            } => canon_result.get_tetraplet(),
        }
    }

    pub fn get_provenance(&self) -> Provenance {
        match self {
            ValueAggregate::Literal(_) => Provenance::Literal,
            ValueAggregate::ServiceResult {
                result: _,
                provenance_cid: cid,
            } => Provenance::ServiceResult { cid: cid.clone() },
            ValueAggregate::Canon {
                result: _,
                provenance_cid: cid,
            } => Provenance::Canon { cid: cid.clone() },
        }
    }
}

pub trait TracePosOperate {
    fn get_trace_pos(&self) -> TracePos;

    fn set_trace_pos(&mut self, pos: TracePos);
}

impl TracePosOperate for ValueAggregate {
    fn get_trace_pos(&self) -> TracePos {
        match self {
            ValueAggregate::Literal(literal) => literal.trace_pos,
            ValueAggregate::ServiceResult {
                result: service_result,
                provenance_cid: _,
            } => service_result.trace_pos,
            ValueAggregate::Canon {
                result: canon_result,
                provenance_cid: _,
            } => canon_result.trace_pos,
        }
    }

    fn set_trace_pos(&mut self, trace_pos: TracePos) {
        let trace_pos_ref = match self {
            ValueAggregate::Literal(literal) => &mut literal.trace_pos,
            ValueAggregate::ServiceResult {
                result: service_result,
                provenance_cid: _,
            } => &mut service_result.trace_pos,
            ValueAggregate::Canon {
                result: canon_result,
                provenance_cid: _,
            } => &mut canon_result.trace_pos,
        };
        *trace_pos_ref = trace_pos;
    }
}

use std::fmt;

impl fmt::Display for ValueAggregate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (result, tetraplet, trace_pos) = self.as_inner_parts();
        write!(
            f,
            "value: {}, tetraplet: {}, position: {}, provenance: {:?} ",
            result,
            tetraplet,
            trace_pos,
            self.get_provenance(),
        )
    }
}

impl<'i> fmt::Display for ScalarRef<'i> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ScalarRef::Value(value) => write!(f, "{value:?}")?,
            ScalarRef::IterableValue(cursor) => {
                let iterable = &cursor.iterable;
                write!(f, "cursor, current value: {:?}", iterable.peek())?;
            }
        }

        Ok(())
    }
}