Skip to content

Commit

Permalink
working on hoop apis
Browse files Browse the repository at this point in the history
  • Loading branch information
wildonion committed Jul 30, 2024
1 parent d48400e commit 1b22395
Show file tree
Hide file tree
Showing 31 changed files with 710 additions and 455 deletions.
342 changes: 176 additions & 166 deletions Cargo.lock

Large diffs are not rendered by default.

5 changes: 2 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@ tracing = "0.1"
tracing-subscriber = "0.3"
serde = {version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["preserve_order"] }
redis = { version = "0.25", features = ["tokio-comp", "cluster-async", "json"] }
redis-async = "0.17"
sha2 = "0.10"
is_type = "0.2.1"
rayon = "1.10.0"
rand = "0.8"
rslock = "0.3.0"
rslock = "0.4.0"
tonic = "0.12"
futures = "0.3"
deadpool-lapin = { version = "0.12.1", features = ["serde", "rt_tokio_1"] }
Expand All @@ -47,7 +46,7 @@ env_logger = "0.11"
bytes = { version = "1", features = ["serde"] }
wallexerr = "0.3.3"
hex = "0.4"
clap = { version = "4.5.9", features = ["derive"] }
clap = { version = "4.5.11", features = ["derive"] }
thiserror = "1.0"
percentage = "0.1.0"
sea-orm = { version = "0.12", features = [
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,9 @@ tokio::spawn( // running the consuming notif job in the background in a free thr
🗞️ HOOPOE LOGS ==> https://api.hoopoe.app/logs
🗂️ HOOPOE ASSETS FOLDER ==> https://api.hoopoe.app/assets
🍀 SWAGGER UI ==> https://api.hoopoe.app/swagger
🍀 RAPIDOC UI ==> https://api.hoopoe.app/rapidoc
🍀 SCALAR UI ==> https://api.hoopoe.app/scalar
🍀 REDOC UI ==> https://api.hoopoe.app/redoc
```

## 🗃️ wikis, docs, erds, schemas and collections
Expand Down
4 changes: 1 addition & 3 deletions hooper/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@



### Hooper video and audio live streamer upon TCP, gRPC, Capnp RPC and P2P (WebSocket, WebRTC (stun,turn), Gossipsub, QUIC) protocols

> start developing with `net.spec`
### Hooper video and audio live streamer upon TCP, gRPC, Capnp RPC and P2P (WebSocket, WebRTC (stun,turn), Gossipsub, QUIC) protocols
5 changes: 0 additions & 5 deletions hooper/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,7 @@ use std::{fs::OpenOptions, io::BufReader};
use rand::Rng;
use rand::random;
use sha2::{Digest, Sha256};
use redis::Client as RedisClient;
use redis::AsyncCommands; // this trait is required to be imported in here to call set() methods on the cluster connection
use redis::RedisResult;
use redis::Commands;
use redis_async::client::{self, PubsubConnection, ConnectionBuilder};
use redis::RedisError;
use uuid::Uuid;
use log::{info, error};
use env_logger::Env;
Expand Down
50 changes: 49 additions & 1 deletion migration/src/m20240503_190902_hoops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ impl MigrationTrait for Migration {
.auto_increment()
.primary_key(),
)
.col(
ColumnDef::new(Hoops::Title)
.string()
.not_null()
)
.col(
ColumnDef::new(Hoops::Description)
.string()
.not_null()
)
.col(
ColumnDef::new(Hoops::Cover)
.string()
.not_null()
)
.col(
ColumnDef::new(Hoops::Etype)
.not_null()
Expand All @@ -50,6 +65,31 @@ impl MigrationTrait for Migration {
.big_integer()
.not_null()
)
.col(
ColumnDef::new(Hoops::Duration)
.big_integer()
.not_null()
)
.col(
ColumnDef::new(Hoops::Capacity)
.big_integer()
.not_null()
)
.col(
ColumnDef::new(Hoops::StartedAt)
.timestamp_with_time_zone()
.not_null()
)
.col(
ColumnDef::new(Hoops::IsFinished)
.boolean()
.default(false)
)
.col(
ColumnDef::new(Hoops::IsLocked)
.boolean()
.default(false)
)
.col(
ColumnDef::new(Hoops::CreatedAt)
.timestamp_with_time_zone()
Expand Down Expand Up @@ -90,8 +130,16 @@ enum Hoops {
Table, // reserved for table name
Id, // primary key to bring the entity into life
Etype,
Title,
Description,
Manager,
EntranceFee,
IsLocked,
IsFinished,
Duration, // in seconds
Capacity,
Cover,
StartedAt,
CreatedAt,
UpdatedAt
}
}
1 change: 1 addition & 0 deletions src/apis/v1/http/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use constants::{CRYPTER_THEMIS_ERROR_CODE, STORAGE_IO_ERROR_CODE};
use context::AppContext;
use deadpool_redis::redis::AsyncCommands;
use log::kv::source;
use wallexerr::misc::{SecureCellConfig, Wallet};
use crate::*;
Expand Down
141 changes: 13 additions & 128 deletions src/apis/v1/http/health.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,133 +18,13 @@ use base58::{ToBase58, FromBase58};



// use for encrypting the image bytes
impl Crypter for &[u8]{
fn encrypt(&self, secure_cell_config: &mut wallexerr::misc::SecureCellConfig){
match wallexerr::misc::Wallet::secure_cell_encrypt(secure_cell_config){ // passing the redis secure_cell_config instance
Ok(data) => {
secure_cell_config.data = data
},
Err(e) => {

tokio::spawn(async move{
let source = &e.to_string(); // we know every goddamn type implements Error trait, we've used it here which allows use to call the source method on the object
let err_instance = crate::error::HoopoeErrorResponse::new(
*constants::CRYPTER_THEMIS_ERROR_CODE, // error hex (u16) code
source.as_bytes().to_vec(), // text of error source in form of utf8 bytes
crate::error::ErrorKind::Crypter(crate::error::CrypterError::Themis(e)), // the actual source of the error caused at runtime
&String::from("CrypterInterface.encrypt.Wallet::secure_cell_decrypt"), // current method name
None
).await;
});

// don't update data field in secure_cell_config instance
// the encrypted data remains the same as before.
}
};
}

fn decrypt(&self, secure_cell_config: &mut wallexerr::misc::SecureCellConfig){
match wallexerr::misc::Wallet::secure_cell_decrypt(secure_cell_config){
Ok(encrypted) => {

let stringified_data = hex::encode(&encrypted);
// update the data field with the encrypted content bytes
secure_cell_config.data = encrypted;

},
Err(e) => {

// log the error in the a lightweight thread of execution inside tokio threads
// since we don't need output or any result from the task inside the thread thus
// there is no channel to send data to outside of tokio::spawn
tokio::spawn(async move{
let source = &e.to_string(); // we know every goddamn type implements Error trait, we've used it here which allows use to call the source method on the object
let err_instance = crate::error::HoopoeErrorResponse::new(
*constants::CRYPTER_THEMIS_ERROR_CODE, // error hex (u16) code
source.as_bytes().to_vec(), // text of error source in form of utf8 bytes
crate::error::ErrorKind::Crypter(crate::error::CrypterError::Themis(e)), // the actual source of the error caused at runtime
&String::from("CrypterInterface.encrypt.Wallet::secure_cell_encrypt"), // current method name
None
).await;
});

// don't update data field in secure_cell_config instance
// the raw data remains the same as before.
}
};

}

}


// use for encrypting the image bytes
impl Crypter for Vec<u8>{
fn encrypt(&self, secure_cell_config: &mut wallexerr::misc::SecureCellConfig){
match wallexerr::misc::Wallet::secure_cell_encrypt(secure_cell_config){ // passing the redis secure_cell_config instance
Ok(data) => {
secure_cell_config.data = data
},
Err(e) => {

tokio::spawn(async move{
let source = &e.to_string(); // we know every goddamn type implements Error trait, we've used it here which allows use to call the source method on the object
let err_instance = crate::error::HoopoeErrorResponse::new(
*constants::CRYPTER_THEMIS_ERROR_CODE, // error hex (u16) code
source.as_bytes().to_vec(), // text of error source in form of utf8 bytes
crate::error::ErrorKind::Crypter(crate::error::CrypterError::Themis(e)), // the actual source of the error caused at runtime
&String::from("CrypterInterface.encrypt.Wallet::secure_cell_decrypt"), // current method name
None
).await;
});

// don't update data field in secure_cell_config instance
// the encrypted data remains the same as before.
}
};
}

fn decrypt(&self, secure_cell_config: &mut wallexerr::misc::SecureCellConfig){
match wallexerr::misc::Wallet::secure_cell_decrypt(secure_cell_config){
Ok(encrypted) => {

let stringified_data = hex::encode(&encrypted);
// update the data field with the encrypted content bytes
secure_cell_config.data = encrypted;

},
Err(e) => {

// log the error in the a lightweight thread of execution inside tokio threads
// since we don't need output or any result from the task inside the thread thus
// there is no channel to send data to outside of tokio::spawn
tokio::spawn(async move{
let source = &e.to_string(); // we know every goddamn type implements Error trait, we've used it here which allows use to call the source method on the object
let err_instance = crate::error::HoopoeErrorResponse::new(
*constants::CRYPTER_THEMIS_ERROR_CODE, // error hex (u16) code
source.as_bytes().to_vec(), // text of error source in form of utf8 bytes
crate::error::ErrorKind::Crypter(crate::error::CrypterError::Themis(e)), // the actual source of the error caused at runtime
&String::from("CrypterInterface.encrypt.Wallet::secure_cell_encrypt"), // current method name
None
).await;
});

// don't update data field in secure_cell_config instance
// the raw data remains the same as before.
}
};

}

}

#[endpoint]
pub async fn check_health(
req: &mut Request,
res: &mut Response,
depot: &mut Depot,
ctrl: &mut FlowCtrl
ctrl: &mut FlowCtrl // with this we can control the flow of each route like executing the next handler
){

let app_ctx = depot.obtain::<Option<AppContext>>().unwrap(); // extracting shared app context
Expand Down Expand Up @@ -268,7 +148,7 @@ pub async fn home(
req: &mut Request,
res: &mut Response,
depot: &mut Depot,
ctrl: &mut FlowCtrl
ctrl: &mut FlowCtrl // with this we can control the flow of each route like executing the next handler
){

res.render(Text::Html(constants::HOME_HTML));
Expand All @@ -280,7 +160,7 @@ pub async fn mint(
req: &mut Request,
res: &mut Response,
depot: &mut Depot,
ctrl: &mut FlowCtrl,
ctrl: &mut FlowCtrl, // with this we can control the flow of each route like executing the next handler
// https://salvo.rs/book/features/openapi.html#extractors (QueryParam, HeaderParam, CookieParam, PathParam, FormBody, JsonBody)
prod: JsonBody<Product>, // used to extract the request body as well as showcasing in swagger ui
){
Expand Down Expand Up @@ -321,7 +201,6 @@ pub async fn mint(
// if you want to use while let Some the prod must be cloned in every iteration
// hence using if let Some is the best option in here to avoid using clone.
if let Some(product) = product_receiver.recv().await{
log::info!("received updated product info: {:?}", product);

let server_time = format!("{}", chrono::Local::now().to_string());
res.status_code = Some(StatusCode::OK);
Expand All @@ -333,7 +212,8 @@ pub async fn mint(
status: StatusCode::OK.as_u16(),
meta: Some(
serde_json::json!({
"server_time": server_time
"server_time": server_time,
"minted_product": product
})
)
}
Expand All @@ -350,7 +230,7 @@ pub async fn picer(
req: &mut Request,
res: &mut Response,
depot: &mut Depot,
ctrl: &mut FlowCtrl,
ctrl: &mut FlowCtrl, // with this we can control the flow of each route like executing the next handler
// https://salvo.rs/book/features/openapi.html#extractors (QueryParam, HeaderParam, CookieParam, PathParam, FormBody, JsonBody)
secure_cell_config: FormBody<UserSecureCellConfig>, // used to extract the request body as well as showcasing in swagger ui
){
Expand All @@ -375,6 +255,10 @@ pub async fn picer(
let mut img_buffer = vec![];
let img_bytes = img.read_to_end(&mut img_buffer).await;


// consider uploading the image to aws or digispaces
// ...

// encrypt the content of the file
let mut secure_cell_config = wallexerr::misc::SecureCellConfig{
secret_key: secure_cell_config.clone().secret_key,
Expand All @@ -390,8 +274,9 @@ pub async fn picer(
f.write_all(&encrypted_data).await;

// let the encrypted file only be there
std::fs::remove_file(dest);
tokio::fs::remove_file(dest).await;

// fill the response object
let server_time = format!("{}", chrono::Local::now().to_string());
res.status_code = Some(StatusCode::OK);
res.render(Json(
Expand All @@ -408,7 +293,7 @@ pub async fn picer(
}
)); // the minting was successfully started
},
Err(e) => {
Err(e) => { // can't copy the file into dest path

// fill the response objcet
let server_time = format!("{}", chrono::Local::now().to_string());
Expand Down
Loading

0 comments on commit 1b22395

Please sign in to comment.