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

Feat/put object #9

Merged
merged 2 commits into from
May 20, 2023
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 .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,5 @@ jobs:
sleep 10
aws --endpoint-url http://localhost:9090 s3 mb s3://sardo
aws --endpoint-url http://localhost:9090 s3 ls
aws --endpoint-url http://localhost:9090 s3 cp ./Cargo.toml s3://sardo

61 changes: 61 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ authors = ["Sardorbek Pulatov <[email protected]>"]

[dependencies]
actix-web = "4.3"
clap = { version = "4.2.7", features = ["derive"] }
actix-router = "0.5"
clap = { version = "4.2", features = ["derive"] }
futures = "0.3"
tracing = "0.1"
tracing-subscriber = "0.3"
serde = { version = "1.0", features = ["derive"] }
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ $ ./s3-chelak --server-url "my_custom_url" --server-port "8080" --working-folder
| PutBucketTagging | :x: |
| PutBucketVersioning | :x: |
| PutBucketWebsite | :x: |
| PutObject | :x: |
| PutObject | :white_check_mark: |
| PutObjectAcl | :x: |
| PutObjectLegalHold | :x: |
| PutObjectLockConfiguration | :x: |
Expand Down
6 changes: 2 additions & 4 deletions src/apis/create_bucket.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use actix_web::{error, put, web, Error, HttpRequest, HttpResponse};
use actix_web::{error, put, web, Error, HttpResponse};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug)]
Expand All @@ -23,12 +23,10 @@ pub struct BucketError {
pub host_id: String,
}

#[put("/{bucket_name}")]
pub async fn create_bucket(
bucket_name: web::Path<String>,
bucket_name: String,
data: web::Data<crate::AppState>,
) -> Result<HttpResponse, Error> {
let bucket_name = bucket_name.into_inner();
let working_folder = &data.working_folder;

let bucket_path = format!("{}/{}", working_folder, bucket_name);
Expand Down
4 changes: 3 additions & 1 deletion src/apis/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
pub mod list_buckets;
pub mod create_bucket;
pub mod list_buckets;
pub mod put_object;
pub mod put_handler;
42 changes: 42 additions & 0 deletions src/apis/put_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use actix_router::{Path, Resource, ResourceDef, Url};

use crate::apis::create_bucket::create_bucket;
use crate::apis::put_object::put_object;
use actix_web::{put, web, Error, HttpRequest, HttpResponse};

#[put("/{tail}*")]
pub async fn handle_put(
_: web::Path<String>,
req: HttpRequest,
data: web::Data<crate::AppState>,
mut payload: Option<web::Payload>,
) -> Result<HttpResponse, Error> {
let mut path = Path::new(Url::new(req.uri().clone()));

let routes = [
("/{bucket}/{object_name}", "bucket and object"),
("/{bucket}", "bucket"),
];

for (pattern, description) in &routes {
if ResourceDef::new(*pattern).capture_match_info(&mut path) {
return match (path.get("bucket"), path.get("object_name")) {
(Some(bucket), Some(object_name)) if *description == "bucket and object" => {
put_object(
bucket.to_string(),
object_name.to_string(),
data,
payload.unwrap(),
)
.await
}
(Some(bucket), None) if *description == "bucket" => {
create_bucket(bucket.to_string(), data).await
}
_ => return Ok(HttpResponse::InternalServerError().finish()),
};
}
}

Err(actix_web::error::ErrorNotFound("Not Found"))
}
23 changes: 23 additions & 0 deletions src/apis/put_object.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use actix_web::{put, web, Error, FromRequest, HttpRequest, HttpResponse};
use futures::StreamExt;
use std::fs::File;
use std::io::Write;

pub async fn put_object(
bucket_name: String,
object_name: String,
data: web::Data<crate::AppState>,
mut payload: web::Payload,
) -> Result<HttpResponse, Error> {
let working_folder = &data.working_folder;

let filepath = format!("{}/{}/{}", working_folder, bucket_name, object_name);
let mut file = File::create(&filepath)?;

while let Some(bytes) = payload.next().await {
let data = bytes.unwrap();
file.write_all(&data)?;
}

Ok(HttpResponse::Ok().finish())
}
9 changes: 8 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ use std::fs;

use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use clap::Parser;
use tracing::error;
use tracing::log::warn;

pub mod apis;
pub mod utils;

async fn not_found(request: HttpRequest) -> impl Responder {
error!("Headers {:?}.", request.headers());
warn!("Cannot find {}.", request.path());
error!("Request Body {:?}.", request);
HttpResponse::NotFound().body(format!("Cannot find {}.", request.path()))
}

Expand Down Expand Up @@ -38,12 +43,14 @@ async fn main() -> std::io::Result<()> {
let server = HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.service(apis::create_bucket::create_bucket)
.service(apis::put_handler::handle_put)
// .service(apis::create_bucket::create_bucket)
.service(apis::list_buckets::list_buckets)
.default_service(web::route().to(not_found))
.app_data(web::Data::new(AppState {
working_folder: config.working_folder.clone(),
}))
.wrap(middleware::Logger::default())
});

let server_url = format!("{}:{}", config.server_url, config.server_port);
Expand Down