Static file caching for the Website service (#6)

This PR contains the work done to add cache-control headers to static file responses by configuring the `FileMiddleware` middleware to tag served static files with *Cache-Control* directives, tuned per media type.

To provide further details about the work done:

* Added a cache control that sets per-type policies: text assets (CSS/JS) get public, max-age, must-revalidate; images get public, max-age; everything else gets a default public, max-age.
* Files stay validated via `ETag/Last-Modified` header.
* Made the max-age values configurable, with defaults, via new cache constants.

Reviewed-on: rock-n-code/loud-amsterdam#6
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 05:49:32 +00:00
committed by javier
parent a621ada0bf
commit 6c1a0f713b
6 changed files with 94 additions and 6 deletions
+1 -1
View File
@@ -39,7 +39,7 @@
"NeverForceUnwrap": true, "NeverForceUnwrap": true,
"NeverUseForceTry": true, "NeverUseForceTry": true,
"NeverUseImplicitlyUnwrappedOptionals": true, "NeverUseImplicitlyUnwrappedOptionals": true,
"NoAccessLevelOnExtensionDeclaration": true, "NoAccessLevelOnExtensionDeclaration": false,
"NoAssignmentInExpressions": true, "NoAssignmentInExpressions": true,
"NoBlockComments": true, "NoBlockComments": true,
"NoCasesWithOnlyFallthrough": true, "NoCasesWithOnlyFallthrough": true,
+47 -3
View File
@@ -12,6 +12,20 @@ import WebsiteCore
func application( func application(
reader: ConfigReader reader: ConfigReader
) async -> some ApplicationProtocol { ) async -> some ApplicationProtocol {
let cacheControl = cacheControl(
textMaxAge: reader.int(
forKey: .Cache.maxAgeText,
default: .Cache.maxAgeText
),
imageMaxAge: reader.int(
forKey: .Cache.maxAgeImage,
default: .Cache.maxAgeImage
),
defaultMaxAge: reader.int(
forKey: .Cache.maxAgeDefault,
default: .Cache.maxAgeDefault
)
)
let logLevel = reader.string( let logLevel = reader.string(
forKey: .Log.level, forKey: .Log.level,
as: Logger.Level.self, as: Logger.Level.self,
@@ -29,6 +43,7 @@ func application(
return Application( return Application(
router: router( router: router(
staticFilesPath: staticFilesPath, staticFilesPath: staticFilesPath,
cacheControl: cacheControl,
logLevel: logLevel logLevel: logLevel
), ),
configuration: ApplicationConfiguration( configuration: ApplicationConfiguration(
@@ -46,6 +61,29 @@ func application(
// Request context used by application // Request context used by application
private typealias AppRequestContext = BasicRequestContext private typealias AppRequestContext = BasicRequestContext
/// Builds the cache-control policy applied to the served static files.
///
/// Static files are public and validated by `FileMiddleware` through their `ETag` and
/// `Last-Modified` headers, so each media type is given a `max-age` after which the browser
/// revalidates. Text-based assets (CSS, JavaScript) are additionally marked `must-revalidate`
/// since they change between deployments while keeping their filenames.
/// - Parameters:
/// - textMaxAge: the max-age, in seconds, applied to text-based static files (CSS, JavaScript, plain text).
/// - imageMaxAge: the max-age, in seconds, applied to image static files (ICO, PNG, SVG).
/// - defaultMaxAge: the max-age, in seconds, applied to all other static files (e.g. the web manifest).
/// - Returns: the configured cache-control policy.
private func cacheControl(
textMaxAge: Int,
imageMaxAge: Int,
defaultMaxAge: Int
) -> CacheControl {
.init([
(.text, [.public, .maxAge(textMaxAge), .mustRevalidate]),
(.image, [.public, .maxAge(imageMaxAge)]),
(.init(type: .any), [.public, .maxAge(defaultMaxAge)]),
])
}
/// Builds the application's logger. /// Builds the application's logger.
/// - Parameters: /// - Parameters:
/// - serverName: the label applied to the logger. /// - serverName: the label applied to the logger.
@@ -65,14 +103,17 @@ private func logger(
/// Builds the application's router. /// Builds the application's router.
/// ///
/// Registers the request-logging middleware, the not-found middleware that serves the error /// Registers the request-logging middleware, the not-found middleware that serves the error
/// page, and the static file middleware that serves the contents of `staticFilesPath`, then /// page, and the static file middleware that serves the contents of `staticFilesPath` (tagging
/// adds the `RootController` routes that render the landing page. /// responses with the given `cacheControl` directives), then adds the `RootController` routes
/// that render the landing page.
/// - Parameters: /// - Parameters:
/// - staticFilesPath: the folder, relative to the working directory, the static files are served from. /// - staticFilesPath: the folder, relative to the working directory, the static files are served from.
/// - cacheControl: the cache-control directives applied to the served static files.
/// - logLevel: the level the request-logging middleware logs at. /// - logLevel: the level the request-logging middleware logs at.
/// - Returns: the configured router. /// - Returns: the configured router.
private func router( private func router(
staticFilesPath: String, staticFilesPath: String,
cacheControl: CacheControl,
logLevel: Logger.Level logLevel: Logger.Level
) -> Router<AppRequestContext> { ) -> Router<AppRequestContext> {
let router = Router(context: AppRequestContext.self) let router = Router(context: AppRequestContext.self)
@@ -80,7 +121,10 @@ private func router(
router.addMiddleware { router.addMiddleware {
LogRequestsMiddleware(logLevel) LogRequestsMiddleware(logLevel)
NotFoundMiddleware() NotFoundMiddleware()
FileMiddleware(staticFilesPath) FileMiddleware(
staticFilesPath,
cacheControl: cacheControl
)
} }
router.addRoutes(RootController<AppRequestContext>().routes) router.addRoutes(RootController<AppRequestContext>().routes)
@@ -1,6 +1,15 @@
import Configuration import Configuration
extension AbsoluteConfigKey { extension AbsoluteConfigKey {
/// A namespace for the static files cache configuration keys, as absolute keys.
public enum Cache {
/// The absolute configuration key for the max-age, in seconds, applied to text-based static files.
public static let maxAgeText: AbsoluteConfigKey = .init(.Cache.maxAgeText)
/// The absolute configuration key for the max-age, in seconds, applied to image static files.
public static let maxAgeImage: AbsoluteConfigKey = .init(.Cache.maxAgeImage)
/// The absolute configuration key for the max-age, in seconds, applied to all other static files.
public static let maxAgeDefault: AbsoluteConfigKey = .init(.Cache.maxAgeDefault)
}
/// A namespace for the HTTP server configuration keys, as absolute keys. /// A namespace for the HTTP server configuration keys, as absolute keys.
public enum HTTP { public enum HTTP {
/// The absolute configuration key for the host the server binds to. /// The absolute configuration key for the host the server binds to.
@@ -1,6 +1,15 @@
import Configuration import Configuration
extension ConfigKey { extension ConfigKey {
/// A namespace for the static files cache configuration keys.
public enum Cache {
/// The configuration key for the max-age, in seconds, applied to text-based static files (CSS, JavaScript, plain text).
public static let maxAgeText: ConfigKey = "cache.maxAge.text"
/// The configuration key for the max-age, in seconds, applied to image static files (ICO, PNG, SVG).
public static let maxAgeImage: ConfigKey = "cache.maxAge.image"
/// The configuration key for the max-age, in seconds, applied to all other static files (e.g. the web manifest).
public static let maxAgeDefault: ConfigKey = "cache.maxAge.default"
}
/// A namespace for the HTTP server configuration keys. /// A namespace for the HTTP server configuration keys.
public enum HTTP { public enum HTTP {
/// The configuration key for the host the server binds to. /// The configuration key for the host the server binds to.
@@ -0,0 +1,11 @@
extension Int {
/// A namespace for the cache's default configuration values.
public enum Cache {
/// The default max-age, in seconds, applied to text-based static files (1 hour).
public static let maxAgeText = 3_600
/// The default max-age, in seconds, applied to image static files (1 week).
public static let maxAgeImage = 604_800
/// The default max-age, in seconds, applied to all other static files (1 day).
public static let maxAgeDefault = 86_400
}
}
+17 -2
View File
@@ -13,6 +13,12 @@ import Testing
struct AppTests { struct AppTests {
// MARK: Constants // MARK: Constants
private let textExtensions: [StaticFile.Extension] = [
.css,
.js,
.txt
]
// Absolute path to the package's "Resources/Static" folder, derived from this // Absolute path to the package's "Resources/Static" folder, derived from this
// file's location so the static files resolve regardless of the working directory. // file's location so the static files resolve regardless of the working directory.
@@ -35,7 +41,7 @@ struct AppTests {
let body = String(buffer: response.body) let body = String(buffer: response.body)
#expect(response.status == .ok) #expect(response.status == .ok)
#expect(response.headers[.contentType]?.hasPrefix("text/html") == true) #expect(response.headers[.contentType] == "text/html; charset=utf-8")
#expect(body.contains("Hello world!")) #expect(body.contains("Hello world!"))
} }
} }
@@ -52,6 +58,15 @@ struct AppTests {
) { response in ) { response in
#expect(response.status == .ok) #expect(response.status == .ok)
#expect(response.headers[.contentType] == file.contentType) #expect(response.headers[.contentType] == file.contentType)
let cacheControl = try #require(response.headers[.cacheControl])
#expect(cacheControl.contains("public") == true)
#expect(cacheControl.contains("max-age=") == true)
if textExtensions.contains(file.fileExtension) {
#expect(cacheControl.contains("must-revalidate") == true)
}
} }
} }
} }
@@ -66,7 +81,7 @@ struct AppTests {
let body = String(buffer: response.body) let body = String(buffer: response.body)
#expect(response.status == .notFound) #expect(response.status == .notFound)
#expect(response.headers[.contentType]?.hasPrefix("text/html") == true) #expect(response.headers[.contentType] == "text/html; charset=utf-8")
#expect(body.contains("Page Not Found")) #expect(body.contains("Page Not Found"))
} }
} }