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
use crate::client::Context;
use derive_new::new;
use serde::{Deserialize, Serialize};
use serde_json::{Error, Value};

use super::{traits::Service, HttpMethods, KeyValue, Limits, ACTION_ENDPOINT, NAMESPACE_ENDPOINT};

/// Representation of Action Service
#[derive(new, Debug, Default, Deserialize, Serialize, Clone)]
pub struct ActionService<T> {
    /// A action service must have a client to handle http request
    client: T,
    /// A action service uses the context which sets openwhisk properties
    context: Context,
}

/// Represenation of Action
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
pub struct Action {
    /// A action must have a namspace where it exists
    #[serde(default)]
    pub namespace: String,
    /// A action must have a name to represent it
    #[serde(default)]
    pub name: String,
    /// A action must have a versioning
    #[serde(skip_serializing)]
    pub version: String,
    /// A action can take concurrrent limit
    #[serde(skip_serializing)]
    pub limits: Limits,
    /// A action must have Exec properties
    pub exec: Exec,
    /// A action must have error to handle error created
    #[serde(default)]
    #[serde(skip_serializing)]
    pub error: String,
    /// Toggle to publish action
    #[serde(skip_serializing)]
    pub publish: bool,
    /// Updated version count of actions
    #[serde(skip_serializing)]
    pub updated: i64,
    /// Keyvalue pair for annotate Actions
    pub annotations: Vec<KeyValue>,
}

/// Actions Execucatble properties
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
pub struct Exec {
    /// Action's Kind
    #[serde(default)]
    pub kind: String,
    /// Action's Code
    #[serde(default)]
    pub code: String,
    /// Action's Image
    #[serde(default)]
    pub image: String,
    /// Action's Init method
    #[serde(default)]
    pub init: String,
    /// Action's Main method
    #[serde(default)]
    pub main: String,
    /// Action's components
    #[serde(default)]
    pub components: Vec<String>,
    /// Toogled to true Action will be of binary
    #[serde(default)]
    pub binary: bool,
}

#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq)]
pub struct ActionList {
    pub name: String,
    pub namespace: String,
}

impl<T> ActionService<T>
where
    T: Service,
{
    /// Returns a list of Actions
    pub fn list(&self) -> Result<Vec<ActionList>, String> {
        let url = format!(
            "{}/api/v1/{}/{}/{}",
            self.context.host(),
            NAMESPACE_ENDPOINT,
            self.context.namespace(),
            ACTION_ENDPOINT
        );

        let user_auth = self.context.auth();
        let user = user_auth.0;
        let pass = user_auth.1;

        let request = match self.client.new_request(
            Some(HttpMethods::GET),
            url.as_str(),
            Some((user, pass)),
            None,
        ) {
            Ok(request) => request,
            Err(error) => return Err(error),
        };

        match self.client.invoke_request(request) {
            Ok(x) => {
                let actions: Result<Vec<Action>, Error> = serde_json::from_value(x);
                match actions {
                    Ok(actions) => {
                        let mut result = Vec::new();
                        for action in actions.into_iter() {
                            let actionlist = ActionList {
                                name: action.name,
                                namespace: action.namespace,
                            };

                            result.push(actionlist)
                        }

                        Ok(result)
                    }
                    Err(error) => return Err(format!("Failed to deserailize actions {}", error)),
                }
            }

            Err(error) => Err(format!("Failed to fetch the list of actions {}", error)),
        }
    }

    ///
    /// Returns Properties of action by using action name
    ///
    /// # Arguments
    /// * `action_name` - String slice that holds action name
    /// * `fetch_code`  - Toggle to get code for the action
    ///

    pub fn get(&self, action_name: &str, fetch_code: bool) -> Result<Action, String> {
        let url = format!(
            "{}/api/v1/{}/{}/{}/{}?code={}",
            self.context.host(),
            NAMESPACE_ENDPOINT,
            self.context.namespace(),
            ACTION_ENDPOINT,
            action_name,
            fetch_code
        );

        let user_auth = self.context.auth();
        let user = user_auth.0;
        let pass = user_auth.1;

        let request = match self.client.new_request(
            Some(HttpMethods::GET),
            url.as_str(),
            Some((user, pass)),
            None,
        ) {
            Ok(request) => request,
            Err(error) => return Err(error),
        };

        match self.client.invoke_request(request) {
            Ok(x) => match serde_json::from_value(x) {
                Ok(actions) => Ok(actions),
                Err(error) => Err(format!("Failed to deserailize actions {}", error)),
            },
            Err(error) => Err(format!("Failed to get action properties {}", error)),
        }
    }

    ///
    /// Delete Action and returns deleted Action by using action name
    ///
    /// # Arguments
    /// * `action_name` - String slice that holds action name
    ///
    pub fn delete(&self, action_name: &str) -> Result<Action, String> {
        let url = format!(
            "{}/api/v1/{}/{}/{}/{}?code=false",
            self.context.host(),
            NAMESPACE_ENDPOINT,
            self.context.namespace(),
            ACTION_ENDPOINT,
            action_name,
        );

        let user_auth = self.context.auth();
        let user = user_auth.0;
        let pass = user_auth.1;

        let request = match self.client.new_request(
            Some(HttpMethods::DELETE),
            url.as_str(),
            Some((user, pass)),
            None,
        ) {
            Ok(request) => request,
            Err(error) => return Err(error),
        };

        match self.client.invoke_request(request) {
            Ok(x) => match serde_json::from_value(x) {
                Ok(actions) => Ok(actions),
                Err(err) => Err(format!("Failed to deserailize actions {}", err)),
            },
            Err(x) => Err(format!("Failed to get action properties {}", x)),
        }
    }

    ///
    /// Insert Action and returns new action created
    ///
    /// # Arguments
    /// * `action`    - String slice that holds action name
    /// * `overwrite` - Bool toggle overwite of action if it present already
    ///
    pub fn insert(&self, action: &Action, overwrite: bool) -> Result<Action, String> {
        let url = format!(
            "{}/api/v1/{}/{}/{}/{}?overwrite={}",
            self.context.host(),
            NAMESPACE_ENDPOINT,
            self.context.namespace(),
            ACTION_ENDPOINT,
            action.name,
            overwrite,
        );

        let user_auth = self.context.auth();
        let user = user_auth.0;
        let pass = user_auth.1;

        let body = serde_json::to_value(action).unwrap();

        let request = match self.client.new_request(
            Some(HttpMethods::PUT),
            url.as_str(),
            Some((user, pass)),
            Some(body),
        ) {
            Ok(request) => request,
            Err(error) => return Err(error),
        };

        match self.client.invoke_request(request) {
            Ok(x) => match serde_json::from_value(x) {
                Ok(actions) => Ok(actions),
                Err(err) => Err(format!("Failed to deserailize actions {}", err)),
            },
            Err(x) => Err(format!("Failed to get action properties {}", x)),
        }
    }

    ///
    /// Invoke Action and returns action result
    ///
    /// # Arguments
    /// * `action_name` - String slice that holds action name
    /// * `payload`     - Params that action takes for exection
    /// * `blocking`    - Toggle to block action execution until it returns result
    /// * `result`      - Toggled only action result is returned
    ///
    pub fn invoke(
        &self,
        action_name: &str,
        payload: Value,
        blocking: bool,
        result: bool,
    ) -> Result<Value, String> {
        let url = format!(
            "{}/api/v1/{}/{}/{}/{}?blocking={}&result={}",
            self.context.host(),
            NAMESPACE_ENDPOINT,
            self.context.namespace(),
            ACTION_ENDPOINT,
            action_name,
            blocking,
            result
        );
        let user_auth = self.context.auth();
        let user = user_auth.0;
        let pass = user_auth.1;

        let request = match self.client.new_request(
            Some(HttpMethods::POST),
            url.as_str(),
            Some((user, pass)),
            Some(payload),
        ) {
            Ok(request) => request,
            Err(error) => return Err(error),
        };

        match self.client.invoke_request(request) {
            Ok(x) => match serde_json::from_value(x) {
                Ok(actions) => Ok(actions),
                Err(err) => Err(format!("Failed to deserailize actions {}", err)),
            },
            Err(x) => Err(format!("Failed to invoke action {}", x)),
        }
    }
}