Optimizations for the Website service (#9)

This PR contains the work done to provide optimizations to the current service, such as a health-check endpoint, pre-renders static HTML pages, and hardens the error page's CSP.

To provide further details about the work:

* Added the `HealthController` controller serving GET `/health` with a static JSON payload.
* Added the `CachedHTMLResponse` response, which renders a static HTMLDocument to bytes once and reuses them per request (no Content-Length, so responses stay compressible).
* Integrated the response into the `RootController` and the  `NotFoundMiddleware` middleware to avoid re-rendering on hot paths.
* Added a `RouterMethods.addRoutes(_:)` extension and switched the router in App+build to use it.
* Moved the inline style from the `ErrorPage` page into a dedicated style file so the CSP needs no inline-style escape hatch.
* Fixed the `IndexPage` page path inconsistencies.
* Written the `README` file.

Reviewed-on: rock-n-code/loud-amsterdam#9
Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit is contained in:
2026-06-28 14:18:04 +00:00
committed by javier
parent 6b6389cb0f
commit 847058d642
16 changed files with 508 additions and 95 deletions
@@ -5,6 +5,8 @@
enum StaticFile: CaseIterable, Sendable {
/// The `js/app.js` script.
case appJS
/// The `css/error.css` stylesheet for the not-found page.
case errorCSS
/// The `favicon.ico` icon.
case faviconICO
/// The `icon.png` icon.
@@ -63,7 +65,8 @@ extension StaticFile {
/// The file's extension.
var fileExtension: Extension {
switch self {
case .styleCSS: .css
case .errorCSS,
.styleCSS: .css
case .appJS: .js
case .faviconICO: .ico
case .iconPNG: .png
@@ -77,6 +80,7 @@ extension StaticFile {
var fileName: String {
switch self {
case .appJS: "app"
case .errorCSS: "error"
case .faviconICO: "favicon"
case .iconPNG,
.iconSVG: "icon"
@@ -102,7 +106,7 @@ extension StaticFile {
///
/// - Parameter basePath: the directory the static files are served from.
/// - Returns: the path to the file, relative to the `basePath` path.
public func path(
func path(
relativeTo basePath: String
) -> String {
guard !basePath.isEmpty else {
@@ -124,7 +128,8 @@ private extension StaticFile {
var subdirectory: String? {
switch self {
case .appJS: "js"
case .styleCSS: "css"
case .errorCSS,
.styleCSS: "css"
default: nil
}
}
@@ -11,14 +11,17 @@ struct ErrorPage: HTMLDocument, Sendable {
p { "Sorry, but the page you were trying to view does not exist." }
}
/// The metadata and inline styles placed in the document head.
/// The metadata and stylesheet link placed in the document head.
var head: some HTML {
meta(.charset(.utf8))
meta(
.name(.viewport),
.content("width=device-width, initial-scale=1")
)
style { Self.styles }
link(
.rel(.stylesheet),
.href("/css/error.css")
)
}
/// The document language.
@@ -28,52 +31,3 @@ struct ErrorPage: HTMLDocument, Sendable {
var title: String { "Page Not Found" }
}
// MARK: - Constants
private extension ErrorPage {
/// The inline CSS applied to the page.
static let styles = """
* {
line-height: 1.2;
margin: 0;
}
html {
color: #888;
display: table;
font-family: sans-serif;
height: 100%;
text-align: center;
width: 100%;
}
body {
display: table-cell;
vertical-align: middle;
margin: 2em auto;
}
h1 {
color: #555;
font-size: 2em;
font-weight: 400;
}
p {
margin: 0 auto;
width: 280px;
}
@media only screen and (max-width: 280px) {
body, p {
width: 95%;
}
h1 {
font-size: 1.5em;
margin: 0 0 0.3em;
}
}
"""
}
@@ -8,7 +8,7 @@ struct IndexPage: HTMLDocument, Sendable {
/// The page's content.
var body: some HTML {
p { "Hello world! This is HTML5 Boilerplate." }
script(.src("js/app.js")) {}
script(.src("/js/app.js")) {}
}
/// The metadata, stylesheet, icon, and manifest links placed in the document head.
@@ -20,7 +20,7 @@ struct IndexPage: HTMLDocument, Sendable {
)
link(
.rel(.stylesheet),
.href("css/style.css")
.href("/css/style.css")
)
link(
.rel(.icon),
@@ -40,11 +40,11 @@ struct IndexPage: HTMLDocument, Sendable {
)
link(
.rel("apple-touch-icon"),
.href("icon.png")
.href("/icon.png")
)
link(
.rel("manifest"),
.href("site.webmanifest")
.href("/site.webmanifest")
)
meta(
.name("theme-color"),
@@ -58,6 +58,8 @@ struct IndexPage: HTMLDocument, Sendable {
}
/// The document title.
var title: String { "" }
var title: String {
"Index page"
}
}
@@ -0,0 +1,54 @@
import Elementary
import Hummingbird
import NIOCore
/// A pre-rendered HTTP response for a fully static HTML page.
///
/// The document is rendered to bytes once, at initialization, and every ``response()`` reuses those
/// bytes instead of re-rendering. This suits pages whose markup never changes between requests the
/// landing page and the not-found page avoiding a per-request Elementary render on hot paths.
///
/// The body is written as an unsized stream (no `Content-Length`), mirroring `HTMLResponse`, so the
/// response-compression middleware downstream treats it exactly as it would a freshly rendered page.
struct CachedHTMLResponse: Sendable {
// MARK: Properties
/// The status applied to every response.
private let status: HTTPResponse.Status
/// The page rendered to bytes once.
private let buffer: ByteBuffer
// MARK: Initializers
/// Renders the given document to bytes once.
/// - Parameters:
/// - status: the status applied to every response. Defaults to `.ok`.
/// - document: the static HTML document to render and cache.
init(
status: HTTPResponse.Status = .ok,
_ document: some HTMLDocument
) {
self.status = status
self.buffer = ByteBuffer(string: document.render())
}
// MARK: Methods
/// Builds a response from the cached, pre-rendered bytes.
///
/// Mirrors the `text/html; charset=utf-8` content type `HTMLResponse` produces, and leaves the
/// `Content-Length` unset so small pages remain eligible for compression.
/// - Returns: the response carrying the cached HTML body.
func response() -> Response {
Response(
status: status,
headers: [.contentType: "text/html; charset=utf-8"],
body: .init { [buffer] writer in
try await writer.write(buffer)
try await writer.finish(nil)
}
)
}
}