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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use crate::client::{Client, ClientConfig, TimeoutAndRetries};
use crate::types::entity::HSMLEntity;
use crate::types::static_schema::entity_schema::ENTITY_SCHEMA_SWID;
use crate::types::static_schema::link_schema::LINK_SCHEMA_SWID;
use once_cell::sync::Lazy;
use pyo3::prelude::*;
use pyo3::types::{PyBool, PyDict, PyFloat, PyInt, PyList, PyLong, PyString, PyTuple};
use pyo3::wrap_pyfunction;
use serde_json::Value;
use std::sync::Arc;
use tokio::sync::Mutex;

// Lazy initialize client with null value to be set later
// because class methods cannot be async which is
// a limitation of Pyo3 / Python interop due to lifetime
// of async functions being potentially longer lived than
// the object we're defining methods on
static mut CLIENT: Lazy<Option<Arc<Mutex<Client>>>> = Lazy::new(|| None);

#[pymodule]
fn genius_core_client(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(new_client_credentials, m)?)?;
    m.add_function(wrap_pyfunction!(new_with_oauth2_token, m)?)?;
    m.add_class::<PyClient>()?;
    m.add_class::<PyHSMLEntity>()?;
    Ok(())
}

#[pyfunction]
pub fn new_client_credentials(
    py: Python,
    protocol: String,
    host: String,
    port: String,
    client_id: String,
    client_secret: String,
    auth_domain: String,
    audience: String,
    timeout: Option<u64>,
    retries: Option<u32>,
) -> PyResult<&PyAny> {
    pyo3_asyncio::tokio::future_into_py(py, async move {
        let config = ClientConfig {
            protocol: crate::client::Protocol::from(protocol.as_str()),
            host,
            port,
            client_id,
            client_secret,
            auth_domain,
            audience,
        };
        let timeout_and_retries = TimeoutAndRetries {
            timeout: tokio::time::Duration::from_secs(timeout.unwrap_or(30)),
            retries: retries.unwrap_or(3),
        };
        let result = Client::new_client_credentials(config, Some(timeout_and_retries)).await;
        eprintln!("genius_core_client: new_client_credentials is deprecated since 0.3.0-rc12. Please upgrade to `new_with_oauth2_token()` instead");
        match result {
            Ok(client) => {
                // Initialize client because class methods cannot be async
                // which is a limitation of Pyo3 / Python interop due to lifetime
                // of async functions being potentially longer lived than
                // the object we're defining methods on
                unsafe {
                    *CLIENT = Some(Arc::new(Mutex::new(client)));
                }
                // Pass back to give a convenient and familiar OOP-like interface
                // that people are familiar with and that way
                // there is no confusion when using static functions
                // whether the client has been initialized because the very fact
                // of the object being returned generally means successful
                // client creation
                Ok(PyClient {
                    inner: unsafe { CLIENT.as_ref().unwrap().clone() },
                })
            }
            Err(err) => Err(PyErr::new::<pyo3::exceptions::PyException, _>(format!(
                "{}",
                err
            ))),
        }
    })
}

#[pyfunction]
pub fn new_with_oauth2_token(
    py: Python,
    protocol: String,
    host: String,
    port: String,
    token: String,
    timeout: Option<u64>,
    retries: Option<u32>,
) -> PyResult<&PyAny> {
    pyo3_asyncio::tokio::future_into_py(py, async move {
        let timeout_and_retries = TimeoutAndRetries {
            timeout: tokio::time::Duration::from_secs(timeout.unwrap_or(30)),
            retries: retries.unwrap_or(3),
        };
        let result = Client::new_with_oauth2_token(
            crate::client::Protocol::from(protocol.as_str()),
            host, 
            port, 
            token, 
            Some(timeout_and_retries)
        ).await;
        match result {
            Ok(client) => {
                // Initialize client because class methods cannot be async
                // which is a limitation of Pyo3 / Python interop due to lifetime
                // of async functions being potentially longer lived than
                // the object we're defining methods on
                unsafe {
                    *CLIENT = Some(Arc::new(Mutex::new(client)));
                }
                // Pass back to give a convenient and familiar OOP-like interface
                // that people are familiar with and that way
                // there is no confusion when using static functions
                // whether the client has been initialized because the very fact
                // of the object being returned generally means successful
                // client creation
                Ok(PyClient {
                    inner: unsafe { CLIENT.as_ref().unwrap().clone() },
                })
            }
            Err(err) => Err(PyErr::new::<pyo3::exceptions::PyException, _>(format!(
                "{}",
                err
            ))),
        }
    })
}

#[pyclass]
pub struct PyClient {
    pub inner: Arc<Mutex<Client>>,
}

#[pymethods]
impl PyClient {
    #[staticmethod]
    fn query(py: Python, query: String) -> PyResult<&PyAny> {
        pyo3_asyncio::tokio::future_into_py(py, async move {
            let mut client = unsafe { CLIENT.as_ref().unwrap().lock().await };
            let result = client.query(query).await;
            match result {
                Ok(value) => {
                    // Convert the HSML Entity into a Python Dictionary
                    // to be usable from Python without have to
                    // pass in a generic parameter to return an abstracted
                    // HSML Entity type, which would not allow it to
                    // be typed as any shape of data structure, and only
                    // the strict type of the generic parameter passed in.
                    let value_str = serde_json::to_string(&value).unwrap();
                    Python::with_gil(|py| {
                        let py_value_str = PyString::new(py, &value_str);
                        let json_module = PyModule::import(py, "json")?;
                        let parsed = json_module.getattr("loads")?.call1((py_value_str,))?;
                        Ok(parsed.to_object(py))
                    })
                }
                Err(err) => {
                    let err_msg = format!("{}", err);
                    Python::with_gil(|_py| {
                        let py_err = PyErr::new::<pyo3::exceptions::PyException, _>(err_msg);
                        Err(py_err)
                    })
                }
            }
        })
    }
}

#[pyclass]
pub struct PyHSMLEntity {
    pub inner: HSMLEntity,
}

#[pymethods]
impl PyHSMLEntity {
    #[new]
    fn new(kwargs: Option<&PyDict>) -> Self {
        let mut entity = HSMLEntity::new(String::from(""));
        if let Some(kwargs) = kwargs {
            for (key, val) in kwargs {
                match key.to_string().as_str() {
                    "swid" => entity.swid = val.extract().unwrap(),
                    "__archived" => entity.__archived = val.extract().unwrap(),
                    "schema" => entity.schema = val.extract().unwrap(),
                    "name" => entity.name = val.extract().unwrap(),
                    "source_swid" => {
                        // Make sure entity schema type is link if contains source_swid
                        entity.schema =
                            vec![ENTITY_SCHEMA_SWID.to_string(), LINK_SCHEMA_SWID.to_string()];
                        if let Ok(py_list) = val.downcast::<PyList>() {
                            let vec: Vec<Value> = py_list
                                .into_iter()
                                .map(|item| {
                                    // Recursively convert each item in the list to a Value
                                    // You may need to handle different types here as well
                                    Value::String(item.extract::<String>().unwrap())
                                })
                                .collect();
                            entity.source_swid = Some(Value::Array(vec));
                        } else {
                            panic!("Invalid type")
                        }
                    }
                    "destination_swid" => {
                        // Make sure entity schema type is link if contains destination_swid
                        entity.schema =
                            vec![ENTITY_SCHEMA_SWID.to_string(), LINK_SCHEMA_SWID.to_string()];
                        if let Ok(py_list) = val.downcast::<PyList>() {
                            let vec: Vec<Value> = py_list
                                .into_iter()
                                .map(|item| {
                                    // Recursively convert each item in the list to a Value
                                    // You may need to handle different types here as well
                                    Value::String(item.extract::<String>().unwrap())
                                })
                                .collect();
                            entity.destination_swid = Some(Value::Array(vec));
                        } else {
                            panic!("Invalid type")
                        }
                    }
                    _ => {
                        let value = if let Ok(py_str) = val.downcast::<PyString>() {
                            Value::String(py_str.to_string())
                        } else if let Ok(py_bool) = val.downcast::<PyBool>() {
                            Value::Bool(py_bool.is_true())
                        } else if let Ok(py_int) = val.downcast::<PyInt>() {
                            Value::Number(py_int.extract::<i64>().unwrap().into())
                        } else if let Ok(py_int) = val.downcast::<PyLong>() {
                            Value::Number(py_int.extract::<i64>().unwrap().into())
                        } else if let Ok(py_float) = val.downcast::<PyFloat>() {
                            Value::Number(
                                serde_json::Number::from_f64(py_float.extract::<f64>().unwrap())
                                    .unwrap(),
                            )
                        } else if let Ok(py_list) = val.downcast::<PyList>() {
                            let vec: Vec<Value> = py_list
                                .into_iter()
                                .map(|item| {
                                    // Recursively convert each item in the list to a Value
                                    // You may need to handle different types here as well
                                    Value::String(item.extract::<String>().unwrap())
                                })
                                .collect();
                            Value::Array(vec)
                        } else {
                            panic!("Invalid type")
                        };
                        entity.extra_fields.insert(key.to_string(), value);
                    }
                }
            }
        }
        PyHSMLEntity { inner: entity }
    }

    // Out of scope:
    // Implement this if we want a convenience function
    // to instantiate a new link entity
    // fn new_link(kwargs: Option<&PyDict>) -> Self {
    //     let entity = HSMLEntity::new_link(String::from(""), &[], &[], None);
    //     PyHSMLEntity { inner: }
    // }

    // Out of scope:
    // Implement this if you want to give users a way to print
    // the entity to a dictionary
    // #[text_signature = "(self)"]
    // fn to_dict(&self, py: Python) -> PyResult<&PyDict> {
    //     let dict = PyDict::new(py);
    //     dict.set_item("swid", self.inner.swid.clone())?;
    //     // Add other fields of the HSMLEntity struct here
    //     // dict.set_item("field_name", self.inner.field_name.clone())?;
    //     Ok(dict)
    // }

    #[getter]
    fn get_swid(&self) -> PyResult<String> {
        Ok(self.inner.swid.clone())
    }

    #[setter]
    fn set_swid(&mut self, swid: String) {
        self.inner.swid = swid;
    }

    #[getter]
    fn get_destination_swid(&self) -> PyResult<Py<PyAny>> {
        Python::with_gil(|py| {
            let list = PyList::empty(py);
            for item in self
                .inner
                .destination_swid
                .clone()
                .unwrap()
                .as_array()
                .unwrap()
            {
                list.append(PyString::new(py, item.as_str().unwrap()))
                    .unwrap();
            }
            Ok(list.to_object(py))
        })
    }

    #[setter]
    fn set_destination_swid(&mut self, destination_swid: &PyList) {
        let vec: Vec<Value> = destination_swid
            .into_iter()
            .map(|item| {
                // Recursively convert each item in the list to a Value
                // You may need to handle different types here as well
                Value::String(item.extract::<String>().unwrap())
            })
            .collect();
        self.inner.destination_swid = Some(Value::Array(vec));
    }
}