Skip to content

Commit f7843ac

Browse files
committed
add custom key extractor to use a fly-specific header, disable locally
1 parent bc3b865 commit f7843ac

2 files changed

Lines changed: 29 additions & 6 deletions

File tree

fly-app/src/key_extractor.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use actix_governor::{KeyExtractor, SimpleKeyExtractionError};
2+
3+
#[derive(Clone, Default)]
4+
pub struct Extractor {}
5+
6+
impl KeyExtractor for Extractor {
7+
type Key = String;
8+
type KeyExtractionError = SimpleKeyExtractionError<&'static str>;
9+
10+
fn extract(
11+
&self,
12+
req: &actix_web::dev::ServiceRequest,
13+
) -> Result<Self::Key, Self::KeyExtractionError> {
14+
let head = req.head();
15+
match head.headers().get("Fly-Client-IP") {
16+
Some(data) => return Ok(data.to_str().unwrap().to_string()),
17+
None => return Err(SimpleKeyExtractionError::new("can not find any token")),
18+
}
19+
}
20+
}

fly-app/src/main.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
use std::env;
2+
13
use actix_governor::{Governor, GovernorConfigBuilder};
2-
use actix_web::{web, App, HttpResponse, HttpServer};
4+
use actix_web::{middleware::Condition, web, App, HttpResponse, HttpServer};
35
use serde::{Deserialize, Serialize};
46
use serde_qs::actix::QsQuery;
57
use sqlx::postgres::PgPoolOptions;
@@ -10,6 +12,7 @@ use tracing_actix_web::{DefaultRootSpanBuilder, RequestId, TracingLogger};
1012
use crate::error::{ErrorResponse, InternalErrorResponse};
1113
use crate::tracing::init_tracing;
1214
mod error;
15+
mod key_extractor;
1316
mod tracing;
1417
mod util;
1518

@@ -844,7 +847,9 @@ async fn main() -> std::io::Result<()> {
844847
.parse()
845848
.expect("PORT must be a valid number");
846849

850+
let is_fly = env::var("FLY_APP_NAME").is_ok();
847851
let governor_conf = GovernorConfigBuilder::default()
852+
.key_extractor(key_extractor::Extractor::default())
848853
.seconds_per_request(2)
849854
.burst_size(5)
850855
.finish()
@@ -867,13 +872,11 @@ async fn main() -> std::io::Result<()> {
867872
.route("/", web::get().to(index))
868873
.service(
869874
web::scope("/v1")
870-
.wrap(Governor::new(&governor_conf))
875+
// add rate-limiter only when deployed to fly.io as it fetches a fly-specific header
876+
.wrap(Condition::new(is_fly, Governor::new(&governor_conf)))
871877
.route("", web::get().to(index_v1))
872878
.route("/wasms", web::get().to(get_wasms))
873-
.route(
874-
"/wasms/{wasm_name}",
875-
web::get().to(get_wasm_root_channel),
876-
)
879+
.route("/wasms/{wasm_name}", web::get().to(get_wasm_root_channel))
877880
.route(
878881
"/wasms/{channel}/{wasm_name}",
879882
web::get().to(get_wasm_latest),

0 commit comments

Comments
 (0)