diff --git a/backend/public/README.md b/backend/public/README.md index 4aa3b72..cd37be1 100644 --- a/backend/public/README.md +++ b/backend/public/README.md @@ -18,3 +18,25 @@ For `public` to work properly, please make sure to first create the `.env` file, - `DATABASE_URL` - needed for connecting to Postgres - `REDIS_URL` - needed for connecting to the cache (Redis or Valkey) - `BASE_URI_WEB` - needed for connecting to the frontend user interface of the system to this service + +### Gemini + +Set `SERVE_APP=gemini` to run the existing Gemini TLS server on port 1965. +It uses `dev-cert.der` and `dev-key.der` in the working directory; database and +cache configuration is shared with HTTP mode. `BASE_URI_WEB` supplies links back +to the web site for RSS, the sitemap, contact forms, and posts without Gemtext. + +The capsule follows the web site's navigation and page sections: + +- `/`, `/contact`, `/health` +- `/posts`, `/posts/all`, `/posts/{id}` +- `/posts/featured`, `/posts/recent`, `/posts/popular`, `/posts/hot` +- `/authors`, `/authors/{id}`, `/authors/{id}/posts` +- `/projects` +- `/comments/index`, `/comments/post/{id}` + +Author and comment indexes accept `?page=1&limit=12` (maximum limit 100). +Author pages include a biography and paginated post links. Article pages render +`body_gemtext` as Gemtext, with author, publication date, and featured status; +articles without it link to the HTML version. Comments are read-only, with a +link to the web page for participation. diff --git a/backend/public/src/datasources/authors.rs b/backend/public/src/datasources/authors.rs index b756def..6c931e9 100644 --- a/backend/public/src/datasources/authors.rs +++ b/backend/public/src/datasources/authors.rs @@ -15,7 +15,7 @@ impl AuthorsDatasource { sqlx::query_as!( Author, "SELECT author_id, first_name, last_name, bio, image FROM authors ORDER BY created_at DESC LIMIT $1 OFFSET $2", - pagination.page, + pagination.limit, offset, ) .fetch_all(pool) diff --git a/backend/public/src/datasources/comments.rs b/backend/public/src/datasources/comments.rs index 1932dfa..b47bcd9 100644 --- a/backend/public/src/datasources/comments.rs +++ b/backend/public/src/datasources/comments.rs @@ -29,7 +29,7 @@ impl CommentsDatasource { pagination: Pagination, ) -> Result, sqlx::Error> { let offset: i64 = (pagination.page - 1) * pagination.limit; - sqlx::query_as!(Comment, "SELECT comment_id, name, body, created_at FROM comments ORDER BY created_at DESC LIMIT $1 OFFSET $2", pagination.page, offset) + sqlx::query_as!(Comment, "SELECT comment_id, name, body, created_at FROM comments ORDER BY created_at DESC LIMIT $1 OFFSET $2", pagination.limit, offset) .fetch_all(pool) .await } diff --git a/backend/public/src/main.rs b/backend/public/src/main.rs index 2f3c507..b48a4eb 100644 --- a/backend/public/src/main.rs +++ b/backend/public/src/main.rs @@ -1,5 +1,5 @@ use axum::Router; -use gemi::{EndpointExt, GeminiConfig, GeminiResponse, GeminiRouter, GeminiServer}; +use gemi::{EndpointExt, GeminiConfig, GeminiServer}; use cache::ClientLike; use config::config; use sqlx::postgres::PgPoolOptions; @@ -154,9 +154,7 @@ async fn main() { .expect("failed to install Rustls crypto provider"); let gemini_state = app_state.clone(); - let mut router = GeminiRouter::default(); - router.nest("/", routes::gemini::root::RootGeminiRoutes::routes().expect("Failed to construct Gemini root routes")); - router.nest("/posts", routes::gemini::posts::PostsGeminiRoutes::routes().expect("Failed to construct Gemini posts routes")); + let router = routes::gemini::routes().expect("Failed to construct Gemini routes"); let config = GeminiConfig::new("localhost"); let app = router.with_state(gemini_state); let server = GeminiServer::new(app, "dev-cert.der", "dev-key.der", config).unwrap(); diff --git a/backend/public/src/routes/gemini/authors.rs b/backend/public/src/routes/gemini/authors.rs new file mode 100644 index 0000000..fa02fd8 --- /dev/null +++ b/backend/public/src/routes/gemini/authors.rs @@ -0,0 +1,93 @@ +use super::format::{self, line, page}; +use crate::{datasources::authors::AuthorsDatasource, state::AppState}; +use gemi::{GeminiRequest, GeminiResponse, GeminiRouter, Params, State}; + +pub struct AuthorsGeminiRoutes; +impl AuthorsGeminiRoutes { + pub fn routes() -> gemi::Result> { + let mut router = GeminiRouter::default(); + router.add_route("/", Self::all)?; + router.add_route("/{id}", Self::one)?; + router.add_route("/{id}/posts", Self::one)?; + Ok(router) + } + + async fn all(State(state): State, request: GeminiRequest) -> GeminiResponse { + let p = match format::pagination(&request) { + Ok(p) => p, + Err(e) => return e, + }; + let pool = state.lock().await.database.clone(); + let result = AuthorsDatasource::get_all( + &pool, + crate::utils::pagination::Pagination { + page: p.page, + limit: p.limit, + }, + ) + .await; + match result { + Ok(authors) => { + let mut body = String::new(); + for author in &authors { + body += &format!( + "=> /authors/{} {} {}\n", + author.author_id, + line(&author.first_name), + line(&author.last_name) + ); + } + if authors.is_empty() { + body += "No authors found.\n"; + } + body += &format::navigation("/authors", &p, authors.len() as i64 == p.limit); + page("Authors", &body) + } + Err(e) => format::error(e), + } + } + + async fn one( + State(state): State, + params: Params, + request: GeminiRequest, + ) -> GeminiResponse { + let id = match format::id(¶ms) { + Ok(id) => id, + Err(e) => return e, + }; + let p = match format::pagination(&request) { + Ok(p) => p, + Err(e) => return e, + }; + let pool = state.lock().await.database.clone(); + let author = match AuthorsDatasource::get_one(&pool, id).await { + Ok(a) => a, + Err(e) => return format::error(e), + }; + match AuthorsDatasource::get_authors_posts( + &pool, + id, + crate::utils::pagination::Pagination { + page: p.page, + limit: p.limit, + }, + ) + .await + { + Ok((posts, total)) => { + let body = format!( + "{}\n\n## Posts\n{}{}", + line(author.bio.as_deref().unwrap_or("")), + format::posts(&posts), + format::navigation(&format!("/authors/{id}"), &p, p.page * p.limit < total) + ); + page( + &format!("{} {}", author.first_name, author.last_name), + &body, + ) + } + Err(e) => format::error(e), + } + } +} diff --git a/backend/public/src/routes/gemini/comments.rs b/backend/public/src/routes/gemini/comments.rs new file mode 100644 index 0000000..3d32b60 --- /dev/null +++ b/backend/public/src/routes/gemini/comments.rs @@ -0,0 +1,80 @@ +use super::format::{self, line, page}; +use crate::{ + datasources::comments::CommentsDatasource, models::comments::Comment, state::AppState, +}; +use gemi::{GeminiRequest, GeminiResponse, GeminiRouter, Params, State}; + +pub struct CommentsGeminiRoutes; +impl CommentsGeminiRoutes { + pub fn routes() -> gemi::Result> { + let mut router = GeminiRouter::default(); + router.add_route("/post/{id}", Self::post)?; + router.add_route("/index", Self::index)?; + Ok(router) + } + + async fn post(State(state): State, params: Params) -> GeminiResponse { + let id = match format::id(¶ms) { + Ok(id) => id, + Err(e) => return e, + }; + let pool = state.lock().await.database.clone(); + match CommentsDatasource::get_posts_comments(&pool, id).await { + Ok(comments) => page( + "Comments", + &format!( + "{}\n=> /posts/{id} Back to post\n=> {} Leave a comment on the web", + render(&comments), + format::web_url(&format!("/posts/{id}")) + ), + ), + Err(e) => format::error(e), + } + } + + async fn index(State(state): State, request: GeminiRequest) -> GeminiResponse { + let p = match format::pagination(&request) { + Ok(p) => p, + Err(e) => return e, + }; + let pool = state.lock().await.database.clone(); + let result = CommentsDatasource::get_index_comments( + &pool, + crate::utils::pagination::Pagination { + page: p.page, + limit: p.limit, + }, + ) + .await; + match result { + Ok(comments) => page( + "Recent comments", + &format!( + "{}{}", + render(&comments), + format::navigation("/comments/index", &p, comments.len() as i64 == p.limit) + ), + ), + Err(e) => format::error(e), + } + } +} + +fn render(comments: &[Comment]) -> String { + if comments.is_empty() { + return "No comments yet.\n".into(); + } + comments + .iter() + .map(|c| { + format!( + "## {}\n{}\n{}\n\n", + line(&c.name), + c.created_at + .map(|d| d.format("%B %d, %Y").to_string()) + .unwrap_or_default(), + line(&c.body) + ) + }) + .collect() +} diff --git a/backend/public/src/routes/gemini/format.rs b/backend/public/src/routes/gemini/format.rs new file mode 100644 index 0000000..c7addf5 --- /dev/null +++ b/backend/public/src/routes/gemini/format.rs @@ -0,0 +1,156 @@ +use crate::{models::posts::Post, utils::pagination::Pagination}; +use gemi::{GeminiRequest, GeminiResponse, Params}; + +pub fn line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +pub fn web_url(path: &str) -> String { + format!( + "{}{}", + std::env::var("BASE_URI_WEB") + .unwrap_or_else(|_| "https://wyattjmiller.com".into()) + .trim_end_matches('/'), + path + ) +} + +pub fn page(title: &str, body: &str) -> GeminiResponse { + format!("# {}\n\n=> / Home\n=> /posts Blog\n=> /projects Projects\n=> /contact Contact\n\n{}\n\n## Elsewhere\n=> /authors Authors\n=> {} RSS\n=> {} Sitemap\n=> mailto:wjmiller2016@gmail.com Email me\n\n© {} Miller Web Solutions. All Rights Reserved. Hosted by Akamai.\n", + line(title), body, web_url("/rss"), web_url("/sitemap"), chrono::Utc::now().format("%Y")).into() +} + +pub fn posts(posts: &[Post]) -> String { + if posts.is_empty() { + return "No posts yet.\n".into(); + } + posts + .iter() + .map(|p| { + let date = p + .publish_date + .or(p.created_at) + .map(|d| d.format("%B %d, %Y").to_string()) + .unwrap_or_default(); + format!( + "=> /posts/{} {}\n{} · {} {}\n\n", + p.post_id, + line(&p.title), + date, + line(p.first_name.as_deref().unwrap_or("")), + line(p.last_name.as_deref().unwrap_or("")) + ) + }) + .collect() +} + +pub fn id(params: &Params) -> Result { + params + .0 + .get("id") + .and_then(|s| s.parse::().ok()) + .filter(|id| *id > 0) + .ok_or_else(|| GeminiResponse::bad_request("Expected a positive numeric ID")) +} + +pub fn pagination(request: &GeminiRequest) -> Result { + let mut result = Pagination { page: 1, limit: 12 }; + for (key, value) in request.url.query_pairs() { + let target = match key.as_ref() { + "page" => &mut result.page, + "limit" => &mut result.limit, + _ => continue, + }; + *target = value + .parse::() + .ok() + .filter(|n| *n > 0) + .ok_or_else(|| { + GeminiResponse::bad_request("page and limit must be positive integers") + })?; + } + if result.limit > 100 || result.page.checked_mul(result.limit).is_none() { + return Err(GeminiResponse::bad_request( + "Pagination out of range (maximum limit: 100)", + )); + } + Ok(result) +} + +pub fn navigation(path: &str, p: &Pagination, has_next: bool) -> String { + let mut result = format!("\nPage {}\n", p.page); + if p.page > 1 { + result += &format!( + "=> {path}?page={}&limit={} Previous page\n", + p.page - 1, + p.limit + ); + } + if has_next { + result += &format!( + "=> {path}?page={}&limit={} Next page\n", + p.page + 1, + p.limit + ); + } + result +} + +pub fn error(error: sqlx::Error) -> GeminiResponse { + match error { + sqlx::Error::RowNotFound => GeminiResponse::not_found("Not found"), + error => { + tracing::error!(%error, "Gemini database request failed"); + GeminiResponse::temporary_failure("Unable to load this page. Please try again later.") + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(query: &str) -> GeminiRequest { + let url = format!("gemini://localhost/authors?{query}") + .parse() + .unwrap(); + GeminiRequest { + url, + path: "/authors".into(), + query: Some(query.into()), + } + } + + #[test] + fn pagination_rejects_invalid_and_overflowing_values() { + for query in [ + "page=0", + "page=-1", + "limit=101", + "limit=no", + "page=9223372036854775807&limit=100", + ] { + assert!(pagination(&request(query)).is_err(), "{query}"); + } + let p = pagination(&request("page=2&limit=10")).ok().unwrap(); + assert_eq!((p.page, p.limit), (2, 10)); + let links = navigation("/authors/1", &p, true); + assert!(links.contains("/authors/1?page=1&limit=10")); + assert!(links.contains("/authors/1?page=3&limit=10")); + } + + #[test] + fn metadata_cannot_inject_gemtext_lines() { + assert_eq!(line("Title\r\n=> /evil link"), "Title => /evil link"); + let response = page("Title\n# Injected", "Article body"); + let body = String::from_utf8(response.body).unwrap(); + assert!(body.starts_with("# Title # Injected\n")); + assert!(body.contains("=> /posts Blog\n")); + } + + #[test] + fn missing_rows_and_database_failures_have_distinct_statuses() { + assert_eq!(error(sqlx::Error::RowNotFound).status_code.to_u8(), 51); + assert_eq!(error(sqlx::Error::PoolClosed).status_code.to_u8(), 40); + } +} diff --git a/backend/public/src/routes/gemini/mod.rs b/backend/public/src/routes/gemini/mod.rs index 546b457..d6542ff 100644 --- a/backend/public/src/routes/gemini/mod.rs +++ b/backend/public/src/routes/gemini/mod.rs @@ -1,2 +1,27 @@ +pub mod authors; +pub mod comments; +mod format; pub mod posts; +pub mod projects; pub mod root; + +use crate::state::AppState; +use gemi::GeminiRouter; + +pub fn routes() -> gemi::Result> { + let mut router = GeminiRouter::default(); + router.nest("/", root::RootGeminiRoutes::routes()?)?; + router.nest("/posts", posts::PostsGeminiRoutes::routes()?)?; + router.nest("/authors", authors::AuthorsGeminiRoutes::routes()?)?; + router.nest("/projects", projects::ProjectsGeminiRoutes::routes()?)?; + router.nest("/comments", comments::CommentsGeminiRoutes::routes()?)?; + Ok(router) +} + +#[cfg(test)] +mod tests { + #[test] + fn routers_compose_without_conflicts() { + assert!(super::routes().is_ok()); + } +} diff --git a/backend/public/src/routes/gemini/posts.rs b/backend/public/src/routes/gemini/posts.rs index 7b42916..8ff59e4 100644 --- a/backend/public/src/routes/gemini/posts.rs +++ b/backend/public/src/routes/gemini/posts.rs @@ -1,23 +1,110 @@ -use crate::state::AppState; -use gemi::{GeminiResponse, GeminiRouter}; +use super::format::{self, page, posts}; +use crate::{datasources::posts::PostsDatasource, state::AppState}; +use gemi::{GeminiResponse, GeminiRouter, Params, State}; pub struct PostsGeminiRoutes; impl PostsGeminiRoutes { pub fn routes() -> gemi::Result> { let mut router = GeminiRouter::default(); - router.add_route("/", Self::root)?; - + router.add_route("/", Self::index)?; + router.add_route("/{id}", Self::get_one)?; + router.add_route("/all", Self::all)?; + router.add_route("/recent", Self::recent)?; + router.add_route("/featured", Self::featured)?; + router.add_route("/popular", Self::popular)?; + router.add_route("/hot", Self::hot)?; Ok(router) } - async fn root() -> impl Into { - "Hello, Gemini!" + async fn index(State(state): State) -> GeminiResponse { + let pool = state.lock().await.database.clone(); + let result = tokio::try_join!( + PostsDatasource::get_featured(&pool), + PostsDatasource::get_recent(&pool), + PostsDatasource::get_popular(&pool) + ); + match result { + Ok((featured, recent, popular)) => page("Blog", &format!("## Featured Posts\nIgnite the impossible\n\n{}## Recent Posts\nNow with 100% fresh perspective\n\n{}## Popular Posts\nContent may cause uncontrollable reading\n\n{}=> /posts/all All posts\n=> /posts/hot Hot posts", posts(&featured), posts(&recent), posts(&popular))), + Err(e) => format::error(e), + } } - async fn post_one() -> impl Into { - // make call to database - // format post to Gemtext - // return response - "" + async fn get_one(State(state): State, params: Params) -> GeminiResponse { + let id = match format::id(¶ms) { + Ok(id) => id, + Err(e) => return e, + }; + let pool = state.lock().await.database.clone(); + match PostsDatasource::get_one(&pool, id).await { + Ok(post) => { + let name = format::line(&format!( + "{} {}", + post.first_name.as_deref().unwrap_or(""), + post.last_name.as_deref().unwrap_or("") + )); + let mut body = String::new(); + if let Some(author_id) = post.author_id { + body += &format!("=> /authors/{author_id} By {name}\n"); + } + if let Some(date) = post.publish_date.or(post.created_at) { + body += &format!("Published {}\n", date.format("%B %d, %Y")); + } + if post.is_featured == Some(true) { + body += "Featured post\n"; + } + body += "\n"; + match post + .body_gemtext + .as_deref() + .filter(|s| !s.trim().is_empty()) + { + Some(gemtext) => body += gemtext, + None => { + body += &format!( + "This post is available on the web.\n=> {} Read this post", + format::web_url(&format!("/posts/{id}")) + ) + } + } + body += &format!("\n\n=> /comments/post/{id} Comments\n=> /posts Back to the blog"); + page(&post.title, &body) + } + Err(e) => format::error(e), + } + } + async fn all(State(state): State) -> GeminiResponse { + let pool = state.lock().await.database.clone(); + match PostsDatasource::get_all(&pool).await { + Ok(items) => page("All posts", &posts(&items)), + Err(e) => format::error(e), + } + } + async fn recent(State(state): State) -> GeminiResponse { + let pool = state.lock().await.database.clone(); + match PostsDatasource::get_recent(&pool).await { + Ok(items) => page("Recent Posts", &posts(&items)), + Err(e) => format::error(e), + } + } + async fn featured(State(state): State) -> GeminiResponse { + let pool = state.lock().await.database.clone(); + match PostsDatasource::get_featured(&pool).await { + Ok(items) => page("Featured Posts", &posts(&items)), + Err(e) => format::error(e), + } + } + async fn popular(State(state): State) -> GeminiResponse { + let pool = state.lock().await.database.clone(); + match PostsDatasource::get_popular(&pool).await { + Ok(items) => page("Popular Posts", &posts(&items)), + Err(e) => format::error(e), + } + } + async fn hot(State(state): State) -> GeminiResponse { + let pool = state.lock().await.database.clone(); + match PostsDatasource::get_hot(&pool).await { + Ok(items) => page("Hot Posts", &posts(&items)), + Err(e) => format::error(e), + } } } diff --git a/backend/public/src/routes/gemini/projects.rs b/backend/public/src/routes/gemini/projects.rs new file mode 100644 index 0000000..1577029 --- /dev/null +++ b/backend/public/src/routes/gemini/projects.rs @@ -0,0 +1,46 @@ +use super::format::{self, line, page}; +use crate::{datasources::projects::ProjectsDatasource, state::AppState}; +use gemi::{GeminiResponse, GeminiRouter, State}; + +pub struct ProjectsGeminiRoutes; +impl ProjectsGeminiRoutes { + pub fn routes() -> gemi::Result> { + let mut router = GeminiRouter::default(); + router.add_route("/", Self::all)?; + Ok(router) + } + + async fn all(State(state): State) -> GeminiResponse { + let pool = state.lock().await.database.clone(); + match ProjectsDatasource::get_all(&pool).await { + Ok(projects) => { + let mut body = String::from("Here's a collection of software and electronics projects I've been tinkering with during my free time - some are ongoing adventures, others are finished experiments!\n\n"); + if projects.is_empty() { + body += "No projects yet.\n"; + } + for project in projects { + body += &format!( + "## {}\n{}\nTechnology: {}\nStatus: {}\n", + line(&project.title), + line(&project.summary), + line(&project.tech), + if project.wip.unwrap_or(true) { + "Work in progress" + } else { + "Complete" + } + ); + if let Some(repo) = project + .repo + .filter(|r| !r.is_empty() && !r.chars().any(char::is_whitespace)) + { + body += &format!("=> {repo} Repository\n"); + } + body += "\n"; + } + page("Projects", &body) + } + Err(e) => format::error(e), + } + } +} diff --git a/backend/public/src/routes/gemini/root.rs b/backend/public/src/routes/gemini/root.rs index 3cb49e3..0876479 100644 --- a/backend/public/src/routes/gemini/root.rs +++ b/backend/public/src/routes/gemini/root.rs @@ -1,3 +1,4 @@ +use super::format::{page, web_url}; use crate::state::AppState; use gemi::{GeminiResponse, GeminiRouter}; @@ -6,11 +7,20 @@ impl RootGeminiRoutes { pub fn routes() -> gemi::Result> { let mut router = GeminiRouter::default(); router.add_route("/", Self::root)?; - + router.add_route("/contact", Self::contact)?; + router.add_route("/health", Self::health)?; Ok(router) } - async fn root() -> impl Into { - "Hello, Gemini!" + async fn root() -> GeminiResponse { + page("Heya! I'm Wyatt", "## Thanks for checking out this corner of the Internet!\n\nI design and develop software for developers, for end users, and everyone in between") + } + + async fn contact() -> GeminiResponse { + page("Contact", &format!("Got a question? Here to yell at me? Send me something!\n\n=> mailto:wjmiller2016@gmail.com Email me\n=> {} Contact form on the web", web_url("/contact"))) + } + + async fn health() -> GeminiResponse { + GeminiResponse::text("OK") } }