Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Re-group api's based on alpha.4 event api update #857

Merged
merged 2 commits into from
Dec 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions core/payment/examples/payment_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use ya_persistence::executor::DbExecutor;
use ya_service_api_web::middleware::auth::dummy::DummyAuth;
use ya_service_api_web::middleware::Identity;
use ya_service_api_web::rest_api_addr;
use ya_service_api_web::scope::ExtendableScope;
use ya_service_bus::typed as bus;
use ya_zksync_driver as zksync;

Expand Down Expand Up @@ -293,14 +294,16 @@ async fn main() -> anyhow::Result<()> {
role: "".to_string(),
};

let provider_scope =
ya_payment::api::provider_scope().wrap(DummyAuth::new(provider_identity));
let requestor_scope =
ya_payment::api::requestor_scope().wrap(DummyAuth::new(requestor_identity));
let provider_api_scope = Scope::new("/provider")
.extend(ya_payment::api::api_scope)
.wrap(DummyAuth::new(provider_identity));
let requestor_api_scope = Scope::new("/requestor")
.extend(ya_payment::api::api_scope)
.wrap(DummyAuth::new(requestor_identity));
let payment_service = Scope::new(PAYMENT_API_PATH)
.data(db.clone())
.service(provider_scope)
.service(requestor_scope);
.service(provider_api_scope)
.service(requestor_api_scope);
App::new()
.wrap(middleware::Logger::default())
.service(payment_service)
Expand Down
25 changes: 15 additions & 10 deletions core/payment/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,27 @@ use ya_client_model::payment::PAYMENT_API_PATH;
use ya_persistence::executor::DbExecutor;
use ya_service_api_web::scope::ExtendableScope;

mod provider;
mod requestor;
mod accounts;
mod allocations;
mod debit_notes;
mod invoices;
mod payments;

pub fn provider_scope() -> Scope {
Scope::new("/provider").extend(provider::register_endpoints)
}

pub fn requestor_scope() -> Scope {
Scope::new("/requestor").extend(requestor::register_endpoints)
pub fn api_scope(scope: Scope) -> Scope {
scope
.extend(accounts::register_endpoints)
.extend(allocations::register_endpoints)
.extend(debit_notes::register_endpoints)
.extend(invoices::register_endpoints)
.extend(payments::register_endpoints)
}

pub fn web_scope(db: &DbExecutor) -> Scope {
Scope::new(PAYMENT_API_PATH)
.data(db.clone())
.service(provider_scope())
.service(requestor_scope())
.service(api_scope(Scope::new("")))
// TODO: TEST
// Scope::new(PAYMENT_API_PATH).extend(api_scope).data(db.clone())
}

pub const DEFAULT_ACK_TIMEOUT: f64 = 60.0; // seconds
Expand Down
56 changes: 56 additions & 0 deletions core/payment/src/api/accounts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Extrnal crates
use actix_web::web::get;
use actix_web::{HttpResponse, Scope};

// Workspace uses
use ya_client_model::payment::*;
use ya_core_model::payment::local::{GetAccounts, BUS_ID as LOCAL_SERVICE};
use ya_service_api_web::middleware::Identity;
use ya_service_bus::{typed as bus, RpcEndpoint};

// Local uses
use crate::utils::*;

pub fn register_endpoints(scope: Scope) -> Scope {
scope
.route("/providerAccounts", get().to(get_provider_accounts))
.route("/requestorAccounts", get().to(get_requestor_accounts))
}

async fn get_provider_accounts(id: Identity) -> HttpResponse {
let node_id = id.identity.to_string();
let all_accounts = match bus::service(LOCAL_SERVICE).send(GetAccounts {}).await {
Ok(Ok(accounts)) => accounts,
Ok(Err(e)) => return response::server_error(&e),
Err(e) => return response::server_error(&e),
};
let recv_accounts: Vec<Account> = all_accounts
.into_iter()
.filter(|account| account.receive)
.filter(|account| account.address == node_id) // TODO: Implement proper account permission system
.map(|account| Account {
platform: account.platform,
address: account.address,
})
.collect();
response::ok(recv_accounts)
}

async fn get_requestor_accounts(id: Identity) -> HttpResponse {
let node_id = id.identity.to_string();
let all_accounts = match bus::service(LOCAL_SERVICE).send(GetAccounts {}).await {
Ok(Ok(accounts)) => accounts,
Ok(Err(e)) => return response::server_error(&e),
Err(e) => return response::server_error(&e),
};
let recv_accounts: Vec<Account> = all_accounts
.into_iter()
.filter(|account| account.send)
.filter(|account| account.address == node_id) // TODO: Implement proper account permission system
.map(|account| Account {
platform: account.platform,
address: account.address,
})
.collect();
response::ok(recv_accounts)
}
163 changes: 163 additions & 0 deletions core/payment/src/api/allocations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Extrnal crates
use actix_web::web::{delete, get, post, put, Data, Json, Path, Query};
use actix_web::{HttpResponse, Scope};
use serde_json::value::Value::Null;

// Workspace uses
use ya_agreement_utils::{ClauseOperator, ConstraintKey, Constraints};
use ya_client_model::payment::*;
use ya_core_model::payment::local::{
ValidateAllocation, ValidateAllocationError, BUS_ID as LOCAL_SERVICE,
};
use ya_core_model::payment::RpcMessageError;
use ya_persistence::executor::DbExecutor;
use ya_service_api_web::middleware::Identity;
use ya_service_bus::{typed as bus, RpcEndpoint};

// Local uses
use crate::api::*;
use crate::dao::*;
use crate::error::{DbError, Error};
use crate::utils::response;
use crate::DEFAULT_PAYMENT_PLATFORM;

pub fn register_endpoints(scope: Scope) -> Scope {
scope
.route("/allocations", post().to(create_allocation))
.route("/allocations", get().to(get_allocations))
.route("/allocations/{allocation_id}", get().to(get_allocation))
.route("/allocations/{allocation_id}", put().to(amend_allocation))
.route(
"/allocations/{allocation_id}",
delete().to(release_allocation),
)
.route("/decorateDemand", get().to(decorate_demand))
}

async fn create_allocation(
db: Data<DbExecutor>,
body: Json<NewAllocation>,
id: Identity,
) -> HttpResponse {
// TODO: Handle deposits & timeouts
let allocation = body.into_inner();
let node_id = id.identity;
let payment_platform = allocation
.payment_platform
.clone()
.unwrap_or(DEFAULT_PAYMENT_PLATFORM.to_string());
let address = allocation.address.clone().unwrap_or(node_id.to_string());

let validate_msg = ValidateAllocation {
platform: payment_platform.clone(),
address: address.clone(),
amount: allocation.total_amount.clone(),
};
match async move { Ok(bus::service(LOCAL_SERVICE).send(validate_msg).await??) }.await {
Ok(true) => {}
Ok(false) => return response::bad_request(&"Insufficient funds to make allocation"),
Err(Error::Rpc(RpcMessageError::ValidateAllocation(
ValidateAllocationError::AccountNotRegistered,
))) => return response::bad_request(&"Account not registered"),
Err(e) => return response::server_error(&e),
}

let dao: AllocationDao = db.as_dao();
match async move {
let allocation_id = dao
.create(allocation, node_id, payment_platform, address)
.await?;
Ok(dao.get(allocation_id, node_id).await?)
}
.await
{
Ok(Some(allocation)) => response::created(allocation),
Ok(None) => response::server_error(&"Database error"),
Err(DbError::Query(e)) => response::bad_request(&e),
Err(e) => response::server_error(&e),
}
}

async fn get_allocations(db: Data<DbExecutor>, id: Identity) -> HttpResponse {
let node_id = id.identity;
let dao: AllocationDao = db.as_dao();
match dao.get_for_owner(node_id).await {
Ok(allocations) => response::ok(allocations),
Err(e) => response::server_error(&e),
}
}

async fn get_allocation(
db: Data<DbExecutor>,
path: Path<AllocationId>,
id: Identity,
) -> HttpResponse {
let allocation_id = path.allocation_id.clone();
let node_id = id.identity;
let dao: AllocationDao = db.as_dao();
match dao.get(allocation_id, node_id).await {
Ok(Some(allocation)) => response::ok(allocation),
Ok(None) => response::not_found(),
Err(e) => response::server_error(&e),
}
}

async fn amend_allocation(
db: Data<DbExecutor>,
path: Path<AllocationId>,
body: Json<Allocation>,
) -> HttpResponse {
response::not_implemented() // TODO
}

async fn release_allocation(
db: Data<DbExecutor>,
path: Path<AllocationId>,
id: Identity,
) -> HttpResponse {
let allocation_id = path.allocation_id.clone();
let node_id = id.identity;
let dao: AllocationDao = db.as_dao();
match dao.release(allocation_id, node_id).await {
Ok(true) => response::ok(Null),
Ok(false) => response::not_found(),
Err(e) => response::server_error(&e),
}
}

async fn decorate_demand(
db: Data<DbExecutor>,
path: Query<AllocationIds>,
id: Identity,
) -> HttpResponse {
let allocation_ids = path.allocation_ids.clone();
let node_id = id.identity;
let dao: AllocationDao = db.as_dao();
let allocations = match dao.get_many(allocation_ids, node_id).await {
Ok(allocations) => allocations,
Err(e) => return response::server_error(&e),
};
if allocations.len() != path.allocation_ids.len() {
return response::not_found();
}

let properties: Vec<MarketProperty> = allocations
.into_iter()
.map(|allocation| MarketProperty {
key: format!(
"golem.com.payment.platform.{}.address",
allocation.payment_platform
),
value: allocation.address,
})
.collect();
let constraints = properties
.iter()
.map(|property| ConstraintKey::new(property.key.as_str()).equal_to(ConstraintKey::new("*")))
.collect();
let constraints = vec![Constraints::new_clause(ClauseOperator::Or, constraints).to_string()];
response::ok(MarketDecoration {
properties,
constraints,
})
}
Loading