Skip to content

Commit

Permalink
fix: fix JobStatus
Browse files Browse the repository at this point in the history
  • Loading branch information
andrew2003 committed Dec 5, 2024
1 parent 640a9fa commit 4a0cef3
Show file tree
Hide file tree
Showing 17 changed files with 66 additions and 88 deletions.
6 changes: 2 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ axum = { version = "0.8.0-alpha.1" }
clap = { version = "4.5.17" }
config = { version = "0.14.0" }
deadpool-diesel = { version = "0.6.1" }
diesel = { version = "2.2.4" }
diesel = { version = "2.2.4", features = ["uuid", "postgres"] }
diesel_migrations = { version = "2.2.0" }
dotenv = { version = "0.15.0" }
ethers = { version = "2.0.14" }
Expand All @@ -51,9 +51,7 @@ scopeguard = { version = "1.2.0" }
serde = { version = "1.0.210", features = ["derive"] }
sqlx = { version = "*" }
serde_json = { version = "1.0.128" }
stone-cli = { git = "https://github.com/zksecurity/stone-cli.git" }
starknet-os = { git = "https://github.com/keep-starknet-strange/snos" }
#starknet-os = { git = "https://github.com/keep-starknet-strange/snos", branch = "main"}
stone-cli = { git = "https://github.com/zksecurity/stone-cli.git", branch = "main"}
tempfile = { version = "3.13.0" }
test-log = { version = "0.2.16" }
testcontainers-modules = { version = "0.11.3" }
Expand Down
6 changes: 3 additions & 3 deletions crates/adapter/src/repositories/postgres/models/job.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::io::{Error, ErrorKind};
use std::io::Error;
use std::str::FromStr;
use std::time::SystemTime;

use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use irelia_core::entities::job::{JobEntity, JobId, JobStatus};
use irelia_core::entities::job::{JobEntity, JobId, CairoJobStatus};
use uuid::Uuid;

#[derive(Debug, Queryable, Insertable, Selectable, AsChangeset, Identifiable, Clone)]
Expand Down Expand Up @@ -46,7 +46,7 @@ impl From<JobModel> for JobEntity {
id: JobId(val.id),
customer_id: val.customer_id,
cairo_job_key: val.cairo_job_key,
status: JobStatus::from_str(val.status.as_str()).unwrap(),
status: CairoJobStatus::from_str(val.status.as_str()).unwrap(),
invalid_reason: val.invalid_reason,
error_log: val.error_log,
validation_done: val.validation_done,
Expand Down
2 changes: 0 additions & 2 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,5 @@ num-bigint = { workspace = true }
regex = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
stone-cli = { workspace = true }
starknet-os = { workspace = true }
thiserror = { workspace = true }
uuid = { workspace = true, features = ["v4", "serde"] }
43 changes: 42 additions & 1 deletion crates/core/src/entities/job.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,50 @@
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};
use starknet_os::sharp::CairoJobStatus;
use uuid::Uuid;

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub enum CairoJobStatus {
FAILED, // Stone failed
INVALID, // Wrong pie format
UNKNOWN, //
IN_PROGRESS, // init status

Check warning on line 12 in crates/core/src/entities/job.rs

View workflow job for this annotation

GitHub Actions / Cargo check

variant `IN_PROGRESS` should have an upper camel case name
NOT_CREATED, //

Check warning on line 13 in crates/core/src/entities/job.rs

View workflow job for this annotation

GitHub Actions / Cargo check

variant `NOT_CREATED` should have an upper camel case name
PROCESSED, // stone completed => to submit on chain
ONCHAIN, // stone completed and submit on chain completed
}

impl fmt::Display for CairoJobStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CairoJobStatus::FAILED => write!(f, "FAILED"),
CairoJobStatus::INVALID => write!(f, "INVALID"),
CairoJobStatus::UNKNOWN => write!(f, "UNKNOWN"),
CairoJobStatus::IN_PROGRESS => write!(f, "IN_PROGRESS"),
CairoJobStatus::NOT_CREATED => write!(f, "NOT_CREATED"),
CairoJobStatus::PROCESSED => write!(f, "PROCESSED"),
CairoJobStatus::ONCHAIN => write!(f, "ONCHAIN"),
}
}
}

impl FromStr for CairoJobStatus {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_uppercase().as_str() {
"FAILED" => Ok(CairoJobStatus::FAILED),
"INVALID" => Ok(CairoJobStatus::INVALID),
"UNKNOWN" => Ok(CairoJobStatus::UNKNOWN),
"IN_PROGRESS" => Ok(CairoJobStatus::IN_PROGRESS),
"NOT_CREATED" => Ok(CairoJobStatus::NOT_CREATED),
"PROCESSED" => Ok(CairoJobStatus::PROCESSED),
"ONCHAIN" => Ok(CairoJobStatus::ONCHAIN),
_ => Err(format!("'{}' is not a valid value of job status", s)),
}
}
}

#[derive(Debug, Eq, Hash, PartialEq, Serialize, Deserialize, Clone)]
pub struct JobId(pub Uuid);

Expand Down
3 changes: 1 addition & 2 deletions crates/core/src/entities/worker_job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use uuid::Uuid;
#[derive(Clone, Debug, PartialEq)]
pub enum WorkerJobStatus {
IncorrectLayout,
AdditionalBadFlag,
NoCairoJobId,
IncorrectOffchainProof,

Expand All @@ -22,4 +21,4 @@ pub struct WorkerJobEntity {
pub offchain_proof: bool,
pub proof_layout: String,
pub cairo_pie: String,
}
}
1 change: 0 additions & 1 deletion crates/public/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ reqwest = { workspace = true, features = ["json"] }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
stone-cli = { workspace = true }
starknet-os = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["full"] }
tokio-postgres = { workspace = true }
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
16 changes: 2 additions & 14 deletions crates/public/src/controllers/worker_job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,35 +10,23 @@ use crate::errors::AppError;
use crate::json_response::JsonResponse;
use crate::services::worker_job::WorkerJobResponse;

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct Request {
pub(crate) cairo_pie: String,
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct CairoPieReq {
pub action: String,
pub(crate) request: Request,
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct NewWorkerJob {
pub customer_id: String,
pub cairo_job_key: Option<String>,
pub offchain_proof: bool,
pub proof_layout: String,
pub bla: Option<bool>,
}

#[instrument(level = "info", skip(app_state))]
pub async fn add_worker_job(
State(app_state): State<AppState>,
Query(params): Query<NewWorkerJob>,
Json(req): Json<CairoPieReq>,
cairo_pie_req: String,
) -> Result<JsonResponse<WorkerJobResponse>, AppError> {
let res = app_state
.worker_service
.add_worker_job(app_state.job_service, params, req)
.add_worker_job(app_state.job_service, params, cairo_pie_req)
.await?;

Ok(JsonResponse(res))
Expand Down
3 changes: 1 addition & 2 deletions crates/public/src/services/job.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use std::sync::Arc;

use irelia_core::entities::job::{JobEntity, JobId, JobStatus};
use irelia_core::entities::job::{JobEntity, JobId, CairoJobStatus};
use irelia_core::ports::job::JobPort;
use serde::{Deserialize, Serialize};
use starknet_os::sharp::CairoJobStatus;
use tracing::log::info;
use uuid::Uuid;

Expand Down
22 changes: 5 additions & 17 deletions crates/public/src/services/worker_job.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
use std::{str::FromStr, sync::Arc};

use irelia_core::entities::worker_job::WorkerJobStatus::{
AdditionalBadFlag, IncorrectLayout, IncorrectOffchainProof, NoCairoJobId, Successfully,
IncorrectLayout, IncorrectOffchainProof, NoCairoJobId, Successfully,
};
use irelia_core::entities::worker_job::{
WorkerJobEntity, WorkerJobId, WorkerJobStatus,
};
use irelia_core::ports::worker::WorkerPort;
use serde::{Deserialize, Serialize};
use stone_cli::args::LayoutName;
use starknet_os::sharp::CairoJobStatus::IN_PROGRESS;
use uuid::Uuid;

use crate::controllers::worker_job::{CairoPieReq, NewWorkerJob};
use irelia_core::entities::job::CairoJobStatus::IN_PROGRESS;
use crate::controllers::worker_job::{NewWorkerJob};
use crate::errors::AppError;
use crate::services::job::JobService;
use crate::utils::save_cairo_pie;
Expand All @@ -34,7 +33,7 @@ impl WorkerJobService {
&self,
job_service: Arc<JobService>,
params: NewWorkerJob,
req: CairoPieReq,
cairo_pie_req: String,
) -> Result<WorkerJobResponse, AppError> {
let response_code = Self::check_job(params.clone());

Expand All @@ -45,7 +44,7 @@ impl WorkerJobService {
return Ok(WorkerJobResponse::get_worker_job_response(response_code));
}

let cairo_pie = save_cairo_pie(&req.request.cairo_pie, &*params.clone().cairo_job_key.unwrap())
let cairo_pie = save_cairo_pie(&cairo_pie_req, &*params.clone().cairo_job_key.unwrap())
.expect("Failed to save cairo pie")
.to_string_lossy()
.to_string();
Expand All @@ -62,11 +61,6 @@ impl WorkerJobService {
})
.await?;

if response_code == AdditionalBadFlag {
let _ = job_service.add_job(params.clone(), IN_PROGRESS, true).await;
return Ok(WorkerJobResponse::get_worker_job_response(response_code))
}

let _ = job_service.add_job(params, IN_PROGRESS, false).await;
Ok(WorkerJobResponse::get_worker_job_response(response_code))
}
Expand All @@ -79,11 +73,6 @@ impl WorkerJobService {
return IncorrectLayout;
}
}
// Check additional bad flag
if params.bla.is_some() && params.bla.unwrap() {
return AdditionalBadFlag;
}

// Check no cairo job id
if params.cairo_job_key.is_none() {
return NoCairoJobId;
Expand Down Expand Up @@ -124,7 +113,6 @@ impl WorkerJobResponse {
pub fn get_worker_job_response(code: WorkerJobStatus) -> Self {
match code {
IncorrectLayout => Self::internal_server_error(),
AdditionalBadFlag => Self::successfully(),
NoCairoJobId => Self::internal_server_error(),
IncorrectOffchainProof => Self::internal_server_error(),

Expand Down
52 changes: 10 additions & 42 deletions crates/public/src/tests/test_add_job.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::fmt::format;
use std::fs;

use reqwest::Client;
Expand Down Expand Up @@ -51,14 +52,7 @@ async fn test_incorrect_layout(client: Client, base_url: String, cairo_pie: Stri
"{}/v1/gateway/add_job?customer_id={}&cairo_job_key={}&offchain_proof={}&proof_layout={}",
base_url, Uuid::new_v4(), Uuid::new_v4(), true, "smal"
);
let correct_body = json!(
{
"action": "add_job",
"request": {
"cairo_pie": cairo_pie
}
}
);
let correct_body = format!("{}", cairo_pie);
let expected = json!(
{
"code": "500",
Expand All @@ -74,14 +68,7 @@ async fn test_additional_bad_flag(client: Client, base_url: String, cairo_pie: S
"{}/v1/gateway/add_job?customer_id={}&cairo_job_key={}&offchain_proof={}&proof_layout={}&bla={}",
base_url, Uuid::new_v4(), Uuid::new_v4(), true, "small", true
);
let correct_body = json!(
{
"action": "add_job",
"request": {
"cairo_pie": cairo_pie
}
}
);
let correct_body = format!("{}", cairo_pie);
let expected = json!(
{"code" : "JOB_RECEIVED_SUCCESSFULLY"}
);
Expand All @@ -97,14 +84,7 @@ async fn test_no_cairo_job_id(client: Client, base_url: String, cairo_pie: Strin
true,
"small"
);
let correct_body = json!(
{
"action": "add_job",
"request": {
"cairo_pie": cairo_pie
}
}
);
let correct_body = format!("{}", cairo_pie);
let expected = json!(
{
"code": "500",
Expand All @@ -121,14 +101,7 @@ async fn test_incorrect_offchain_proof(client: Client, base_url: String, cairo_p
"{}/v1/gateway/add_job?customer_id={}&cairo_job_key={}&offchain_proof={}&proof_layout={}",
base_url, Uuid::new_v4(), Uuid::new_v4(), false, "small"
);
let correct_body = json!(
{
"action": "add_job",
"request": {
"cairo_pie": cairo_pie
}
}
);
let correct_body = format!("{}", cairo_pie);
let expected = json!(
{
"code": "500",
Expand All @@ -145,25 +118,20 @@ async fn test_successfully(client: Client, base_url: String, cairo_pie: String)
"{}/v1/gateway/add_job?customer_id={}&cairo_job_key={}&offchain_proof={}&proof_layout={}",
base_url, Uuid::new_v4(), Uuid::new_v4(), true, "small"
);
let correct_body = json!(
{
"action": "add_job",
"request": {
"cairo_pie": cairo_pie
}
}
);

let correct_body = format!("{}", cairo_pie);

let expected = json!(
{"code" : "JOB_RECEIVED_SUCCESSFULLY"}
);
let res = post_request(client, url, correct_body).await;
assert_eq!(res, expected, "Response did not match expected value");
}

async fn post_request(client: Client, url: String, body: Value) -> Value {
async fn post_request(client: Client, url: String, body:String) -> Value {
client
.post(&url)
.json(&body)
.body(body)
.send()
.await
.expect("Failed to send POST request")
Expand Down

0 comments on commit 4a0cef3

Please sign in to comment.