Skip to content

Commit

Permalink
Add cached redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
cofob committed May 14, 2024
1 parent 5904236 commit 2040471
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/crawler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,25 @@ impl Crawler {
}
}

pub async fn get_redirect_urls_for_service(
&self,
alias: &str,
) -> Result<Vec<Url>, CrawlerError> {
let guard = self.data.read().await;
let data = guard.as_ref();
let Some(services) = data else {
return Err(CrawlerError::CrawlerNotFetchedYet)?;
};
let Some(service) = services.get_service_by_alias(alias) else {
return Err(CrawlerError::ServiceNotFound)?;
};
Ok(service
.get_alive_instances()
.iter()
.map(|i| i.url.clone())
.collect())
}

async fn crawl_single_instance(
service: &Service,
instance: &Url,
Expand Down
31 changes: 30 additions & 1 deletion src/routes/redirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use actix_web::{
};
use askama::Template;
use thiserror::Error;
use url::Url;

use crate::{
config::AppConfig,
Expand All @@ -18,6 +19,7 @@ use crate::{
pub fn scope(_config: &AppConfig) -> Scope {
web::scope("")
.service(history_redirect)
.service(cached_redirect)
.service(base_redirect)
}

Expand All @@ -37,7 +39,34 @@ impl_api_error!(RedirectError,
);

#[derive(Template)]
#[template(path = "history_redirect.html")]
#[template(path = "cached_redirect.html", escape = "none")]
pub struct CachedRedirectTemplate {
pub urls: Vec<Url>,
}

#[get("/cached/{service_name}")]
async fn cached_redirect(
path: web::Path<String>,
config: web::Data<AppConfig>,
crawler: web::Data<Arc<Crawler>>,
) -> actix_web::Result<impl Responder> {
let service_name = path.into_inner();

let urls = crawler
.get_redirect_urls_for_service(&service_name)
.await
.map_err(RedirectError::from)?;

let template = CachedRedirectTemplate { urls };

Ok(actix_web::HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.append_header(("cache-control", format!("public, max-age {}, only-if-cached, stale-while-revalidate 86400, stale-if-error 86400, immutable", config.crawler.ping_interval.as_secs())))
.body(template.render().expect("failed to render error page")))
}

#[derive(Template)]
#[template(path = "history_redirect.html", escape = "none")]
pub struct HistoryRedirectTemplate<'a> {
pub path: &'a str,
}
Expand Down
21 changes: 21 additions & 0 deletions templates/cached_redirect.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<head>
<title>Fastside Cached Redirect</title>
<script>
let instances = [{% for instance in urls %}"{{ instance }}", {% endfor %}];
let randomIndex = Math.floor(Math.random() * instances.length);
let randomEntry = instances[randomIndex];
let hash = window.location.hash;
let data = hash.substring(1);
if (data.startsWith("/")) {
data = data.substring(1);
}
window.location.href = randomEntry + data;
</script>
</head>

<body>
<span>Redirecting...</span>
<ul>
{% for instance in urls %}<li>{{ instance }}</li>{% endfor %}
</ul>
</body>

0 comments on commit 2040471

Please sign in to comment.