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

Endpoint: Trigger SSA #189

Merged
merged 1 commit into from
May 20, 2024
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
1 change: 1 addition & 0 deletions fplus-http-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ async fn main() -> std::io::Result<()> {
.service(router::application::delete_branch)
.service(router::application::cache_renewal)
.service(router::application::update_from_issue)
.service(router::application::trigger_ssa)
.service(router::blockchain::address_allowance)
.service(router::blockchain::verified_clients)
.service(router::verifier::verifiers)
Expand Down
13 changes: 11 additions & 2 deletions fplus-http-server/src/router/application.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use actix_web::{get, post, web, HttpResponse, Responder};
use fplus_lib::core::{
application::file::VerifierInput, ApplicationQueryParams, BranchDeleteInfo, CompleteGovernanceReviewInfo, CompleteNewApplicationApprovalInfo, CompleteNewApplicationProposalInfo, CreateApplicationInfo, DcReachedInfo, GithubQueryParams, LDNApplication, MoreInfoNeeded, RefillInfo, ValidationPullRequestData, VerifierActionsQueryParams
application::file::VerifierInput, ApplicationQueryParams, BranchDeleteInfo, CompleteGovernanceReviewInfo, CompleteNewApplicationApprovalInfo, CompleteNewApplicationProposalInfo, CreateApplicationInfo, DcReachedInfo, GithubQueryParams, LDNApplication, MoreInfoNeeded, RefillInfo, ValidationPullRequestData, VerifierActionsQueryParams, TriggerSSAInfo
};


Expand All @@ -22,7 +22,6 @@ pub async fn single(
query: web::Query<ApplicationQueryParams>,
) -> impl Responder {
let ApplicationQueryParams { id, owner, repo } = query.into_inner();

match LDNApplication::load_from_db(id, owner, repo).await {
Ok(app_file) => {
return HttpResponse::Ok().body(serde_json::to_string_pretty(&app_file).unwrap())
Expand Down Expand Up @@ -456,3 +455,13 @@ pub async fn check_for_changes(
pub async fn health() -> impl Responder {
HttpResponse::Ok().body("OK")
}

#[post("application/trigger_ssa")]
pub async fn trigger_ssa(info: web::Json<TriggerSSAInfo>) -> impl Responder {
match LDNApplication::trigger_ssa(info.into_inner()).await {
Ok(()) => {
return HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap())
}
Err(e) => return HttpResponse::BadRequest().body(e.to_string()),
};
}
11 changes: 11 additions & 0 deletions fplus-lib/src/core/application/allocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use chrono::Utc;
use super::file::{
Allocation, AllocationRequest, AllocationRequestType, Allocations, Verifiers, Verifier,
};
use crate::helpers::parse_size_to_bytes;

impl Default for Verifiers {
fn default() -> Self {
Expand Down Expand Up @@ -138,4 +139,14 @@ impl Allocations {
self.0.push(allocation);
self.clone()
}

pub fn total_requested(&self) -> u64 {
let mut total_amount: u64 = 0;
for allocation in self.0.iter() {
if let Some(amount) = parse_size_to_bytes(&allocation.amount) {
total_amount += amount;
}
}
return total_amount;
}
}
6 changes: 6 additions & 0 deletions fplus-lib/src/core/application/file.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::str::FromStr;

use futures::stream::All;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
Expand Down Expand Up @@ -338,6 +339,11 @@ impl ApplicationFile {
Err("No active allocation found")
}
}

pub fn get_last_request_allowance(&self) -> Option<Allocation> {
let request_id = self.lifecycle.active_request.clone()?;
self.allocation.find_one(request_id)
}
}

#[derive(Serialize, Deserialize, Debug, Clone)]
Expand Down
51 changes: 50 additions & 1 deletion fplus-lib/src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::{
blockchain::BlockchainData, filecoin::get_multisig_threshold_for_actor, github::{
github_async_new, CreateMergeRequestData, CreateRefillMergeRequestData, GithubWrapper,
}
}, helpers::{compare_allowance_and_allocation, process_amount}, parsers::ParsedIssue
}, helpers::{compare_allowance_and_allocation, process_amount, parse_size_to_bytes}, parsers::ParsedIssue
};
use fplus_database::database::allocation_amounts::get_allocation_quantity_options;
use fplus_database::database::{
Expand Down Expand Up @@ -45,6 +45,15 @@ pub struct CreateApplicationInfo {
pub repo: String,
}

#[derive(Deserialize)]
pub struct TriggerSSAInfo {
pub id: String,
pub owner: String,
pub repo: String,
pub amount: String,
pub amount_type: String,
}

#[derive(Deserialize)]
pub struct BranchDeleteInfo {
pub owner: String,
Expand Down Expand Up @@ -3524,6 +3533,46 @@ _The initial issue can be edited in order to solve the request of the verifier.

Ok(updated_application) // Return the updated ApplicationFile
}

pub async fn trigger_ssa(info: TriggerSSAInfo) -> Result<(), LDNError> {
let app_model =
Self::get_application_model(info.id.clone(), info.owner.clone(), info.repo.clone())
.await?;

let app_str = app_model.application.ok_or_else(|| {
LDNError::Load(format!(
"Application {} does not have an application field",
info.id
))
})?;
let application_file = serde_json::from_str::<ApplicationFile>(&app_str).unwrap();

if application_file.lifecycle.state != AppState::Granted {
return Err(LDNError::Load(format!("Application state is {:?}. Expected Granted", application_file.lifecycle.state)));
}
let last_allocation = application_file.get_last_request_allowance().ok_or(LDNError::Load("Last allocation not found".into()))?;
if last_allocation.is_active {
return Err(LDNError::Load("Last active allocation ID is active".into()));
}

let requested_so_far = application_file.allocation.total_requested();
let total_requested = parse_size_to_bytes(&application_file.datacap.total_requested_amount).ok_or(
LDNError::Load("Can not parse total requested amount to bytes".into()),
)?;

if requested_so_far >= total_requested {
Copy link
Collaborator Author

@kacperzuk-neti kacperzuk-neti May 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Filip-L

Suggested change
if requested_so_far >= total_requested {
if requested_so_far + ssa_amount > total_requested {

Where ssa_amount is info.amount converted to bytes.

return Err(LDNError::Load("Total datacap reached".into()));
}
let refill_info = RefillInfo {
id: info.id,
amount: info.amount,
amount_type: info.amount_type,
owner: app_model.owner,
repo: app_model.repo,
};
Self::refill(refill_info).await?;
Ok(())
}
}

#[derive(Serialize, Deserialize, Debug)]
Expand Down
2 changes: 1 addition & 1 deletion fplus-lib/src/helpers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use regex::Regex;

fn parse_size_to_bytes(size: &str) -> Option<u64> {
pub fn parse_size_to_bytes(size: &str) -> Option<u64> {
let re = Regex::new(r"^(\d+)([a-zA-Z]+)$").unwrap();
let caps = re.captures(size.trim())?;

Expand Down
Loading