Adjustments to the Localization package dependency (#11)

This PR contains the work done to refactor the _Localization_ package and tidy the project a little bit.

To provider further details about the work:

* The `Negotiate` function was moved to the _Localization_ package.
* The `WebsiteRequestContext` context no longer resolves a default language at creation; it starts empty and relies on the `LocalizationMiddleware` middleware to fill it in.
* Fixed the local dependency path to Packages/Localization for the **Website** package as it only resolved inside the Xcode workspace before, breaking swift build, the Makefile, and the Docker build).
* Updated the `README` file to document language negotiation, the GET /health route, and the full middleware chain; doc comments across the moved/renamed types were brought back in sync with the code.

Reviewed-on: rock-n-code/loud-amsterdam#11
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-07-03 03:48:25 +00:00
committed by javier
parent 6c66ea74cc
commit b6f9633420
11 changed files with 207 additions and 51 deletions
@@ -1,43 +1,45 @@
import Foundation import Foundation
import Localization
/// Negotiates the best supported language for a request from its `Accept-Language` header. /// Negotiates the best supported language for a request from its `Accept-Language` header.
/// ///
/// Bound to the module's catalog languages via ``LanguageList``, an instance is invoked like a /// Bound to a bundle's catalog languages via ``LanguageList``, an instance is invoked like a
/// function through ``callAsFunction(forAcceptLanguage:)`` to resolve a header value to a /// function through ``callAsFunction(acceptLanguage:)`` to resolve a header value to a
/// supported language identifier, falling back to the default language. /// supported language identifier, falling back to the default language.
struct NegotiateLanguage { public struct Negotiate: Sendable {
// MARK: Properties // MARK: Properties
/// The supported languages and default language, derived from the module's String Catalog. /// The supported languages and default language, derived from the bundle's String Catalog.
private let list: LanguageList private let list: LanguageList
// MARK: Initializers // MARK: Initializers
/// Creates a language negotiator backed by the module's String Catalog. /// Creates a language negotiator backed by the given bundle's String Catalog.
init() { /// - Parameter bundle: the bundle whose String Catalog defines the supported languages.
self.list = .init(bundle: .module) public init(
bundle: Bundle
) {
self.list = .init(bundle: bundle)
} }
// MARK: Methods // MARK: Methods
/// Picks the best supported language for the given `Accept-Language` header value. /// Picks the best supported language for the given `Accept-Language` header value.
/// ///
/// Invoked by calling the instance directly, for example `negotiate(forAcceptLanguage: header)`. /// Invoked by calling the instance directly, for example `negotiate(acceptLanguage: header)`.
/// The header is split into its language tags (dropping any `q` weights), then matched against /// The header is split into its language tags (dropping any `q` weights), then matched against
/// the supported languages with `Bundle.preferredLocalizations(from:forPreferences:)`. When the /// the supported languages with `Bundle.preferredLocalizations(from:forPreferences:)`. When the
/// header is absent or matches nothing, the default language is returned. /// header is absent or matches nothing, the default language is returned.
/// - Parameter acceptLanguage: the raw `Accept-Language` header value, if any. /// - Parameter acceptLanguage: the raw `Accept-Language` header value, if any.
/// - Returns: the identifier of the supported language to serve. /// - Returns: the identifier of the supported language to serve.
func callAsFunction( public func callAsFunction(
forAcceptLanguage acceptLanguage: String? acceptLanguage language: String?
) -> String { ) -> String {
guard let acceptLanguage else { guard let language else {
return list.default return list.default
} }
let tags = tags(from: acceptLanguage) let tags = tags(from: language)
guard !tags.isEmpty else { guard !tags.isEmpty else {
return list.default return list.default
@@ -56,7 +58,7 @@ struct NegotiateLanguage {
// MARK: - Helpers // MARK: - Helpers
private extension NegotiateLanguage { private extension Negotiate {
// MARK: Methods // MARK: Methods
@@ -71,15 +73,29 @@ private extension NegotiateLanguage {
from acceptLanguage: String from acceptLanguage: String
) -> [String] { ) -> [String] {
acceptLanguage acceptLanguage
.split(separator: ",") .split(separator: .Separator.comma)
.map { entry in .map { entry in
entry entry
.split(separator: ";") .split(separator: .Separator.semicolon)
.first .first
.map(String.init)? .map(String.init)?
.trimmingCharacters(in: .whitespaces) ?? "" .trimmingCharacters(in: .whitespaces)
?? .empty
} }
.filter { !$0.isEmpty } .filter { !$0.isEmpty }
} }
} }
// MARK: - Constants
private extension Character {
enum Separator {
static let comma: Character = ","
static let semicolon: Character = ";"
}
}
private extension String {
static let empty: String = ""
}
@@ -0,0 +1,78 @@
import Foundation
import Testing
@testable import Localization
@Suite("Negotiate method")
struct NegotiateTests {
// MARK: Constants
private let negotiate = Negotiate(bundle: .module)
// MARK: Functional tests
@Test
func `matches an exact language tag`() {
let language = negotiate(acceptLanguage: "de")
#expect(language == "de")
}
@Test
func `matches a regional language tag`() {
let language = negotiate(acceptLanguage: "de-AT")
#expect(language == "de")
}
@Test
func `respects the header order of preference`() {
let language = negotiate(acceptLanguage: "de, en")
#expect(language == "de")
}
@Test
func `strips quality weights from the language tags`() {
let language = negotiate(acceptLanguage: "de;q=0.5, en;q=0.9")
#expect(language == "de")
}
@Test
func `trims whitespace around the language tags`() {
let language = negotiate(acceptLanguage: " de , en ")
#expect(language == "de")
}
@Test
func `falls back to the default for an unsupported language`() {
let language = negotiate(acceptLanguage: "fr")
#expect(language == "en")
}
@Test
func `falls back to the default for a missing header`() {
let language = negotiate(acceptLanguage: nil)
#expect(language == "en")
}
@Test
func `falls back to the default for an empty header`() {
let language = negotiate(acceptLanguage: "")
#expect(language == "en")
}
@Test
func `falls back to the default for a header without language tags`() {
let language = negotiate(acceptLanguage: " , ;q=0.5,")
#expect(language == "en")
}
}
@@ -26,13 +26,8 @@
buildConfiguration = "Debug" buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"> shouldUseLaunchSchemeArgsEnv = "YES"
<TestPlans> shouldAutocreateTestPlan = "YES">
<TestPlanReference
reference = "container:Website.xctestplan"
default = "YES">
</TestPlanReference>
</TestPlans>
<Testables> <Testables>
<TestableReference <TestableReference
skipped = "NO"> skipped = "NO">
@@ -50,8 +45,7 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0" launchStyle = "0"
useCustomWorkingDirectory = "YES" useCustomWorkingDirectory = "NO"
customWorkingDirectory = "/Users/logan/Documents/Development/Platforms/Ro&#x308;ck+Co&#x308;de/Loud/Services/Website"
ignoresPersistentStateOnLaunch = "NO" ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES" debugDocumentVersioning = "YES"
debugServiceExtension = "internal" debugServiceExtension = "internal"
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2700"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "WebsiteCoreTests"
BuildableName = "WebsiteCoreTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES"
queueDebuggingEnabled = "No">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
+1 -1
View File
@@ -21,7 +21,7 @@ let package = Package(
], ],
dependencies: [ dependencies: [
.package( .package(
path: "../Packages/Localization" path: "../../Packages/Localization"
), ),
.package( .package(
url: "https://github.com/elementary-swift/elementary.git", url: "https://github.com/elementary-swift/elementary.git",
+11 -4
View File
@@ -3,9 +3,11 @@ The **Loud** public website service — a [Hummingbird](https://github.com/hummi
## Overview ## Overview
The service: The service:
- Serves the landing page at `GET /` (rendered once with [Elementary](https://github.com/elementary-swift/elementary) and cached). - Serves the landing page at `GET /` (rendered once per supported language with [Elementary](https://github.com/elementary-swift/elementary) and cached).
- Negotiates each request's language from its `Accept-Language` header against the languages in the `WebsiteCore` String Catalog, falling back to the default (`en`); pages are served from the per-language cache with `Content-Language` and `Vary: Accept-Language` headers.
- Answers health checks at `GET /health` with a static JSON payload.
- Serves static files (CSS, JS, icons, manifest, `robots.txt`) from `Resources/Static` via Hummingbird's `FileMiddleware`, tagged with media-type-specific `Cache-Control`. - Serves static files (CSS, JS, icons, manifest, `robots.txt`) from `Resources/Static` via Hummingbird's `FileMiddleware`, tagged with media-type-specific `Cache-Control`.
- Returns a custom HTML 404 page for any request that matches neither a route nor a static file. - Returns a custom HTML 404 page, localized like the landing page, for any request that matches neither a route nor a static file.
- Compresses responses (gzip/deflate) above a configurable size when the client advertises support. - Compresses responses (gzip/deflate) above a configurable size when the client advertises support.
- Stamps a hardened set of security headers on every response. - Stamps a hardened set of security headers on every response.
@@ -20,14 +22,18 @@ Two SwiftPM targets:
| `Website` | executable | `Sources/App` | Entry point: reads configuration, builds and runs the application. | | `Website` | executable | `Sources/App` | Entry point: reads configuration, builds and runs the application. |
| `WebsiteCore` | library | `Sources/Library` | Controllers, middlewares, pages, cached responses, and configuration helpers. | | `WebsiteCore` | library | `Sources/Library` | Controllers, middlewares, pages, cached responses, and configuration helpers. |
`WebsiteCore` also depends on the local `Localization` package (`Packages/Localization`), which provides the `Localize` and `Negotiate` helpers and the `LanguageList` of catalog languages.
Requests pass through the middleware chain in this order (outermost first), then reach the routes: Requests pass through the middleware chain in this order (outermost first), then reach the routes:
``` ```
LogRequestsMiddleware LogRequestsMiddleware
→ SecurityHeadersMiddleware (security headers on every response) → SecurityHeadersMiddleware (security headers on every response)
→ ResponseCompressionMiddleware (gzip/deflate above the size threshold) → ResponseCompressionMiddleware (gzip/deflate above the size threshold)
NotFoundMiddleware (renders the 404 page on .notFound) LocalizationMiddleware (negotiates the request's language)
→ NotFoundMiddleware (renders the localized 404 page on .notFound)
→ FileMiddleware (serves Resources/Static) → FileMiddleware (serves Resources/Static)
RootController (GET / → landing page) RootController (GET / → landing page)
HealthController (GET /health → health check)
``` ```
## Configuration ## Configuration
@@ -92,7 +98,7 @@ swift run Website # binds to Hummingbird's default 127.0.0.1:8080
swift run Website --http-host 0.0.0.0 --http-port 9000 --log-level debug swift run Website --http-host 0.0.0.0 --http-port 9000 --log-level debug
``` ```
Or via the Makefile / Docker (uses `docker-compose.override.yml`, which builds from source and sets`LOG_LEVEL=debug`: Or via the Makefile / Docker (uses `docker-compose.override.yml`, which builds from source and sets `LOG_LEVEL=debug`):
```sh ```sh
make pkg-build # swift build make pkg-build # swift build
make img-mount # docker compose up --build --detach make img-mount # docker compose up --build --detach
@@ -100,6 +106,7 @@ make img-unmount # docker compose down + remove the local image
``` ```
`make help` lists every available target. `make help` lists every available target.
## Testing ## Testing
```sh ```sh
make pkg-test make pkg-test
@@ -10,7 +10,7 @@ import NIOCore
/// pages whose markup never changes between requests, such as the landing page and the not-found /// pages whose markup never changes between requests, such as the landing page and the not-found
/// page, avoiding a per-request Elementary render on hot paths. /// page, avoiding a per-request Elementary render on hot paths.
/// ///
/// ``LocalizedHTMLResponses`` builds on this type, caching one instance per supported language. /// ``LocalizedHTMLCollectionResponse`` builds on this type, caching one instance per supported language.
/// ///
/// The body is written as an unsized stream (no `Content-Length`), mirroring `HTMLResponse`, so the /// 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. /// response-compression middleware downstream treats it exactly as it would a freshly rendered page.
@@ -1,5 +1,4 @@
import Hummingbird import Hummingbird
import Localization
/// A request context that carries the language negotiated for the request. /// A request context that carries the language negotiated for the request.
/// ///
@@ -34,9 +33,17 @@ public struct WebsiteRequestContext: LocalizedRequestContext {
/// Creates a request context for the given source. /// Creates a request context for the given source.
/// - Parameter source: the source the context is initialized from. /// - Parameter source: the source the context is initialized from.
public init(source: Source) { public init(
source: Source,
) {
self.coreContext = .init(source: source) self.coreContext = .init(source: source)
self.language = LanguageList(bundle: .module).default self.language = .empty
} }
} }
// MARK: - Constants
private extension String {
static let empty = ""
}
@@ -2,9 +2,9 @@ import HTTPTypes
extension HTTPField.Name { extension HTTPField.Name {
/// The `Permissions-Policy` field name (not provided as a standard `HTTPField.Name`). /// The `Permissions-Policy` field name (not provided as a standard `HTTPField.Name`).
static let permissionsPolicy = Self("Permissions-Policy")! public static let permissionsPolicy = Self("Permissions-Policy")!
/// The `Referrer-Policy` field name (not provided as a standard `HTTPField.Name`). /// The `Referrer-Policy` field name (not provided as a standard `HTTPField.Name`).
static let referrerPolicy = Self("Referrer-Policy")! public static let referrerPolicy = Self("Referrer-Policy")!
/// The `X-Frame-Options` field name (not provided as a standard `HTTPField.Name`). /// The `X-Frame-Options` field name (not provided as a standard `HTTPField.Name`).
static let frameOptions = Self("X-Frame-Options")! public static let frameOptions = Self("X-Frame-Options")!
} }
@@ -15,13 +15,13 @@ public struct LocalizationMiddleware<Context: LocalizedRequestContext> {
// MARK: Properties // MARK: Properties
/// Negotiates the request's language from its `Accept-Language` header. /// Negotiates the request's language from its `Accept-Language` header.
private let negotiate: NegotiateLanguage private let negotiate: Negotiate
// MARK: Initializers // MARK: Initializers
/// Creates a localization middleware. /// Creates a localization middleware that negotiates against the module's String Catalog languages.
public init() { public init() {
self.negotiate = .init() self.negotiate = .init(bundle: .module)
} }
} }
@@ -47,7 +47,7 @@ extension LocalizationMiddleware: RouterMiddleware {
var context = context var context = context
context.language = negotiate( context.language = negotiate(
forAcceptLanguage: request.headers[.acceptLanguage] acceptLanguage: request.headers[.acceptLanguage]
) )
return try await next(request, context) return try await next(request, context)