Migrate to rust dyn lib

This commit is contained in:
Adrian Woźniak 2023-05-05 14:20:50 +02:00
parent b4d8522511
commit 8e1f9625d1
30 changed files with 1583 additions and 4269 deletions

1846
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/fulfillment_adapter",
# "crates/payment_adapter_pay_u", # "crates/payment_adapter_pay_u",
# artifacts # artifacts
# "crates/db-seed", # "crates/db-seed",
@ -27,9 +28,11 @@ members = [
# vendor # vendor
# "vendor/t_pay", # "vendor/t_pay",
# "vendor/pay_u", # "vendor/pay_u",
"crates/pay_u_adapter",
"crates/stripe_adapter",
] ]
exclude = [ exclude = [
"crates/payment_adapter_pay_u",
] ]
[profile.release] [profile.release]

View File

@ -6,7 +6,7 @@ pub enum Topic {}
pub enum Error {} pub enum Error {}
pub mod create_pair { pub mod create_pair {
use model::{AccessToken, AccessTokenString, RefreshToken, Token}; use model::{AccessToken, AccessTokenString, RefreshToken};
pub use model::{AccountId, Role}; pub use model::{AccountId, Role};
use super::Error; use super::Error;

View File

@ -88,7 +88,7 @@ impl WebConfig {
} }
pub fn pass_salt(&self) -> SaltString { pub fn pass_salt(&self) -> SaltString {
SaltString::new( SaltString::from_b64(
&self &self
.pass_salt .pass_salt
.as_ref() .as_ref()

View File

@ -0,0 +1,9 @@
[package]
name = "fulfillment_adapter"
version = "0.1.0"
edition = "2021"
[dependencies]
tracing = { version = "0" }
thiserror = { version = "1.0.40" }
async-trait = { version = "0.1.68" }

View File

@ -0,0 +1,73 @@
pub enum FError {
HttpError,
}
pub type FResult<T> = Result<T, FError>;
pub struct FulfillmentOption {}
pub trait FulfillmentPayload {}
pub trait FulfillmentCart {}
pub trait FulfillmentAdapter {
fn identifier() -> &'static str;
/**
* Called before a shipping option is created in Admin. The method
* should return all of the options that the fulfillment provider
* can be used with, and it is here the distinction between
* different shipping options are enforced. For example, a
* fulfillment provider may offer Standard Shipping and Express
* Shipping as fulfillment options, it is up to the store operator
* to create shipping options in Medusa that can be chosen between by
* the customer.
*/
fn fulfillment_options(&mut self) -> FResult<&[FulfillmentOption]>;
/**
* Called before a shipping method is set on a cart to ensure that the
* data sent with the shipping method is valid. The data object may
* contain extra data about the shipment such as an id of a drop
* point. It is up to the fulfillment provider to enforce that the
* correct data is being sent through.
*/
fn validate_fulfillment_payload<P: FulfillmentPayload, C: FulfillmentCart>(
&mut self,
payload: P,
cart: C,
) -> FResult<bool>;
/**
* Called before a shipping option is created in Admin. Use this to
* ensure that a fulfillment option does in fact exist.
*/
fn validate_option<P: FulfillmentPayload>(&mut self, payload: P) -> FResult<bool>;
fn can_calculate<P: FulfillmentPayload>(&mut self, payload: P) -> FResult<bool>;
/**
* Used to calculate a price for a given shipping option.
*/
fn calculate_price<P: FulfillmentPayload, C: FulfillmentCart>(data: P, cart: C)
-> FResult<u64>;
// FULFILLMENT
fn create_fulfillment(&mut self);
fn cancel_fulfillment(&mut self);
/**
* Used to retrieve documents associated with a fulfillment.
* Will default to returning no documents.
*/
fn fulfillment_documents(&mut self);
// REFUND
fn create_return(&mut self);
fn return_documents(&mut self);
//
fn shipment_documents(&mut self);
fn documents(&mut self);
}

View File

@ -21,7 +21,7 @@ argon2 = { version = "0", features = ["parallel", "password-hash"] }
chrono = { version = "0", features = ["serde"] } chrono = { version = "0", features = ["serde"] }
derive_more = { version = "0" } derive_more = { version = "0" }
fake = { version = "2", features = ["derive", "chrono", "http", "uuid", "dummy"], optional = true } fake = { version = "2", features = ["derive", "chrono", "http", "uuid", "dummy"], optional = true }
password-hash = { version = "0", features = ["alloc"] } password-hash = { version = "=0.4.2", features = ["alloc"] }
rand = { version = "0", optional = true } rand = { version = "0", optional = true }
rand_core = { version = "0", features = ["std"] } rand_core = { version = "0", features = ["std"] }
serde = { version = "1" } serde = { version = "1" }
@ -30,3 +30,4 @@ sqlx-core = { version = "0", features = [], optional = true }
thiserror = { version = "1" } thiserror = { version = "1" }
uuid = { version = "1", features = ["serde"] } uuid = { version = "1", features = ["serde"] }
validator = { version = "0" } validator = { version = "0" }
tracing = { version = "0.1.37" }

View File

@ -1,5 +1,5 @@
use argon2::{Algorithm, Argon2, Params, Version}; use argon2::{Algorithm, Argon2, Params, PasswordHasher, PasswordVerifier, Version};
use password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; use password_hash::{PasswordHash, SaltString};
pub trait Encrypt { pub trait Encrypt {
fn encrypt(&self, salt: &SaltString) -> password_hash::Result<String>; fn encrypt(&self, salt: &SaltString) -> password_hash::Result<String>;
@ -10,11 +10,9 @@ 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(
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)
.to_string(), .map(|r| r.to_string())
)
} }
fn validate(&self, pass_hash: &crate::PassHash) -> password_hash::Result<()> { fn validate(&self, pass_hash: &crate::PassHash) -> password_hash::Result<()> {

View File

@ -28,11 +28,11 @@ pub enum TransformError {
pub type RecordId = i32; pub type RecordId = i32;
macro_rules! category_svg { // macro_rules! category_svg {
($name: expr) => { // ($name: expr) => {
concat!("/svg/", $name, ".svg") // concat!("/svg/", $name, ".svg")
}; // };
} // }
pub struct CategoryMapper; pub struct CategoryMapper;

View File

@ -149,7 +149,7 @@ checksum = "f3f6d59c71e7dc3af60f0af9db32364d96a16e9310f3f5db2b55ed642162dd35"
name = "config" name = "config"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"parking_lot 0.12.1", "parking_lot",
"password-hash", "password-hash",
"serde", "serde",
"serde_json", "serde_json",
@ -559,15 +559,6 @@ dependencies = [
"hashbrown", "hashbrown",
] ]
[[package]]
name = "instant"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.4" version = "1.0.4"
@ -688,6 +679,7 @@ dependencies = [
"rand_core", "rand_core",
"serde", "serde",
"thiserror", "thiserror",
"tracing",
"uuid", "uuid",
"validator", "validator",
] ]
@ -753,17 +745,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]]
name = "parking_lot"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
dependencies = [
"instant",
"lock_api",
"parking_lot_core 0.8.5",
]
[[package]] [[package]]
name = "parking_lot" name = "parking_lot"
version = "0.12.1" version = "0.12.1"
@ -771,21 +752,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [ dependencies = [
"lock_api", "lock_api",
"parking_lot_core 0.9.5", "parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216"
dependencies = [
"cfg-if",
"instant",
"libc",
"redox_syscall",
"smallvec",
"winapi",
] ]
[[package]] [[package]]
@ -812,12 +779,6 @@ dependencies = [
"subtle", "subtle",
] ]
[[package]]
name = "paste"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1de2e551fb905ac83f73f7aedf2f0cb4a0da7e35efa24a202a936269f1f18e1"
[[package]] [[package]]
name = "payment_adapter" name = "payment_adapter"
version = "0.1.0" version = "0.1.0"
@ -841,9 +802,7 @@ dependencies = [
"payment_adapter", "payment_adapter",
"serde", "serde",
"serde_json", "serde_json",
"thiserror", "tracing",
"wapc-codec",
"wapc-guest",
] ]
[[package]] [[package]]
@ -974,28 +933,6 @@ version = "0.6.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848"
[[package]]
name = "rmp"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44519172358fd6d58656c86ab8e7fbc9e1490c3e8f14d35ed78ca0dd07403c9f"
dependencies = [
"byteorder",
"num-traits",
"paste",
]
[[package]]
name = "rmp-serde"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5b13be192e0220b8afb7222aa5813cb62cc269ebb5cac346ca6487681d2913e"
dependencies = [
"byteorder",
"rmp",
"serde",
]
[[package]] [[package]]
name = "rustc_version" name = "rustc_version"
version = "0.4.0" version = "0.4.0"
@ -1334,26 +1271,6 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "wapc-codec"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "547c5bc15ef114be946d56ce368ff990d91b22603ac09cc0c0d476213289fcd2"
dependencies = [
"rmp-serde",
"serde",
]
[[package]]
name = "wapc-guest"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51d55cfd1e7647db9da8b283424bb2b24aa9c470dbe18991d0126f83aa085851"
dependencies = [
"once_cell",
"parking_lot 0.11.2",
]
[[package]] [[package]]
name = "wasi" name = "wasi"
version = "0.10.0+wasi-snapshot-preview1" version = "0.10.0+wasi-snapshot-preview1"

View File

@ -1,19 +1,21 @@
[package] [package]
name = "payment_adapter_pay_u" name = "pay_u_adapter"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
[lib] [lib]
crate-type = ['cdylib'] crate-type = ['dylib']
[build]
rustflags = ["-C", "prefer-dynamic", "-C", "rpath"]
[dependencies] [dependencies]
bincode = { version = "1" } bincode = { version = "1" }
#tracing = { version = "0" } tracing = { version = "0" }
chrono = { version = "0", features = ['alloc', 'wasmbind'] } chrono = { version = "0", features = ['alloc', 'wasmbind'] }
common_macros = { version = "0" } common_macros = { version = "0" }
payment_adapter = { path = "../payment_adapter" } payment_adapter = { path = "../payment_adapter" }
fulfillment_adapter = { path = "../fulfillment_adapter" }
serde = { version = "1", features = ['derive'] } serde = { version = "1", features = ['derive'] }
serde_json = { version = "1" } serde_json = { version = "1" }
thiserror = { version = "1" } async-trait = { version = "0.1.68" }
wapc-codec = { version = "1" }
wapc-guest = { version = "1" }

View File

@ -1,3 +1,5 @@
#![crate_type = "rlib"]
mod credit; mod credit;
mod deserialize; mod deserialize;
mod model; mod model;
@ -9,13 +11,14 @@ mod serialize;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use fulfillment_adapter::{
FResult, FulfillmentAdapter, FulfillmentCart, FulfillmentOption, FulfillmentPayload,
};
use payment_adapter::*; use payment_adapter::*;
use wapc_codec::messagepack::*;
use wapc_guest as wapc;
use crate::req::OrderCreate; use crate::req::OrderCreate;
struct PayU { pub struct PayUPayment {
sandbox: bool, sandbox: bool,
merchant_pos_id: i32, merchant_pos_id: i32,
client_id: String, client_id: String,
@ -24,7 +27,7 @@ struct PayU {
bearer_expires_at: chrono::DateTime<chrono::Utc>, bearer_expires_at: chrono::DateTime<chrono::Utc>,
} }
impl PayU { impl PayUPayment {
/// Create new PayU client /// Create new PayU client
pub fn new(client_id: String, client_secret: String, merchant_pos_id: i32) -> Self { pub fn new(client_id: String, client_secret: String, merchant_pos_id: i32) -> Self {
Self { Self {
@ -54,20 +57,118 @@ impl PayU {
} }
} }
static mut CONFIG: Option<Arc<Mutex<PayU>>> = None; impl PaymentAdapter for PayUPayment {
fn init(&mut self) -> PResult<Status> {
todo!()
}
fn client() -> Arc<Mutex<PayU>> { fn teardown(&mut self) -> PResult<Status> {
todo!()
}
fn create_payment(&mut self, msg: CreatePayment) -> PResult<PaymentCreated> {
todo!()
}
fn retrieve_payment(&mut self) {
todo!()
}
fn authorize_payment(&mut self) {
todo!()
}
fn capture_payment(&mut self) {
todo!()
}
fn refund_payment(&mut self, msg: RefundPayment) -> PResult<Refunded> {
todo!()
}
fn delete_payment(&mut self, msg: DeletePayment) -> PResult<Deleted> {
todo!()
}
}
pub struct PayUFulfillment {}
impl FulfillmentAdapter for PayUFulfillment {
fn identifier() -> &'static str {
"pay-u"
}
fn fulfillment_options(&mut self) -> FResult<&[FulfillmentOption]> {
todo!()
}
fn validate_fulfillment_payload<P: FulfillmentPayload, C: FulfillmentCart>(
&mut self,
payload: P,
cart: C,
) -> FResult<bool> {
todo!()
}
fn validate_option<P: FulfillmentPayload>(&mut self, payload: P) -> FResult<bool> {
todo!()
}
fn can_calculate<P: FulfillmentPayload>(&mut self, payload: P) -> FResult<bool> {
todo!()
}
fn calculate_price<P: FulfillmentPayload, C: FulfillmentCart>(
data: P,
cart: C,
) -> FResult<u64> {
todo!()
}
fn create_fulfillment(&mut self) {
todo!()
}
fn cancel_fulfillment(&mut self) {
todo!()
}
fn fulfillment_documents(&mut self) {
todo!()
}
fn create_return(&mut self) {
todo!()
}
fn return_documents(&mut self) {
todo!()
}
fn shipment_documents(&mut self) {
todo!()
}
fn documents(&mut self) {
todo!()
}
}
static mut CONFIG: Option<Arc<Mutex<PayUPayment>>> = None;
fn client() -> Arc<Mutex<PayUPayment>> {
unsafe { CONFIG.as_ref().unwrap().clone() } unsafe { CONFIG.as_ref().unwrap().clone() }
} }
/*
impl PayU { impl PayU {
fn mount() { fn mount() {
wapc::register_function("teardown", Self::teardown); // wapc::register_function("teardown", Self::teardown);
wapc::register_function("name", Self::name); // wapc::register_function("name", Self::name);
wapc::register_function("init", Self::init); // wapc::register_function("init", Self::init);
wapc::register_function("create_payment", Self::create_payment); // wapc::register_function("create_payment", Self::create_payment);
wapc::register_function("cancel_order", Self::cancel_order); // wapc::register_function("cancel_order", Self::cancel_order);
wapc::register_function("update_status", Self::update_status); // wapc::register_function("update_status", Self::update_status);
} }
fn teardown(_msg: &[u8]) -> wapc::CallResult { fn teardown(_msg: &[u8]) -> wapc::CallResult {
@ -110,7 +211,7 @@ impl PayU {
order_id, order_id,
ext_order_id: _, ext_order_id: _,
} = create_payment(c)?; } = create_payment(c)?;
Ok(serialize(OrderCreated { Ok(serialize(PaymentCreated {
redirect_uri: Some(redirect_uri), redirect_uri: Some(redirect_uri),
ext_order_id: Some(ExtOrderId::new(order_id)), ext_order_id: Some(ExtOrderId::new(order_id)),
}) })
@ -243,53 +344,54 @@ fn create_payment(c: CreatePayment) -> Result<res::CreateOrder, Error> {
pub fn wapc_init() { pub fn wapc_init() {
PayU::mount(); PayU::mount();
} }
*/
fn authorize() -> Result<bool, Error> { // fn authorize() -> Result<bool, Error> {
use chrono::{Duration, Utc}; // use chrono::{Duration, Utc};
//
let config = client(); // let config = client();
let mut pay_u = config.lock().unwrap(); // let mut pay_u = config.lock().unwrap();
//
let now = Utc::now() - Duration::seconds(1); // let now = Utc::now() - Duration::seconds(1);
info!("Now is {:?}", now); // info!("Now is {:?}", now);
if now < pay_u.bearer_expires_at && pay_u.bearer.is_some() { // if now < pay_u.bearer_expires_at && pay_u.bearer.is_some() {
info!("Bearer ok"); // info!("Bearer ok");
return Ok(true); // return Ok(true);
} // }
#[derive(serde::Deserialize)] // #[derive(serde::Deserialize)]
struct BearerResult { // struct BearerResult {
access_token: String, // access_token: String,
expires_in: i64, // expires_in: i64,
} // }
//
info!("calling host http 'authorize'!"); // info!("calling host http 'authorize'!");
let res = { // let res = {
let msg = serialize(HttpRequest { // let msg = serialize(HttpRequest {
method: HttpMethod::Post, // method: HttpMethod::Post,
url: format!( // url: format!(
"{}?grant_type=client_credentials&client_id={}&client_secret={}", //
pay_u.auth_url(), // "{}?grant_type=client_credentials&client_id={}&client_secret={}",
pay_u.client_id, // pay_u.auth_url(), pay_u.client_id,
pay_u.client_secret, // pay_u.client_secret,
), // ),
headers: json_header(), // headers: json_header(),
bearer_auth: None, // bearer_auth: None,
body: None, // body: None,
}) // })
.unwrap(); // .unwrap();
info!("authorize msg {:?}", msg); // info!("authorize msg {:?}", msg);
wapc::host_call("authorize", "http:req", "http_req", &msg).map_err(|e| { // wapc::host_call("authorize", "http:req", "http_req",
error!("{}", e); // &msg).map_err(|e| { error!("{}", e);
Error::AuthorizeFailed // Error::AuthorizeFailed
})? // })?
}; // };
let res: BearerResult = serde_json::from_slice(&res).map_err(|e| { // let res: BearerResult = serde_json::from_slice(&res).map_err(|e| {
error!("{}", e); // error!("{}", e);
Error::MalformedAuthorize // Error::MalformedAuthorize
})?; // })?;
info!("Authorized with calling host"); // info!("Authorized with calling host");
trace!("Bearer is {}", res.access_token); // trace!("Bearer is {}", res.access_token);
pay_u.bearer_expires_at = Utc::now() + Duration::seconds(res.expires_in); // pay_u.bearer_expires_at = Utc::now() + Duration::seconds(res.expires_in);
pay_u.bearer = Some(res.access_token); // pay_u.bearer = Some(res.access_token);
Ok(true) // Ok(true)
} // }

View File

@ -11,3 +11,4 @@ serde = { version = "1", features = ['derive'] }
thiserror = { version = "1" } thiserror = { version = "1" }
tracing = { version = "0" } tracing = { version = "0" }
uuid = { version = "1", features = ['v4'] } uuid = { version = "1", features = ['v4'] }
async-trait = { version = "0.1.68" }

View File

@ -79,7 +79,7 @@ pub struct CreatePayment {
} }
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OrderCreated { pub struct PaymentCreated {
pub ext_order_id: Option<ExtOrderId>, pub ext_order_id: Option<ExtOrderId>,
pub redirect_uri: Option<String>, pub redirect_uri: Option<String>,
} }
@ -93,14 +93,14 @@ pub enum RefundType {
} }
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Cancel { pub struct RefundPayment {
pub refund: RefundType, pub refund: RefundType,
pub provider_order_id: String, pub provider_order_id: String,
pub description: String, pub description: String,
} }
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Cancelled {} pub struct Refunded {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UpdateStatus { pub struct UpdateStatus {
@ -110,12 +110,29 @@ pub struct UpdateStatus {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StatusUpdated {} pub struct StatusUpdated {}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DeletePayment {
pub ext_order_id: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Deleted {
pub ext_order_id: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum HttpMethod { pub enum HttpMethod {
Get, Get,
Post, Post,
} }
pub enum PaymentSessionStatus {
Pending,
RequiresMore,
Canceled,
Authorized,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[repr(C)] #[repr(C)]
pub struct HttpRequest { pub struct HttpRequest {
@ -154,40 +171,18 @@ pub mod tracing {
log_levels!(error, warn, debug, info, trace, log); log_levels!(error, warn, debug, info, trace, log);
} }
// #[tarpc::service] pub enum PError {}
// pub trait PaymentAdapter {
// async fn create_payment(msg: CreatePayment) -> Status; pub type PResult<T> = Result<T, PError>;
// }
// pub trait PaymentAdapter {
// pub async fn start_server<Server, Req, Build>(name: &str, port: u16, build: fn init(&mut self) -> PResult<Status>;
// Build) where fn teardown(&mut self) -> PResult<Status>;
// Server: Serve<Req> + Send + 'static + Clone,
// Build: Fn() -> Server, fn create_payment(&mut self, msg: CreatePayment) -> PResult<PaymentCreated>;
// <Server as Serve<Req>>::Fut: Send, fn retrieve_payment(&mut self);
// <Server as Serve<Req>>::Resp: serde::Serialize + Send + 'static, fn authorize_payment(&mut self);
// Req: Send + 'static, fn capture_payment(&mut self);
// Req: for<'l> serde::Deserialize<'l>, fn refund_payment(&mut self, msg: RefundPayment) -> PResult<Refunded>;
// { fn delete_payment(&mut self, msg: DeletePayment) -> PResult<Deleted>;
// 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");
// }

View File

@ -32,16 +32,16 @@ pub enum WasmMsg {
tx: Sender<ResultMsg>, tx: Sender<ResultMsg>,
}, },
Cancel { Cancel {
cancel: payment_adapter::Cancel, cancel: payment_adapter::RefundPayment,
tx: Sender<ResultMsg>, tx: Sender<ResultMsg>,
}, },
} }
#[derive(Clone)] #[derive(Clone)]
pub enum ResultMsg { pub enum ResultMsg {
OrderCreated(payment_adapter::OrderCreated), OrderCreated(payment_adapter::PaymentCreated),
StatusUpdated(payment_adapter::StatusUpdated), StatusUpdated(payment_adapter::StatusUpdated),
Cancel(payment_adapter::Cancelled), Cancel(payment_adapter::Refunded),
} }
pub struct HostChannel { pub struct HostChannel {

View File

@ -4,7 +4,7 @@ use channels::payments::rpc::Payments;
use channels::payments::{adapters, cancel, notification, start_payment}; use channels::payments::{adapters, cancel, notification, start_payment};
use channels::{payments, AsyncClient}; use channels::{payments, AsyncClient};
use config::SharedAppConfig; use config::SharedAppConfig;
use payment_adapter::Cancel; use payment_adapter::RefundPayment;
use tarpc::context; use tarpc::context;
use crate::{Modules, ResultMsg, WasmMsg}; use crate::{Modules, ResultMsg, WasmMsg};
@ -96,7 +96,7 @@ impl Payments for PaymentsServer {
} = input; } = input;
let module = self.adapter_sender(adapter_name)?; let module = self.adapter_sender(adapter_name)?;
let res = module.send(|tx| WasmMsg::Cancel { let res = module.send(|tx| WasmMsg::Cancel {
cancel: Cancel { cancel: RefundPayment {
refund: match refund { refund: match refund {
RefundType::Full => payment_adapter::RefundType::Full, RefundType::Full => payment_adapter::RefundType::Full,
RefundType::Partial(v) => payment_adapter::RefundType::Partial(v), RefundType::Partial(v) => payment_adapter::RefundType::Partial(v),

View File

@ -0,0 +1,18 @@
[package]
name = "stripe_adapter"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ['dylib']
[build]
rustflags = ["-C", "prefer-dynamic", "-C", "rpath"]
[dependencies]
payment_adapter = { path = "../payment_adapter" }
fulfillment_adapter = { path = "../fulfillment_adapter" }
tokio = { version = "1.27.0" }
payup = { version = "*" }
tracing = { version = "0.1.37" }
async-trait = { version = "0.1.68" }

View File

@ -0,0 +1,126 @@
#![crate_type = "rlib"]
use fulfillment_adapter::{
FError, FResult, FulfillmentAdapter, FulfillmentCart, FulfillmentOption, FulfillmentPayload,
};
use payment_adapter::{
CreatePayment, DeletePayment, Deleted, PResult, PaymentAdapter, PaymentCreated,
PaymentSessionStatus, RefundPayment, Refunded, Status,
};
pub struct StripeAdapter {
stripe: payup::stripe::Auth,
}
impl StripeAdapter {
fn payment_status(&mut self, ext_id: String) -> FResult<PaymentSessionStatus> {
let charge = payup::stripe::Charge::get(self.stripe.clone(), ext_id).map_err(|e| {
tracing::warn!("{e}");
FError::HttpError
})?;
Ok(match charge.status.as_deref() {
Some("requires_payment_method" | "requires_confirmation" | "processing") => {
PaymentSessionStatus::Pending
}
Some("requires_action") => PaymentSessionStatus::RequiresMore,
Some("canceled") => PaymentSessionStatus::Canceled,
Some("requires_capture" | "succeeded") => PaymentSessionStatus::Authorized,
_ => PaymentSessionStatus::Pending,
})
}
}
impl PaymentAdapter for StripeAdapter {
fn init(&mut self) -> PResult<Status> {
todo!()
}
fn teardown(&mut self) -> PResult<Status> {
todo!()
}
async fn create_payment(&mut self, msg: CreatePayment) -> PResult<PaymentCreated> {
todo!()
}
async fn retrieve_payment(&mut self) {
todo!()
}
async fn authorize_payment(&mut self) {
todo!()
}
fn capture_payment(&mut self) {
todo!()
}
async fn refund_payment(&mut self, msg: RefundPayment) -> PResult<Refunded> {
todo!()
}
async fn delete_payment(&mut self, msg: DeletePayment) -> PResult<Deleted> {
todo!()
}
}
impl FulfillmentAdapter for StripeAdapter {
fn identifier() -> &'static str {
"stripe"
}
fn fulfillment_options(&mut self) -> FResult<&[FulfillmentOption]> {
todo!()
}
fn validate_fulfillment_payload<P: FulfillmentPayload, C: FulfillmentCart>(
&mut self,
payload: P,
cart: C,
) -> FResult<bool> {
todo!()
}
fn validate_option<P: FulfillmentPayload>(&mut self, payload: P) -> FResult<bool> {
todo!()
}
fn can_calculate<P: FulfillmentPayload>(&mut self, payload: P) -> FResult<bool> {
todo!()
}
fn calculate_price<P: FulfillmentPayload, C: FulfillmentCart>(
data: P,
cart: C,
) -> FResult<u64> {
todo!()
}
fn create_fulfillment(&mut self) {
todo!()
}
fn cancel_fulfillment(&mut self) {
todo!()
}
fn fulfillment_documents(&mut self) {
todo!()
}
fn create_return(&mut self) {
todo!()
}
fn return_documents(&mut self) {
todo!()
}
fn shipment_documents(&mut self) {
todo!()
}
fn documents(&mut self) {
todo!()
}
}

View File

@ -1,45 +0,0 @@
<!DOCTYPE html><html lang="pl"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="/logo-5d25fab096a85f61.png">
<title>Bazzar</title>
<link rel="stylesheet" href="/tailwind-ad72042a0c3f7966.css">
<link rel="copy-file" href="assets/logo.png">
<link rel="copy-file" href="tmp/tailwind.css">
<base href="/">
<link rel="preload" href="/web-edbdf95f1008e472_bg.wasm" as="fetch" type="application/wasm" crossorigin="">
<link rel="modulepreload" href="/web-edbdf95f1008e472.js"></head>
<body>
<main id="main">
</main>
<script type="module">import init from '/web-edbdf95f1008e472.js';init('/web-edbdf95f1008e472_bg.wasm');</script><script>(function () {
var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
var url = protocol + '//' + window.location.host + '/_trunk/ws';
var poll_interval = 5000;
var reload_upon_connect = () => {
window.setTimeout(
() => {
// when we successfully reconnect, we'll force a
// reload (since we presumably lost connection to
// trunk due to it being killed, so it will have
// rebuilt on restart)
var ws = new WebSocket(url);
ws.onopen = () => window.location.reload();
ws.onclose = reload_upon_connect;
},
poll_interval);
};
var ws = new WebSocket(url);
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data);
if (msg.reload) {
window.location.reload();
}
};
ws.onclose = reload_upon_connect;
})()
</script></body></html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.