ocre/runtime/seo.rs
1//! [`redirect_www`], [`indexnow_routes`] and [`submit_to_indexnow`]: the parts of `ocre::seo` that read the Worker's settings.
2
3use axum::{
4 Router,
5 extract::{Request, State},
6 http::{StatusCode, header},
7 middleware::Next,
8 response::{IntoResponse, Response},
9 routing::get,
10};
11
12use super::Ctx;
13use crate::{
14 Error, Result, http,
15 mail::APP_URL,
16 seo::{INDEXNOW_ENDPOINT, INDEXNOW_KEY, INDEXNOW_KEY_PATH, indexnow_body, valid_indexnow_key, www_target},
17};
18
19fn var(ctx: &Ctx, name: &str) -> Option<String> {
20 ctx.env().var(name).ok().map(|value| value.to_string().trim().to_owned()).filter(|value| !value.is_empty())
21}
22
23/// Middleware sending `www.` + the host of `APP_URL` to `APP_URL`, same path and query, with `301 Moved Permanently`.
24///
25/// For an app answering on both `example.com` and `www.example.com`
26/// (two custom domains of the Worker): search engines and links then see
27/// one address per page. Requests to any other host, or without `APP_URL`,
28/// go through unchanged. Add it with
29/// `.layer(axum::middleware::from_fn(ocre::seo::redirect_www))` in
30/// `routes()`. Reads one variable; no billed resource.
31///
32/// # Examples
33///
34/// ```
35/// use axum::{Router, middleware::from_fn, routing::get};
36/// use ocre::Ctx;
37///
38/// fn routes() -> Router<Ctx> {
39/// Router::new().route("/", get(|| async { "home" })).layer(from_fn(ocre::seo::redirect_www))
40/// }
41/// # let _ = routes;
42/// ```
43pub async fn redirect_www(request: Request, next: Next) -> Response {
44 let Some(ctx) = request.extensions().get::<Ctx>().cloned() else { return next.run(request).await };
45 let host = request.headers().get(header::HOST).and_then(|value| value.to_str().ok()).or(request.uri().host());
46 let path = request.uri().path_and_query().map_or("/", |path| path.as_str());
47 match var(&ctx, APP_URL).and_then(|base| www_target(&base, host, path)) {
48 Some(target) => (StatusCode::MOVED_PERMANENTLY, [(header::LOCATION, target)]).into_response(),
49 None => next.run(request).await,
50 }
51}
52
53/// `GET /indexnow.txt`: the [`INDEXNOW_KEY`](crate::seo::INDEXNOW_KEY), which search engines fetch to check a submission.
54///
55/// 404 when the variable is not set. Merge it into `routes()`:
56/// `.merge(ocre::seo::indexnow_routes())`.
57pub fn indexnow_routes() -> Router<Ctx> {
58 Router::new().route(
59 INDEXNOW_KEY_PATH,
60 get(|State(ctx): State<Ctx>| async move {
61 match var(&ctx, INDEXNOW_KEY) {
62 Some(key) => ([(header::CONTENT_TYPE, "text/plain; charset=utf-8")], key).into_response(),
63 None => StatusCode::NOT_FOUND.into_response(),
64 }
65 }),
66 )
67}
68
69/// Tells IndexNow-participating search engines (Bing, Yandex, Seznam, Naver...) that `urls` were added or changed.
70///
71/// One `POST` to [`INDEXNOW_ENDPOINT`](crate::seo::INDEXNOW_ENDPOINT)
72/// with the URLs (absolute, on `APP_URL`'s host, at most 10,000), the
73/// [`INDEXNOW_KEY`](crate::seo::INDEXNOW_KEY) and where to check it
74/// ([`indexnow_routes`]). Call it after publishing (a deploy script, a
75/// job): engines may ignore sites that submit unchanged pages often.
76///
77/// # Errors
78///
79/// [`Error::Internal`](crate::Error::Internal) when `APP_URL` or a valid
80/// `INDEXNOW_KEY` is missing, or IndexNow refuses the submission (it
81/// answers 200 or 202 when accepted).
82///
83/// # Examples
84///
85/// ```no_run
86/// use ocre::{Ctx, Result, seo};
87///
88/// async fn published(ctx: &Ctx, slug: &str) -> Result<()> {
89/// let url = ocre::mail::url(ctx, &format!("/blog/{slug}"))?;
90/// seo::submit_to_indexnow(ctx, &[url]).await
91/// }
92/// ```
93pub fn submit_to_indexnow(ctx: &Ctx, urls: &[String]) -> impl Future<Output = Result<()>> + Send + use<> {
94 let request = (|| {
95 let base =
96 var(ctx, APP_URL).ok_or_else(|| Error::internal("IndexNow needs APP_URL, the site's public origin"))?;
97 let key = var(ctx, INDEXNOW_KEY).filter(|key| valid_indexnow_key(key)).ok_or_else(|| {
98 Error::internal(
99 "IndexNow needs INDEXNOW_KEY: 8 to 128 letters, digits or `-` (e.g. from `ocre secret`), in worker.env",
100 )
101 })?;
102 let body =
103 indexnow_body(&base, &key, urls).ok_or_else(|| Error::internal("APP_URL is not an http(s) origin"))?;
104 Ok::<_, Error>(http::Request::post(INDEXNOW_ENDPOINT).json(&body))
105 })();
106 async move {
107 request?.send().await?.error_for_status()?;
108 Ok(())
109 }
110}