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

Implement bulk endpoints #40

Merged
merged 9 commits into from
Jan 4, 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
12 changes: 12 additions & 0 deletions server/Cargo.lock

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

1 change: 1 addition & 0 deletions server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,4 @@ serde_with = "3.3.0"
bech32 = "0.10.0-alpha"
crc32fast = "1.3.2"
ciborium = "0.2.1"
serde_qs = "0.12.0"
1 change: 1 addition & 0 deletions server/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use axum::async_trait;
use enstate_shared::cache::{CacheError, CacheLayer};
use redis::{aio::ConnectionManager, AsyncCommands};

#[derive(Clone)]
pub struct Redis {
redis: ConnectionManager,
}
Expand Down
6 changes: 5 additions & 1 deletion server/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use tracing::info;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;

use crate::models::bulk::BulkResponse;
use crate::models::error::ErrorResponse;
use crate::models::profile::ENSProfile;
use crate::routes;
Expand All @@ -18,7 +19,7 @@ use crate::state::AppState;
#[derive(OpenApi)]
#[openapi(
paths(routes::address::get, routes::name::get, routes::universal::get),
components(schemas(ENSProfile, ErrorResponse))
components(schemas(ENSProfile, BulkResponse<ENSProfile>, ErrorResponse))
)]
pub struct ApiDoc;

Expand Down Expand Up @@ -59,6 +60,9 @@ pub fn setup(state: AppState) -> App {
.directory_route("/u/:name_or_address", get(routes::universal::get))
.directory_route("/i/:name_or_address", get(routes::image::get))
.directory_route("/h/:name_or_address", get(routes::header::get))
.directory_route("/bulk/a", get(routes::address::get_bulk))
.directory_route("/bulk/n", get(routes::name::get_bulk))
.directory_route("/bulk/u", get(routes::universal::get_bulk))
.fallback(routes::four_oh_four::handler)
.layer(CorsLayer::permissive())
.layer(TraceLayer::new_for_http())
Expand Down
16 changes: 16 additions & 0 deletions server/src/models/bulk.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use utoipa::ToSchema;

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct BulkResponse<T> {
pub(crate) response_length: usize,
pub(crate) response: Vec<T>,
}

impl<T> From<Vec<T>> for BulkResponse<T> {
fn from(value: Vec<T>) -> Self {
BulkResponse {
response_length: value.len(),
response: value,
}
}
}
1 change: 1 addition & 0 deletions server/src/models/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod bulk;
pub mod error;
pub mod profile;
25 changes: 19 additions & 6 deletions server/src/provider.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,38 @@
use std::sync::Arc;

use enstate_shared::utils::factory::Factory;
use ethers::providers::{Http, Provider};
use rand::seq::SliceRandom;
use tracing::warn;

#[derive(Clone)]
pub struct RoundRobin {
providers: Vec<Provider<Http>>,
providers: Vec<Arc<Provider<Http>>>,
}

impl RoundRobin {
pub fn new(rpc_urls: Vec<String>) -> Self {
Self {
providers: rpc_urls
.into_iter()
.map(|rpc_url| {
Provider::<Http>::try_from(rpc_url).expect("rpc_url should be a valid URL")
.filter_map(|rpc_url| {
let provider = Provider::<Http>::try_from(&rpc_url);
if let Err(err) = provider {
warn!("provider {rpc_url} is not valid: {err}");
}

provider.ok().map(Arc::new)
})
.collect(),
}
}
}

// returns a random rpc provider
pub fn get_provider(&self) -> Option<&Provider<Http>> {
self.providers.choose(&mut rand::thread_rng())
impl Factory<Arc<Provider<Http>>> for RoundRobin {
fn get_instance(&self) -> Arc<Provider<Http>> {
self.providers
.choose(&mut rand::thread_rng())
.expect("provider should exist")
.clone()
}
}
90 changes: 65 additions & 25 deletions server/src/routes/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,15 @@ use axum::{
Json,
};
use enstate_shared::models::profile::Profile;
use ethers_core::types::Address;
use futures::future::try_join_all;
use serde::Deserialize;

use crate::cache;
use crate::routes::{http_simple_status_error, profile_http_error_mapper, FreshQuery, RouteError};
use crate::models::bulk::BulkResponse;
use crate::routes::{
http_simple_status_error, profile_http_error_mapper, validate_bulk_input, FreshQuery, Qs,
RouteError,
};

#[utoipa::path(
get,
Expand All @@ -28,30 +34,64 @@ pub async fn get(
Query(query): Query<FreshQuery>,
State(state): State<Arc<crate::AppState>>,
) -> Result<Json<Profile>, RouteError> {
let address = address
.parse()
.map_err(|_| http_simple_status_error(StatusCode::BAD_REQUEST))?;

let cache = Box::new(cache::Redis::new(state.redis.clone()));
let rpc = state
.provider
.get_provider()
.ok_or_else(|| http_simple_status_error(StatusCode::INTERNAL_SERVER_ERROR))?
.clone();

let opensea_api_key = &state.opensea_api_key;

let profile = Profile::from_address(
address,
query.fresh,
cache,
rpc,
opensea_api_key,
&state.profile_records,
&state.profile_chains,
get_bulk(
Qs(AddressGetBulkQuery {
fresh: query,
addresses: vec![address],
}),
State(state),
)
.await
.map_err(profile_http_error_mapper)?;
.map(|res| Json(res.0.response.get(0).expect("index 0 should exist").clone()))
}

#[derive(Deserialize)]
pub struct AddressGetBulkQuery {
// TODO (@antony1060): remove when proper serde error handling
#[serde(default)]
addresses: Vec<String>,

#[serde(flatten)]
fresh: FreshQuery,
}

#[utoipa::path(
get,
path = "/bulk/a/",
responses(
(status = 200, description = "Successfully found address.", body = BulkResponse<ENSProfile>),
(status = BAD_REQUEST, description = "Invalid address.", body = ErrorResponse),
(status = NOT_FOUND, description = "No name was associated with this address.", body = ErrorResponse),
(status = UNPROCESSABLE_ENTITY, description = "Reverse record not owned by this address.", body = ErrorResponse),
),
params(
("addresses" = Vec<String>, Path, description = "Addresses to lookup name data for"),
)
)]
pub async fn get_bulk(
Qs(query): Qs<AddressGetBulkQuery>,
State(state): State<Arc<crate::AppState>>,
) -> Result<Json<BulkResponse<Profile>>, RouteError> {
let addresses = validate_bulk_input(&query.addresses, 10)?;

let addresses = addresses
.iter()
.map(|address| address.parse::<Address>())
.collect::<Result<Vec<_>, _>>()
.map_err(|_| http_simple_status_error(StatusCode::BAD_REQUEST))?;

let profiles = addresses
.iter()
.map(|address| {
state
.service
.resolve_from_address(*address, query.fresh.fresh)
})
.collect::<Vec<_>>();

let joined = try_join_all(profiles)
.await
.map_err(profile_http_error_mapper)?;

Ok(Json(profile))
Ok(Json(joined.into()))
}
15 changes: 4 additions & 11 deletions server/src/routes/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::Redirect;

use crate::routes::{
http_simple_status_error, profile_http_error_mapper, universal_profile_resolve, FreshQuery,
RouteError,
};
use crate::routes::{http_simple_status_error, profile_http_error_mapper, FreshQuery, RouteError};

// #[utoipa::path(
// get,
Expand All @@ -27,13 +24,9 @@ pub async fn get(
Query(query): Query<FreshQuery>,
State(state): State<Arc<crate::AppState>>,
) -> Result<Redirect, RouteError> {
let rpc = state
.provider
.get_provider()
.ok_or_else(|| http_simple_status_error(StatusCode::INTERNAL_SERVER_ERROR))?
.clone();

let profile = universal_profile_resolve(&name_or_address, query.fresh, rpc, &state)
let profile = state
.service
.resolve_from_name_or_address(&name_or_address, query.fresh)
.await
.map_err(profile_http_error_mapper)?;

Expand Down
15 changes: 4 additions & 11 deletions server/src/routes/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::Redirect;

use crate::routes::{
http_simple_status_error, profile_http_error_mapper, universal_profile_resolve, FreshQuery,
RouteError,
};
use crate::routes::{http_simple_status_error, profile_http_error_mapper, FreshQuery, RouteError};

// #[utoipa::path(
// get,
Expand All @@ -27,13 +24,9 @@ pub async fn get(
Query(query): Query<FreshQuery>,
State(state): State<Arc<crate::AppState>>,
) -> Result<Redirect, RouteError> {
let rpc = state
.provider
.get_provider()
.ok_or_else(|| http_simple_status_error(StatusCode::INTERNAL_SERVER_ERROR))?
.clone();

let profile = universal_profile_resolve(&name_or_address, query.fresh, rpc, &state)
let profile = state
.service
.resolve_from_name_or_address(&name_or_address, query.fresh)
.await
.map_err(profile_http_error_mapper)?;

Expand Down
Loading