Skip to content
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
8 changes: 0 additions & 8 deletions Cargo.lock

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

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ thiserror = { version = "2.0" }
tokio = { version = "1.44.2" }
toml = { version = "0.8.20" }
unindent = { version = "0.2.4" }
urlencoding = { version = "2.1.3" }

[workspace.lints.rust]
unknown_lints = "deny"
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ To get started with Percas, you can follow these steps:
Now, you can put and get a key-value pair into the cache using the following command:

```shell
curl -X PUT -H 'Content-Type: application/json' http://localhost:7654/my_lovely_key -d 'my_lovely_value'
curl -X GET -H 'Content-Type: application/json' http://localhost:7654/my_lovely_key
curl -X PUT http://localhost:7654/my/lovely/key -d 'my_lovely_value'
curl -X GET http://localhost:7654/my/lovely/key
```

## License
Expand Down
1 change: 0 additions & 1 deletion api/client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ version.workspace = true
error-stack = { workspace = true }
reqwest = { workspace = true }
thiserror = { workspace = true }
urlencoding = { workspace = true }

[lints]
workspace = true
31 changes: 0 additions & 31 deletions api/client/src/builder.rs

This file was deleted.

54 changes: 27 additions & 27 deletions api/client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use error_stack::Result;
use error_stack::ResultExt;
use error_stack::bail;
use reqwest::IntoUrl;
use reqwest::StatusCode;
use reqwest::Url;

Expand All @@ -29,21 +30,27 @@ pub enum Error {
Other(String),
}

pub struct Client {
pub struct ClientBuilder {
endpoint: String,
client: reqwest::Client,
}

impl Client {
pub(crate) fn new(
endpoint: impl Into<String>,
builder: reqwest::ClientBuilder,
) -> Result<Self, reqwest::Error> {
let client = builder.build()?;
let endpoint = endpoint.into();
Ok(Client { endpoint, client })
impl ClientBuilder {
pub fn new(endpoint: String) -> Self {
Self { endpoint }
}

pub fn build(self) -> Result<Client, Error> {
let builder = reqwest::ClientBuilder::new().no_proxy();
Client::new(self.endpoint, builder)
}
}

pub struct Client {
client: reqwest::Client,
base_url: Url,
}

impl Client {
pub async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, Error> {
do_get(self, key).await
}
Expand All @@ -55,15 +62,18 @@ impl Client {
pub async fn delete(&self, key: &str) -> Result<(), Error> {
do_delete(self, key).await
}

fn new(base_url: impl IntoUrl, builder: reqwest::ClientBuilder) -> Result<Self, Error> {
let client = builder.build().map_err(Error::Http)?;
let base_url = base_url.into_url().map_err(Error::Http)?;
Ok(Client { client, base_url })
}
}

async fn do_get(client: &Client, key: &str) -> Result<Option<Vec<u8>>, Error> {
let make_error = || Error::Other("failed to get".to_string());
let mut url = Url::parse(&client.endpoint).change_context_lazy(make_error)?;

let encoded_key = urlencoding::encode(key);

url = url.join(&encoded_key).change_context_lazy(make_error)?;
let url = client.base_url.join(key).change_context_lazy(make_error)?;
let resp = client
.client
.get(url)
Expand All @@ -72,24 +82,19 @@ async fn do_get(client: &Client, key: &str) -> Result<Option<Vec<u8>>, Error> {
.change_context_lazy(make_error)?;

match resp.status() {
StatusCode::NOT_FOUND => Ok(None),
StatusCode::OK => {
let body = resp.bytes().await.change_context_lazy(make_error)?;
Ok(Some(body.to_vec()))
}

StatusCode::NOT_FOUND => Ok(None),

_ => bail!(Error::Other(resp.status().to_string())),
}
}

async fn do_put(client: &Client, key: &str, value: &[u8]) -> Result<(), Error> {
let make_error = || Error::Other("failed to put".to_string());
let mut url = Url::parse(&client.endpoint).change_context_lazy(make_error)?;

let encoded_key = urlencoding::encode(key);
url = url.join(&encoded_key).change_context_lazy(make_error)?;

let url = client.base_url.join(key).change_context_lazy(make_error)?;
let resp = client
.client
.put(url)
Expand All @@ -100,18 +105,14 @@ async fn do_put(client: &Client, key: &str, value: &[u8]) -> Result<(), Error> {

match resp.status() {
StatusCode::OK | StatusCode::CREATED => Ok(()),

_ => bail!(Error::Other(resp.status().to_string())),
}
}

async fn do_delete(client: &Client, key: &str) -> Result<(), Error> {
let make_error = || Error::Other("failed to delete".to_string());
let mut url = Url::parse(&client.endpoint).change_context_lazy(make_error)?;

let encoded_key = urlencoding::encode(key);
url = url.join(&encoded_key).change_context_lazy(make_error)?;

let url = client.base_url.join(key).change_context_lazy(make_error)?;
let resp = client
.client
.delete(url)
Expand All @@ -121,7 +122,6 @@ async fn do_delete(client: &Client, key: &str) -> Result<(), Error> {

match resp.status() {
StatusCode::OK | StatusCode::NO_CONTENT => Ok(()),

_ => bail!(Error::Other(resp.status().to_string())),
}
}
3 changes: 1 addition & 2 deletions api/client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

mod builder;
mod client;

pub use builder::ClientBuilder;
pub use client::Client;
pub use client::ClientBuilder;
1 change: 0 additions & 1 deletion crates/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ pin-project = { workspace = true }
poem = { workspace = true }
scopeguard = { workspace = true }
tokio = { workspace = true }
urlencoding = { workspace = true }

[lints]
workspace = true
53 changes: 12 additions & 41 deletions crates/server/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ pub async fn start_server(
let wg_clone = wg.clone();

let route = Route::new()
.at("/:key", poem::get(get).put(put).delete(delete))
.at("/*key", poem::get(get).put(put).delete(delete))
.data(ctx)
.with(LoggerMiddleware);
let signal = async move {
Expand Down Expand Up @@ -191,20 +191,9 @@ fn resolve_advertise_addr(
#[handler]
pub async fn get(Data(ctx): Data<&Arc<PercasContext>>, key: Path<String>) -> Response {
let metrics = &GlobalMetrics::get().operation;
let Ok(key) = urlencoding::decode(&key) else {
let labels = OperationMetrics::operation_labels(
OperationMetrics::OPERATION_GET,
OperationMetrics::STATUS_FAILURE,
);
metrics.count.add(1, &labels);
return Response::builder()
.status(StatusCode::BAD_REQUEST)
.body("bad request");
};
let start = std::time::Instant::now();
let value = ctx.engine.get(key.as_bytes()).await;

match value {
match ctx.engine.get(key.as_bytes()).await {
Some(value) => {
let labels = OperationMetrics::operation_labels(
OperationMetrics::OPERATION_GET,
Expand Down Expand Up @@ -233,31 +222,21 @@ pub async fn get(Data(ctx): Data<&Arc<PercasContext>>, key: Path<String>) -> Res

Response::builder()
.status(StatusCode::NOT_FOUND)
.body("not found")
.typed_header(ContentType::text())
.body(StatusCode::NOT_FOUND.to_string())
}
}
}

#[handler]
pub async fn put(Data(ctx): Data<&Arc<PercasContext>>, key: Path<String>, body: Body) -> Response {
let metrics = &GlobalMetrics::get().operation;
let Ok(key) = urlencoding::decode(&key) else {
let labels = OperationMetrics::operation_labels(
OperationMetrics::OPERATION_PUT,
OperationMetrics::STATUS_FAILURE,
);
metrics.count.add(1, &labels);
return Response::builder()
.status(StatusCode::BAD_REQUEST)
.body("bad request");
};
let start = std::time::Instant::now();
let put_result = body.into_bytes().await.map(|bytes| {

match body.into_bytes().await.map(|bytes| {
ctx.engine.put(key.as_bytes(), &bytes);
bytes.len()
});

match put_result {
}) {
Ok(len) => {
let labels = OperationMetrics::operation_labels(
OperationMetrics::OPERATION_PUT,
Expand All @@ -271,7 +250,8 @@ pub async fn put(Data(ctx): Data<&Arc<PercasContext>>, key: Path<String>, body:

Response::builder()
.status(StatusCode::CREATED)
.body("created")
.typed_header(ContentType::text())
.body(StatusCode::CREATED.to_string())
}
Err(_) => {
let labels = OperationMetrics::operation_labels(
Expand All @@ -285,24 +265,15 @@ pub async fn put(Data(ctx): Data<&Arc<PercasContext>>, key: Path<String>, body:

Response::builder()
.status(StatusCode::BAD_REQUEST)
.body("bad request")
.typed_header(ContentType::text())
.body(StatusCode::BAD_REQUEST.to_string())
}
}
}

#[handler]
pub async fn delete(Data(ctx): Data<&Arc<PercasContext>>, key: Path<String>) -> Response {
let metrics = &GlobalMetrics::get().operation;
let Ok(key) = urlencoding::decode(&key) else {
let labels = OperationMetrics::operation_labels(
OperationMetrics::OPERATION_DELETE,
OperationMetrics::STATUS_FAILURE,
);
metrics.count.add(1, &labels);
return Response::builder()
.status(StatusCode::BAD_REQUEST)
.body("bad request");
};
let start = std::time::Instant::now();
ctx.engine.delete(key.as_bytes());

Expand All @@ -315,5 +286,5 @@ pub async fn delete(Data(ctx): Data<&Arc<PercasContext>>, key: Path<String>) ->
.duration
.record(start.elapsed().as_secs_f64(), &labels);

Response::builder().status(StatusCode::NO_CONTENT).body("")
Response::builder().status(StatusCode::NO_CONTENT).finish()
}
2 changes: 1 addition & 1 deletion tests/behavior/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ where

rt.block_on(async move {
let server_addr = format!("http://{}/", state.server_state.server_advertise_addr());
let client = ClientBuilder::new(server_addr).build();
let client = ClientBuilder::new(server_addr).build().unwrap();

let exit_code = test(Testkit { client }).await.report();

Expand Down
18 changes: 15 additions & 3 deletions tests/behavior/tests/common_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,22 @@ use test_harness::test;

#[test(harness)]
async fn test_put_get(testkit: Testkit) {
testkit.client.put("key", "value".as_bytes()).await.unwrap();
let value = testkit.client.get("key").await.unwrap();
let (key, value) = ("key", "value");
testkit.client.put(key, value.as_bytes()).await.unwrap();
let actual_value = testkit.client.get(key).await.unwrap().unwrap();
assert_snapshot!(
render_hex(value.unwrap()),
render_hex(actual_value),
@r"
Length: 5 (0x5) bytes
0000: 76 61 6c 75 65 value
"
);

let (key, value) = ("multiple/level/key", "value");
testkit.client.put(key, value.as_bytes()).await.unwrap();
let actual_value = testkit.client.get(key).await.unwrap().unwrap();
assert_snapshot!(
render_hex(actual_value),
@r"
Length: 5 (0x5) bytes
0000: 76 61 6c 75 65 value
Expand Down