Skip to content

Commit

Permalink
Merge pull request #85 from pubky/feat/no-wasted-cache
Browse files Browse the repository at this point in the history
feat(server): pkarr relay should return expired packets as a last resort
  • Loading branch information
Nuhvi authored Oct 4, 2024
2 parents 6105246 + 775efe3 commit 15de577
Showing 1 changed file with 32 additions and 16 deletions.
48 changes: 32 additions & 16 deletions server/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use axum::{extract::State, response::IntoResponse};

use bytes::Bytes;
use http::{header, StatusCode};
use pkarr::mainline::MutableItem;
use tracing::error;

use pkarr::{PublicKey, DEFAULT_MAXIMUM_TTL, DEFAULT_MINIMUM_TTL};
Expand Down Expand Up @@ -50,22 +51,37 @@ pub async fn get(
let public_key = PublicKey::try_from(public_key.as_str())
.map_err(|error| Error::new(StatusCode::BAD_REQUEST, Some(error)))?;

if let Some(signed_packet) =
state
.client
.resolve(&public_key)
.await
.map_err(|error| match error {
pkarr::Error::DhtIsShutdown => {
error!("Dht is shutdown");
Error::with_status(StatusCode::INTERNAL_SERVER_ERROR)
}
error => {
error!(?error, "Unexpected error");
Error::with_status(StatusCode::INTERNAL_SERVER_ERROR)
}
})?
{
let signed_packet = {
if let Some(signed_packet) =
state
.client
.resolve(&public_key)
.await
.map_err(|error| match error {
pkarr::Error::DhtIsShutdown => {
error!("Dht is shutdown");
Error::with_status(StatusCode::INTERNAL_SERVER_ERROR)
}
error => {
error!(?error, "Unexpected error");
Error::with_status(StatusCode::INTERNAL_SERVER_ERROR)
}
})?
{
Some(signed_packet)
} else {
// Respond with what we have, even if expired.
// TODO: move this fallback to the client itself, closing #67
state
.client
.cache()
.get_read_only(&MutableItem::target_from_key(public_key.as_bytes(), &None))
}
};

if let Some(signed_packet) = signed_packet {
tracing::debug!(?public_key, "cache hit responding with packet!");

let body = signed_packet.to_relay_payload();

let ttl = signed_packet.ttl(DEFAULT_MINIMUM_TTL, DEFAULT_MAXIMUM_TTL);
Expand Down

0 comments on commit 15de577

Please sign in to comment.