repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
mrjs
github_2023
javascript
177
Volumetrics-io
hanbollar
@@ -35,10 +48,12 @@ export class Surface extends Entity { * */ connected() { - this.windowVerticalScale = this.height / 3; - this.windowHorizontalScale = this.width / 3; + // this.clipping = new ClippingGeometry(new THREE.BoxGeometry(this.width, this.height, 0.3));
can this line be deleted?
mrjs
github_2023
javascript
177
Volumetrics-io
hanbollar
@@ -35,10 +48,12 @@ export class Surface extends Entity { * */ connected() { - this.windowVerticalScale = this.height / 3; - this.windowHorizontalScale = this.width / 3; + // this.clipping = new ClippingGeometry(new THREE.BoxGeometry(this.width, this.height, 0.3)); + this.windowVerticalScale = this.height; /// 3; + this.windowHorizontalScale = this.width; // / 3;
question for understanding: (i see this was moved to line 67) is the divide by 3 just a choice or is there a reason we're using 3 specifically?
mrjs
github_2023
javascript
177
Volumetrics-io
hanbollar
@@ -111,18 +126,24 @@ export class Surface extends Entity { this.object3D.position.copy(this.anchorPosition); this.object3D.quaternion.copy(this.anchorQuaternion); + console.log('floating', this.floating); + + if (!this.floating) { + this.rotationPlane.rotation.x = (3 * Math.PI) / 2;
need comment as to why this additional rotation is needed
mrjs
github_2023
others
177
Volumetrics-io
hanbollar
@@ -43,98 +43,54 @@ Both options require you generate an ssl certificate & key via openssl: # Features -## General Starting CSS +## Familiar 2D UI API -*For now there is some needed initial css for readability of the following feature examples* -*Play around with the options as you get more used to the 2D/3D html setup* +Create 2D UI using CSS and `mr-panel` -```css -* { - padding: 0; - margin: 0; - border: none; - border-collapse: collapse; -} - -html { - overflow: hidden; - overscroll-behavior: none; -} - -body { - position: fixed; -} - -mr-container { - height: 100vh; - width: 100%; +```html +<style> +.layout { + display: grid; + grid-template-columns: 1fr 2fr 1fr; + gap: 10px; + grid-auto-rows: minmax(100px, auto); } +.title { + margin: 0 auto; + font-size: 5vw; + line-height: 100%; + color: rgba(24, 24, 24, 0.75); -mr-app * { - display: block; + grid-column: 2; } -mr-text { - color: red; - font-size: 100px; +mr-img { + object-fit: cover; + grid-row: 3 / 6; + grid-column: 1 / -1; } -mr-model { - scale: 0.001; - z-index: 100; +#logo { + grid-column : 2; + scale: 0.001; /* set 3D content size */ + z-index: 100; /* set position on Z-axis */ } - -``` - -## 2D UI & Layout Components - -```html +</style> <mr-app> - <!-- The 3D Area --> - <mr-surface> - <!-- The 3D UI Container --> - <mr-container> - <mr-row> - <mr-text> - This is a quick example of an image gallery with explainer text. - </mr-text> - <mr-column> - <mr-img src="..."></mr-img> - <mr-row height="0.02"> - <mr-button onClick="Prev()"> <- </mr-button> - <mr-button onClick="Next()"> -> </mr-button> - </mr-row> - </mr-column> - </mr-row> - </mr-container> - </mr-surface> + <!-- The 2D UI Panel -->
could we also put one element that is 3d outside of the panel for the readme demo? ik we have included the mr-model elemnt on line 88, just a bit concerned of using just the naming of 2D though
mrjs
github_2023
javascript
173
Volumetrics-io
michaelthatsit
@@ -1,24 +1,29 @@ import System from '../core/System'; /** - * + * This system supports 3D clipping following threejs's clipping planes setup. + * See https://threejs.org/docs/?q=material#api/en/materials/Material.clippingPlanes for more information. */ export class ClippingSystem extends System { /** - * + * ClippingSystem's default constructor + * // TODO - add more info */ constructor() { super(false); + // TODO - how would you describe these vectors in relation to the clipping planes?
these are coplanar points. My understanding is they're needed to calculate the orientation and position if the plane. They're here to be reused for every plane so we're not generating a ton of vectors to be garbage collected.
mrjs
github_2023
javascript
173
Volumetrics-io
michaelthatsit
@@ -48,9 +71,11 @@ export class ClippingSystem extends System { }); } +// TODO - is this function still needed? i dont see it called at all?
Yes still needed! this is called on an event whenever a new entity is added. all systems have it but not all of them utilize it.
mrjs
github_2023
javascript
173
Volumetrics-io
michaelthatsit
@@ -2,12 +2,15 @@ import * as THREE from 'three'; import System from '../core/System'; import { COLLIDER_CURSOR_MAP } from './RapierPhysicsSystem'; +// TODO - is this item still needed?
This whole system can be thrown out. it was for the initial demo and we will be removing this from the framework and building it on the platform.
mrjs
github_2023
javascript
173
Volumetrics-io
michaelthatsit
@@ -87,6 +94,7 @@ class InstancingSystem extends System { entity.object3D.add(instancedMesh); } +// TODO - can i delete the below two items?
if you're referring to updated and detached component, yeah you can delete them if you're not utilizing them.
mrjs
github_2023
javascript
173
Volumetrics-io
michaelthatsit
@@ -4,6 +4,9 @@ import * as THREE from 'three'; // mat-phong // "color: red; emissive: blue; specular: yellow; opacity: 0.5; shininess: 100; wireframe: true" +// TODO - this should not be in this folder +// TODO - is this even still needed? i dont see it used in the rest of the code
lol it is not, feel free to delete it. this is a leftover experimental way to add material via data attributes
mrjs
github_2023
javascript
187
Volumetrics-io
hanbollar
@@ -15,8 +15,14 @@ export function threeToPx(val) { * @returns {number} - the 3D representation of value. */ export function pxToThree(val) { + let px; + if (val instanceof String) { + px = val.split('px')[0]; + } else { + px = val; + }
the above should be a ternary for better readability `let px = (val instanceof String) ? val.split('px'[0] : val;`
mrjs
github_2023
javascript
192
Volumetrics-io
michaelthatsit
@@ -410,7 +424,37 @@ export class MRApp extends MRElement { this.stats.end(); } - this.renderer.render(this.scene, this.user); + // ----- Actually Render ----- // + + // TODO (in future) - once this gets more complicated, it will be nice to have a render system separate + // from the pure loop but it is okay as is here for now. + + // Need to wait until we have all needed rendering-associated systems loaded. + if (this.maskingSystem == undefined) { + return; + } + + const camera = this.user;
Let's just pass `this.user` into the render calls.
mrjs
github_2023
javascript
192
Volumetrics-io
michaelthatsit
@@ -410,7 +424,37 @@ export class MRApp extends MRElement { this.stats.end(); } - this.renderer.render(this.scene, this.user); + // ----- Actually Render ----- // + + // TODO (in future) - once this gets more complicated, it will be nice to have a render system separate + // from the pure loop but it is okay as is here for now. + + // Need to wait until we have all needed rendering-associated systems loaded. + if (this.maskingSystem == undefined) { + return; + } + + const camera = this.user; + + this.renderer.clear(); + + // Render panel to stencil buffer + this.renderer.state.buffers.stencil.setTest(true); + this.renderer.state.buffers.stencil.setMask(0xff); + this.renderer.render(this.scene, camera); + + // Render child-objects to where the stencil buffer is set; must start at 1, see MaskingSystem for more details. + for (let panel_ref = 1; panel_ref <= this.maskingSystem.panels.length; ++panel_ref) { + this.renderer.state.buffers.stencil.setFunc(THREE.EqualStencilFunc, panel_ref, 0xff); + this.renderer.render(this.scene, camera);
This is what's causing the hit. I tried commenting it out and got the FPS back, and masking still worked.
mrjs
github_2023
others
201
Volumetrics-io
hanbollar
@@ -64,5 +73,16 @@ <footer> <script src="./assets/js/AnimationSystem.js"></script> + <script> + + let model = document.querySelector('#logo-model') + + function spin() { + let animationComp = model.components.get('animation') + model.components.set('animation', {maxspeed: animationComp.maxspeed * 10000, acceleration: animationComp.acceleration * 10000}) + } +
lines 75-84 include two different ways to do animation - are we keeping both?
mrjs
github_2023
javascript
201
Volumetrics-io
hanbollar
@@ -0,0 +1,35 @@ +import { MRTextEntity } from './MRTextEntity'; + +/** + * @class A + * @classdesc 3D representation of a hyperlink. `mr-a` + * @augments MRDivEntity + */
you have to include { MRDivEntity } as a normal include at the top of the file for the documentation to be happy
mrjs
github_2023
javascript
201
Volumetrics-io
hanbollar
@@ -13,7 +13,7 @@ export class StyleSystem extends MRSystem { * @description StyleSystem's default constructor with a starting framerate of 1/15. */ constructor() { - super(false, 1 / 15); + super(false, 1 / 30);
since this is updating, make sure also update the comment of line 13 for the new frame rate
mrjs
github_2023
javascript
201
Volumetrics-io
hanbollar
@@ -44,15 +44,14 @@ export class TextSystem extends MRSystem { ); }); }); + } - const entities = this.app.querySelectorAll('mr-text, mr-textfield, mr-textarea'); - for (const entity of entities) { - this.registry.add(entity); - this.addText(entity); - entity.textObj.sync(() => { - entity.needsUpdate = true; - }); - } + /** + * When a new entity is created, adds it to the physics registry and initializes the physics aspects of the entity. + * @param {MREntity} entity - the entity being set up
this should be rewritten as ``` /** * @function * @description When a new entity is created, adds it to the physics registry and initializes the physics aspects of the entity. * @param {MREntity} entity - the entity being set up ```
mrjs
github_2023
javascript
201
Volumetrics-io
hanbollar
@@ -1,42 +1,19 @@ -import { MRDivEntity } from 'mrjs/core/MRDivEntity'; +import { MRTextEntity } from '../MRTextEntity'; /** * @class Button * @classdesc 3D representation of a Button mimicking the html version. `mr-button` * @augments MRDivEntity */
the above warning in the pr is for the same reason as mentioned before
mrjs
github_2023
javascript
201
Volumetrics-io
hanbollar
@@ -22,6 +22,7 @@ import './core/MREntity'; import './core/MRHand'; import './core/MRSystem'; import './core/MRTextEntity'; +import './core/MRHyperlink.js';
are we sure we want this directly in core and not in entities - not too hardlined here but am leaning more towards in entities
swift-openapi-runtime
github_2023
others
99
apple
czechboy0
@@ -96,6 +96,10 @@ extension JSONDecoder.DateDecodingStrategy { } } +public protocol DecodingErrorHandler: Sendable { + func willThrow(_ error: any Error)
Would you be interested in the context this was thrown in? See `ClientError` and `ServerError`, where we add more context.
swift-openapi-runtime
github_2023
others
99
apple
czechboy0
@@ -113,9 +119,11 @@ public struct Configuration: Sendable { /// - multipartBoundaryGenerator: The generator to use when creating mutlipart bodies. public init( dateTranscoder: any DateTranscoder = .iso8601, - multipartBoundaryGenerator: any MultipartBoundaryGenerator = .random + multipartBoundaryGenerator: any MultipartBoundaryGenerator = .random, + decodingErrorHandler: (any DecodingErrorHandler)? = nil
Looks good, please just add a deprecated 2-parameter version of this initializer in Deprecated.swift, as adding a param is technically a source break. Similar to https://github.com/apple/swift-openapi-runtime/pull/102#discussion_r1547909598
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -141,3 +141,43 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret @_spi(Generated) public func throwUnexpectedResponseBody(expectedContent: String, body: any Sendable) throws -> Never { throw RuntimeError.unexpectedResponseBody(expectedContent: expectedContent, body: body) } + +/// HTTP Response status definition for ``RuntimeError``. +extension RuntimeError: HTTPResponseConvertible { + public var httpStatus: HTTPTypes.HTTPResponse.Status { + switch self { + case .invalidServerURL, + .invalidServerVariableValue: + .notFound + case .invalidExpectedContentType, + .missingCoderForCustomContentType, + .unexpectedContentTypeHeader: + .unsupportedMediaType + case .unexpectedAcceptHeader(_): + .notAcceptable + case .missingOrMalformedContentDispositionName: + .unprocessableContent
> The HTTP 422 Unprocessable Content [client error response](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses) status code indicates that the server understood the content type of the request content, and the syntax of the request content was correct, but it was unable to process the contained instructions. — https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422 Sounds like this one might not be the correct response for missing or malformed. Should we return 401 instead here?
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -141,3 +141,43 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret @_spi(Generated) public func throwUnexpectedResponseBody(expectedContent: String, body: any Sendable) throws -> Never { throw RuntimeError.unexpectedResponseBody(expectedContent: expectedContent, body: body) } + +/// HTTP Response status definition for ``RuntimeError``. +extension RuntimeError: HTTPResponseConvertible { + public var httpStatus: HTTPTypes.HTTPResponse.Status { + switch self { + case .invalidServerURL, + .invalidServerVariableValue: + .notFound + case .invalidExpectedContentType, + .missingCoderForCustomContentType, + .unexpectedContentTypeHeader: + .unsupportedMediaType + case .unexpectedAcceptHeader(_):
Nit (probably will get picked up by the formatter): ```suggestion case .unexpectedAcceptHeader: ```
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -141,3 +141,43 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret @_spi(Generated) public func throwUnexpectedResponseBody(expectedContent: String, body: any Sendable) throws -> Never { throw RuntimeError.unexpectedResponseBody(expectedContent: expectedContent, body: body) } + +/// HTTP Response status definition for ``RuntimeError``. +extension RuntimeError: HTTPResponseConvertible { + public var httpStatus: HTTPTypes.HTTPResponse.Status { + switch self { + case .invalidServerURL, + .invalidServerVariableValue: + .notFound + case .invalidExpectedContentType, + .missingCoderForCustomContentType, + .unexpectedContentTypeHeader: + .unsupportedMediaType + case .unexpectedAcceptHeader(_): + .notAcceptable + case .missingOrMalformedContentDispositionName: + .unprocessableContent + case .failedToDecodeStringConvertibleValue, + .invalidAcceptSubstring, + .invalidBase64String, + .invalidHeaderFieldName, + .malformedAcceptHeader, + .missingMultipartBoundaryContentTypeParameter, + .missingRequiredHeaderField, + .missingRequiredMultipartFormDataContentType, + .missingRequiredQueryParameter, + .missingRequiredPathParameter, + .missingRequiredRequestBody, + .pathUnset,
Not sure but opening discussion: should this be 404 instead?
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -141,3 +141,43 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret @_spi(Generated) public func throwUnexpectedResponseBody(expectedContent: String, body: any Sendable) throws -> Never { throw RuntimeError.unexpectedResponseBody(expectedContent: expectedContent, body: body) } + +/// HTTP Response status definition for ``RuntimeError``. +extension RuntimeError: HTTPResponseConvertible { + public var httpStatus: HTTPTypes.HTTPResponse.Status { + switch self { + case .invalidServerURL, + .invalidServerVariableValue: + .notFound + case .invalidExpectedContentType, + .missingCoderForCustomContentType, + .unexpectedContentTypeHeader:
I think that these two are more 422 IIUC?
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -0,0 +1,80 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes +@_spi(Generated) @testable import OpenAPIRuntime +import XCTest + +struct MockRuntimeErrorHandler: Sendable { + var failWithError: (any Error)? = nil + func greet(_ input: String) async throws -> String { + if failWithError != nil { throw failWithError! }
```suggestion if let failWithError { throw failWithError } ```
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -0,0 +1,80 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes +@_spi(Generated) @testable import OpenAPIRuntime +import XCTest + +struct MockRuntimeErrorHandler: Sendable { + var failWithError: (any Error)? = nil + func greet(_ input: String) async throws -> String { + if failWithError != nil { throw failWithError! } + guard input == "hello" else { throw TestError() } + return "bye" + } + + static let requestBody: HTTPBody = HTTPBody("hello") + static let responseBody: HTTPBody = HTTPBody("bye") +} + +final class Test_RuntimeError: XCTestCase { + + func testRuntimeError_withUnderlyingErrorNotConfirming_returns500() async throws { + + let server = UniversalServer(handler: MockRuntimeErrorHandler(failWithError: RuntimeError.transportFailed(TestError())), + middlewares: [ErrorHandlingMiddleware()]) + let response = try await server.handle( + request: .init(soar_path: "/", method: .post), + requestBody: MockHandler.requestBody, + metadata: .init(), + forOperation: "op", + using: { MockRuntimeErrorHandler.greet($0) }, + deserializer: { request, body, metadata in + let body = try XCTUnwrap(body) + return try await String(collecting: body, upTo: 10) + }, + serializer: { output, _ in fatalError() } + ) + XCTAssertEqual(response.0.status, .internalServerError) + } + + func testRuntimeError_withUnderlyingErrorConfirming_returns500() async throws {
This test name sounds wrong?
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -141,3 +141,26 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret @_spi(Generated) public func throwUnexpectedResponseBody(expectedContent: String, body: any Sendable) throws -> Never { throw RuntimeError.unexpectedResponseBody(expectedContent: expectedContent, body: body) } + +/// HTTP Response status definition for ``RuntimeError``. +extension RuntimeError: HTTPResponseConvertible { + /// HTTP Status code corresponding to each error case + public var httpStatus: HTTPTypes.HTTPResponse.Status { + switch self { + case .invalidServerURL, .invalidServerVariableValue: .notFound + case .invalidExpectedContentType, .unexpectedContentTypeHeader: .unsupportedMediaType + case .missingCoderForCustomContentType: .unprocessableContent + case .unexpectedAcceptHeader: .notAcceptable + case .failedToDecodeStringConvertibleValue, .invalidAcceptSubstring, .invalidBase64String, + .invalidHeaderFieldName, .malformedAcceptHeader, .missingMultipartBoundaryContentTypeParameter, + .missingOrMalformedContentDispositionName, .missingRequiredHeaderField, + .missingRequiredMultipartFormDataContentType, .missingRequiredQueryParameter, .missingRequiredPathParameter, + .missingRequiredRequestBody, .unsupportedParameterStyle: + .badRequest + case .pathUnset: .notFound
Nit: Can we group this with the others that are returning `.notFound`?
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import protocol Foundation.LocalizedError import struct Foundation.Data - +import HTTPTypes
Nit. ```suggestion import HTTPTypes ```
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -0,0 +1,77 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes +@_spi(Generated) @testable import OpenAPIRuntime +import XCTest + +struct MockRuntimeErrorHandler: Sendable { + var failWithError: (any Error)? = nil + func greet(_ input: String) async throws -> String { + if let failWithError { throw failWithError } + guard input == "hello" else { throw TestError() } + return "bye" + } + + static let requestBody: HTTPBody = HTTPBody("hello") + static let responseBody: HTTPBody = HTTPBody("bye") +} + +final class Test_RuntimeError: XCTestCase { + func testRuntimeError_withUnderlyingErrorNotConfirming_returns500() async throws {
Typo: ```suggestion func testRuntimeError_withUnderlyingErrorNotConforming_returns500() async throws { ```
swift-openapi-runtime
github_2023
others
135
apple
simonjbeaumont
@@ -0,0 +1,77 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes +@_spi(Generated) @testable import OpenAPIRuntime +import XCTest + +struct MockRuntimeErrorHandler: Sendable { + var failWithError: (any Error)? = nil + func greet(_ input: String) async throws -> String { + if let failWithError { throw failWithError } + guard input == "hello" else { throw TestError() } + return "bye" + } + + static let requestBody: HTTPBody = HTTPBody("hello") + static let responseBody: HTTPBody = HTTPBody("bye") +} + +final class Test_RuntimeError: XCTestCase { + func testRuntimeError_withUnderlyingErrorNotConfirming_returns500() async throws { + let server = UniversalServer( + handler: MockRuntimeErrorHandler(failWithError: RuntimeError.transportFailed(TestError())), + middlewares: [ErrorHandlingMiddleware()] + ) + let response = try await server.handle( + request: .init(soar_path: "/", method: .post), + requestBody: MockHandler.requestBody, + metadata: .init(), + forOperation: "op", + using: { MockRuntimeErrorHandler.greet($0) }, + deserializer: { request, body, metadata in + let body = try XCTUnwrap(body) + return try await String(collecting: body, upTo: 10) + }, + serializer: { output, _ in fatalError() } + ) + XCTAssertEqual(response.0.status, .internalServerError) + } + + func testRuntimeError_withUnderlyingErrorConfirming_returnsCorrectStatusCode() async throws {
Typo ```suggestion func testRuntimeError_withUnderlyingErrorConforming_returnsCorrectStatusCode() async throws { ```
swift-openapi-runtime
github_2023
others
134
apple
FranzBusch
@@ -12,7 +12,7 @@ // //===----------------------------------------------------------------------===// import Foundation
Isn't this API breaking? You were previously importing Foundation as `public` but with the changed flag it is now imported as `internal`. Since imports are leaky in Swift this would be API breaking.
swift-openapi-runtime
github_2023
others
133
apple
czechboy0
@@ -23,30 +23,24 @@ let swiftSettings: [SwiftSetting] = [ let package = Package( name: "swift-openapi-runtime", - platforms: [ - .macOS(.v10_15), .macCatalyst(.v13), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .visionOS(.v1) - ], - products: [ - .library( - name: "OpenAPIRuntime", - targets: ["OpenAPIRuntime"] - ) - ], - dependencies: [ - .package(url: "https://github.com/apple/swift-http-types", from: "1.0.0"), - ], + platforms: [.macOS(.v10_15), .macCatalyst(.v13), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .visionOS(.v1)], + products: [.library(name: "OpenAPIRuntime", targets: ["OpenAPIRuntime"])], + dependencies: [.package(url: "https://github.com/apple/swift-http-types", from: "1.0.0")],
Curious why this got reformatted now, even though the CI was green previously as well?
swift-openapi-runtime
github_2023
others
133
apple
czechboy0
@@ -23,30 +23,24 @@ let swiftSettings: [SwiftSetting] = [ let package = Package( name: "swift-openapi-runtime", - platforms: [ - .macOS(.v10_15), .macCatalyst(.v13), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .visionOS(.v1) - ], - products: [ - .library( - name: "OpenAPIRuntime", - targets: ["OpenAPIRuntime"] - ) - ], - dependencies: [ - .package(url: "https://github.com/apple/swift-http-types", from: "1.0.0"), - ], + platforms: [.macOS(.v10_15), .macCatalyst(.v13), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .visionOS(.v1)], + products: [.library(name: "OpenAPIRuntime", targets: ["OpenAPIRuntime"])], + dependencies: [.package(url: "https://github.com/apple/swift-http-types", from: "1.0.0")], targets: [ .target( name: "OpenAPIRuntime", - dependencies: [ - .product(name: "HTTPTypes", package: "swift-http-types") - ], - swiftSettings: swiftSettings - ), - .testTarget( - name: "OpenAPIRuntimeTests", - dependencies: ["OpenAPIRuntime"], + dependencies: [.product(name: "HTTPTypes", package: "swift-http-types")], swiftSettings: swiftSettings - ), + ), .testTarget(name: "OpenAPIRuntimeTests", dependencies: ["OpenAPIRuntime"], swiftSettings: swiftSettings), ] ) + +// --- STANDARD CROSS-REPO SETTINGS DO NOT EDIT --- //
Are we missing a START: here?
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -0,0 +1,90 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Foundation + +/// A component of a `URIParsedKey`. +typealias URIParsedKeyComponent = String.SubSequence + +/// A parsed key for a parsed value. +/// +/// For example, `foo=bar` in a `form` string would parse the key as `foo` (single component). +/// In an unexploded `form` string `root=foo,bar`, the key would be `root/foo` (two components). +/// In a `simple` string `bar`, the key would be empty (0 components). +struct URIParsedKey: Hashable { + + /// The individual string components. + let components: [URIParsedKeyComponent] + /// Creates a new parsed key. + /// - Parameter components: The key components. + init(_ components: [URIParsedKeyComponent]) { self.components = components } + + /// A new empty key. + static var empty: Self { .init([]) } +} + +/// A primitive value produced by `URIParser`. +typealias URIParsedValue = String.SubSequence + +/// An array of primitive values produced by `URIParser`. +typealias URIParsedValueArray = [URIParsedValue] + +/// A key-value produced by `URIParser`. +struct URIParsedPair: Equatable { + + /// The key of the pair. + /// + /// In `foo=bar`, `foo` is the key. + var key: URIParsedKey + + /// The value of the pair. + /// + /// In `foo=bar`, `bar` is the value. + var value: URIParsedValue +} + +/// An array of key-value pairs produced by `URIParser`. +typealias URIParsedPairArray = [URIParsedPair] + +// MARK: - Extensions + +extension URIParsedKey: CustomStringConvertible { + /// A textual representation of this instance. + /// + /// Calling this property directly is discouraged. Instead, convert an + /// instance of any type to a string by using the `String(describing:)` + /// initializer. This initializer works with any type, and uses the custom + /// `description` property for types that conform to + /// `CustomStringConvertible`: + /// + /// struct Point: CustomStringConvertible { + /// let x: Int, y: Int + /// + /// var description: String { + /// return "(\(x), \(y))" + /// } + /// } + /// + /// let p = Point(x: 21, y: 30) + /// let s = String(describing: p) + /// print(s) + /// // Prints "(21, 30)" + /// + /// The conversion of `p` to a string in the assignment to `s` uses the + /// `Point` type's `description` property. + var description: String {
We've done this before in some of the other OpenAPI packages: ```suggestion // swift-format-ignore: AllPublicDeclarationsHaveDocumentation var description: String { ``` I'd like us to do the same here because propagating this protocol-level comment both unnecessary, and confusing, because it comes with an irrelevant example.
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -128,6 +128,18 @@ extension URIEncodedNode { } } + /// Marks the node as an array, starting as empty. + /// - Throws: If the node is already set to be anything else but an array. + mutating func markAsArray() throws { + switch self { + case .array: + // Already an array. + break + case .unset: self = .array([]) + default: throw InsertionError.appendingToNonArrayContainer
Looks like this is the wrong error; do we need a new one?
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -0,0 +1,90 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Foundation + +/// A component of a `URIParsedKey`. +typealias URIParsedKeyComponent = String.SubSequence + +/// A parsed key for a parsed value. +/// +/// For example, `foo=bar` in a `form` string would parse the key as `foo` (single component). +/// In an unexploded `form` string `root=foo,bar`, the key would be `root/foo` (two components). +/// In a `simple` string `bar`, the key would be empty (0 components). +struct URIParsedKey: Hashable { + + /// The individual string components. + let components: [URIParsedKeyComponent] + /// Creates a new parsed key. + /// - Parameter components: The key components. + init(_ components: [URIParsedKeyComponent]) { self.components = components }
```suggestion /// The individual string components. let components: [URIParsedKeyComponent] /// Creates a new parsed key. /// - Parameter components: The key components. init(_ components: [URIParsedKeyComponent]) { self.components = components } ```
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -0,0 +1,90 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Foundation + +/// A component of a `URIParsedKey`. +typealias URIParsedKeyComponent = String.SubSequence + +/// A parsed key for a parsed value. +/// +/// For example, `foo=bar` in a `form` string would parse the key as `foo` (single component). +/// In an unexploded `form` string `root=foo,bar`, the key would be `root/foo` (two components). +/// In a `simple` string `bar`, the key would be empty (0 components). +struct URIParsedKey: Hashable { + + /// The individual string components. + let components: [URIParsedKeyComponent] + /// Creates a new parsed key. + /// - Parameter components: The key components. + init(_ components: [URIParsedKeyComponent]) { self.components = components } + + /// A new empty key. + static var empty: Self { .init([]) } +} + +/// A primitive value produced by `URIParser`. +typealias URIParsedValue = String.SubSequence + +/// An array of primitive values produced by `URIParser`. +typealias URIParsedValueArray = [URIParsedValue]
There's a lot of type aliases kicking around and I'm not sure they're adding to the clarity of the code. Especially something like `typealias FooArray = [Foo]` seems an unnecessary layer of indirection. Do we really need these ones—can't we just use these types in the below struct (my preference)? At the very least, can these type aliases be _scoped within_ the struct? Can you elaborate on the difference between these `URIParsed...` set of type aliases and the `URIDecoded...` set of aliases?
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -0,0 +1,90 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import Foundation + +/// A component of a `URIParsedKey`. +typealias URIParsedKeyComponent = String.SubSequence + +/// A parsed key for a parsed value. +/// +/// For example, `foo=bar` in a `form` string would parse the key as `foo` (single component). +/// In an unexploded `form` string `root=foo,bar`, the key would be `root/foo` (two components). +/// In a `simple` string `bar`, the key would be empty (0 components). +struct URIParsedKey: Hashable { + + /// The individual string components. + let components: [URIParsedKeyComponent] + /// Creates a new parsed key. + /// - Parameter components: The key components. + init(_ components: [URIParsedKeyComponent]) { self.components = components } + + /// A new empty key. + static var empty: Self { .init([]) } +} + +/// A primitive value produced by `URIParser`. +typealias URIParsedValue = String.SubSequence + +/// An array of primitive values produced by `URIParser`. +typealias URIParsedValueArray = [URIParsedValue] + +/// A key-value produced by `URIParser`. +struct URIParsedPair: Equatable { + + /// The key of the pair. + /// + /// In `foo=bar`, `foo` is the key. + var key: URIParsedKey + + /// The value of the pair. + /// + /// In `foo=bar`, `bar` is the value. + var value: URIParsedValue +} + +/// An array of key-value pairs produced by `URIParser`. +typealias URIParsedPairArray = [URIParsedPair]
Query: unnecessary type alias?
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -97,9 +94,15 @@ extension URIKeyedDecodingContainer { extension URIKeyedDecodingContainer: KeyedDecodingContainerProtocol { - var allKeys: [Key] { values.keys.map { key in Key.init(stringValue: String(key))! } } + var allKeys: [Key] { + do { return try decoder.elementKeysInCurrentDictionary().compactMap { .init(stringValue: $0) } } catch { + return [] + } + } - func contains(_ key: Key) -> Bool { values[key.stringValue[...]] != nil } + func contains(_ key: Key) -> Bool { + do { return try decoder.containsElementInCurrentDictionary(forKey: key.stringValue) } catch { return false } + }
Can we push the error handling into `containsElementInCurrentDictionary(forKey: key.stringValue)`, please? From picking through the docs and implementation, that can only throw in the root doesn't parse so I think _that_ API should be the one transforming that error into a boolean and this layer can just call through.
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -24,7 +24,7 @@ struct URISingleValueDecodingContainer { extension URISingleValueDecodingContainer { /// The underlying value as a single value. - var value: URIParsedValue { get throws { try decoder.currentElementAsSingleValue() } } + var value: URIParsedValue? { get throws { try decoder.currentElementAsSingleValue() } }
What does this mean to be both throwing and nullable? Is it the difference between a present, explicit `null` value? Can we document the semantics as I'm finding it hard to reason about its later use.
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -79,11 +109,23 @@ extension URISingleValueDecodingContainer: SingleValueDecodingContainer { var codingPath: [any CodingKey] { decoder.codingPath } - func decodeNil() -> Bool { false } + func decodeNil() -> Bool { do { return try value == nil } catch { return false } }
```suggestion (try? self.value) == nil ```
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -33,7 +33,17 @@ extension URISingleValueDecodingContainer { /// - Returns: The converted value found. /// - Throws: An error if the conversion failed. private func _decodeBinaryFloatingPoint<T: BinaryFloatingPoint>(_: T.Type = T.self) throws -> T { - guard let double = try Double(value) else { + guard let value = try value else { + throw DecodingError.valueNotFound( + T.self, + DecodingError.Context.init( + codingPath: codingPath, + debugDescription: "Value not found.", + underlyingError: nil + )
```suggestion DecodingError.Context( codingPath: codingPath, debugDescription: "Value not found.", underlyingError: nil ) ``` This use of explicit `.init` shouldn't be here. Comment applies elsewhere too. Surprised this wasn't picked up by the formatter.
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -16,25 +16,15 @@ import Foundation /// An unkeyed container used by `URIValueFromNodeDecoder`. struct URIUnkeyedDecodingContainer { - /// The associated decoder. let decoder: URIValueFromNodeDecoder - /// The underlying array. - let values: URIParsedValueArray - - /// The index of the item being currently decoded. - private var index: Int + /// The index of the next item to be decoded. + private var index: URIParsedValueArray.Index = 0
Can we keep the initialisation of this property in the initialiser?
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -46,7 +36,7 @@ extension URIUnkeyedDecodingContainer { /// - Throws: An error if the container ran out of items. private mutating func _decodingNext<R>(in work: () throws -> R) throws -> R { guard !isAtEnd else { throw URIValueFromNodeDecoder.GeneralError.reachedEndOfUnkeyedContainer } - defer { values.formIndex(after: &index) } + defer { index += 1 }
I think the previous use of the Index APIs was more correct.
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -111,9 +101,9 @@ extension URIUnkeyedDecodingContainer { extension URIUnkeyedDecodingContainer: UnkeyedDecodingContainer { - var count: Int? { values.count } + var count: Int? { try? decoder.countOfCurrentArray() } - var isAtEnd: Bool { index == values.endIndex } + var isAtEnd: Bool { index == count } var currentIndex: Int { index }
Do we need this index too? What value is it adding on `index`?
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -167,153 +135,240 @@ extension URIValueFromNodeDecoder { throw DecodingError.typeMismatch(String.self, .init(codingPath: codingPath, debugDescription: message)) } - /// Extracts the root value of the provided node using the root key. - /// - Parameter node: The node which to expect for the root key. - /// - Returns: The value found at the root key in the provided node. - /// - Throws: A `DecodingError` if the value is not found at the root key - private func rootValue(in node: URIParsedNode) throws -> URIParsedValueArray { - guard let value = node[rootKey] else { - if style == .simple, let valueForFallbackKey = node[""] { - // The simple style doesn't encode the key, so single values - // get encoded as a value only, and parsed under the empty - // string key. - return valueForFallbackKey + // MARK: - withParsed methods + + /// Use the root as a primitive value. + /// - Parameter work: The closure in which to use the value. + /// - Returns: Any value returned from the closure. + /// - Throws: When parsing the root fails. + private func withParsedRootAsPrimitive<R>(_ work: (URIDecodedPrimitive?) throws -> R) throws -> R { + let value: URIDecodedPrimitive? + if let cached = cache.primitive { + value = try cached.get() + } else { + let result: Result<URIDecodedPrimitive?, any Error> + do { + value = try parser.parseRootAsPrimitive(rootKey: rootKey)?.value + result = .success(value) + } catch { + result = .failure(error) + throw error } - return [] + cache.primitive = result } - return value + return try work(value)
I'd like to see this pattern factored out as it's pretty repetitive. I'm also wondering if `Optional<Result<>>` is the best representation for the state of the cache. I understand it fits with the three cases: (1) haven't tried, (2) tried and got a thing, and (3) tried and got an error; but I think an actual `enum CacheResult` with the three states in one enum might help us build some better layered logic.
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -345,16 +344,19 @@ extension URIValueFromNodeDecoder { /// contains a value for the provided key. /// - Parameter key: The key for which to look for a value. /// - Returns: `true` if a value was found, `false` otherwise. - /// - Throws: When parsing the root fails. - func containsElementInCurrentDictionary(forKey key: String) throws -> Bool { - try withCurrentDictionaryElements { dictionary in dictionary[key[...]] != nil } + func containsElementInCurrentDictionary(forKey key: String) -> Bool { + do { return try withCurrentDictionaryElements { dictionary in dictionary[key[...]] != nil } } catch { + return false + }
nit: I still think if we're just swallowing the error and returning something else, then this is the nicer pattern, but it's not a blocker: ```suggestion (try? withCurrentDictionaryElements { dictionary in dictionary[key[...]] != nil }) ?? false ```
swift-openapi-runtime
github_2023
others
127
apple
simonjbeaumont
@@ -345,16 +344,19 @@ extension URIValueFromNodeDecoder { /// contains a value for the provided key. /// - Parameter key: The key for which to look for a value. /// - Returns: `true` if a value was found, `false` otherwise. - /// - Throws: When parsing the root fails. - func containsElementInCurrentDictionary(forKey key: String) throws -> Bool { - try withCurrentDictionaryElements { dictionary in dictionary[key[...]] != nil } + func containsElementInCurrentDictionary(forKey key: String) -> Bool { + do { return try withCurrentDictionaryElements { dictionary in dictionary[key[...]] != nil } } catch { + return false + } } /// Returns a list of keys found in the current top-of-stack dictionary. /// - Returns: A list of keys from the dictionary. /// - Throws: When parsing the root fails. - func elementKeysInCurrentDictionary() throws -> [String] { - try withCurrentDictionaryElements { dictionary in dictionary.keys.map(String.init) } + func elementKeysInCurrentDictionary() -> [String] { + do { return try withCurrentDictionaryElements { dictionary in dictionary.keys.map(String.init) } } catch { + return [] + }
nit: I still think if we're just swallowing the error and returning something else, then this is the nicer pattern, but it's not a blocker: ```suggestion (try? withCurrentDictionaryElements { dictionary in dictionary.keys.map(String.init) } ) ?? [] ```
swift-openapi-runtime
github_2023
others
126
apple
simonjbeaumont
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
```suggestion // Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors ```
swift-openapi-runtime
github_2023
others
126
apple
simonjbeaumont
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// Error Handling middleware that converts an error to a HTTP response +/// +/// This is an opt-in middleware that adopters may choose to include to convert application errors +/// to a HTTP Response +/// +/// Inclusion of this ErrorHandling Middleware should be accompanied by confirming errors to +/// HTTPResponseConvertible protocol. Only errors confirming to HTTPResponseConvertible are converted to a HTTP response. Other errors are re-thrown from this middleware. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the error middleware while registering the handler +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// + +public struct ErrorHandlingMiddleware: ServerMiddleware {
Thank you so much for adding documentation comments; we really value them! Do you mind polishing them up a little, though? - Ending sentences with punctuation: either full stop or colon, depending on context. - Reflowing lines at a consistent width. - The second sentence seems a little redundant given the headline comment. - In the third, can we remove the double-space in the middle of the sentence, and use double-backticks to link to the referred documentation of `HTTPResponseConvertible`? - Terminate the final code-fence. - Remove any empty comment lines at the end of the doc comment block. - Remove any empty lines between the comment block and the symbol to which it should be attached. Aside: it's likely the soundness checks will help you here: the documentation checker will check that the double-backtick-referred symbols exist, and the reflowing will be taken care of by swift-format. This feedback applies to any other documentation comments too.
swift-openapi-runtime
github_2023
others
126
apple
simonjbeaumont
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// Error Handling middleware that converts an error to a HTTP response +/// +/// This is an opt-in middleware that adopters may choose to include to convert application errors +/// to a HTTP Response +/// +/// Inclusion of this ErrorHandling Middleware should be accompanied by confirming errors to +/// HTTPResponseConvertible protocol. Only errors confirming to HTTPResponseConvertible are converted to a HTTP response. Other errors are re-thrown from this middleware. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the error middleware while registering the handler +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// + +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept(_ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?)) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { + return try await next(request, body, metadata) + } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return (HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody) + } else { + throw error + } + } + } +} + +/// Protocol used by ErrorHandling middleware to map an error to a HTTPResponse +/// +/// Adopters who wish to convert their application error to a HTTPResponse +/// should confirm their error(s) to this protocol + +public protocol HTTPResponseConvertible { + /// HTTP status to return in the response + var httpStatus: HTTPResponse.Status { get } + + /// (Optional) Headers to return in the response + var httpHeaderFields: HTTPTypes.HTTPFields { get } + + /// (Optional) The body of the response to return + var httpBody: OpenAPIRuntime.HTTPBody? { get } +}
I'll go and double check the proposal myself but I thought we were going to make these all optional? Right now, we have all three flavours: - `httpStatus` is non-optional, with no default implementation; - `httpHeaderFields` is non-optional, but has a default implementation; and - `httpBody` is optional, with a default implementation. IMO, if we're providing a default implementation in a protocol extension, we should _not_ use optional for the requirement. I'll go double-check the proposal again, but, regardless of API spelling, is this the semantics we wanted here? Specifically, if someone adds the `ErrorHandlingMiddleware`, don't we want it transform errors that do not conform into `500` and, in debug mode, possibly include something in the header or body?
swift-openapi-runtime
github_2023
others
126
apple
simonjbeaumont
@@ -0,0 +1,144 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
```suggestion // Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors ```
swift-openapi-runtime
github_2023
others
126
apple
simonjbeaumont
@@ -0,0 +1,144 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +import XCTest +@_spi(Generated) @testable import OpenAPIRuntime + +
Adding these tests are great. IMO we don't need an integration test for this.
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// Error Handling middleware that converts an error to a HTTP response +/// +/// This is an opt-in middleware that adopters may choose to include to convert application errors +/// to a HTTP Response +/// +/// Inclusion of this ErrorHandling Middleware should be accompanied by confirming errors to +/// HTTPResponseConvertible protocol. Only errors confirming to HTTPResponseConvertible are converted to a HTTP response. Other errors are re-thrown from this middleware. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the error middleware while registering the handler +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// + +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept(_ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?)) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { + return try await next(request, body, metadata) + } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return (HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody) + } else { + throw error + } + } + } +} + +/// Protocol used by ErrorHandling middleware to map an error to a HTTPResponse +/// +/// Adopters who wish to convert their application error to a HTTPResponse +/// should confirm their error(s) to this protocol
I'm fine with it staying all in the same file.
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response.
```suggestion /// An opt-in error handling middleware that converts an error to a HTTP response. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol.
```suggestion /// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code.
```suggestion /// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage
```suggestion /// ## Example usage ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol:
```suggestion /// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self {
```suggestion /// switch self { ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = try await RequestHandler()
```suggestion /// let handler = RequestHandler() ``` We can just show a simpler example, to avoid people assuming their handlers are expected/required to use `try await` for initializers.
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept(
```suggestion public struct ErrorHandlingMiddleware: ServerMiddleware { public init() {} public func intercept( ``` We need a public initializer here. And please add doc comments to both.
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// Protocol used by ErrorHandling middleware to map an error to a HTTPResponse.
```suggestion /// A protocol used by ``ErrorHandlingMiddleware`` to map an error to an `HTTPResponse` and ``HTTPBody``. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// Protocol used by ErrorHandling middleware to map an error to a HTTPResponse. +/// Adopters who wish to convert their application error to a HTTPResponse should confirm their error(s) to this protocol.
```suggestion /// Adopters who wish to convert their application error to an `HTTPResponse` and ``HTTPBody`` should conform the error type to this protocol. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// Protocol used by ErrorHandling middleware to map an error to a HTTPResponse. +/// Adopters who wish to convert their application error to a HTTPResponse should confirm their error(s) to this protocol. +public protocol HTTPResponseConvertible { + + /// HTTP status to return in the response.
```suggestion /// An HTTP status to return in the response. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// Protocol used by ErrorHandling middleware to map an error to a HTTPResponse. +/// Adopters who wish to convert their application error to a HTTPResponse should confirm their error(s) to this protocol. +public protocol HTTPResponseConvertible { + + /// HTTP status to return in the response. + var httpStatus: HTTPResponse.Status { get } + /// Headers to return in the response. + /// This is optional as default values are provided in the extension.
```suggestion /// /// This is optional as default values are provided in the extension. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// Protocol used by ErrorHandling middleware to map an error to a HTTPResponse. +/// Adopters who wish to convert their application error to a HTTPResponse should confirm their error(s) to this protocol. +public protocol HTTPResponseConvertible { + + /// HTTP status to return in the response. + var httpStatus: HTTPResponse.Status { get } + /// Headers to return in the response. + /// This is optional as default values are provided in the extension. + var httpHeaderFields: HTTPTypes.HTTPFields { get } + /// (Optional) The body of the response to return
```suggestion /// The body of the HTTP response. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// Protocol used by ErrorHandling middleware to map an error to a HTTPResponse. +/// Adopters who wish to convert their application error to a HTTPResponse should confirm their error(s) to this protocol. +public protocol HTTPResponseConvertible { + + /// HTTP status to return in the response. + var httpStatus: HTTPResponse.Status { get } + /// Headers to return in the response.
```suggestion /// The HTTP headers of the response. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error Handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by confirming errors to ``HTTPResponseConvertible`` protocol. +/// Undocumented errors, i.e, errors not confriming to ``HTTPResponseConvertible`` are converted to a response with 500 status code. +/// +/// Example usage +/// 1. Create an error type that conforms to HTTPResponseConvertible protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = try await RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// Protocol used by ErrorHandling middleware to map an error to a HTTPResponse. +/// Adopters who wish to convert their application error to a HTTPResponse should confirm their error(s) to this protocol. +public protocol HTTPResponseConvertible { + + /// HTTP status to return in the response. + var httpStatus: HTTPResponse.Status { get } + /// Headers to return in the response. + /// This is optional as default values are provided in the extension. + var httpHeaderFields: HTTPTypes.HTTPFields { get } + /// (Optional) The body of the response to return + var httpBody: OpenAPIRuntime.HTTPBody? { get } +} + +/// Extension to HTTPResponseConvertible to provide default values for certian fields. +public extension HTTPResponseConvertible { + var httpHeaderFields: HTTPTypes.HTTPFields { [:] } + var httpBody: OpenAPIRuntime.HTTPBody? { nil } +}
```suggestion /// Extension to HTTPResponseConvertible to provide default values for certain fields. extension HTTPResponseConvertible { public var httpHeaderFields: HTTPTypes.HTTPFields { [:] } public var httpBody: OpenAPIRuntime.HTTPBody? { nil } } ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,141 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +import XCTest +@_spi(Generated) @testable import OpenAPIRuntime + +final class Test_ErrorHandlingMiddlewareTests: XCTestCase { + static let mockRequest: HTTPRequest = .init(soar_path: "http://abc.com", method: .get) + static let mockBody: HTTPBody = HTTPBody("hello") + static let errorHandlingMiddleware = ErrorHandlingMiddleware() + + func testSuccessfulRequest() async throws { + let response = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .never) + ) + XCTAssertEqual(response.0.status, .ok) + } + func testError_confirmingToProtocol_convertedToResponse() async throws { + let (response, responseBody) = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .convertibleError) + ) + XCTAssertEqual(response.status, .badGateway) + XCTAssertEqual(response.headerFields, [.contentType: "application/json"]) + XCTAssertEqual(responseBody, TEST_HTTP_BODY) + } + + func testError_confirmingToProtocolWithoutAllValues_convertedToResponse() async throws { + let (response, responseBody) = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .partialConvertibleError) + ) + XCTAssertEqual(response.status, .badRequest) + XCTAssertEqual(response.headerFields, [:]) + XCTAssertEqual(responseBody, nil) + } + func testError_notConfirmingToProtocol_returns500() async throws { + let (response, responseBody) = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .nonConvertibleError) + ) + XCTAssertEqual(response.status, .internalServerError) + XCTAssertEqual(response.headerFields, [:]) + XCTAssertEqual(responseBody, nil) + } + private func getNextMiddleware(failurePhase: MockErrorMiddleware_Next.FailurePhase) -> @Sendable ( + HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + let mockNext: + @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) = { request, body, metadata in + try await MockErrorMiddleware_Next(failurePhase: failurePhase) + .intercept( + request, + body: body, + metadata: metadata, + operationID: "testop", + next: { _, _, _ in (HTTPResponse.init(status: .ok), nil) } + ) + } + return mockNext + } +} + +struct MockErrorMiddleware_Next: ServerMiddleware { + enum FailurePhase { + case never + case convertibleError + case nonConvertibleError + case partialConvertibleError + } + var failurePhase: FailurePhase = .never + + @Sendable func intercept( + _ request: HTTPRequest, + body: HTTPBody?, + metadata: ServerRequestMetadata, + operationID: String, + next: (HTTPRequest, HTTPBody?, ServerRequestMetadata) async throws -> (HTTPResponse, HTTPBody?) + ) async throws -> (HTTPResponse, HTTPBody?) { + var error: (any Error)? + switch failurePhase { + case .never: break + case .convertibleError: error = ConvertibleError() + case .nonConvertibleError: error = NonConvertibleError() + case .partialConvertibleError: error = PartialConvertibleError() + } + if let underlyingError = error { + throw ServerError( + operationID: operationID, + request: request, + requestBody: body, + requestMetadata: metadata, + causeDescription: "", + underlyingError: underlyingError + ) + } + let (response, responseBody) = try await next(request, body, metadata) + return (response, responseBody) + } +} + +struct ConvertibleError: Error, HTTPResponseConvertible { + var httpStatus: HTTPTypes.HTTPResponse.Status = HTTPResponse.Status.badGateway + var httpHeaderFields: HTTPFields = [.contentType: "application/json"] + var httpBody: OpenAPIRuntime.HTTPBody? = TEST_HTTP_BODY +} + +struct PartialConvertibleError: Error, HTTPResponseConvertible { + var httpStatus: HTTPTypes.HTTPResponse.Status = HTTPResponse.Status.badRequest +} + +struct NonConvertibleError: Error {} + +let TEST_HTTP_BODY = HTTPBody(try! JSONEncoder().encode(["error", " test error"]))
```suggestion let testHTTPBody = HTTPBody(try! JSONEncoder().encode(["error", " test error"])) ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + + /// Creates an ErrorHandlingMiddleware. + public init() {} + + /// Intercepts an outgoing HTTP request and an incoming HTTP Response, and converts errors(if any) that confirms to ``HTTPResponseConvertible`` to an HTTP response. + /// - Parameters: + /// - request: The HTTP request created during the operation. + /// - body: The HTTP request body created during the operation. + /// - metadata: Request metadata + /// - operationID: The OpenAPI operation identifier. + /// - next: A closure that calls the next middleware, or the transport. + /// - Returns: An HTTPResponse and an optional HTTPBody. + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) {
```suggestion do { return try await next(request, body, metadata) } catch { if let serverError = error as? ServerError, let appError = serverError.underlyingError as? (any HTTPResponseConvertible) { ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response.
```suggestion /// An opt-in error handling middleware that converts an error to an HTTP response. ``` Nit: for consistency, we use "an HTTP ..." in this project.
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol:
```suggestion /// ## Example usage /// /// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares.
```suggestion /// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. It should be determined based on the specific needs of each application. Consider the order of execution and dependencies between middlewares. ``` I believe they have to be on the same line to end up in the same docc "note" block.
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler:
```suggestion /// 2. Opt into the ``ErrorHandlingMiddleware`` while registering the handler: ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + + /// Creates an ErrorHandlingMiddleware.
```suggestion /// Creates a new middleware. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + + /// Creates an ErrorHandlingMiddleware. + public init() {} + + /// Intercepts an outgoing HTTP request and an incoming HTTP Response, and converts errors(if any) that confirms to ``HTTPResponseConvertible`` to an HTTP response. + /// - Parameters: + /// - request: The HTTP request created during the operation. + /// - body: The HTTP request body created during the operation. + /// - metadata: Request metadata + /// - operationID: The OpenAPI operation identifier. + /// - next: A closure that calls the next middleware, or the transport. + /// - Returns: An HTTPResponse and an optional HTTPBody. + public func intercept(
```suggestion // swift-format-ignore: AllPublicDeclarationsHaveDocumentation public func intercept( ``` As I learned recently from @simonjbeaumont 🙂
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + + /// Creates an ErrorHandlingMiddleware. + public init() {} + + /// Intercepts an outgoing HTTP request and an incoming HTTP Response, and converts errors(if any) that confirms to ``HTTPResponseConvertible`` to an HTTP response. + /// - Parameters: + /// - request: The HTTP request created during the operation. + /// - body: The HTTP request body created during the operation. + /// - metadata: Request metadata + /// - operationID: The OpenAPI operation identifier. + /// - next: A closure that calls the next middleware, or the transport. + /// - Returns: An HTTPResponse and an optional HTTPBody. + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// A protocol used by ``ErrorHandlingMiddleware`` to map an error to an ``HTTPResponse`` and ``HTTPBody``. +/// Adopters who wish to convert their application error to an `HTTPResponse` and ``HTTPBody`` should conform the error type to this protocol. +public protocol HTTPResponseConvertible {
```suggestion /// A value that can be converted to an HTTP response and body. /// /// Conform your error type to this protocol to convert it to an `HTTPResponse` and ``HTTPBody``. /// /// Used by ``ErrorHandlingMiddleware``. public protocol HTTPResponseConvertible { ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + + /// Creates an ErrorHandlingMiddleware. + public init() {} + + /// Intercepts an outgoing HTTP request and an incoming HTTP Response, and converts errors(if any) that confirms to ``HTTPResponseConvertible`` to an HTTP response. + /// - Parameters: + /// - request: The HTTP request created during the operation. + /// - body: The HTTP request body created during the operation. + /// - metadata: Request metadata + /// - operationID: The OpenAPI operation identifier. + /// - next: A closure that calls the next middleware, or the transport. + /// - Returns: An HTTPResponse and an optional HTTPBody. + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// A protocol used by ``ErrorHandlingMiddleware`` to map an error to an ``HTTPResponse`` and ``HTTPBody``. +/// Adopters who wish to convert their application error to an `HTTPResponse` and ``HTTPBody`` should conform the error type to this protocol. +public protocol HTTPResponseConvertible { + + /// An HTTP status to return in the response. + var httpStatus: HTTPResponse.Status { get } + /// The HTTP headers of the response.
```suggestion var httpStatus: HTTPResponse.Status { get } /// The HTTP header fields of the response. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + + /// Creates an ErrorHandlingMiddleware. + public init() {} + + /// Intercepts an outgoing HTTP request and an incoming HTTP Response, and converts errors(if any) that confirms to ``HTTPResponseConvertible`` to an HTTP response. + /// - Parameters: + /// - request: The HTTP request created during the operation. + /// - body: The HTTP request body created during the operation. + /// - metadata: Request metadata + /// - operationID: The OpenAPI operation identifier. + /// - next: A closure that calls the next middleware, or the transport. + /// - Returns: An HTTPResponse and an optional HTTPBody. + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// A protocol used by ``ErrorHandlingMiddleware`` to map an error to an ``HTTPResponse`` and ``HTTPBody``. +/// Adopters who wish to convert their application error to an `HTTPResponse` and ``HTTPBody`` should conform the error type to this protocol. +public protocol HTTPResponseConvertible { + + /// An HTTP status to return in the response. + var httpStatus: HTTPResponse.Status { get } + /// The HTTP headers of the response. + /// This is optional as default values are provided in the extension. + var httpHeaderFields: HTTPTypes.HTTPFields { get } + /// The body of the HTTP response.
```suggestion var httpHeaderFields: HTTPTypes.HTTPFields { get } /// The body of the HTTP response. ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +/// An opt-in error handling middleware that converts an error to a HTTP response. +/// +/// Inclusion of ``ErrorHandlingMiddleware`` should be accompanied by conforming errors to the ``HTTPResponseConvertible`` protocol. +/// Errors not conforming to ``HTTPResponseConvertible`` are converted to a response with the 500 status code. +/// +/// ## Example usage +/// 1. Create an error type that conforms to the ``HTTPResponseConvertible`` protocol: +/// +/// ```swift +/// extension MyAppError: HTTPResponseConvertible { +/// var httpStatus: HTTPResponse.Status { +/// switch self { +/// case .invalidInputFormat: +/// .badRequest +/// case .authorizationError: +/// .forbidden +/// } +/// } +/// } +/// ``` +/// +/// 2. Opt in to the ``ErrorHandlingMiddleware`` while registering the handler: +/// +/// ```swift +/// let handler = RequestHandler() +/// try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()]) +/// ``` +/// - Note: The placement of ``ErrorHandlingMiddleware`` in the middleware chain is important. +/// It should be determined based on the specific needs of each application. +/// Consider the order of execution and dependencies between middlewares. +public struct ErrorHandlingMiddleware: ServerMiddleware { + + /// Creates an ErrorHandlingMiddleware. + public init() {} + + /// Intercepts an outgoing HTTP request and an incoming HTTP Response, and converts errors(if any) that confirms to ``HTTPResponseConvertible`` to an HTTP response. + /// - Parameters: + /// - request: The HTTP request created during the operation. + /// - body: The HTTP request body created during the operation. + /// - metadata: Request metadata + /// - operationID: The OpenAPI operation identifier. + /// - next: A closure that calls the next middleware, or the transport. + /// - Returns: An HTTPResponse and an optional HTTPBody. + public func intercept( + _ request: HTTPTypes.HTTPRequest, + body: OpenAPIRuntime.HTTPBody?, + metadata: OpenAPIRuntime.ServerRequestMetadata, + operationID: String, + next: @Sendable (HTTPTypes.HTTPRequest, OpenAPIRuntime.HTTPBody?, OpenAPIRuntime.ServerRequestMetadata) + async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) + ) async throws -> (HTTPTypes.HTTPResponse, OpenAPIRuntime.HTTPBody?) { + do { return try await next(request, body, metadata) } catch let error as ServerError { + if let appError = error.underlyingError as? (any HTTPResponseConvertible) { + return ( + HTTPResponse(status: appError.httpStatus, headerFields: appError.httpHeaderFields), + appError.httpBody + ) + } else { + return (HTTPResponse(status: .internalServerError), nil) + } + } + } +} + +/// A protocol used by ``ErrorHandlingMiddleware`` to map an error to an ``HTTPResponse`` and ``HTTPBody``. +/// Adopters who wish to convert their application error to an `HTTPResponse` and ``HTTPBody`` should conform the error type to this protocol. +public protocol HTTPResponseConvertible { + + /// An HTTP status to return in the response. + var httpStatus: HTTPResponse.Status { get } + /// The HTTP headers of the response. + /// This is optional as default values are provided in the extension. + var httpHeaderFields: HTTPTypes.HTTPFields { get } + /// The body of the HTTP response. + var httpBody: OpenAPIRuntime.HTTPBody? { get } +} + +/// Extension to HTTPResponseConvertible to provide default values for certain fields. +extension HTTPResponseConvertible { + public var httpHeaderFields: HTTPTypes.HTTPFields { [:] } + public var httpBody: OpenAPIRuntime.HTTPBody? { nil } +}
```suggestion extension HTTPResponseConvertible { // swift-format-ignore: AllPublicDeclarationsHaveDocumentation public var httpHeaderFields: HTTPTypes.HTTPFields { [:] } // swift-format-ignore: AllPublicDeclarationsHaveDocumentation public var httpBody: OpenAPIRuntime.HTTPBody? { nil } } ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,141 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +import XCTest +@_spi(Generated) @testable import OpenAPIRuntime + +final class Test_ErrorHandlingMiddlewareTests: XCTestCase { + static let mockRequest: HTTPRequest = .init(soar_path: "http://abc.com", method: .get) + static let mockBody: HTTPBody = HTTPBody("hello") + static let errorHandlingMiddleware = ErrorHandlingMiddleware() + + func testSuccessfulRequest() async throws { + let response = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .never) + ) + XCTAssertEqual(response.0.status, .ok) + } + func testError_confirmingToProtocol_convertedToResponse() async throws {
```suggestion } func testError_conformingToProtocol_convertedToResponse() async throws { ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,141 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +import XCTest +@_spi(Generated) @testable import OpenAPIRuntime + +final class Test_ErrorHandlingMiddlewareTests: XCTestCase { + static let mockRequest: HTTPRequest = .init(soar_path: "http://abc.com", method: .get) + static let mockBody: HTTPBody = HTTPBody("hello") + static let errorHandlingMiddleware = ErrorHandlingMiddleware() + + func testSuccessfulRequest() async throws { + let response = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .never) + ) + XCTAssertEqual(response.0.status, .ok) + } + func testError_confirmingToProtocol_convertedToResponse() async throws { + let (response, responseBody) = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .convertibleError) + ) + XCTAssertEqual(response.status, .badGateway) + XCTAssertEqual(response.headerFields, [.contentType: "application/json"]) + XCTAssertEqual(responseBody, TEST_HTTP_BODY) + } + + func testError_confirmingToProtocolWithoutAllValues_convertedToResponse() async throws {
```suggestion func testError_conformingToProtocolWithoutAllValues_convertedToResponse() async throws { ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,141 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +import XCTest +@_spi(Generated) @testable import OpenAPIRuntime + +final class Test_ErrorHandlingMiddlewareTests: XCTestCase { + static let mockRequest: HTTPRequest = .init(soar_path: "http://abc.com", method: .get) + static let mockBody: HTTPBody = HTTPBody("hello") + static let errorHandlingMiddleware = ErrorHandlingMiddleware() + + func testSuccessfulRequest() async throws { + let response = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .never) + ) + XCTAssertEqual(response.0.status, .ok) + } + func testError_confirmingToProtocol_convertedToResponse() async throws { + let (response, responseBody) = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .convertibleError) + ) + XCTAssertEqual(response.status, .badGateway) + XCTAssertEqual(response.headerFields, [.contentType: "application/json"]) + XCTAssertEqual(responseBody, TEST_HTTP_BODY) + } + + func testError_confirmingToProtocolWithoutAllValues_convertedToResponse() async throws { + let (response, responseBody) = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .partialConvertibleError) + ) + XCTAssertEqual(response.status, .badRequest) + XCTAssertEqual(response.headerFields, [:]) + XCTAssertEqual(responseBody, nil) + } + func testError_notConfirmingToProtocol_returns500() async throws {
```suggestion } func testError_notConformingToProtocol_returns500() async throws { ```
swift-openapi-runtime
github_2023
others
126
apple
czechboy0
@@ -0,0 +1,141 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2024 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import HTTPTypes + +import XCTest +@_spi(Generated) @testable import OpenAPIRuntime + +final class Test_ErrorHandlingMiddlewareTests: XCTestCase { + static let mockRequest: HTTPRequest = .init(soar_path: "http://abc.com", method: .get) + static let mockBody: HTTPBody = HTTPBody("hello") + static let errorHandlingMiddleware = ErrorHandlingMiddleware() + + func testSuccessfulRequest() async throws { + let response = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .never) + ) + XCTAssertEqual(response.0.status, .ok) + } + func testError_confirmingToProtocol_convertedToResponse() async throws { + let (response, responseBody) = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .convertibleError) + ) + XCTAssertEqual(response.status, .badGateway) + XCTAssertEqual(response.headerFields, [.contentType: "application/json"]) + XCTAssertEqual(responseBody, TEST_HTTP_BODY) + } + + func testError_confirmingToProtocolWithoutAllValues_convertedToResponse() async throws { + let (response, responseBody) = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .partialConvertibleError) + ) + XCTAssertEqual(response.status, .badRequest) + XCTAssertEqual(response.headerFields, [:]) + XCTAssertEqual(responseBody, nil) + } + func testError_notConfirmingToProtocol_returns500() async throws { + let (response, responseBody) = try await Test_ErrorHandlingMiddlewareTests.errorHandlingMiddleware.intercept( + Test_ErrorHandlingMiddlewareTests.mockRequest, + body: Test_ErrorHandlingMiddlewareTests.mockBody, + metadata: .init(), + operationID: "testop", + next: getNextMiddleware(failurePhase: .nonConvertibleError) + ) + XCTAssertEqual(response.status, .internalServerError) + XCTAssertEqual(response.headerFields, [:]) + XCTAssertEqual(responseBody, nil) + } + private func getNextMiddleware(failurePhase: MockErrorMiddleware_Next.FailurePhase) -> @Sendable (
```suggestion } private func getNextMiddleware(failurePhase: MockErrorMiddleware_Next.FailurePhase) -> @Sendable ( ```
swift-openapi-runtime
github_2023
others
113
apple
simonjbeaumont
@@ -56,11 +56,34 @@ extension Converter { // Drop everything after the optional semicolon (q, extensions, ...) value.split(separator: ";")[0].trimmingCharacters(in: .whitespacesAndNewlines).lowercased() } - if acceptValues.isEmpty { return } - if acceptValues.contains("*/*") { return } - if acceptValues.contains("\(substring.split(separator: "/")[0].lowercased())/*") { return } - if acceptValues.contains(where: { $0.localizedCaseInsensitiveContains(substring) }) { return } + guard let parsedSubstring = OpenAPIMIMEType(substring) else { + throw RuntimeError.invalidAcceptSubstring(substring) + } + guard case .concrete(let substringType, let substringSubtype) = parsedSubstring.kind else { + // If the substring content type has a wildcard, just let it through. + // It's not well defined how such a case should behave, so be permissive. + return + }
Is this case correct? The function is supposed to throw an error if the `Accept` header is present but incompatible with the provided content type. The comments here indicate that this case is handling where the header is wildcards, and there is such a case in the deleted part of the diff, but it looks like this handles any `.concrete` with arbitrary associated values for `substringType` and `substringSubtype`. Is this missing some use of `.any` values? Currently, adding the following to the tests fails, ```diff let cases: [(HTTPFields, String, Bool)] = [ + ([.accept: "text/plain"], "application/*", false), ```
swift-openapi-runtime
github_2023
others
113
apple
simonjbeaumont
@@ -56,11 +56,34 @@ extension Converter { // Drop everything after the optional semicolon (q, extensions, ...) value.split(separator: ";")[0].trimmingCharacters(in: .whitespacesAndNewlines).lowercased() } - if acceptValues.isEmpty { return } - if acceptValues.contains("*/*") { return } - if acceptValues.contains("\(substring.split(separator: "/")[0].lowercased())/*") { return } - if acceptValues.contains(where: { $0.localizedCaseInsensitiveContains(substring) }) { return } + guard let parsedSubstring = OpenAPIMIMEType(substring) else { + throw RuntimeError.invalidAcceptSubstring(substring) + } + guard case .concrete(let substringType, let substringSubtype) = parsedSubstring.kind else { + // If the substring content type has a wildcard, just let it through. + // It's not well defined how such a case should behave, so be permissive. + return + } + + // Look for the first match. + for acceptValue in acceptValues { + // Fast path. + if acceptValue == substring { return } + guard let parsedAcceptValue = OpenAPIMIMEType(acceptValue) else { + throw RuntimeError.invalidExpectedContentType(acceptValue) + }
How permissive would we like to be here? If a client sends an `Accept` header with a valid content-type that the server supports, and an invalid one, should the server permit it? IIUC, this `guard` statement suggests not, but is that the desired behaviour?
swift-openapi-runtime
github_2023
others
113
apple
simonjbeaumont
@@ -56,11 +56,42 @@ extension Converter { // Drop everything after the optional semicolon (q, extensions, ...) value.split(separator: ";")[0].trimmingCharacters(in: .whitespacesAndNewlines).lowercased() } - if acceptValues.isEmpty { return } - if acceptValues.contains("*/*") { return } - if acceptValues.contains("\(substring.split(separator: "/")[0].lowercased())/*") { return } - if acceptValues.contains(where: { $0.localizedCaseInsensitiveContains(substring) }) { return } + guard let parsedSubstring = OpenAPIMIMEType(substring) else { + throw RuntimeError.invalidAcceptSubstring(substring) + } + // Look for the first match. + for acceptValue in acceptValues { + // Fast path. + if acceptValue == substring { return } + guard let parsedAcceptValue = OpenAPIMIMEType(acceptValue) else { + throw RuntimeError.invalidExpectedContentType(acceptValue) + } + switch (parsedAcceptValue.kind, parsedSubstring.kind) { + case (.any, _): + // Accept: */* always matches + return + case (.anySubtype(type: let acceptType), let substring): + switch substring { + case .any: + // */* as a concrete content type is NOT a match for an Accept header of foo/* + break + case .anySubtype(type: let substringType): + // Only match if the types match. + if substringType.lowercased() == acceptType.lowercased() { return } + case .concrete(type: let substringType, _): + if substringType.lowercased() == acceptType.lowercased() { return } + } + case (.concrete(type: let acceptType, subtype: let acceptSubtype), let substring): + if case let .concrete(substringType, substringSubtype) = substring { + if acceptType.lowercased() == substringType.lowercased() + && acceptSubtype.lowercased() == substringSubtype.lowercased() + { + return + } + } + } + }
Functionally I've convinced myself this is fine but I found the combination of doing all accept header values in the loop, the use of nested switch and the early-return to be a challenge to understand. I'd really like to factor this out into a function that operates on two parsed `OpenAPIMIMETypes` and returns a boolean whether one can satisfy the other. Essentially, adding _this_ to `OpenAPIMIMEType`: ```swift func satisfies(parsedAcceptValue: OpenAPIMIMEType) -> Bool { switch (parsedAcceptValue.kind, self.kind) { case (.concrete, .any), (.concrete, .anySubtype), (.anySubtype, .any): // The response content-type must be at least as specific as the accept header. return false case (.any, _): // Accept: */* -- Any content-type satisfies the accept header. return true case (.anySubtype(let acceptType), .anySubtype(let substringType)), (.anySubtype(let acceptType), .concrete(let substringType, _)): // Accept: type/* -- The content-type should match the partially-specified accept header. return acceptType.lowercased() == substringType.lowercased() case (.concrete(let acceptType, let acceptSubtype), .concrete(let substringType, let substringSubtype)): // Accept: type/subtype -- The content-type should match the concrete type. return acceptType.lowercased() == substringType.lowercased() && acceptSubtype.lowercased() == substringSubtype.lowercased() } } ``` Then this function that does validation and throws can become: ```swift ... // Look for the first match. for acceptValue in acceptValues { // Fast path. if acceptValue == substring { return } guard let parsedAcceptValue = OpenAPIMIMEType(acceptValue) else { throw RuntimeError.invalidExpectedContentType(acceptValue) } if parsedSubstring.satisfies(parsedAcceptValue: parsedAcceptValue) { return } } throw RuntimeError.unexpectedAcceptHeader(acceptHeader) ``` It affords for a more testable, composable function too.
swift-openapi-runtime
github_2023
others
122
apple
simonjbeaumont
@@ -9,22 +9,15 @@ jobs: name: Soundness uses: apple/swift-nio/.github/workflows/soundness.yml@main with: - api_breakage_check_enabled: true - broken_symlink_check_enabled: true - docs_check_enabled: true - format_check_enabled: true - license_header_check_enabled: true license_header_check_project_name: "SwiftOpenAPIGenerator" - shell_check_enabled: true - unacceptable_language_check_enabled: true
Why are we removing these?
swift-openapi-runtime
github_2023
others
122
apple
czechboy0
@@ -9,22 +9,15 @@ jobs: name: Soundness uses: apple/swift-nio/.github/workflows/soundness.yml@main
Should this be switched to the reusable one?
swift-openapi-runtime
github_2023
others
122
apple
czechboy0
@@ -9,9 +9,9 @@ jobs: name: Unit tests uses: apple/swift-nio/.github/workflows/unit_tests.yml@main
Same here? https://github.com/apple/swift-openapi-runtime/pull/122/files#r1801118837
swift-openapi-runtime
github_2023
others
122
apple
czechboy0
@@ -7,24 +7,17 @@ on: jobs:
Seems the indentation is off two lines higher, @FranzBusch
swift-openapi-runtime
github_2023
others
120
apple
simonjbeaumont
@@ -47,6 +47,16 @@ enum URIEncodedNode: Equatable { /// A date value. case date(Date) } + + /// A primitive value or an array of primitive values. + enum PrimitiveOrArrayOfPrimitives: Equatable { + + /// A primitive value. + case primitive(Primitive) + + /// An array of primitive values. + case arrayOfPrimitives([Primitive])
OOI, why do we need this additional nested enum. Can't we have this as a case in the outer enum?
swift-openapi-runtime
github_2023
others
119
apple
czechboy0
@@ -0,0 +1,24 @@ +// swift-tools-version: 5.9 +import PackageDescription + +let package = Package( + name: "swift-openapi-runtime-benchmarks", + platforms: [ .macOS("14") ], + dependencies: [ + .package(name: "swift-openapi-runtime", path: "../"), + .package(url: "https://github.com/ordo-one/package-benchmark.git", from: "1.22.0"), + ], + targets: [ + .executableTarget( + name: "OpenAPIRuntimeBenchmarks", + dependencies: [ + .product(name: "Benchmark", package: "package-benchmark"), + .product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"), + ], + path: "Benchmarks/OpenAPIRuntimeBenchmarks",
Do we need this nested Benchmarks folder?
swift-openapi-runtime
github_2023
others
115
apple
czechboy0
@@ -79,26 +100,34 @@ extension AsyncSequence where Element == ArraySlice<UInt8>, Self: Sendable { /// Returns another sequence that decodes each event's data as the provided type using the provided decoder. /// /// Use this method if the event's `data` field is not JSON, or if you don't want to parse it using `asDecodedServerSentEventsWithJSONData`. + /// - Parameter: An optional closure that determines whether the given byte sequence is the terminating byte sequence defined by the API. /// - Returns: A sequence that provides the events. - public func asDecodedServerSentEvents() -> ServerSentEventsDeserializationSequence< + public func asDecodedServerSentEvents(terminate: (@Sendable (ArraySlice<UInt8>) -> Bool)? = nil) -> ServerSentEventsDeserializationSequence< ServerSentEventsLineDeserializationSequence<Self> - > { .init(upstream: ServerSentEventsLineDeserializationSequence(upstream: self)) } + > { .init(upstream: ServerSentEventsLineDeserializationSequence(upstream: self), terminate: terminate) }
```suggestion > { .init(upstream: ServerSentEventsLineDeserializationSequence(upstream: self).prefix(while: { !terminate($0) }) } ```
swift-openapi-runtime
github_2023
others
115
apple
czechboy0
@@ -79,26 +100,34 @@ extension AsyncSequence where Element == ArraySlice<UInt8>, Self: Sendable { /// Returns another sequence that decodes each event's data as the provided type using the provided decoder. /// /// Use this method if the event's `data` field is not JSON, or if you don't want to parse it using `asDecodedServerSentEventsWithJSONData`. + /// - Parameter: An optional closure that determines whether the given byte sequence is the terminating byte sequence defined by the API. /// - Returns: A sequence that provides the events. - public func asDecodedServerSentEvents() -> ServerSentEventsDeserializationSequence< + public func asDecodedServerSentEvents(terminate: (@Sendable (ArraySlice<UInt8>) -> Bool)? = nil) -> ServerSentEventsDeserializationSequence<
A possible alternative, but I don't feel strongly either way, looking for feedback ```suggestion public func asDecodedServerSentEvents(terminate: @Sendable (ArraySlice<UInt8>) -> Bool = { _ in false }) -> ServerSentEventsDeserializationSequence< ```
swift-openapi-runtime
github_2023
others
115
apple
czechboy0
@@ -110,6 +139,19 @@ extension AsyncSequence where Element == ArraySlice<UInt8>, Self: Sendable { ) } } + + public func asDecodedServerSentEventsWithJSONData<JSONDataType: Decodable>( + of dataType: JSONDataType.Type = JSONDataType.self, + decoder: JSONDecoder = .init(), + terminatingData: ArraySlice<UInt8>
`lastElement` or `stopOn` are other alternatives
swift-openapi-runtime
github_2023
others
115
apple
czechboy0
@@ -28,9 +28,19 @@ where Upstream.Element == ArraySlice<UInt8> { /// The upstream sequence. private let upstream: Upstream + /// A closure that determines whether the given byte sequence is the terminating byte sequence defined by the API. + /// - Parameter: A byte chunk. + /// - Returns: `True` until the terminating byte sequence is received. + private let predicate: @Sendable (ArraySlice<UInt8>) -> Bool
```suggestion /// A closure that determines whether the given byte chunk should be forwarded to the consumer. /// - Parameter: A byte chunk. /// - Returns: `true` if the byte chunk should be forwarded, `false` if this byte chunk is the terminating sequence. private let predicate: @Sendable (ArraySlice<UInt8>) -> Bool ```
swift-openapi-runtime
github_2023
others
115
apple
czechboy0
@@ -28,9 +28,19 @@ where Upstream.Element == ArraySlice<UInt8> { /// The upstream sequence. private let upstream: Upstream + /// A closure that determines whether the given byte sequence is the terminating byte sequence defined by the API. + /// - Parameter: A byte chunk. + /// - Returns: `True` until the terminating byte sequence is received. + private let predicate: @Sendable (ArraySlice<UInt8>) -> Bool + /// Creates a new sequence. - /// - Parameter upstream: The upstream sequence of arbitrary byte chunks. - public init(upstream: Upstream) { self.upstream = upstream }
This single-parameter initializer also needs to be copied into `Deprecated.swift` rather than renamed, otherwise it'll cause an API break.
swift-openapi-runtime
github_2023
others
115
apple
czechboy0
@@ -28,9 +28,19 @@ where Upstream.Element == ArraySlice<UInt8> { /// The upstream sequence. private let upstream: Upstream + /// A closure that determines whether the given byte sequence is the terminating byte sequence defined by the API. + /// - Parameter: A byte chunk. + /// - Returns: `True` until the terminating byte sequence is received. + private let predicate: @Sendable (ArraySlice<UInt8>) -> Bool + /// Creates a new sequence. - /// - Parameter upstream: The upstream sequence of arbitrary byte chunks. - public init(upstream: Upstream) { self.upstream = upstream } + /// - Parameters: + /// - upstream: The upstream sequence of arbitrary byte chunks. + /// - while: A closure that determines whether the given byte sequence is the terminating byte sequence defined by the API.
```suggestion /// - while: A closure that determines whether the given byte chunk should be forwarded to the consumer. ```