juiz_core 0.0.9

Core library for JUIZ application. This package is not required if you want to build juiz functional module.
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use image::EncodableLayout;
use juiz_sdk::anyhow::anyhow;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
// use crate::prelude::*;
use crate::brokers::CRUDBroker;

use axum::extract::Multipart;
use axum::http::HeaderValue;

// #[cfg(feature="opencv4")]
// use opencv::{core::{Vector, VectorToVec}, imgcodecs::imencode};

use tower_http::services::ServeDir;
use utoipa::openapi::{
    path::OperationBuilder, request_body::RequestBodyBuilder, ContentBuilder, PathItem,
    PathItemType,
};
use utoipa::{IntoParams, OpenApi};
use utoipa_swagger_ui::SwaggerUi;

use axum::{
    body::Body,
    extract::Query,
    http::StatusCode,
    response::{IntoResponse, Response},
    Json, Router,
};
use serde::Deserialize;

use crate::prelude::*;

pub mod any;
pub mod any_process;
pub mod broker;
pub mod connection;
pub mod container;
pub mod container_process;
pub mod execution_context;
pub mod process;
pub mod system;
pub mod topic;
// use cv_convert::TryFromCv;

#[derive(Deserialize, IntoParams, Debug)]
pub struct IdentifierQuery {
    identifier: Option<String>,
}

#[derive(Deserialize, IntoParams, Debug)]
pub struct PathQuery {
    path: Option<String>,
}

#[allow(unused)]
#[derive(Deserialize, IntoParams, Debug)]
pub struct RecursiveQuery {
    recursive: Option<String>,
}

#[derive(Deserialize, IntoParams, Debug)]
pub struct IdAndRecurQuery {
    identifier: Option<String>,
    recursive: Option<String>,
}

#[derive(Deserialize, IntoParams, Debug)]
pub struct IdAndUuidQuery {
    identifier: Option<String>,
    system_uuid: Option<String>,
}

#[allow(unused)]
#[derive(Deserialize, IntoParams, Debug)]
pub struct TopicNameAndUuidQuery {
    topic_name: Option<String>,
    system_uuid: Option<String>,
}

#[derive(Deserialize, IntoParams, Debug)]
pub struct FullQuery {
    identifier: Option<String>,
    path: Option<String>,
    recursive: Option<String>,
    system_uuid: Option<String>,
    topic_name: Option<String>,
}

#[allow(unused)]
pub fn id_query_to_map(query: &Query<IdentifierQuery>) -> HashMap<String, String> {
    let mut map: HashMap<String, String> = HashMap::new();
    match query.identifier.clone() {
        None => {}
        Some(v) => {
            map.insert("identifier".to_owned(), v);
        }
    }
    map
}

#[allow(unused)]
pub fn path_query_to_map(query: &Query<PathQuery>) -> HashMap<String, String> {
    let mut map: HashMap<String, String> = HashMap::new();
    match query.path.clone() {
        None => {}
        Some(v) => {
            map.insert("path".to_owned(), v);
        }
    }
    map
}

#[allow(unused)]
pub fn id_and_recur_query_to_map(query: &Query<IdAndRecurQuery>) -> HashMap<String, String> {
    let mut map: HashMap<String, String> = HashMap::new();
    match query.identifier.clone() {
        None => {}
        Some(v) => {
            map.insert("identifier".to_owned(), v);
        }
    }
    match query.recursive.clone() {
        None => {}
        Some(v) => {
            map.insert("recursive".to_owned(), v);
        }
    }
    map
}

#[allow(unused)]
pub fn id_and_uuid_query_to_map(query: &Query<IdAndUuidQuery>) -> HashMap<String, String> {
    let mut map: HashMap<String, String> = HashMap::new();
    match query.identifier.clone() {
        None => {}
        Some(v) => {
            map.insert("identifier".to_owned(), v);
        }
    }
    match query.system_uuid.clone() {
        None => {}
        Some(v) => {
            map.insert("system_uuid".to_owned(), v);
        }
    }
    map
}

pub fn full_query_to_map(query: &Query<FullQuery>) -> HashMap<String, String> {
    let mut map: HashMap<String, String> = HashMap::new();
    match query.identifier.clone() {
        None => {}
        Some(v) => {
            map.insert("identifier".to_owned(), v);
        }
    }
    match query.recursive.clone() {
        None => {}
        Some(v) => {
            map.insert("recursive".to_owned(), v);
        }
    }
    match query.path.clone() {
        None => {}
        Some(v) => {
            map.insert("path".to_owned(), v);
        }
    }
    match query.system_uuid.clone() {
        None => {}
        Some(v) => {
            map.insert("system_uuid".to_owned(), v);
        }
    }
    match query.topic_name.clone() {
        None => {}
        Some(v) => {
            map.insert("topic_name".to_owned(), v);
        }
    }
    map
}

#[allow(unused)]
pub fn json_wrap(result: JuizResult<CapsulePtr>) -> impl IntoResponse {
    match result {
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(jvalue!({
                "message": format!("Internal Server Error:  {:#}, {:}", e, e.to_string())
            })),
        )
            .into_response(),
        Ok(arc) => {
            let result = capsule_to_value(arc);
            if result.is_err() {
                let e = result.err().unwrap();
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(jvalue!({
                        "message": format!("Internal Server Error:  {:#}, {:}", e, e.to_string())
                    })),
                )
                    .into_response();
            }
            Json::<Value>(result.unwrap()).into_response()
        }
    }
}

pub fn json_output_wrap(result: JuizResult<CapsulePtr>) -> impl IntoResponse {
    //log::trace!("json_output_wrap() called");
    if result.is_err() {
        let e = result.err().unwrap();
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(jvalue!({
                "message": format!("Internal Server Error:  {:#}, {:}", e, e.to_string())
            })),
        )
            .into_response();
    }
    match result {
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(jvalue!({
                "message": format!("Internal Server Error:  {:#}, {:}", e, e.to_string())
            })),
        )
            .into_response(),
        Ok(v) => capsule_ptr_to_response(v),
    }
}

//#[cfg(not(feature= "opencv4"))]
fn capsule_ptr_to_response(v: CapsulePtr) -> axum::http::Response<Body> {
    use juiz_sdk::image::ImageFormat;

    if v.is_value().unwrap() {
        v.lock_as_value(|value| {
            let mut r = Json(value).into_response();
            let hdrs = r.headers_mut();
            hdrs.append("Cache-Control", HeaderValue::from_str("no-cache").unwrap());
            r
        })
        .unwrap()
    } else if v.is_image().unwrap() {
        use std::io::{BufWriter, Cursor};
        // log::trace!("Detect Image Response v={v:?}");
        v.lock_as_image(|image| {
            let mut buffer = BufWriter::new(Cursor::new(Vec::new()));
            image.write_to(&mut buffer, ImageFormat::Png).unwrap();

            //let bytes = buffer.into_inner().unwrap().into_inner().as_bytes();
            Response::builder()
                .extension("png")
                .header("Content-Type", "image/png")
                .status(StatusCode::OK)
                .body(Body::from(buffer.into_inner().unwrap().into_inner()))
                .unwrap()
                .into_response()
        })
        .unwrap()
    } else {
        Json(jvalue!({})).into_response()
    }
}

// #[cfg(feature= "opencv4")]
// fn capsule_ptr_to_response(v: CapsulePtr) -> axum::http::Response<Body>  {
//     if v.is_value().unwrap() {
//         v.lock_as_value(|value| {
//             let mut r = Json(value).into_response();
//             let hdrs = r.headers_mut();
//             hdrs.append("Cache-Control", HeaderValue::from_str("no-cache").unwrap());
//             r
//         }).unwrap()
//     } else if v.is_mat().unwrap() {
//         v.lock_as_mat(|result| {
//             let mut buf : opencv::core::Vector<u8> = Vector::new();

//             match imencode(".png", result, &mut buf, &Vector::new()) {
//                 Ok(_result) => {
//                     Response::builder()
//                         .extension("png")
//                         .header("Content-Type", "image/png")
//                         .status(StatusCode::OK)
//                         .body(Body::from(buf.to_vec())).unwrap().into_response()
//                 },
//                 Err(e) => {
//                     Json(jvalue!({
//                         "result": "Error",
//                         "error": format!("{}", e)
//                     })).into_response()
//                 },
//             }

//         }).unwrap()
//     } else {
//         Json(jvalue!({})).into_response()
//     }
// }

pub async fn multipart_to_capsule_map(mut multipart: Multipart) -> JuizResult<CapsuleMap> {
    let mut cm = CapsuleMap::new();

    loop {
        match multipart.next_field().await {
            Ok(opt_field) => {
                if let Some(field) = opt_field {
                    // log::trace!(" - field: {:?}", field);
                    if field.name().is_none() {
                        log::error!("Multipart/FormData does not have 'field_name' field. This can not be handled.");
                        return Err(anyhow!(JuizError::InvalidArgumentError{message:"Multipart/FormData does not have 'fieldname' field. This can not be handled.".to_owned()}));
                    }
                    let field_name = field.name().unwrap().to_owned();
                    match field.content_type() {
                        Some(content_type) => match content_type {
                            "image/png" => {
                                match image::load_from_memory_with_format(
                                    field.bytes().await.unwrap().as_bytes(),
                                    image::ImageFormat::Png,
                                ) {
                                    Ok(img) => {
                                        cm.insert(field_name, img.into());
                                    }
                                    Err(_) => todo!(),
                                }
                            }
                            "application/json" => {
                                let ft = field.text().await;
                                println!("match ({field_name}, {:?})", ft);
                                let v = serde_json::Value::from(ft.unwrap().as_str());
                                cm.insert(field_name, v.into());
                            }
                            _ => {
                                log::error!("Multipart/FormData does not have available 'content-type' field ({content_type}). This can not be handled.");
                                return Err(anyhow!(JuizError::InvalidArgumentError{message:format!("Multipart/FormData does not have available 'content-type' field ({content_type}). This can not be handled.")}));
                            }
                        },
                        None => {
                            log::error!("Multipart/FormData does not have 'content-type' field. This can not be handled.");
                            return Err(anyhow!(JuizError::InvalidArgumentError{message:"Multipart/FormData does not have 'content-type' field. This can not be handled.".to_owned()}));
                        }
                    }
                } else {
                    break;
                }
            }
            Err(e) => {
                log::error!("Multipart parse error. {e:?}");
                return Err(anyhow!(JuizError::InvalidArgumentError {
                    message: format!("Multipart/FormData parsing error. Err({e}).")
                }));
            }
        }
    }
    Ok(cm)
}

#[derive(OpenApi)]
#[openapi(tags(), paths(), components(schemas()))]
struct ApiDoc;

pub fn app_new(
    crud_broker: Arc<Mutex<CRUDBroker>>,
    static_filepaths: Option<Vec<(String, PathBuf)>>,
) -> Router {
    let mut api = ApiDoc::openapi();
    api.merge(system::ApiDoc::openapi());
    api.merge(process::ApiDoc::openapi());
    api.merge(container::ApiDoc::openapi());
    api.merge(container_process::ApiDoc::openapi());
    api.merge(broker::ApiDoc::openapi());
    api.merge(execution_context::ApiDoc::openapi());
    api.merge(connection::ApiDoc::openapi());
    api.merge(topic::ApiDoc::openapi());
    log::trace!("app_new(static_filepaths: {static_filepaths:?}) called");
    let mut r = Router::new()
        .merge(SwaggerUi::new("/docs").url("/api-docs/openapi.json", api))
        .nest("/api/", any::object_router(crud_broker.clone()));

    match static_filepaths {
        Some(paths) => {
            for (url, path) in paths.iter() {
                log::debug!("http_broker serves url={url} for path={path:?}");
                r = r.nest_service(url.as_str(), ServeDir::new(path));
            }
            r
        }
        None => r,
    }
}

#[allow(unused)]
pub fn append_route(
    api: &mut utoipa::openapi::OpenApi,
    body_context: Value,
    description: &str,
    operation_key: &str,
) -> () {
    let ctt = ContentBuilder::new().example(Some(body_context)).build();
    let rb = RequestBodyBuilder::new()
        .description(Some(description.to_owned()))
        .content("application/json", ctt)
        .build();
    let operation = OperationBuilder::new().request_body(Some(rb)).build();
    api.paths.paths.insert(
        operation_key.to_owned(),
        PathItem::new(PathItemType::Patch, operation),
    );
}