Files
amiibo-service/Sources/AmiiboService/Public/Clients/AmiiboLiveClient.swift
T
javierandjavier 0c41e5d4ce Several fixes and optimizations all over the library (#28)
This PR contains the work done to cleans up the library after the Swift 6.2 migration: drops the legacy conditional-compilation paths, hardens the OpenAPI specification, removes boilerplate from the live client, and makes the live test suite resilient to changes in the upstream service data.

* Swift 6.2 baseline
  * Adopted swift-tools-version: 6.2, which allowed removing every #if swift(>=6.0) / #if swift(>=6.2) branch and natural-language test names are now the only code paths.
  * `AmiiboClient` client now refines `Sendable`, and both `AmiiboLiveClient` and `AmiiboService` conform to it, so instances can be shared across concurrency domains.

* Live client
  * Extracted a generic `perform(_:)` helper that wraps every generated API call and funnels transport errors through the existing error mapper — replaces six repeated do/catch blocks and lets the private fetch* methods use typed throws end-to-end.
  * Added the internal `KeyNamePayload` protocol and a generic makeModels(from:), collapsing the four near-identical mapping/sorting blocks for amiibo series, types, game characters and game series into one.
  * The server URL is now resolved once into a static let constant instead of on every initialization.
  * Improved error mapping: URLError.cancelled → .cancelled, .cannotParseResponse → .decoding, and .dataNotAllowed, .internationalRoamingOff, .secureConnectionFailed now map to .notAvailable.
  * Simplified the Amiibo.Platform initializer ([Amiibo+Platform.swift](vscode-webview://1m6rk4uhpaukb4hrbp3j54p77iq693fq2ql7o9oup2pca1omf7f6/Sources/AmiiboService/Public/Models/Amiibo/Amiibo+Platform.swift)) using optional chaining and ?? [] instead of nested guards and immediately-invoked closures.
  * Set the en_US_POSIX locale on both fixed-format date formatters so the user's locale or 12/24-hour setting can no longer break parsing.

* OpenAPI specification
  * Replaced the shared Tuple schema with explicit per-type schemas (AmiiboSeries, AmiiboType, GameCharacter, GameSeries), so the generated code exposes real properties instead of allOf wrappers with .value1 accessors.
  * Extracted named list schemas (AmiiboList, AmiiboSeriesList, …) for the wrapper payloads, which turns the generated .case2 enum cases into readable .AmiiboSeriesList cases.
  * Added validation patterns and length bounds to the id, head, tail and key query parameters, and collapsed the redundant pattern/minLength/maxLength triplets on head/tail into ^[0-9a-fA-F]{8}$.
  * Extracted the shared InternalServerError response, replacing the five inline 500 descriptions.
  * Documented the two non-standard date/time decoding behaviours (date-only strings for release dates, offset-less timestamps for lastUpdated) and why the optional amiibo wrapper property must stay optional.
  * Corrected the info.version value from v1.0.0 to 1.0.0.

* ⚠️ Breaking changes
  *  Minimum Swift version raised from 5.10 to 6.2.
  *  `AmiiboServiceError.unknown` now carries a String description of the underlying error.
  *  `AmiiboClient` requires Sendable conformance, so existing custom mock clients must be Sendable.

Reviewed-on: #28
Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
2026-07-26 09:56:32 +00:00

404 lines
16 KiB
Swift

// ===----------------------------------------------------------------------===
//
// This source file is part of the Amiibo Service open source project
//
// Copyright (c) 2026 Röck+Cöde VoF. and the Amiibo Service project authors
// Licensed under Apache license v2.0
//
// See LICENSE for license information
// See CONTRIBUTORS for the list of Amiibo Service project authors
//
// SPDX-License-Identifier: Apache-2.0
//
// ===----------------------------------------------------------------------===
import Foundation
import OpenAPIRuntime
import OpenAPIURLSession
/// A type that implements a live client to the [Amiibo API](https://www.amiiboapi.org) online service.
///
/// This client maps any transport error or unsuccessful HTTP response to an ``AmiiboServiceError`` error, and sorts the items of the list responses in ascending order by identifier or key.
public struct AmiiboLiveClient: Sendable {
// MARK: Constants
/// The base URL of the live service, resolved once from the server defined in the OpenAPI specification.
///
/// The validity of the URL is guaranteed by the bundled `openapi.yaml` specification and enforced by a unit test, so resolution is not expected to fail at runtime.
static let serverURL: URL = {
guard let url = try? Servers.Server1.url() else {
fatalError("The server URL defined in the OpenAPI specification could not be resolved. Verify that the 'openapi.yaml' server definition is valid.")
}
return url
}()
// MARK: Properties
/// A client generated by the OpenAPI Runtime library to perform API calls.
private let client: Client
// MARK: Initializers
/// Initializes this client with a transport for performing HTTP operations.
/// - Parameter transport: A transport that performs HTTP operations. Defaults to a `URLSessionTransport` using the shared session.
public init(transport: any ClientTransport = URLSessionTransport()) {
self.client = .init(
serverURL: Self.serverURL,
configuration: .init(dateTranscoder: ISODateTimeTranscoder()),
transport: transport
)
}
}
// MARK: - AmiiboClient
// TODO: Remove the documentation from the functions inside the following extension as the `--enable-inherited-docs` flag when generating DocC documentation is not working as intended (?).
extension AmiiboLiveClient: AmiiboClient {
// MARK: Functions
/// Gets a list of amiibo items based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of filtered amiibo items.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
public func getAmiibos(
by filter: AmiiboFilter
) async throws(AmiiboServiceError) -> [Amiibo] {
try await fetchAmiibos(filter)
}
/// Gets a list of amiibo series based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of filtered amiibo series.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
public func getAmiiboSeries(
by filter: AmiiboSeriesFilter
) async throws(AmiiboServiceError) -> [AmiiboSeries] {
try await fetchAmiiboSeries(filter)
}
/// Gets a list of amiibo types based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of filtered amiibo types.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
public func getAmiiboTypes(
by filter: AmiiboTypeFilter
) async throws(AmiiboServiceError) -> [AmiiboType] {
try await fetchAmiiboTypes(filter)
}
/// Gets a list of game characters based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of filtered game characters.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
public func getGameCharacters(
by filter: GameCharacterFilter
) async throws(AmiiboServiceError) -> [GameCharacter] {
try await fetchGameCharacters(filter)
}
/// Gets a list of game series based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of filtered game series.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
public func getGameSeries(
by filter: GameSeriesFilter
) async throws(AmiiboServiceError) -> [GameSeries] {
try await fetchGameSeries(filter)
}
/// Gets the date when the data was last updated.
/// - Returns: A last updated date, decoded as UTC.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
public func getLastUpdated() async throws(AmiiboServiceError) -> Date {
try await fetchLastUpdated()
}
}
// MARK: - Helpers
private extension AmiiboLiveClient {
// MARK: Functions
/// Fetches a list of amiibo items based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of fetched amiibo items filtered, if requested.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
func fetchAmiibos(
_ filter: AmiiboFilter
) async throws(AmiiboServiceError) -> [Amiibo] {
let response = try await perform {
try await client.getAmiibos(.init(query: .init(
id: filter.identifier,
head: filter.head,
tail: filter.tail,
name: filter.name,
_type: filter.type,
amiiboSeries: filter.series,
character: filter.gameCharacter,
gameseries: filter.gameSeries,
showgames: filter.showGames,
showusage: filter.showUsage
)))
}
switch response {
case let .ok(ok):
switch ok.body {
case let .json(output):
switch output.amiibo {
case let .Amiibo(object):
return [Amiibo(object)]
case let .AmiiboList(list):
return list
.map { Amiibo($0) }
.sorted { $0.identifier < $1.identifier }
case .none:
// The service returns `"amiibo": null` when an `id` filter matches nothing.
return []
}
}
case .badRequest:
throw AmiiboServiceError.badRequest
case .notFound:
throw AmiiboServiceError.notFound
case .internalServerError:
throw AmiiboServiceError.notAvailable
case let .undocumented(statusCode, _):
throw AmiiboServiceError.undocumented(statusCode)
}
}
/// Fetches a list of amiibo series based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of fetched amiibo series filtered, if requested.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
func fetchAmiiboSeries(
_ filter: AmiiboSeriesFilter
) async throws(AmiiboServiceError) -> [AmiiboSeries] {
let response = try await perform {
try await client.getAmiiboSeries(.init(query: .init(
key: filter.key,
name: filter.name
)))
}
switch response {
case let .ok(ok):
switch ok.body {
case let .json(output):
switch output.amiibo {
case let .AmiiboSeries(payload):
return makeModels(from: [payload])
case let .AmiiboSeriesList(list):
return makeModels(from: list)
}
}
case .badRequest:
throw AmiiboServiceError.badRequest
case .internalServerError:
throw AmiiboServiceError.notAvailable
case .notFound:
throw AmiiboServiceError.notFound
case let .undocumented(statusCode, _):
throw AmiiboServiceError.undocumented(statusCode)
}
}
/// Fetches a list of amiibo types based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of fetched amiibo types filtered, if requested.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
func fetchAmiiboTypes(
_ filter: AmiiboTypeFilter
) async throws(AmiiboServiceError) -> [AmiiboType] {
let response = try await perform {
try await client.getAmiiboTypes(.init(query: .init(
key: filter.key,
name: filter.name
)))
}
switch response {
case let .ok(ok):
switch ok.body {
case let .json(output):
switch output.amiibo {
case let .AmiiboType(payload):
return makeModels(from: [payload])
case let .AmiiboTypeList(list):
return makeModels(from: list)
}
}
case .badRequest:
throw AmiiboServiceError.badRequest
case .internalServerError:
throw AmiiboServiceError.notAvailable
case .notFound:
throw AmiiboServiceError.notFound
case let .undocumented(statusCode, _):
throw AmiiboServiceError.undocumented(statusCode)
}
}
/// Fetches a list of game characters based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of fetched game characters filtered, if requested.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
func fetchGameCharacters(
_ filter: GameCharacterFilter
) async throws(AmiiboServiceError) -> [GameCharacter] {
let response = try await perform {
try await client.getGameCharacters(.init(query: .init(
key: filter.key,
name: filter.name
)))
}
switch response {
case let .ok(ok):
switch ok.body {
case let .json(output):
switch output.amiibo {
case let .GameCharacter(payload):
return makeModels(from: [payload])
case let .GameCharacterList(list):
return makeModels(from: list)
}
}
case .badRequest:
throw AmiiboServiceError.badRequest
case .internalServerError:
throw AmiiboServiceError.notAvailable
case .notFound:
throw AmiiboServiceError.notFound
case let .undocumented(statusCode, _):
throw AmiiboServiceError.undocumented(statusCode)
}
}
/// Fetches a list of game series based on a given filter.
/// - Parameter filter: A filter to remove unwanted items from the result.
/// - Returns: A list of fetched game series filtered, if requested.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
func fetchGameSeries(
_ filter: GameSeriesFilter
) async throws(AmiiboServiceError) -> [GameSeries] {
let response = try await perform {
try await client.getGameSeries(.init(query: .init(
key: filter.key,
name: filter.name
)))
}
switch response {
case let .ok(ok):
switch ok.body {
case let .json(output):
switch output.amiibo {
case let .GameSeries(payload):
return makeModels(from: [payload])
case let .GameSeriesList(list):
return makeModels(from: list)
}
}
case .badRequest:
throw AmiiboServiceError.badRequest
case .internalServerError:
throw AmiiboServiceError.notAvailable
case .notFound:
throw AmiiboServiceError.notFound
case let .undocumented(statusCode, _):
throw AmiiboServiceError.undocumented(statusCode)
}
}
/// Fetches the date when the data was last updated.
/// - Returns: A fetched last updated date, decoded as UTC.
/// - Throws: An ``AmiiboServiceError`` error in case some issue is encountered while generating the result.
func fetchLastUpdated() async throws(AmiiboServiceError) -> Date {
let response = try await perform {
try await client.getLastUpdated()
}
switch response {
case let .ok(ok):
switch ok.body {
case let .json(output):
return output.lastUpdated
}
case .internalServerError:
throw AmiiboServiceError.notAvailable
case let .undocumented(statusCode, _):
throw AmiiboServiceError.undocumented(statusCode)
}
}
/// Performs an API call, mapping any error thrown by the underlying client to an ``AmiiboServiceError`` error.
/// - Parameter operation: A closure that performs the API call.
/// - Returns: The output of the performed API call.
/// - Throws: An ``AmiiboServiceError`` error in case the API call failed.
func perform<Output>(
_ operation: () async throws -> Output
) async throws(AmiiboServiceError) -> Output {
do {
return try await operation()
} catch {
try handle(error: error)
}
}
/// Maps a list of key-name payloads into a sorted list of models.
/// - Parameter payloads: A list of payloads to map into models.
/// - Returns: A list of models sorted by their keys in ascending order.
func makeModels<Model: KeyNameModel>(from payloads: [some KeyNamePayload]) -> [Model] {
payloads
.map { Model($0) }
.sorted { $0.key < $1.key }
}
/// Maps a given error to an ``AmiiboServiceError`` error.
/// - Parameter error: An error to map.
/// - Throws: An ``AmiiboServiceError`` error that corresponds to the given error.
func handle(error: any Error) throws(AmiiboServiceError) -> Never {
switch error {
case is CancellationError:
throw AmiiboServiceError.cancelled
case let clientError as ClientError:
switch clientError.underlyingError {
case is DecodingError:
throw AmiiboServiceError.decoding
case let urlError as URLError:
switch urlError.code {
case .cancelled:
throw AmiiboServiceError.cancelled
case .cannotParseResponse:
throw AmiiboServiceError.decoding
case .cannotFindHost,
.cannotConnectToHost,
.dataNotAllowed,
.dnsLookupFailed,
.internationalRoamingOff,
.networkConnectionLost,
.notConnectedToInternet,
.secureConnectionFailed,
.timedOut:
throw AmiiboServiceError.notAvailable
default:
throw AmiiboServiceError.unknown(String(describing: urlError))
}
default:
throw AmiiboServiceError.unknown(String(describing: clientError.underlyingError))
}
default:
throw AmiiboServiceError.unknown(String(describing: error))
}
}
}