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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use crate::{Executor, ExecutorType, StagedFiles, TeaclaveRuntime};

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use anyhow::{Context, Result};

pub type FunctionRuntime = Box<dyn TeaclaveRuntime + Send + Sync>;
type ArgumentValue = serde_json::Value;

#[derive(Clone, Serialize, Deserialize, Debug, Default)]
pub struct FunctionArguments {
    inner: serde_json::Map<String, ArgumentValue>,
}

impl From<HashMap<String, String>> for FunctionArguments {
    fn from(map: HashMap<String, String>) -> Self {
        let inner = map.iter().fold(serde_json::Map::new(), |mut acc, (k, v)| {
            acc.insert(k.to_owned(), v.to_owned().into());
            acc
        });

        Self { inner }
    }
}

impl std::convert::TryFrom<String> for FunctionArguments {
    type Error = anyhow::Error;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        let v: ArgumentValue = serde_json::from_str(&s)?;
        let inner = match v {
            ArgumentValue::Object(o) => o,
            _ => anyhow::bail!("Cannot convert to function arguments"),
        };

        Ok(Self { inner })
    }
}

impl FunctionArguments {
    pub fn from_json(json: ArgumentValue) -> Result<Self> {
        let inner = match json {
            ArgumentValue::Object(o) => o,
            _ => anyhow::bail!("Not an json object"),
        };

        Ok(Self { inner })
    }

    pub fn from_map(map: HashMap<String, String>) -> Self {
        map.into()
    }

    pub fn inner(&self) -> &serde_json::Map<String, ArgumentValue> {
        &self.inner
    }

    pub fn inner_mut(&mut self) -> &mut serde_json::Map<String, ArgumentValue> {
        &mut self.inner
    }

    pub fn get(&self, key: &str) -> anyhow::Result<&ArgumentValue> {
        self.inner
            .get(key)
            .with_context(|| format!("key not found: {}", key))
    }

    pub fn into_vec(self) -> Vec<String> {
        let mut vector = Vec::new();

        self.inner.into_iter().for_each(|(k, v)| {
            vector.push(k);
            match v {
                ArgumentValue::String(s) => vector.push(s),
                _ => vector.push(v.to_string()),
            }
        });

        vector
    }

    pub fn into_string(self) -> String {
        ArgumentValue::Object(self.inner).to_string()
    }

    pub fn insert(&mut self, k: String, v: ArgumentValue) -> Option<ArgumentValue> {
        self.inner.insert(k, v)
    }
}

#[derive(Debug, Default)]
pub struct StagedFunction {
    pub name: String,
    pub arguments: FunctionArguments,
    pub payload: Vec<u8>,
    pub input_files: StagedFiles,
    pub output_files: StagedFiles,
    pub executor_type: ExecutorType,
    pub executor: Executor,
    pub runtime_name: String,
}

#[derive(Default)]
pub struct StagedFunctionBuilder {
    function: StagedFunction,
}

impl StagedFunctionBuilder {
    pub fn new() -> Self {
        Self {
            function: StagedFunction::default(),
        }
    }

    pub fn name(mut self, name: impl ToString) -> Self {
        self.function.name = name.to_string();
        self
    }

    pub fn executor(mut self, executor: Executor) -> Self {
        self.function.executor = executor;
        self
    }

    pub fn payload(mut self, payload: Vec<u8>) -> Self {
        self.function.payload = payload;
        self
    }

    pub fn arguments(mut self, arguments: FunctionArguments) -> Self {
        self.function.arguments = arguments;
        self
    }

    pub fn input_files(mut self, input_files: StagedFiles) -> Self {
        self.function.input_files = input_files;
        self
    }

    pub fn output_files(mut self, output_files: StagedFiles) -> Self {
        self.function.output_files = output_files;
        self
    }

    pub fn runtime_name(mut self, runtime_name: impl ToString) -> Self {
        self.function.runtime_name = runtime_name.to_string();
        self
    }

    pub fn executor_type(mut self, executor_type: ExecutorType) -> Self {
        self.function.executor_type = executor_type;
        self
    }

    pub fn build(self) -> StagedFunction {
        self.function
    }
}