This commit is contained in:
Adrian Woźniak 2022-12-08 16:22:20 +01:00
parent 2f2e6b8c2f
commit 940983d3f7
16 changed files with 2557 additions and 692 deletions

View File

@ -3,5 +3,5 @@ linker = "clang"
rustflags = [ rustflags = [
"-C", "link-arg=-fuse-ld=mold", "-C", "link-arg=-fuse-ld=mold",
] ]
[build] #[build]
rustc-wrapper = "/usr/bin/sccache" #rustc-wrapper = ""

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
/target target
bazzar.toml bazzar.toml
/tmp /tmp
/uploads /uploads

1361
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -19,6 +19,7 @@ members = [
"crates/fs_manager", "crates/fs_manager",
"crates/lang_provider", "crates/lang_provider",
"crates/payment_adapter", "crates/payment_adapter",
# "crates/payment_adapter_pay_u",
# artifacts # artifacts
# "crates/db-seed", # "crates/db-seed",
# "crates/api", # "crates/api",

View File

@ -16,4 +16,3 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", features = [] } serde_json = { version = "1.0", features = [] }
thiserror = { version = "1.0" } thiserror = { version = "1.0" }
toml = { version = "0.5", features = [] } toml = { version = "0.5", features = [] }
tracing = { version = "0.1.34" }

View File

@ -776,8 +776,7 @@ pub fn load(config_path: &str, opts: &impl UpdateConfig) -> SharedAppConfig {
std::process::exit(1); std::process::exit(1);
} }
Err(e) => { Err(e) => {
tracing::error!("{e:?}"); panic!("Config file was not found at path {config_path:?}. {}", e)
panic!("Config file was not found at path {config_path:?}")
} }
} }
} }

View File

@ -28,6 +28,6 @@ serde = { version = "1.0.137" }
sqlx = { version = "0.6.2", features = ["migrate", "runtime-actix-rustls", "all-types", "postgres"], optional = true } sqlx = { version = "0.6.2", features = ["migrate", "runtime-actix-rustls", "all-types", "postgres"], optional = true }
sqlx-core = { version = "0.6.2", features = [], optional = true } sqlx-core = { version = "0.6.2", features = [], optional = true }
thiserror = { version = "1.0.31" } thiserror = { version = "1.0.31" }
tracing = { version = "0.1.34" }
uuid = { version = "1.2.1", features = ["serde"] } uuid = { version = "1.2.1", features = ["serde"] }
validator = { version = "0.16.0" } validator = { version = "0.16.0" }
#tracing = { version = "0.1.34" }

View File

@ -9,7 +9,7 @@ pub trait Encrypt {
impl Encrypt for crate::Password { impl Encrypt for crate::Password {
fn encrypt(&self, salt: &SaltString) -> password_hash::Result<String> { fn encrypt(&self, salt: &SaltString) -> password_hash::Result<String> {
tracing::debug!("Hashing password {:?}", self); // tracing::debug!("Hashing password {:?}", self);
Ok( Ok(
Argon2::new(Algorithm::Argon2id, Version::V0x13, Params::default()) Argon2::new(Algorithm::Argon2id, Version::V0x13, Params::default())
.hash_password(self.as_bytes(), &salt)? .hash_password(self.as_bytes(), &salt)?
@ -18,7 +18,7 @@ impl Encrypt for crate::Password {
} }
fn validate(&self, pass_hash: &crate::PassHash) -> password_hash::Result<()> { fn validate(&self, pass_hash: &crate::PassHash) -> password_hash::Result<()> {
tracing::debug!("Validating password {:?} {:?}", self, pass_hash); // tracing::debug!("Validating password {:?} {:?}", self, pass_hash);
Argon2::default().verify_password( Argon2::default().verify_password(
self.as_bytes(), self.as_bytes(),

View File

@ -6,3 +6,8 @@ edition = "2021"
[dependencies] [dependencies]
config = { path = "../config", default-features = false, features = [] } config = { path = "../config", default-features = false, features = [] }
model = { path = "../model" } model = { path = "../model" }
serde = { version = "1.0.149", features = ['derive'] }
uuid = { version = "1.2.2", features = ['v4'] }
futures = { version = "0.3.25" }
tracing = { version = "0.1.37" }
thiserror = { version = "1.0.37" }

View File

@ -1,18 +1,24 @@
use std::collections::HashMap;
pub use config::PaymentProviderConfig; pub use config::PaymentProviderConfig;
pub use model::*; pub use model::*;
pub use uuid;
pub const CONFIG_POS: u32 = 3; pub const CONFIG_POS: u32 = 3;
#[derive(Debug)] #[derive(Debug, Clone, Copy, thiserror::Error, serde::Serialize, serde::Deserialize)]
#[repr(C)]
pub enum Error {
#[error("Malformed create payment message")]
MalformedCreatePayment,
}
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
#[repr(C)] #[repr(C)]
pub enum Status { pub enum Status {
Success = 0, Success = 0,
Failure = 1, Failure = 1,
} }
#[derive(Debug)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[repr(C)] #[repr(C)]
pub struct Buyer { pub struct Buyer {
/// Required customer e-mail /// Required customer e-mail
@ -27,17 +33,25 @@ pub struct Buyer {
pub language: String, pub language: String,
} }
#[derive(Debug)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[repr(C)] #[repr(C)]
pub struct Product { pub struct Product {
pub id: ProductId, pub id: i32,
pub name: String, pub name: String,
pub unit_price: Price, pub unit_price: i32,
pub quantity_unit: QuantityUnit, pub quantity_unit: String,
pub quantity: Quantity, pub quantity: i32,
} }
#[derive(Debug)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[repr(C)]
pub struct Item {
pub product_id: i32,
pub quantity: i32,
pub quantity_unit: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[repr(C)] #[repr(C)]
pub struct CreatePayment { pub struct CreatePayment {
// pub client: PayUClient, // pub client: PayUClient,
@ -46,16 +60,46 @@ pub struct CreatePayment {
pub currency: String, pub currency: String,
pub description: String, pub description: String,
pub cart_products: Vec<Product>, pub cart_products: Vec<Product>,
pub items: HashMap<ProductId, (Quantity, QuantityUnit)>, pub items: Vec<Item>,
pub order_ext_id: String, pub order_ext_id: String,
pub notify_uri: String, pub notify_uri: String,
pub continue_uri: String, pub continue_uri: String,
} }
pub trait PaymentAdapter { // #[tarpc::service]
fn name() -> &'static str; // pub trait PaymentAdapter {
// async fn create_payment(msg: CreatePayment) -> Status;
fn init(&mut self, config: PaymentProviderConfig); // }
//
fn create_payment(&self, msg: CreatePayment) -> Status; // pub async fn start_server<Server, Req, Build>(name: &str, port: u16, build:
} // Build) where
// Server: Serve<Req> + Send + 'static + Clone,
// Build: Fn() -> Server,
// <Server as Serve<Req>>::Fut: Send,
// <Server as Serve<Req>>::Resp: serde::Serialize + Send + 'static,
// Req: Send + 'static,
// Req: for<'l> serde::Deserialize<'l>,
// {
// let server_addr = (IpAddr::V4(Ipv4Addr::LOCALHOST), port);
//
// let mut listener = tarpc::serde_transport::tcp::listen(&server_addr,
// Bincode::default) .await
// .unwrap();
// tracing::info!("Starting {} rpc at {}", name, listener.local_addr());
// listener.config_mut().max_frame_length(usize::MAX);
// listener
// // Ignore accept errors.
// .filter_map(|r| futures::future::ready(r.ok()))
// .map(server::BaseChannel::with_defaults)
// // Limit channels to 8 per IP.
// .max_channels_per_key(8, |t| t.transport().peer_addr().unwrap().ip())
// .max_concurrent_requests_per_channel(20)
// // serve is generated by the service attribute. It takes as input any
// type implementing // the generated World trait.
// .map(|channel| channel.execute(build()))
// // Max 10 channels.
// .buffer_unordered(10)
// .for_each(|_| async {})
// .await;
// tracing::info!("RPC channel closed");
// }

1597
crates/payment_adapter_pay_u/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -9,9 +9,7 @@ crate-type = ['cdylib']
[dependencies] [dependencies]
pay_u = { path = "../../vendor/pay_u" } pay_u = { path = "../../vendor/pay_u" }
payment_adapter = { path = "../payment_adapter" } payment_adapter = { path = "../payment_adapter" }
#wasmer-wasi = { version = "3.0.2" } bincode = { version = "1.3.3" }
wasmer = { version = "3.0.2", default-features = false, features = ['js', 'std', 'wasmer-compiler-llvm', 'enable-serde'] } wapc-codec = { version = "1.0.0" }
#wasm-bindgen = { version = "0.2.83", features = [] } wapc-guest = { version = "1.0.0" }
#js-sys = { version = "0.3.60", features = [] } tokio = { version="1.21.1", features=["rt","sync","time"] }
#web-sys = { version = "0.3.60", features = [] }
wee_alloc = { version = "0.4.5" }

View File

@ -1,20 +1,78 @@
use std::os::wasi::prelude::*; use std::sync::{Arc, Mutex};
use payment_adapter::{CreatePayment, Status}; use pay_u::{ClientId, ClientSecret, MerchantPosId};
// use wasm_bindgen::prelude::*; use payment_adapter::{CreatePayment, PaymentProviderConfig, Status};
use wapc_codec::messagepack::*;
use wapc_guest as wapc;
#[global_allocator] struct PayU {
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; client: Arc<Mutex<pay_u::Client>>,
// #[wasm_bindgen]
#[no_mangle]
pub extern "C" fn name() -> String {
"pay_u".into()
} }
// #[wasm_bindgen] static mut CLIENT: Option<PayU> = None;
#[no_mangle] static mut RUNTIME: Option<tokio::runtime::Runtime> = None;
pub extern "C" fn create_payment(msg: *const CreatePayment) -> i32 {
eprintln!("{:?}", msg); impl PayU {
Status::Failure as i32 fn mount() {
wapc::register_function("init", Self::init);
wapc::register_function("create_payment", Self::create_payment);
}
fn init(msg: &[u8]) -> wapc::CallResult {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.enable_time()
.build()
.unwrap();
unsafe {
RUNTIME = Some(runtime);
}
let config: PaymentProviderConfig = match deserialize(msg) {
Ok(c) => c,
_ => return Err(Box::new(payment_adapter::Error::MalformedCreatePayment)),
};
let res_client = Arc::new(Mutex::new({
pay_u::Client::new(
ClientId::new(config.client_id.unwrap()),
ClientSecret::new(config.client_secret.unwrap()),
MerchantPosId::new(config.merchant_id.unwrap().parse().unwrap()),
)
}));
let c = res_client.clone();
unsafe { RUNTIME.as_ref().unwrap() }.block_on(async {
c.lock().unwrap().authorize().await.unwrap_or_else(|e| {
// tracing::error!("{e}");
dbg!(e);
std::process::exit(1);
});
});
unsafe {
CLIENT = Some(Self { client: res_client });
}
Ok(vec![])
}
fn create_payment(msg: &[u8]) -> wapc::CallResult {
let client = unsafe { CLIENT.as_ref().unwrap() };
let c: CreatePayment = match deserialize(msg) {
Ok(c) => c,
_ => return Err(Box::new(payment_adapter::Error::MalformedCreatePayment)),
};
wapc::console_log(&format!(
"IN_WASM: Received request for `ping` operation with payload : {:?}",
c
));
eprintln!("{:?}", c);
// let _res = wapc::host_call("binding", "sample:namespace", "pong", msg)?;
Ok(serialize(Status::Success).unwrap())
}
}
#[no_mangle]
pub fn wapc_init() {
PayU::mount();
} }

View File

@ -15,8 +15,6 @@ db-utils = { path = "../db-utils" }
gumdrop = { version = "0.8.1", features = [] } gumdrop = { version = "0.8.1", features = [] }
llvmenv = { version = "0.3.2" } llvmenv = { version = "0.3.2" }
model = { path = "../model", features = ["db"] } model = { path = "../model", features = ["db"] }
openssl-src = { version = "111" }
openssl-sys = { version = "0.9", features = ['openssl-src'] }
opentelemetry = { version = "0.17.0" } opentelemetry = { version = "0.17.0" }
opentelemetry-jaeger = { version = "0.17.0" } opentelemetry-jaeger = { version = "0.17.0" }
payment_adapter = { path = "../payment_adapter" } payment_adapter = { path = "../payment_adapter" }
@ -30,9 +28,12 @@ tokio = { version = "1.21.2", features = ['full'] }
tracing = { version = "0.1.6" } tracing = { version = "0.1.6" }
tracing-opentelemetry = { version = "0.17.4" } tracing-opentelemetry = { version = "0.17.4" }
tracing-subscriber = { version = "0.3.16", features = ["env-filter"] } tracing-subscriber = { version = "0.3.16", features = ["env-filter"] }
uuid = { version = "1.2.1", features = ["serde"] } uuid = { version = "1.2.1", features = ["serde", "v4"] }
wasmer = { version = "3", default-features = false, features = ['sys-default', 'wasmer-compiler-cranelift'] } bincode = { version = "1.3.3" }
wasmer-wasi = { version = "3.0.2", default-features = false, features = ['host-fs', 'host-vnet'] } wapc = { version = "1.0.0", features = [] }
wapc-codec = { version = "1.0.0" }
wapc-pool = { version = "1.0.0" }
wasmtime-provider = { version = "1.3.2", features = [] }
[dev-dependencies] [dev-dependencies]
fake = { version = "2.5.0" } fake = { version = "2.5.0" }

View File

@ -2,6 +2,7 @@ use std::fs::read_dir;
use std::path::PathBuf; use std::path::PathBuf;
use config::{AppConfig, UpdateConfig}; use config::{AppConfig, UpdateConfig};
use wapc_pool::HostPoolBuilder;
// use payment_adapter::{CreatePayment, PaymentAdapter, Status}; // use payment_adapter::{CreatePayment, PaymentAdapter, Status};
// mod actions; // mod actions;
@ -30,18 +31,7 @@ async fn main() {
let opts: Opts = gumdrop::parse_args_default_or_exit(); let opts: Opts = gumdrop::parse_args_default_or_exit();
let config = config::default_load(&opts); let config = config::default_load(&opts);
let payment_config = { config.lock().payment().clone() }; let _payment_config = config.lock().payment().clone();
use wasmer::{Instance, Module, Store, Value};
let imports = wasmer::imports! {
// "" => { "name" => name, "create_payment" => create_payment, }
};
let mut store = wasmer::Store::default();
// store.add_fuel(u64::MAX).unwrap();
// store.data_mut().table().insert_at(
// payment_adapter::CONFIG_POS,
// Box::new(payment_config.clone()),
// );
{ {
let adapters_path = config.lock().payment().adapters_path.clone(); let adapters_path = config.lock().payment().adapters_path.clone();
@ -57,16 +47,24 @@ async fn main() {
if file.extension().and_then(|s| s.to_str()) != Some("wasm") { if file.extension().and_then(|s| s.to_str()) != Some("wasm") {
continue; continue;
} }
// let module = wasmtime::Module::from_file(&engine, file).unwrap();
// let instance = linker.instantiate(&mut store, &module).unwrap();
// // let config = wasmtime::ExternRef::new(payment_config.clone());
//
// let f = instance
// .get_typed_func::<Option<wasmtime::ExternRef>, i32, _>(&mut store,
// "create_payment") .unwrap();
let module = wasmer::Module::from_file(&store, file).unwrap(); let module = std::fs::read(&file).unwrap();
let instance = Instance::new(&mut store, &module, &imports).unwrap(); let engine = wasmtime_provider::WasmtimeEngineProviderBuilder::new()
.module_bytes(&module)
.build()
.unwrap();
let pool = HostPoolBuilder::new()
.name("pool")
.factory(move || {
wapc::WapcHost::new(
Box::new(engine.clone()),
Some(Box::new(move |_a, _b, _c, _d, _e| Ok(vec![]))),
)
.unwrap()
})
.max_threads(5)
.build();
{ {
let msg = payment_adapter::CreatePayment { let msg = payment_adapter::CreatePayment {
@ -87,26 +85,18 @@ async fn main() {
continue_uri: "continue_uri".to_string(), continue_uri: "continue_uri".to_string(),
}; };
let create_payment = instance.exports.get_function("create_payment").unwrap(); let call_result = pool
let ext = wasmer::ExternRef::new(&mut store, msg); .call(
let result = create_payment.call(&mut store, &[Value::ExternRef(Some(ext))]); "create_payment",
wapc_codec::messagepack::serialize(msg).unwrap(),
)
.await
.unwrap();
let result: payment_adapter::Status =
wapc_codec::messagepack::deserialize(&call_result).unwrap();
eprintln!("create payment res {:?}", result) eprintln!("create payment res {:?}", result)
} }
// let fnc =
// match instance.get_typed_func::<(), dyn PaymentAdapter,
// _>(&mut store, "adapter") { Err(e) => {
// tracing::error!("{}", e);
// continue;
// }
// Ok(fnc) => fnc,
// };
// let adapter = match fnc.call(&mut store, ()) {
// Err(e) => {
// tracing::error!("{}", e);
// continue;
// }
// Ok(adapter) => adapter,
// };
} }
} }

12
scripts/build-adapters Executable file
View File

@ -0,0 +1,12 @@
#!/usr/bin/env zsh
target=wasm32-wasi
#target=wasm32-unknown-unknown
mkdir -p adapters
for d in $(ls crates | grep payment_adapter_); do
# echo $d
echo "cargo build --target ${target} -p ${d} --manifest-path ./crates/${d}/Cargo.toml"
cargo build --target-dir ./target --target ${target} -p ${d} --manifest-path ./crates/$d/Cargo.toml
cp ./target/${target}/debug/${d}.wasm ./adapters/
done