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
swift-openapi-runtime
github_2023
others
55
apple
czechboy0
@@ -0,0 +1,105 @@ +//===----------------------------------------------------------------------===// +// +// 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 + +/// Provides a route to encode or decode base64-encoded data +/// +/// This type holds raw, unencoded, data as a slice of bytes. It can be used to encode that +/// data to a provided `Encoder` as base64-encoded data or to decode from base64 encoding when +/// initialized from a decoder. +/// +/// There is a convenience initializer to create an instance backed by provided data in the form +/// of a slice of bytes: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let base64EncodedData = Base64EncodedData(data: bytes) +/// ``` +/// +/// To decode base64-encoded data it is possible to call the initializer directly, providing a decoder: +/// ```swift +/// let base64EncodedData = Base64EncodedData(from: decoder) +///``` +/// +/// However more commonly the decoding initializer would be called by a decoder e.g.
```suggestion /// However more commonly the decoding initializer would be called by a decoder, for example: ```
swift-openapi-runtime
github_2023
others
55
apple
czechboy0
@@ -0,0 +1,105 @@ +//===----------------------------------------------------------------------===// +// +// 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 + +/// Provides a route to encode or decode base64-encoded data +/// +/// This type holds raw, unencoded, data as a slice of bytes. It can be used to encode that +/// data to a provided `Encoder` as base64-encoded data or to decode from base64 encoding when +/// initialized from a decoder. +/// +/// There is a convenience initializer to create an instance backed by provided data in the form +/// of a slice of bytes: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let base64EncodedData = Base64EncodedData(data: bytes) +/// ``` +/// +/// To decode base64-encoded data it is possible to call the initializer directly, providing a decoder: +/// ```swift +/// let base64EncodedData = Base64EncodedData(from: decoder) +///``` +/// +/// However more commonly the decoding initializer would be called by a decoder e.g. +/// ```swift +/// let encodedData: Data = ... +/// let decoded = try JSONDecoder().decode(Base64EncodedData.self, from: encodedData) +///``` +/// +/// Once an instance is holding data, it may be base64 encoded to a provided encoder: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let base64EncodedData = Base64EncodedData(data: bytes) +/// base64EncodedData.encode(to: encoder) +/// ``` +/// +/// However more commonly it would be called by an encoder e.g.
```suggestion /// However more commonly it would be called by an encoder, for example: ```
swift-openapi-runtime
github_2023
others
55
apple
czechboy0
@@ -0,0 +1,105 @@ +//===----------------------------------------------------------------------===// +// +// 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 + +/// Provides a route to encode or decode base64-encoded data +/// +/// This type holds raw, unencoded, data as a slice of bytes. It can be used to encode that +/// data to a provided `Encoder` as base64-encoded data or to decode from base64 encoding when +/// initialized from a decoder. +/// +/// There is a convenience initializer to create an instance backed by provided data in the form +/// of a slice of bytes: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let base64EncodedData = Base64EncodedData(data: bytes) +/// ``` +/// +/// To decode base64-encoded data it is possible to call the initializer directly, providing a decoder: +/// ```swift +/// let base64EncodedData = Base64EncodedData(from: decoder) +///``` +/// +/// However more commonly the decoding initializer would be called by a decoder e.g. +/// ```swift +/// let encodedData: Data = ... +/// let decoded = try JSONDecoder().decode(Base64EncodedData.self, from: encodedData) +///``` +/// +/// Once an instance is holding data, it may be base64 encoded to a provided encoder: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let base64EncodedData = Base64EncodedData(data: bytes) +/// base64EncodedData.encode(to: encoder) +/// ``` +/// +/// However more commonly it would be called by an encoder e.g. +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let encodedData = JSONEncoder().encode(encodedBytes) +/// ``` +public struct Base64EncodedData: Sendable, Hashable { + /// data to be encoded
```suggestion /// A container of the raw bytes. ```
swift-openapi-runtime
github_2023
others
55
apple
czechboy0
@@ -0,0 +1,105 @@ +//===----------------------------------------------------------------------===// +// +// 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 + +/// Provides a route to encode or decode base64-encoded data +/// +/// This type holds raw, unencoded, data as a slice of bytes. It can be used to encode that +/// data to a provided `Encoder` as base64-encoded data or to decode from base64 encoding when +/// initialized from a decoder. +/// +/// There is a convenience initializer to create an instance backed by provided data in the form +/// of a slice of bytes: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let base64EncodedData = Base64EncodedData(data: bytes) +/// ``` +/// +/// To decode base64-encoded data it is possible to call the initializer directly, providing a decoder: +/// ```swift +/// let base64EncodedData = Base64EncodedData(from: decoder) +///``` +/// +/// However more commonly the decoding initializer would be called by a decoder e.g. +/// ```swift +/// let encodedData: Data = ... +/// let decoded = try JSONDecoder().decode(Base64EncodedData.self, from: encodedData) +///``` +/// +/// Once an instance is holding data, it may be base64 encoded to a provided encoder: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let base64EncodedData = Base64EncodedData(data: bytes) +/// base64EncodedData.encode(to: encoder) +/// ``` +/// +/// However more commonly it would be called by an encoder e.g. +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let encodedData = JSONEncoder().encode(encodedBytes) +/// ``` +public struct Base64EncodedData: Sendable, Hashable { + /// data to be encoded + public var data: ArraySlice<UInt8> + + /// Initializes an instance of ``Base64EncodedData`` wrapping the provided slice of bytes. + /// - Parameter data: The underlying bytes to wrap. + public init(data: ArraySlice<UInt8>) { + self.data = data + } +} + +extension Base64EncodedData: Codable { + /// Creates a new instance by decoding from the given decoder. + /// + /// This initializer throws an error if reading from the decoder fails, or + /// if the data read is corrupted or otherwise invalid. + /// + /// - Parameter decoder: The decoder to read data from. + public init(from decoder: any Decoder) throws {
```suggestion public init(from decoder: any Decoder) throws { ``` We skip documenting conformances.
swift-openapi-runtime
github_2023
others
55
apple
czechboy0
@@ -0,0 +1,105 @@ +//===----------------------------------------------------------------------===// +// +// 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 + +/// Provides a route to encode or decode base64-encoded data +/// +/// This type holds raw, unencoded, data as a slice of bytes. It can be used to encode that +/// data to a provided `Encoder` as base64-encoded data or to decode from base64 encoding when +/// initialized from a decoder. +/// +/// There is a convenience initializer to create an instance backed by provided data in the form +/// of a slice of bytes: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let base64EncodedData = Base64EncodedData(data: bytes) +/// ``` +/// +/// To decode base64-encoded data it is possible to call the initializer directly, providing a decoder: +/// ```swift +/// let base64EncodedData = Base64EncodedData(from: decoder) +///``` +/// +/// However more commonly the decoding initializer would be called by a decoder e.g. +/// ```swift +/// let encodedData: Data = ... +/// let decoded = try JSONDecoder().decode(Base64EncodedData.self, from: encodedData) +///``` +/// +/// Once an instance is holding data, it may be base64 encoded to a provided encoder: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let base64EncodedData = Base64EncodedData(data: bytes) +/// base64EncodedData.encode(to: encoder) +/// ``` +/// +/// However more commonly it would be called by an encoder e.g. +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let encodedData = JSONEncoder().encode(encodedBytes) +/// ``` +public struct Base64EncodedData: Sendable, Hashable { + /// data to be encoded + public var data: ArraySlice<UInt8> + + /// Initializes an instance of ``Base64EncodedData`` wrapping the provided slice of bytes. + /// - Parameter data: The underlying bytes to wrap. + public init(data: ArraySlice<UInt8>) { + self.data = data + } +} + +extension Base64EncodedData: Codable { + /// Creates a new instance by decoding from the given decoder. + /// + /// This initializer throws an error if reading from the decoder fails, or + /// if the data read is corrupted or otherwise invalid. + /// + /// - Parameter decoder: The decoder to read data from. + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + let base64EncodedString = try container.decode(String.self) + + // permissive decoding + let options = Data.Base64DecodingOptions.ignoreUnknownCharacters + + guard let data = Data(base64Encoded: base64EncodedString, options: options) else { + throw RuntimeError.invalidBase64String(base64EncodedString) + } + self.init(data: ArraySlice(data)) + } + + /// Encodes this value into the given encoder. + /// + /// If the value fails to encode anything, `encoder` will encode an empty + /// keyed container in its place. + /// + /// This function throws an error if any values are invalid for the given + /// encoder's format. + /// + /// - Parameter encoder: The encoder to write data to. + public func encode(to encoder: any Encoder) throws {
```suggestion public func encode(to encoder: any Encoder) throws { ``` Same here.
swift-openapi-runtime
github_2023
others
55
apple
czechboy0
@@ -73,6 +74,8 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret return "Invalid expected content type: '\(string)'" case .invalidHeaderFieldName(let name): return "Invalid header field name: '\(name)'" + case .invalidBase64String(let string): + return "Invalid base64-encoded string: '\(string)'"
Let's cap how many bytes we'd actually print. ```suggestion return "Invalid base64-encoded string (first 128 bytes): '\(string.prefix(128))'" ```
swift-openapi-runtime
github_2023
others
56
apple
czechboy0
@@ -96,6 +100,20 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret return "Transport failed with error: \(underlyingError.localizedDescription)" case .handlerFailed(let underlyingError): return "User handler failed with error: \(underlyingError.localizedDescription)" + case .unexpectedResponseStatus(let expectedStatus, let response): + return "Unexpected response, expected status code: \(expectedStatus), response: \(response)" + case .unexpectedResponseBody(let expectedContentType, let response): + return "Unexpected response body, expected content type: \(expectedContentType), response: \(response)"
```suggestion case .unexpectedResponseBody(let expectedContentType, let body): return "Unexpected response body, expected content type: \(expectedContentType), body: \(body)" ```
swift-openapi-runtime
github_2023
others
56
apple
czechboy0
@@ -96,6 +100,20 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret return "Transport failed with error: \(underlyingError.localizedDescription)" case .handlerFailed(let underlyingError): return "User handler failed with error: \(underlyingError.localizedDescription)" + case .unexpectedResponseStatus(let expectedStatus, let response): + return "Unexpected response, expected status code: \(expectedStatus), response: \(response)" + case .unexpectedResponseBody(let expectedContentType, let response): + return "Unexpected response body, expected content type: \(expectedContentType), response: \(response)" } } } + +@_spi(Generated) +public func throwUnexpectedResponseStatus(expectedStatus: String, response: Any) throws -> Never { + throw RuntimeError.unexpectedResponseStatus(expectedStatus: expectedStatus, response: response) +} + +@_spi(Generated) +public func throwUnexpectedResponseBody(expectedContent: String, body: Any) throws -> Never { + throw RuntimeError.unexpectedResponseBody(expectedContent: expectedContent, body: body) +}
I think these could go into `ErrorExtensions.swift`, and maybe return the constructed error rather than throw it (similar to `DecodingError.failedToDecodeAnySchema(...)` etc).
swift-openapi-runtime
github_2023
others
47
apple
FranzBusch
@@ -47,7 +47,7 @@ "UseLetInEveryBoundCaseVariable" : false, "UseShorthandTypeNames" : true, "UseSingleLinePropertyGetter" : false, - "UseSynthesizedInitializer" : true, + "UseSynthesizedInitializer" : false,
Can we report this upstream?
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false
Do you think there's any benefit to putting the locking in some accessors so we don't forget to do it at the call site? ```suggestion private var _iteratorCreated: Bool = false private var iteratorCreated: Bool { get { lock.lock() defer { lock.unlock() } return _iteratorCreated } set { lock.lock() defer { lock.unlock() } _iteratorCreated = newValue } } ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body.
```suggestion /// - length: The total length of the body. ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +extension HTTPBody.ByteChunk { + /// Creates a byte chunk by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await body.collect(upTo: maxBytes) + } +} + +extension Array where Element == UInt8 { + /// Creates a byte array by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Array(body.collect(upTo: maxBytes)) + } +} + +// MARK: - String-based bodies + +extension HTTPBody { + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + /// - length: The total length of the body. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable, + length: Length + ) { + self.init( + ByteChunk.init(string), + length: length + ) + } + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable + ) { + self.init( + ByteChunk.init(string), + length: .known(string.count) + ) + } + + /// Creates a new body with the provided async throwing stream of strings. + /// - Parameters: + /// - stream: An async throwing stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<some StringProtocol & Sendable, any Error & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream of strings. + /// - Parameters: + /// - stream: An async stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<some StringProtocol & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence of string chunks. + /// - Parameters: + /// - sequence: An async sequence that provides the string chunks. + /// - length: The total lenght of the body.
```suggestion /// - length: The total length of the body. ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body.
```suggestion /// - length: The total length of the body. ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init()
```suggestion var buffer = ByteChunk() ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { +
In the case where `self.length == .known` we should fail early and leave the sequence un-iterated.
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +extension HTTPBody.ByteChunk { + /// Creates a byte chunk by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await body.collect(upTo: maxBytes) + } +} + +extension Array where Element == UInt8 { + /// Creates a byte array by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Array(body.collect(upTo: maxBytes)) + } +} + +// MARK: - String-based bodies + +extension HTTPBody { + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + /// - length: The total length of the body. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable, + length: Length + ) { + self.init( + ByteChunk.init(string),
```suggestion ByteChunk(string), ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +extension HTTPBody.ByteChunk { + /// Creates a byte chunk by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await body.collect(upTo: maxBytes) + } +} + +extension Array where Element == UInt8 { + /// Creates a byte array by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Array(body.collect(upTo: maxBytes)) + } +} + +// MARK: - String-based bodies + +extension HTTPBody { + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + /// - length: The total length of the body. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable, + length: Length + ) { + self.init( + ByteChunk.init(string), + length: length + ) + } + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable + ) { + self.init( + ByteChunk.init(string),
```suggestion ByteChunk(string), ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +extension HTTPBody.ByteChunk { + /// Creates a byte chunk by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await body.collect(upTo: maxBytes) + } +} + +extension Array where Element == UInt8 { + /// Creates a byte array by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Array(body.collect(upTo: maxBytes)) + } +} + +// MARK: - String-based bodies + +extension HTTPBody { + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + /// - length: The total length of the body. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable, + length: Length + ) { + self.init( + ByteChunk.init(string), + length: length + ) + } + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable + ) { + self.init( + ByteChunk.init(string), + length: .known(string.count) + ) + } + + /// Creates a new body with the provided async throwing stream of strings. + /// - Parameters: + /// - stream: An async throwing stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<some StringProtocol & Sendable, any Error & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)),
```suggestion self.init(stream.map(ByteChunk.init)), ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +extension HTTPBody.ByteChunk { + /// Creates a byte chunk by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await body.collect(upTo: maxBytes) + } +} + +extension Array where Element == UInt8 { + /// Creates a byte array by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Array(body.collect(upTo: maxBytes)) + } +} + +// MARK: - String-based bodies + +extension HTTPBody { + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + /// - length: The total length of the body. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable, + length: Length + ) { + self.init( + ByteChunk.init(string), + length: length + ) + } + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable + ) { + self.init( + ByteChunk.init(string), + length: .known(string.count) + ) + } + + /// Creates a new body with the provided async throwing stream of strings. + /// - Parameters: + /// - stream: An async throwing stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<some StringProtocol & Sendable, any Error & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream of strings. + /// - Parameters: + /// - stream: An async stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<some StringProtocol & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)),
```suggestion self.init(stream.map(ByteChunk.init)), ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +extension HTTPBody.ByteChunk { + /// Creates a byte chunk by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await body.collect(upTo: maxBytes) + } +} + +extension Array where Element == UInt8 { + /// Creates a byte array by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Array(body.collect(upTo: maxBytes)) + } +} + +// MARK: - String-based bodies + +extension HTTPBody { + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + /// - length: The total length of the body. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable, + length: Length + ) { + self.init( + ByteChunk.init(string), + length: length + ) + } + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable + ) { + self.init( + ByteChunk.init(string), + length: .known(string.count) + ) + } + + /// Creates a new body with the provided async throwing stream of strings. + /// - Parameters: + /// - stream: An async throwing stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<some StringProtocol & Sendable, any Error & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream of strings. + /// - Parameters: + /// - stream: An async stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<some StringProtocol & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence of string chunks. + /// - Parameters: + /// - sequence: An async sequence that provides the string chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Strings: AsyncSequence>( + _ sequence: Strings, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Strings.Element: StringProtocol & Sendable, Strings: Sendable { + self.init( + .init(sequence.map(ByteChunk.init)),
```suggestion self.init(sequence.map(ByteChunk.init)), ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +extension HTTPBody.ByteChunk { + /// Creates a byte chunk by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await body.collect(upTo: maxBytes) + } +} + +extension Array where Element == UInt8 { + /// Creates a byte array by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Array(body.collect(upTo: maxBytes)) + } +} + +// MARK: - String-based bodies + +extension HTTPBody { + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + /// - length: The total length of the body. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable, + length: Length + ) { + self.init( + ByteChunk.init(string), + length: length + ) + } + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable + ) { + self.init( + ByteChunk.init(string), + length: .known(string.count) + ) + } + + /// Creates a new body with the provided async throwing stream of strings. + /// - Parameters: + /// - stream: An async throwing stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<some StringProtocol & Sendable, any Error & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream of strings. + /// - Parameters: + /// - stream: An async stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<some StringProtocol & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence of string chunks. + /// - Parameters: + /// - sequence: An async sequence that provides the string chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Strings: AsyncSequence>( + _ sequence: Strings, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Strings.Element: StringProtocol & Sendable, Strings: Sendable { + self.init( + .init(sequence.map(ByteChunk.init)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody.ByteChunk { + + /// Creates a byte chunk compatible with the `HTTPBody` type from the provided string. + /// - Parameter string: The string to encode. + @inlinable init(_ string: some StringProtocol & Sendable) { + self = Array(string.utf8)[...] + } +} + +extension String { + /// Creates a string by accumulating the full body in-memory into a single buffer up to + /// the provided maximum number of bytes, converting it to string using the provided encoding.
This function doesn't take a "provided encoding" and unilaterally uses UTF8. We should either update the docs or the function.
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +extension HTTPBody.ByteChunk { + /// Creates a byte chunk by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await body.collect(upTo: maxBytes) + } +} + +extension Array where Element == UInt8 { + /// Creates a byte array by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Array(body.collect(upTo: maxBytes)) + } +} + +// MARK: - String-based bodies + +extension HTTPBody { + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + /// - length: The total length of the body. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable, + length: Length + ) { + self.init( + ByteChunk.init(string), + length: length + ) + } + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable + ) { + self.init( + ByteChunk.init(string), + length: .known(string.count) + ) + } + + /// Creates a new body with the provided async throwing stream of strings. + /// - Parameters: + /// - stream: An async throwing stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<some StringProtocol & Sendable, any Error & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream of strings. + /// - Parameters: + /// - stream: An async stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<some StringProtocol & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence of string chunks. + /// - Parameters: + /// - sequence: An async sequence that provides the string chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Strings: AsyncSequence>( + _ sequence: Strings, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Strings.Element: StringProtocol & Sendable, Strings: Sendable { + self.init( + .init(sequence.map(ByteChunk.init)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody.ByteChunk { + + /// Creates a byte chunk compatible with the `HTTPBody` type from the provided string. + /// - Parameter string: The string to encode. + @inlinable init(_ string: some StringProtocol & Sendable) { + self = Array(string.utf8)[...] + } +} + +extension String { + /// Creates a string by accumulating the full body in-memory into a single buffer up to + /// the provided maximum number of bytes, converting it to string using the provided encoding. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await String( + decoding: body.collect(upTo: maxBytes), + as: UTF8.self + ) + } +} + +// MARK: - HTTPBody conversions + +extension HTTPBody: ExpressibleByStringLiteral { + public convenience init(stringLiteral value: String) { + self.init(value) + } +} + +extension HTTPBody { + + /// Creates a new body from the provided array of bytes. + /// - Parameter bytes: An array of bytes. + @inlinable public convenience init(_ bytes: [UInt8]) { + self.init(bytes[...]) + } +} + +extension HTTPBody: ExpressibleByArrayLiteral { + public typealias ArrayLiteralElement = UInt8 + public convenience init(arrayLiteral elements: UInt8...) { + self.init(elements) + } +} + +extension HTTPBody { + + /// Creates a new body from the provided data chunk. + /// - Parameter data: A single data chunk. + public convenience init(data: Data) { + self.init(ArraySlice(data)) + } +} + +extension Data { + /// Creates a string by accumulating the full body in-memory into a single buffer up to
```suggestion /// Creates a Data by accumulating the full body in-memory into a single buffer up to ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,754 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// A body of an HTTP request or HTTP response. +/// +/// Under the hood, it represents an async sequence of byte chunks. +/// +/// ## Creating a body from a buffer +/// There are convenience initializers to create a body from common types, such +/// as `Data`, `[UInt8]`, `ArraySlice<UInt8>`, and `String`. +/// +/// Create an empty body: +/// ```swift +/// let body = HTTPBody() +/// ``` +/// +/// Create a body from a byte chunk: +/// ```swift +/// let bytes: ArraySlice<UInt8> = ... +/// let body = HTTPBody(bytes) +/// ``` +/// +/// Create a body from `Foundation.Data`: +/// ```swift +/// let data: Foundation.Data = ... +/// let body = HTTPBody(data) +/// ``` +/// +/// Create a body from a string: +/// ```swift +/// let body = HTTPBody("Hello, world!") +/// ``` +/// +/// ## Creating a body from an async sequence +/// The body type also supports initialization from an async sequence. +/// +/// ```swift +/// let producingSequence = ... // an AsyncSequence +/// let length: HTTPBody.Length = .known(1024) // or .unknown +/// let body = HTTPBody( +/// producingSequence, +/// length: length, +/// iterationBehavior: .single // or .multiple +/// ) +/// ``` +/// +/// In addition to the async sequence, also provide the total body length, +/// if known (this can be sent in the `content-length` header), and whether +/// the sequence is safe to be iterated multiple times, or can only be iterated +/// once. +/// +/// Sequences that can be iterated multiple times work better when an HTTP +/// request needs to be retried, or if a redirect is encountered. +/// +/// In addition to providing the async sequence, you can also produce the body +/// using an `AsyncStream` or `AsyncThrowingStream`: +/// +/// ```swift +/// let body = HTTPBody( +/// AsyncStream(ArraySlice<UInt8>.self, { continuation in +/// continuation.yield([72, 69]) +/// continuation.yield([76, 76, 79]) +/// continuation.finish() +/// }), +/// length: .known(5) +/// ) +/// ``` +/// +/// ## Consuming a body as an async sequence +/// The `HTTPBody` type conforms to `AsyncSequence` and uses `ArraySlice<UInt8>` +/// as its element type, so it can be consumed in a streaming fashion, without +/// ever buffering the whole body in your process. +/// +/// For example, to get another sequence that contains only the size of each +/// chunk, and print each size, use: +/// +/// ```swift +/// let chunkSizes = body.map { chunk in chunk.count } +/// for try await chunkSize in chunkSizes { +/// print("Chunk size: \(chunkSize)") +/// } +/// ``` +/// +/// ## Consuming a body as a buffer +/// If you need to collect the whole body before processing it, use one of +/// the convenience initializers on the target types that take an `HTTPBody`. +/// +/// To get all the bytes, use the initializer on `ArraySlice<UInt8>` or `[UInt8]`: +/// +/// ```swift +/// let buffer = try await ArraySlice(collecting: body, upTo: 2 * 1024 * 1024) +/// ``` +/// +/// The body type provides more variants of the collecting initializer on commonly +/// used buffers, such as: +/// - `Foundation.Data` +/// - `Swift.String` +/// +/// > Important: You must provide the maximum number of bytes you can buffer in +/// memory, in the example above we provide 2 MB. If more bytes are available, +/// the method throws the `TooManyBytesError` to stop the process running out +/// of memory. While discouraged, you can provide `upTo: .max` to +/// read all the available bytes, without a limit. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying byte chunk type. + public typealias ByteChunk = ArraySlice<UInt8> + + /// Describes how many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// The body's iteration behavior, which controls how many times + /// the input sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// Describes the total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// A flag indicating whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + /// Creates a new body. + /// - Parameters: + /// - sequence: The input sequence providing the byte chunks. + /// - length: The total length of the body, in other words the accumulated + /// length of all the byte chunks. + /// - iterationBehavior: The sequence's iteration behavior, which + /// indicates whether the sequence can be iterated multiple times. + @usableFromInline init( + _ sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } + + /// Creates a new body with the provided sequence of byte chunks. + /// - Parameters: + /// - byteChunks: A sequence of byte chunks. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @usableFromInline convenience init( + _ byteChunks: some Sequence<ByteChunk> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + .init(WrappedSyncSequence(sequence: byteChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + /// Creates a new empty body. + @inlinable public convenience init() { + self.init( + .init(EmptySequence()), + length: .known(0), + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: ByteChunk, + length: Length + ) { + self.init([bytes], length: length, iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte chunk. + /// - Parameter bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: ByteChunk + ) { + self.init([bytes], length: .known(bytes.count), iterationBehavior: .multiple) + } + + /// Creates a new body with the provided byte sequence. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init( + _ bytes: some Sequence<UInt8> & Sendable, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.init( + [ArraySlice(bytes)], + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + /// - length: The total length of the body. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable, + length: Length + ) { + self.init( + ArraySlice(bytes), + length: length, + iterationBehavior: .multiple + ) + } + + /// Creates a new body with the provided byte collection. + /// - Parameters: + /// - bytes: A byte chunk. + @inlinable public convenience init( + _ bytes: some Collection<UInt8> & Sendable + ) { + self.init(bytes, length: .known(bytes.count)) + } + + /// Creates a new body with the provided async throwing stream. + /// - Parameters: + /// - stream: An async throwing stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<ByteChunk, any Error>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream. + /// - Parameters: + /// - stream: An async stream that provides the byte chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<ByteChunk>, + length: HTTPBody.Length + ) { + self.init( + .init(stream), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes.Element == ByteChunk, Bytes: Sendable { + self.init( + .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } + + /// Creates a new body with the provided async sequence of byte sequences. + /// - Parameters: + /// - sequence: An async sequence that provides the byte chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Bytes: AsyncSequence>( + _ sequence: Bytes, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Bytes: Sendable, Bytes.Element: Sequence, Bytes.Element.Element == UInt8 { + self.init( + sequence.map { ArraySlice($0) }, + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = ByteChunk + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +extension HTTPBody { + + /// An error thrown by the collecting initializer when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + + /// The maximum number of bytes acceptable by the user. + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the collecting initializer when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + /// - Returns: A byte chunk containing all the accumulated bytes. + fileprivate func collect(upTo maxBytes: Int) async throws -> ByteChunk { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = ByteChunk.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +extension HTTPBody.ByteChunk { + /// Creates a byte chunk by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await body.collect(upTo: maxBytes) + } +} + +extension Array where Element == UInt8 { + /// Creates a byte array by accumulating the full body in-memory into a single buffer + /// up to the provided maximum number of bytes and returning it. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Array(body.collect(upTo: maxBytes)) + } +} + +// MARK: - String-based bodies + +extension HTTPBody { + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + /// - length: The total length of the body. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable, + length: Length + ) { + self.init( + ByteChunk.init(string), + length: length + ) + } + + /// Creates a new body with the provided string encoded as UTF-8 bytes. + /// - Parameters: + /// - string: A string to encode as bytes. + @inlinable public convenience init( + _ string: some StringProtocol & Sendable + ) { + self.init( + ByteChunk.init(string), + length: .known(string.count) + ) + } + + /// Creates a new body with the provided async throwing stream of strings. + /// - Parameters: + /// - stream: An async throwing stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncThrowingStream<some StringProtocol & Sendable, any Error & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async stream of strings. + /// - Parameters: + /// - stream: An async stream that provides the string chunks. + /// - length: The total length of the body. + @inlinable public convenience init( + _ stream: AsyncStream<some StringProtocol & Sendable>, + length: HTTPBody.Length + ) { + self.init( + .init(stream.map(ByteChunk.init)), + length: length, + iterationBehavior: .single + ) + } + + /// Creates a new body with the provided async sequence of string chunks. + /// - Parameters: + /// - sequence: An async sequence that provides the string chunks. + /// - length: The total lenght of the body. + /// - iterationBehavior: The iteration behavior of the sequence, which + /// indicates whether it can be iterated multiple times. + @inlinable public convenience init<Strings: AsyncSequence>( + _ sequence: Strings, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where Strings.Element: StringProtocol & Sendable, Strings: Sendable { + self.init( + .init(sequence.map(ByteChunk.init)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension HTTPBody.ByteChunk { + + /// Creates a byte chunk compatible with the `HTTPBody` type from the provided string. + /// - Parameter string: The string to encode. + @inlinable init(_ string: some StringProtocol & Sendable) { + self = Array(string.utf8)[...] + } +} + +extension String { + /// Creates a string by accumulating the full body in-memory into a single buffer up to + /// the provided maximum number of bytes, converting it to string using the provided encoding. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await String( + decoding: body.collect(upTo: maxBytes), + as: UTF8.self + ) + } +} + +// MARK: - HTTPBody conversions + +extension HTTPBody: ExpressibleByStringLiteral { + public convenience init(stringLiteral value: String) { + self.init(value) + } +} + +extension HTTPBody { + + /// Creates a new body from the provided array of bytes. + /// - Parameter bytes: An array of bytes. + @inlinable public convenience init(_ bytes: [UInt8]) { + self.init(bytes[...]) + } +} + +extension HTTPBody: ExpressibleByArrayLiteral { + public typealias ArrayLiteralElement = UInt8 + public convenience init(arrayLiteral elements: UInt8...) { + self.init(elements) + } +} + +extension HTTPBody { + + /// Creates a new body from the provided data chunk. + /// - Parameter data: A single data chunk. + public convenience init(data: Data) { + self.init(ArraySlice(data)) + } +} + +extension Data { + /// Creates a string by accumulating the full body in-memory into a single buffer up to + /// the provided maximum number of bytes and converting it to `Data`. + /// - Parameters: + /// - body: The HTTP body to collect. + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the body contains more + /// than `maxBytes`. + public init(collecting body: HTTPBody, upTo maxBytes: Int) async throws { + self = try await Data(body.collect(upTo: maxBytes)) + } +} + +// MARK: - Underlying async sequences + +extension HTTPBody { + + /// An async iterator of both input async sequences and of the body itself. + public struct Iterator: AsyncIteratorProtocol { + + /// The element byte chunk type. + public typealias Element = HTTPBody.ByteChunk + + /// The closure that produces the next element. + private let produceNext: () async throws -> Element? + + /// Creates a new type-erased iterator from the provided iterator. + /// - Parameter iterator: The iterator to type-erase. + @usableFromInline init<Iterator: AsyncIteratorProtocol>( + _ iterator: Iterator + ) where Iterator.Element == Element { + var iterator = iterator + self.produceNext = { + try await iterator.next() + } + } + + public mutating func next() async throws -> Element? { + try await produceNext() + } + } +} + +extension HTTPBody { + + /// A type-erased async sequence that wraps input sequences. + @usableFromInline struct BodySequence: AsyncSequence, Sendable { + + /// The type of the type-erased iterator. + @usableFromInline typealias AsyncIterator = HTTPBody.Iterator + + /// The byte chunk element type. + @usableFromInline typealias Element = ByteChunk + + /// A closure that produces a new iterator. + @usableFromInline let produceIterator: @Sendable () -> AsyncIterator + + /// Creates a new sequence. + /// - Parameter sequence: The input sequence to type-erase. + @inlinable init<Bytes: AsyncSequence>(_ sequence: Bytes) where Bytes.Element == Element, Bytes: Sendable { + self.produceIterator = { + .init(sequence.makeAsyncIterator())
```suggestion self.init(sequence.makeAsyncIterator()) ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -142,53 +110,42 @@ extension Converter { // | client | set | request body | binary | optional | setOptionalRequestBodyAsBinary | public func setOptionalRequestBodyAsBinary( - _ value: Data?, - headerFields: inout [HeaderField], + _ value: HTTPBody?, + headerFields: inout HTTPFields, contentType: String - ) throws -> Data? { + ) throws -> HTTPBody? { try setOptionalRequestBody( value, headerFields: &headerFields, contentType: contentType, - convert: convertDataToBinary + convert: { $0 } ) } // | client | set | request body | binary | required | setRequiredRequestBodyAsBinary | public func setRequiredRequestBodyAsBinary( - _ value: Data, - headerFields: inout [HeaderField], + _ value: HTTPBody, + headerFields: inout HTTPFields, contentType: String - ) throws -> Data { + ) throws -> HTTPBody { try setRequiredRequestBody( value, headerFields: &headerFields, contentType: contentType, - convert: convertDataToBinary - ) - } - - // | client | get | response body | string | required | getResponseBodyAsString | - public func getResponseBodyAsString<T: Decodable, C>( - _ type: T.Type, - from data: Data, - transforming transform: (T) -> C - ) throws -> C { - try getResponseBody( - type, - from: data, - transforming: transform, - convert: convertFromStringData + convert: { $0 } ) } // | client | get | response body | JSON | required | getResponseBodyAsJSON | public func getResponseBodyAsJSON<T: Decodable, C>( _ type: T.Type, - from data: Data, + from data: HTTPBody?, transforming transform: (T) -> C - ) throws -> C { - try getResponseBody( + ) async throws -> C { + guard let data else { + throw RuntimeError.missingRequiredResponseBody + }
These functions used to take non-optional `Data`. Why are they now taking optional `HTTPBody?`?
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -114,10 +43,44 @@ extension ParameterStyle { } } +extension HTTPField.Name { + + /// Creates a new name for the provided string. + /// - Parameter name: A field name. + /// - Throws: If the name isn't a valid field name. + init(validated name: String) throws { + guard let fieldName = Self.init(name) else {
```suggestion guard let fieldName = Self(name) else { ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -312,17 +306,50 @@ extension Converter { style: style, explode: explode ) - let uriSnippet = try convert(value, resolvedStyle, resolvedExplode) - request.addEscapedQuerySnippet(uriSnippet) + let escapedUriSnippet = try convert(value, resolvedStyle, resolvedExplode) + + let pathAndAll = try request.requiredPath + + // https://datatracker.ietf.org/doc/html/rfc3986#section-3.4 + // > The query component is indicated by the first question + // > mark ("?") character and terminated by a number sign ("#") + // > character or by the end of the URI. + + let fragmentStart = pathAndAll.firstIndex(of: "#") ?? pathAndAll.endIndex + let fragment = pathAndAll[fragmentStart..<pathAndAll.endIndex] + + let queryStart = pathAndAll.firstIndex(of: "?") + + let pathEnd = queryStart ?? fragmentStart + let path = pathAndAll[pathAndAll.startIndex..<pathEnd] + + guard let queryStart else { + // No existing query substring, add the question mark. + request.path = path.appending("?\(escapedUriSnippet)\(fragment)") + return + } + + let query = pathAndAll[pathAndAll.index(after: queryStart)..<fragmentStart] + request.path = path.appending("?\(query)&\(escapedUriSnippet)\(fragment)")
Do we have new tests to cover this revised logic? I didn't see any, and it looks like Test_CurrencyExtensions has been deleted.
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -35,7 +40,13 @@ public struct ClientError: Error { /// /// Will be nil if the error resulted before the request was generated, /// for example if generating the request from the Input failed. - public var request: Request? + public var request: HTTPRequest? + + /// The HTTP request body created during the operation. + /// + /// Will be nil if the error resulted before the request was generated, + /// for example if generating the request from the Input failed. + public var requestBody: HTTPBody?
Have we considered keeping these as a tuple in our layer given they are only ever both nil under the same circumstance. If that claim is false, then the docs for `requestBody` should be updated to include the case where we expect to have a nil body. Ditto: for `response` and `responseBody`.
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -11,25 +11,31 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -import Foundation + +import HTTPTypes +import protocol Foundation.LocalizedError /// An error thrown by a server handling an OpenAPI operation. public struct ServerError: Error { + /// Identifier of the operation that threw the error. public var operationID: String - /// HTTP request provided to the server. - public var request: Request + /// The HTTP request provided to the server. + public var request: HTTPRequest + + /// The HTTP request body provided to the server. + public var requestBody: HTTPBody? - /// Request metadata extracted by the server. - public var requestMetadata: ServerRequestMetadata + /// The request metadata extracted by the server. + public var metadata: ServerRequestMetadata
Why did this change? FWIW I think it was clearer before as it made the distinction between request metadata and metadata about the error.
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -122,14 +132,16 @@ public protocol ClientTransport: Sendable { /// HTTP response. /// - Parameters: /// - request: An HTTP request. + /// - body: An HTTP request body. /// - baseURL: A server base URL. /// - operationID: The identifier of the OpenAPI operation. - /// - Returns: An HTTP response. + /// - Returns: An HTTP response and its body. func send( - _ request: Request, + _ request: HTTPRequest, + body: HTTPBody?, baseURL: URL, operationID: String - ) async throws -> Response + ) async throws -> (HTTPResponse, HTTPBody?)
Can this return a tuple with named parameters, then we can access with e.g. `.body`, rather than `.1`? Similar for middleware.
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -11,281 +11,100 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if canImport(Darwin) -import Foundation -#else -@preconcurrency import struct Foundation.Data -@preconcurrency import struct Foundation.URLQueryItem -#endif -/// A header field used in an HTTP request or response. -public struct HeaderField: Hashable, Sendable { +import HTTPTypes - /// The name of the HTTP header field. - public var name: String +/// A container for request metadata already parsed and validated +/// by the server transport. +public struct ServerRequestMetadata: Hashable, Sendable { - /// The value of the HTTP header field. - public var value: String + /// The path parameters parsed from the URL of the HTTP request. + public var pathParameters: [String: Substring] - /// Creates a new HTTP header field. + /// Creates a new metadata wrapper with the specified path and query parameters. /// - Parameters: - /// - name: A name of the HTTP header field. - /// - value: A value of the HTTP header field. - public init(name: String, value: String) { - self.name = name - self.value = value + /// - pathParameters: Path parameters parsed from the URL of the HTTP + /// request. + public init( + pathParameters: [String: Substring] = [:] + ) { + self.pathParameters = pathParameters } } -/// Describes the HTTP method used in an OpenAPI operation. -/// -/// https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#fixed-fields-7 -public struct HTTPMethod: RawRepresentable, Hashable, Sendable { +extension HTTPRequest { - /// Describes an HTTP method explicitly supported by OpenAPI. - private enum OpenAPIHTTPMethod: String, Hashable, Sendable { - case GET - case PUT - case POST - case DELETE - case OPTIONS - case HEAD - case PATCH - case TRACE - } - - /// The underlying HTTP method. - private let value: OpenAPIHTTPMethod - - /// Creates a new method from the provided known supported HTTP method. - private init(value: OpenAPIHTTPMethod) { - self.value = value + /// Creates a new request. + /// - Parameters: + /// - path: The URL path of the resource. + /// - method: The HTTP method. + /// - headerFields: The HTTP header fields. + public init(soar_path path: String, method: Method, headerFields: HTTPFields = .init()) {
Are we having the `soar_path` label in the API? If this is a value-preserving type conversion we probably want `init(from:method:headerFields:)`
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -11,281 +11,100 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if canImport(Darwin) -import Foundation -#else -@preconcurrency import struct Foundation.Data -@preconcurrency import struct Foundation.URLQueryItem -#endif -/// A header field used in an HTTP request or response. -public struct HeaderField: Hashable, Sendable { +import HTTPTypes - /// The name of the HTTP header field. - public var name: String +/// A container for request metadata already parsed and validated +/// by the server transport. +public struct ServerRequestMetadata: Hashable, Sendable { - /// The value of the HTTP header field. - public var value: String + /// The path parameters parsed from the URL of the HTTP request. + public var pathParameters: [String: Substring] - /// Creates a new HTTP header field. + /// Creates a new metadata wrapper with the specified path and query parameters. /// - Parameters: - /// - name: A name of the HTTP header field. - /// - value: A value of the HTTP header field. - public init(name: String, value: String) { - self.name = name - self.value = value + /// - pathParameters: Path parameters parsed from the URL of the HTTP + /// request. + public init( + pathParameters: [String: Substring] = [:] + ) { + self.pathParameters = pathParameters } } -/// Describes the HTTP method used in an OpenAPI operation. -/// -/// https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#fixed-fields-7 -public struct HTTPMethod: RawRepresentable, Hashable, Sendable { +extension HTTPRequest { - /// Describes an HTTP method explicitly supported by OpenAPI. - private enum OpenAPIHTTPMethod: String, Hashable, Sendable { - case GET - case PUT - case POST - case DELETE - case OPTIONS - case HEAD - case PATCH - case TRACE - } - - /// The underlying HTTP method. - private let value: OpenAPIHTTPMethod - - /// Creates a new method from the provided known supported HTTP method. - private init(value: OpenAPIHTTPMethod) { - self.value = value + /// Creates a new request. + /// - Parameters: + /// - path: The URL path of the resource. + /// - method: The HTTP method. + /// - headerFields: The HTTP header fields. + public init(soar_path path: String, method: Method, headerFields: HTTPFields = .init()) { + self.init(method: method, scheme: nil, authority: nil, path: path, headerFields: headerFields) } - public init?(rawValue: String) { - guard let value = OpenAPIHTTPMethod(rawValue: rawValue) else { + /// The query substring of the request's path. + public var soar_query: Substring? {
Do we want these in the public API? Are they used by the end-user or the transport? If it's the latter, should we consider making a new SPI "transport", like we have "generated"?
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -11,281 +11,100 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -#if canImport(Darwin) -import Foundation -#else -@preconcurrency import struct Foundation.Data -@preconcurrency import struct Foundation.URLQueryItem -#endif -/// A header field used in an HTTP request or response. -public struct HeaderField: Hashable, Sendable { +import HTTPTypes - /// The name of the HTTP header field. - public var name: String +/// A container for request metadata already parsed and validated +/// by the server transport. +public struct ServerRequestMetadata: Hashable, Sendable { - /// The value of the HTTP header field. - public var value: String + /// The path parameters parsed from the URL of the HTTP request. + public var pathParameters: [String: Substring] - /// Creates a new HTTP header field. + /// Creates a new metadata wrapper with the specified path and query parameters. /// - Parameters: - /// - name: A name of the HTTP header field. - /// - value: A value of the HTTP header field. - public init(name: String, value: String) { - self.name = name - self.value = value + /// - pathParameters: Path parameters parsed from the URL of the HTTP + /// request. + public init( + pathParameters: [String: Substring] = [:] + ) { + self.pathParameters = pathParameters } } -/// Describes the HTTP method used in an OpenAPI operation. -/// -/// https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#fixed-fields-7 -public struct HTTPMethod: RawRepresentable, Hashable, Sendable { +extension HTTPRequest { - /// Describes an HTTP method explicitly supported by OpenAPI. - private enum OpenAPIHTTPMethod: String, Hashable, Sendable { - case GET - case PUT - case POST - case DELETE - case OPTIONS - case HEAD - case PATCH - case TRACE - } - - /// The underlying HTTP method. - private let value: OpenAPIHTTPMethod - - /// Creates a new method from the provided known supported HTTP method. - private init(value: OpenAPIHTTPMethod) { - self.value = value + /// Creates a new request. + /// - Parameters: + /// - path: The URL path of the resource. + /// - method: The HTTP method. + /// - headerFields: The HTTP header fields. + public init(soar_path path: String, method: Method, headerFields: HTTPFields = .init()) { + self.init(method: method, scheme: nil, authority: nil, path: path, headerFields: headerFields) } - public init?(rawValue: String) { - guard let value = OpenAPIHTTPMethod(rawValue: rawValue) else { + /// The query substring of the request's path. + public var soar_query: Substring? { + guard let path else { return nil } - self.value = value - } - - public var rawValue: String { - value.rawValue - } - - /// The name of the HTTP method. - public var name: String { - rawValue - } - - /// Returns an HTTP GET method. - public static var get: Self { - .init(value: .GET) - } - - /// Returns an HTTP PUT method. - public static var put: Self { - .init(value: .PUT) - } - - /// Returns an HTTP POST method. - public static var post: Self { - .init(value: .POST) - } - - /// Returns an HTTP DELETE method. - public static var delete: Self { - .init(value: .DELETE) - } - - /// Returns an HTTP OPTIONS method. - public static var options: Self { - .init(value: .OPTIONS) - } - - /// Returns an HTTP HEAD method. - public static var head: Self { - .init(value: .HEAD) - } - - /// Returns an HTTP PATCH method. - public static var patch: Self { - .init(value: .PATCH) + guard let queryStart = path.firstIndex(of: "?") else { + return nil + } + let queryEnd = path.firstIndex(of: "#") ?? path.endIndex + let query = path[path.index(after: queryStart)..<queryEnd] + return query } - /// Returns an HTTP TRACE method. - public static var trace: Self { - .init(value: .TRACE) + /// The request path, without any query or fragment portions. + public var soar_pathOnly: Substring { + guard let path else { + return ""[...] + } + let pathEndIndex = path.firstIndex(of: "?") ?? path.firstIndex(of: "#") ?? path.endIndex + return path[path.startIndex..<pathEndIndex] } } -/// An HTTP request, sent by the client to the server. -public struct Request: Hashable, Sendable { +extension HTTPResponse { - /// The path of the URL for the HTTP request. - public var path: String - - /// The query string of the URL for the HTTP request. - /// - /// A query string provides support for assigning values to parameters - /// within a URL. - /// - /// _URL encoding_, officially known as _percent-encoding_, is a method - /// to encode arbitrary data in a URI using only ASCII characters. - /// - /// An example of a URL with a query string is: - /// - /// ``` - /// https://example.com?name=Maria%20Ruiz&email=mruiz2%40icloud.com - /// ``` - /// - /// For this request, the query string is: - /// - /// ``` - /// name=Maria%20Ruiz&email=mruiz2%40icloud.com - /// ``` - /// - /// - NOTE: The `?` is a seperator in the URL and is **not** part of - /// the query string. - /// - NOTE: Only query parameter names and values are percent-encoded, - /// the `&` and `=` remain. - public var query: String? - - /// The method of the HTTP request. - public var method: HTTPMethod - - /// The header fields of the HTTP request. - public var headerFields: [HeaderField] - - /// The body data of the HTTP request. - public var body: Data? - - /// Creates a new HTTP request. + /// Creates a new response. /// - Parameters: - /// - path: The path of the URL for the request. This must not include - /// the base URL of the server. - /// - query: The query string of the URL for the request. This should not - /// include the separator question mark (`?`) and the names and values - /// should be percent-encoded. See ``query`` for more information. - /// - method: The method of the HTTP request. - /// - headerFields: The header fields of the HTTP request. - /// - body: The body data of the HTTP request. - /// - /// An example of a request: - /// ``` - /// let request = Request( - /// path: "/users", - /// query: "name=Maria%20Ruiz&email=mruiz2%40icloud.com", - /// method: .GET, - /// headerFields: [ - /// .init(name: "Accept", value: "application/json" - /// ], - /// body: nil - /// ) - /// ``` - public init( - path: String, - query: String? = nil, - method: HTTPMethod, - headerFields: [HeaderField] = [], - body: Data? = nil - ) { - self.path = path - self.query = query - self.method = method - self.headerFields = headerFields - self.body = body + /// - statusCode: The status code of the response.AsString + /// - headerFields: The HTTP header fields. + public init(soar_statusCode statusCode: Int, headerFields: HTTPFields = .init()) {
I don't understand. The docs imply this is a string, but it is an integer parameter. If it's an integer, surely there's no divergence between what it means and we can just name this `statusCode` in the API?
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -108,14 +110,15 @@ public protocol ServerTransport { /// - Parameters: /// - handler: A handler to be invoked when an HTTP request is received. /// - method: An HTTP request method. - /// - path: The URL path components, for example `["pets", ":petId"]`. - /// - queryItemNames: The names of query items to be extracted - /// from the request URL that matches the provided HTTP operation. + /// - path: A URL template for the path, for example `/pets/{petId}`. + /// - Important: The `path` can have mixed component, such
```suggestion /// - Important: The `path` can have mixed components, such ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -13,6 +13,13 @@ //===----------------------------------------------------------------------===// import XCTest @_spi(Generated)@testable import OpenAPIRuntime +import HTTPTypes + +extension HTTPField.Name { + static var foo: Self { + .init("foo")!
```suggestion Self("foo")! ```
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,189 @@ +//===----------------------------------------------------------------------===// +// +// 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 XCTest +@_spi(Generated)@testable import OpenAPIRuntime +import Foundation + +final class Test_Body: Test_Runtime { + + func testCreateAndCollect() async throws { + + // A single string. + do { + let body: HTTPBody = HTTPBody("hello") + try await _testConsume( + body, + expected: "hello" + ) + } + + // A literal string. + do { + let body: HTTPBody = "hello" + try await _testConsume( + body, + expected: "hello" + ) + } + + // A single substring. + do { + let body: HTTPBody = HTTPBody("hello") + try await _testConsume( + body, + expected: "hello" + ) + }
This test is identical to `// A single string.`.
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,189 @@ +//===----------------------------------------------------------------------===// +// +// 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 XCTest +@_spi(Generated)@testable import OpenAPIRuntime +import Foundation + +final class Test_Body: Test_Runtime { + + func testCreateAndCollect() async throws { + + // A single string. + do { + let body: HTTPBody = HTTPBody("hello") + try await _testConsume( + body, + expected: "hello" + ) + } + + // A literal string. + do { + let body: HTTPBody = "hello" + try await _testConsume( + body, + expected: "hello" + ) + } + + // A single substring. + do { + let body: HTTPBody = HTTPBody("hello") + try await _testConsume( + body, + expected: "hello" + ) + } + + // A single array of bytes. + do { + let body: HTTPBody = HTTPBody([0]) + try await _testConsume( + body, + expected: [0] + ) + } + + // A literal array of bytes. + do { + let body: HTTPBody = [0] + try await _testConsume( + body, + expected: [0] + ) + } + + // A single data. + do { + let body: HTTPBody = HTTPBody(data: Data([0])) + try await _testConsume( + body, + expected: [0] + ) + } + + // A single slice of an array of bytes. + do { + let body: HTTPBody = HTTPBody([0][...]) + try await _testConsume( + body, + expected: [0][...] + ) + } + + // An async throwing stream. + do { + let body: HTTPBody = HTTPBody( + AsyncThrowingStream( + String.self, + { continuation in + continuation.yield("hel") + continuation.yield("lo") + continuation.finish() + } + ), + length: .known(5) + ) + try await _testConsume( + body, + expected: "hello" + ) + } + + // An async stream. + do { + let body: HTTPBody = HTTPBody( + AsyncStream( + String.self, + { continuation in + continuation.yield("hel") + continuation.yield("lo") + continuation.finish() + } + ), + length: .known(5) + ) + try await _testConsume( + body, + expected: "hello" + ) + } + + // Another async sequence. + do { + let sequence = AsyncStream( + String.self, + { continuation in + continuation.yield("hel") + continuation.yield("lo") + continuation.finish() + } + ) + .map { $0 } + let body: HTTPBody = HTTPBody( + sequence, + length: .known(5), + iterationBehavior: .single + ) + try await _testConsume( + body, + expected: "hello" + ) + }
Can we add some with "unknown" length (even if we do really know the length)?
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -0,0 +1,189 @@ +//===----------------------------------------------------------------------===// +// +// 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 XCTest +@_spi(Generated)@testable import OpenAPIRuntime +import Foundation + +final class Test_Body: Test_Runtime {
There are no error tests for iterating a sequence more than once?
swift-openapi-runtime
github_2023
others
47
apple
simonjbeaumont
@@ -427,18 +438,14 @@ extension HTTPBody { // iterate a sequence for the second time, if it's only safe to be // iterated once. if iterationBehavior == .single { - try { - lock.lock() - defer { - lock.unlock() - } - guard !locked_iteratorCreated else { + try withIteratorCreated { iteratorCreated in + guard !iteratorCreated else { throw TooManyIterationsError() } - }() + } }
Shouldn't we be setting `iteratorCreated` to true here? Maybe we'd be better to rework the new `withIteratorCreated<R>(_:)` to be the place where this is set, so the semantics of it become: - If it's already been set throw; - If it's not set, set it, and perform the provided operation.
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -273,6 +273,34 @@ extension Converter { ) } + // | server | get | request body | URLEncodedForm | codable | optional | getOptionalRequestBodyAsURLEncodedForm |
Please add the `getOptionalRequestBodyAsURLEncodedForm` names to the documentation at `Sources/swift-openapi-generator/Documentation.docc/Development/Converting-between-data-and-Swift-types.md` as well, in the same location in the list as here in the implementation.
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -177,12 +177,50 @@ extension Converter { try decoder.decode(T.self, from: data) } + func convertURLEncodedFormToCodable<T: Decodable>( + _ data: Data + ) throws -> T { + + let decoder = URIDecoder( + configuration: .init( + style: .form, + explode: true, + spaceEscapingCharacter: .percentEncoded,
```suggestion spaceEscapingCharacter: .plus, ``` According to https://www.rfc-editor.org/rfc/rfc1866.html#section-8.2.1 > 1. The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped as per [URL];
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -23,6 +23,7 @@ internal enum RuntimeError: Error, CustomStringConvertible, LocalizedError, Pret // Data conversion case failedToDecodeStringConvertibleValue(type: String) + case failedToSerializeCodableData
You can get rid of this, we'll never hit it with my suggestion above.
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -177,12 +177,50 @@ extension Converter { try decoder.decode(T.self, from: data) } + func convertURLEncodedFormToCodable<T: Decodable>( + _ data: Data + ) throws -> T { + + let decoder = URIDecoder( + configuration: .init( + style: .form, + explode: true, + spaceEscapingCharacter: .percentEncoded, + dateTranscoder: configuration.dateTranscoder + ) + ) + guard let uriString = String(data: data, encoding: .utf8) else {
Prefer `String(decoding: data, as: UTF8.self)` which isn't failable.
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -177,12 +177,50 @@ extension Converter { try decoder.decode(T.self, from: data) } + func convertURLEncodedFormToCodable<T: Decodable>( + _ data: Data + ) throws -> T { + + let decoder = URIDecoder( + configuration: .init( + style: .form, + explode: true, + spaceEscapingCharacter: .percentEncoded, + dateTranscoder: configuration.dateTranscoder + ) + ) + guard let uriString = String(data: data, encoding: .utf8) else { + throw RuntimeError.failedToSerializeCodableData + } + + return try decoder.decode(T.self, from: uriString) + } + func convertBodyCodableToJSON<T: Encodable>( _ value: T ) throws -> Data { try encoder.encode(value) } + func convertBodyCodableToURLFormData<T: Encodable>( + _ value: T + ) throws -> Data { + + let encoder = URIEncoder( + configuration: .init( + style: .form, + explode: true, + spaceEscapingCharacter: .percentEncoded,
```suggestion spaceEscapingCharacter: .plus, ``` See above.
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -177,12 +177,50 @@ extension Converter { try decoder.decode(T.self, from: data) } + func convertURLEncodedFormToCodable<T: Decodable>( + _ data: Data + ) throws -> T { + + let decoder = URIDecoder( + configuration: .init( + style: .form, + explode: true, + spaceEscapingCharacter: .percentEncoded, + dateTranscoder: configuration.dateTranscoder + ) + ) + guard let uriString = String(data: data, encoding: .utf8) else { + throw RuntimeError.failedToSerializeCodableData + } + + return try decoder.decode(T.self, from: uriString) + } + func convertBodyCodableToJSON<T: Encodable>( _ value: T ) throws -> Data { try encoder.encode(value) } + func convertBodyCodableToURLFormData<T: Encodable>( + _ value: T + ) throws -> Data { + + let encoder = URIEncoder( + configuration: .init( + style: .form, + explode: true, + spaceEscapingCharacter: .percentEncoded, + dateTranscoder: configuration.dateTranscoder + ) + ) + guard let data = try encoder.encode(value, forKey: "").data(using: .utf8) else {
To convert the string to Data, use `Data(string.utf8)` instead, as that's not failable and we don't need to handle the error.
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -98,6 +102,10 @@ class Test_Runtime: XCTestCase { """# } + var testStructURLFormString: String { + "age=3&name=Fluffz&type=Dog"
Please make one of the strings have a space, and a special character, to verify escaping.
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -234,6 +234,59 @@ final class Test_ClientConverterExtensions: Test_Runtime { ) } + // | client | set | request body | urlEncodedForm | codable | optional | setRequiredRequestBodyAsURLEncodedForm | + func test_setOptionalRequestBodyAsURLEncodedForm_codable() throws { + var headerFields: [HeaderField] = [] + let body = try converter.setOptionalRequestBodyAsURLEncodedForm( + testStructDetailed, + headerFields: &headerFields, + contentType: "application/x-www-form-urlencoded" + ) + + XCTAssertEqual(body, testStructURLFormData) + XCTAssertEqual( + headerFields, + [ + .init(name: "content-type", value: "application/x-www-form-urlencoded") + ] + ) + } + + // | client | set | request body | urlEncodedForm | codable | required | setRequiredRequestBodyAsURLEncodedForm | + func test_setRequiredRequestBodyAsURLEncodedForm_codable_string() throws { + var headerFields: [HeaderField] = [] + let body = try converter.setRequiredRequestBodyAsURLEncodedForm( + testStructDetailed, + headerFields: &headerFields, + contentType: "application/x-www-form-urlencoded" + ) + + XCTAssertEqual(String(data: body, encoding: .utf8), testStructURLFormString) + XCTAssertEqual( + headerFields, + [ + .init(name: "content-type", value: "application/x-www-form-urlencoded") + ] + ) + } + + func test_setRequiredRequestBodyAsURLEncodedForm_codable() throws {
I don't think you need this test, it's testing the same logic as above just comparing using data vs string, am I reading it correctly?
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -234,6 +234,59 @@ final class Test_ClientConverterExtensions: Test_Runtime { ) } + // | client | set | request body | urlEncodedForm | codable | optional | setRequiredRequestBodyAsURLEncodedForm | + func test_setOptionalRequestBodyAsURLEncodedForm_codable() throws { + var headerFields: [HeaderField] = [] + let body = try converter.setOptionalRequestBodyAsURLEncodedForm( + testStructDetailed, + headerFields: &headerFields, + contentType: "application/x-www-form-urlencoded" + ) + + XCTAssertEqual(body, testStructURLFormData) + XCTAssertEqual( + headerFields, + [ + .init(name: "content-type", value: "application/x-www-form-urlencoded") + ] + ) + } + + // | client | set | request body | urlEncodedForm | codable | required | setRequiredRequestBodyAsURLEncodedForm | + func test_setRequiredRequestBodyAsURLEncodedForm_codable_string() throws { + var headerFields: [HeaderField] = [] + let body = try converter.setRequiredRequestBodyAsURLEncodedForm( + testStructDetailed, + headerFields: &headerFields, + contentType: "application/x-www-form-urlencoded" + ) + + XCTAssertEqual(String(data: body, encoding: .utf8), testStructURLFormString)
It's fine to just compare it using `XCTAssertEqual(body, testStructURLFormData)`. Alternatively, you could bring over `XCTAssertEqualStringifiedData` from the generator repo.
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -177,12 +177,45 @@ extension Converter { try decoder.decode(T.self, from: data) } + func convertURLEncodedFormToCodable<T: Decodable>( + _ data: Data + ) throws -> T { +
```suggestion ```
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -177,12 +177,45 @@ extension Converter { try decoder.decode(T.self, from: data) } + func convertURLEncodedFormToCodable<T: Decodable>( + _ data: Data + ) throws -> T { + + let decoder = URIDecoder( + configuration: .init( + style: .form, + explode: true, + spaceEscapingCharacter: .plus, + dateTranscoder: configuration.dateTranscoder + ) + ) + let uriString = String(decoding: data, as: UTF8.self) + return try decoder.decode(T.self, from: uriString) + } + func convertBodyCodableToJSON<T: Encodable>( _ value: T ) throws -> Data { try encoder.encode(value) } + func convertBodyCodableToURLFormData<T: Encodable>( + _ value: T + ) throws -> Data { +
```suggestion ```
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -13,6 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest @_spi(Generated)@testable import OpenAPIRuntime +import PetstoreConsumerTestCore
```suggestion ```
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -339,6 +339,26 @@ final class Test_ServerConverterExtensions: Test_Runtime { XCTAssertEqual(body, testStruct) } + // | server | get | request body | URLEncodedForm | optional | getOptionalRequestBodyAsJSON |
```suggestion // | server | get | request body | urlEncodedForm | optional | getOptionalRequestBodyAsURLEncodedForm | ```
swift-openapi-runtime
github_2023
others
53
apple
czechboy0
@@ -339,6 +339,26 @@ final class Test_ServerConverterExtensions: Test_Runtime { XCTAssertEqual(body, testStruct) } + // | server | get | request body | URLEncodedForm | optional | getOptionalRequestBodyAsJSON | + func test_getOptionalRequestBodyAsURLEncodedForm_codable() throws { + let body: TestPetDetailed? = try converter.getOptionalRequestBodyAsURLEncodedForm( + TestPetDetailed.self, + from: testStructURLFormData, + transforming: { $0 } + ) + XCTAssertEqual(body, testStructDetailed) + } + + // | server | get | request body | URLEncodedForm | required | getRequiredRequestBodyAsJSON |
```suggestion // | server | get | request body | urlEncodedForm | required | getRequiredRequestBodyAsURLEncodedForm | ```
swift-openapi-runtime
github_2023
others
52
apple
czechboy0
@@ -294,6 +294,10 @@ extension URIValueFromNodeDecoder { array = try rootValue(in: values) } guard array.count == 1 else { + if style == .simple { + return Substring(array.joined(separator: ",")) + } +
```suggestion ```
swift-openapi-runtime
github_2023
others
39
apple
czechboy0
@@ -158,12 +158,56 @@ extension Converter { ) throws -> T { try decoder.decode(T.self, from: data) } + + func convertURLEncodedFormToCodable<T:Decodable>( + _ data: Data + ) throws -> T { + // convert data to string + guard let urlFormString = String(data: data, encoding: .utf8) else { + throw RuntimeError.failedToSerializeCodableData(type: String(describing: T.self)) + } + + //separate string into dictionary by = and & + var dictionary: [String: String] = [:] + let pairs = urlFormString.split(separator: "&") + for pair in pairs { + let components = pair.split(separator: "=") + let key = String(components[0]) + let value = String(components[1]) + dictionary[key] = value + } + + //deserialize into JSON representation + let jsonData = try JSONSerialization.data(withJSONObject: dictionary)
What happens if the Codable type has a property `foo: Int`? I suspect it won't parse, as in the JSON it'll be `"1"` instead of `1`? Same for other non-string primitive types that have a native JSON type?
swift-openapi-runtime
github_2023
others
50
apple
glbrntt
@@ -12,7 +12,10 @@ // //===----------------------------------------------------------------------===// import XCTest -@testable import OpenAPIRuntime +@_spi(Generated)@testable import OpenAPIRuntime +#if os(Linux) +@preconcurrency import Foundation
Why don't we need a `Foundation` import on other platforms? Should we use a more specific `Foundation` import here (i.e. for the types we're using)?
swift-openapi-runtime
github_2023
others
50
apple
glbrntt
@@ -17,26 +17,27 @@ import Foundation /// A single value container used by `URIValueFromNodeDecoder`. struct URISingleValueDecodingContainer { - /// The coder used to serialize Date values. - let dateTranscoder: any DateTranscoder - - /// The coding path of the container. - let codingPath: [any CodingKey] - - /// The underlying value. - let value: URIParsedValue + /// The associated decoder. + let decoder: URIValueFromNodeDecoder } extension URISingleValueDecodingContainer { + /// The underlying value as a single value. + var value: URIParsedValue { + get throws { + try decoder.currentElementAsSingleValue() + } + } + /// Returns the value found in the underlying node converted to /// the provided type. /// - 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 = Double(value) else { + guard let double = try Double(value) else {
Why are these all throwing now?
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable {
Why is this a class? Also can we get rid of the `@unchecked Sendable` here and rather make ourselves a `LockedValueBox` abstraction that is conditionally `Sendable` when its contents are. This way we are making sure we really are `Sendable`
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable {
This probably should be a `struct`.
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple
Are we ever expecting an `AsyncSequence` based body to be `multiple` here? Right now that just doesn't exist in the ecosystem.
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable {
Same here. Probably a `struct`
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable {
I am not sure if we really need `Equatable` and `Hashable` on the body
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } +
These two methods seem unnecessary when you already have the generic one which takes an `AsyncSequence`
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator()
We shouldn't have to do this at all. If we just delegate to call `makeAsyncIterator` on the underlying sequence then that base async sequence should enforce if it is `unicast` or `multicast`.
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension Body { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks(
Interesting. What is the use-case for this?
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension Body { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> Body { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.Body.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return Body( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consumption utils + +extension Body { + + /// An error thrown by the `collect` function when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.Body contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the `collect` function when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes` and returns it.
This contradicts each other. Collects the whole body and up to.
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension Body { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> Body { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.Body.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return Body( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consumption utils + +extension Body { + + /// An error thrown by the `collect` function when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.Body contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the `collect` function when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes` and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the sequence contains more + /// than `maxBytes`. + public func collect(upTo maxBytes: Int) async throws -> DataType { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single {
Same here. Shouldn't have to do that.
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension Body { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> Body { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.Body.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return Body( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consumption utils + +extension Body { + + /// An error thrown by the `collect` function when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.Body contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the `collect` function when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes` and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the sequence contains more + /// than `maxBytes`. + public func collect(upTo maxBytes: Int) async throws -> DataType {
FWIW in async-altos we spelled this like that [AsyncSyncSequence](https://github.com/apple/swift-async-algorithms/blob/4a1fb99f0089a9d9db07859bcad55b4a77e3c3dd/Sources/AsyncAlgorithms/AsyncSyncSequence.swift#L17). Maybe we should just add a variant with a `upTo` in async-algos.
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension Body { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> Body { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.Body.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return Body( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consumption utils + +extension Body { + + /// An error thrown by the `collect` function when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.Body contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the `collect` function when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes` and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the sequence contains more + /// than `maxBytes`. + public func collect(upTo maxBytes: Int) async throws -> DataType { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = DataType.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +// MARK: - String-based bodies + +extension StringProtocol { + fileprivate var asBodyChunk: Body.DataType { + Array(utf8)[...] + } +} + +extension Body { + + public convenience init( + data: some StringProtocol, + length: Length + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: length + ) + } + + public convenience init( + data: some StringProtocol + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk) + ) + } + + public convenience init( + stream: AsyncThrowingStream<some StringProtocol, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<some StringProtocol>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + }
Same here as above.
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension Body { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> Body { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.Body.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return Body( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consumption utils + +extension Body { + + /// An error thrown by the `collect` function when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.Body contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the `collect` function when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes` and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the sequence contains more + /// than `maxBytes`. + public func collect(upTo maxBytes: Int) async throws -> DataType { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = DataType.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +// MARK: - String-based bodies + +extension StringProtocol { + fileprivate var asBodyChunk: Body.DataType { + Array(utf8)[...] + } +} + +extension Body { + + public convenience init( + data: some StringProtocol, + length: Length + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: length + ) + } + + public convenience init( + data: some StringProtocol + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk) + ) + } + + public convenience init( + stream: AsyncThrowingStream<some StringProtocol, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<some StringProtocol>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element: StringProtocol { + self.init( + sequence: .init(sequence.map(\.asBodyChunk)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension Body { + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes`, converts it to String, and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the body contains more + /// than `maxBytes`. + public func collectAsString(upTo maxBytes: Int) async throws -> String { + let bytes: DataType = try await collect(upTo: maxBytes) + return String(decoding: bytes, as: UTF8.self) + } +} + +// MARK: - Body conversions + +extension Body: ExpressibleByStringLiteral { + + public convenience init(stringLiteral value: String) { + self.init(data: value) + } +} + +extension Body { + + public convenience init(data: [UInt8]) { + self.init(data: data[...]) + } +} + +extension Body: ExpressibleByArrayLiteral { + + public typealias ArrayLiteralElement = UInt8 + + public convenience init(arrayLiteral elements: UInt8...) { + self.init(data: elements) + } +} + +extension Body { + + public convenience init(data: Data) { + self.init(data: ArraySlice(data)) + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes`, converts it to Foundation.Data, and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the body contains more + /// than `maxBytes`. + public func collectAsData(upTo maxBytes: Int) async throws -> Data { + let bytes: DataType = try await collect(upTo: maxBytes) + return Data(bytes) + }
IMO this doesn't carry its weight for me since it is a one-liner for the user.
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension Body { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> Body { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.Body.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return Body( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consumption utils + +extension Body { + + /// An error thrown by the `collect` function when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.Body contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the `collect` function when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes` and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the sequence contains more + /// than `maxBytes`. + public func collect(upTo maxBytes: Int) async throws -> DataType { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = DataType.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +// MARK: - String-based bodies + +extension StringProtocol { + fileprivate var asBodyChunk: Body.DataType { + Array(utf8)[...] + } +} + +extension Body { + + public convenience init( + data: some StringProtocol, + length: Length + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: length + ) + } + + public convenience init( + data: some StringProtocol + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk) + ) + } + + public convenience init( + stream: AsyncThrowingStream<some StringProtocol, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<some StringProtocol>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element: StringProtocol { + self.init( + sequence: .init(sequence.map(\.asBodyChunk)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension Body { + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes`, converts it to String, and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the body contains more + /// than `maxBytes`. + public func collectAsString(upTo maxBytes: Int) async throws -> String { + let bytes: DataType = try await collect(upTo: maxBytes) + return String(decoding: bytes, as: UTF8.self) + } +} + +// MARK: - Body conversions + +extension Body: ExpressibleByStringLiteral { + + public convenience init(stringLiteral value: String) { + self.init(data: value) + } +} + +extension Body { + + public convenience init(data: [UInt8]) { + self.init(data: data[...]) + } +} + +extension Body: ExpressibleByArrayLiteral { + + public typealias ArrayLiteralElement = UInt8 + + public convenience init(arrayLiteral elements: UInt8...) { + self.init(data: elements) + } +} + +extension Body { + + public convenience init(data: Data) { + self.init(data: ArraySlice(data)) + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes`, converts it to Foundation.Data, and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the body contains more + /// than `maxBytes`. + public func collectAsData(upTo maxBytes: Int) async throws -> Data { + let bytes: DataType = try await collect(upTo: maxBytes) + return Data(bytes) + } +} + +// MARK: - Underlying async sequences + +extension Body { + + /// Async iterator of both input async sequences and of the body itself. + public struct Iterator: AsyncIteratorProtocol { + + public typealias Element = Body.DataType + + private let produceNext: () async throws -> Element? + + init<Iterator: AsyncIteratorProtocol>( + _ iterator: Iterator + ) where Iterator.Element == Element { + var iterator = iterator + self.produceNext = { + try await iterator.next() + }
Why are we not storing the iterator here but a closure?
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension Body { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> Body { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.Body.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return Body( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consumption utils + +extension Body { + + /// An error thrown by the `collect` function when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.Body contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the `collect` function when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes` and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the sequence contains more + /// than `maxBytes`. + public func collect(upTo maxBytes: Int) async throws -> DataType { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = DataType.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +// MARK: - String-based bodies + +extension StringProtocol { + fileprivate var asBodyChunk: Body.DataType { + Array(utf8)[...] + } +} + +extension Body { + + public convenience init( + data: some StringProtocol, + length: Length + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: length + ) + } + + public convenience init( + data: some StringProtocol + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk) + ) + } + + public convenience init( + stream: AsyncThrowingStream<some StringProtocol, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<some StringProtocol>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element: StringProtocol { + self.init( + sequence: .init(sequence.map(\.asBodyChunk)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension Body { + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes`, converts it to String, and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the body contains more + /// than `maxBytes`. + public func collectAsString(upTo maxBytes: Int) async throws -> String { + let bytes: DataType = try await collect(upTo: maxBytes) + return String(decoding: bytes, as: UTF8.self) + } +} + +// MARK: - Body conversions + +extension Body: ExpressibleByStringLiteral { + + public convenience init(stringLiteral value: String) { + self.init(data: value) + } +} + +extension Body { + + public convenience init(data: [UInt8]) { + self.init(data: data[...]) + } +} + +extension Body: ExpressibleByArrayLiteral { + + public typealias ArrayLiteralElement = UInt8 + + public convenience init(arrayLiteral elements: UInt8...) { + self.init(data: elements) + } +} + +extension Body { + + public convenience init(data: Data) { + self.init(data: ArraySlice(data)) + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes`, converts it to Foundation.Data, and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the body contains more + /// than `maxBytes`. + public func collectAsData(upTo maxBytes: Int) async throws -> Data { + let bytes: DataType = try await collect(upTo: maxBytes) + return Data(bytes) + } +} + +// MARK: - Underlying async sequences + +extension Body { + + /// Async iterator of both input async sequences and of the body itself. + public struct Iterator: AsyncIteratorProtocol { + + public typealias Element = Body.DataType + + private let produceNext: () async throws -> Element? + + init<Iterator: AsyncIteratorProtocol>( + _ iterator: Iterator + ) where Iterator.Element == Element { + var iterator = iterator + self.produceNext = { + try await iterator.next() + } + } + + public func next() async throws -> Element? { + try await produceNext() + } + } +} + +extension Body { + + /// A type-erased async sequence that wraps input sequences. + private struct BodySequence: AsyncSequence { + + typealias AsyncIterator = Body.Iterator + typealias Element = DataType + + private let produceIterator: () -> AsyncIterator
Same here
swift-openapi-runtime
github_2023
others
46
apple
FranzBusch
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class Body: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension Body: Equatable { + public static func == ( + lhs: Body, + rhs: Body + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Body: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the Body + +extension Body { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: Body.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension Body: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension Body { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> Body { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.Body.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return Body( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consumption utils + +extension Body { + + /// An error thrown by the `collect` function when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.Body contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the `collect` function when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.Body attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes` and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the sequence contains more + /// than `maxBytes`. + public func collect(upTo maxBytes: Int) async throws -> DataType { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = DataType.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +// MARK: - String-based bodies + +extension StringProtocol { + fileprivate var asBodyChunk: Body.DataType { + Array(utf8)[...] + } +} + +extension Body { + + public convenience init( + data: some StringProtocol, + length: Length + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: length + ) + } + + public convenience init( + data: some StringProtocol + ) { + self.init( + dataChunks: [data.asBodyChunk], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk), + length: length + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element: StringProtocol { + self.init( + dataChunks: dataChunks.map(\.asBodyChunk) + ) + } + + public convenience init( + stream: AsyncThrowingStream<some StringProtocol, any Error>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<some StringProtocol>, + length: Body.Length + ) { + self.init( + sequence: .init(stream.map(\.asBodyChunk)), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: Body.Length, + iterationBehavior: IterationBehavior + ) where S.Element: StringProtocol { + self.init( + sequence: .init(sequence.map(\.asBodyChunk)), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +extension Body { + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes`, converts it to String, and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the body contains more + /// than `maxBytes`. + public func collectAsString(upTo maxBytes: Int) async throws -> String { + let bytes: DataType = try await collect(upTo: maxBytes) + return String(decoding: bytes, as: UTF8.self) + } +} + +// MARK: - Body conversions + +extension Body: ExpressibleByStringLiteral { + + public convenience init(stringLiteral value: String) { + self.init(data: value) + } +} + +extension Body { + + public convenience init(data: [UInt8]) { + self.init(data: data[...]) + } +} + +extension Body: ExpressibleByArrayLiteral { + + public typealias ArrayLiteralElement = UInt8 + + public convenience init(arrayLiteral elements: UInt8...) { + self.init(data: elements) + } +} + +extension Body { + + public convenience init(data: Data) { + self.init(data: ArraySlice(data)) + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes`, converts it to Foundation.Data, and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the body contains more + /// than `maxBytes`. + public func collectAsData(upTo maxBytes: Int) async throws -> Data { + let bytes: DataType = try await collect(upTo: maxBytes) + return Data(bytes) + } +} + +// MARK: - Underlying async sequences + +extension Body { + + /// Async iterator of both input async sequences and of the body itself. + public struct Iterator: AsyncIteratorProtocol { + + public typealias Element = Body.DataType + + private let produceNext: () async throws -> Element? + + init<Iterator: AsyncIteratorProtocol>( + _ iterator: Iterator + ) where Iterator.Element == Element { + var iterator = iterator + self.produceNext = { + try await iterator.next() + } + } + + public func next() async throws -> Element? { + try await produceNext() + } + } +} + +extension Body { + + /// A type-erased async sequence that wraps input sequences. + private struct BodySequence: AsyncSequence { + + typealias AsyncIterator = Body.Iterator + typealias Element = DataType + + private let produceIterator: () -> AsyncIterator + + init<S: AsyncSequence>(_ sequence: S) where S.Element == Element { + self.produceIterator = { + .init(sequence.makeAsyncIterator()) + } + } + + func makeAsyncIterator() -> AsyncIterator { + produceIterator() + } + } + + /// A wrapper for a sync sequence. + private struct WrappedSyncSequence<S: Sequence>: AsyncSequence
FWIW we have this in async-algorithms.
swift-openapi-runtime
github_2023
others
46
apple
dnadoba
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: HTTPBody.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: HTTPBody.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension HTTPBody { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> HTTPBody { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.HTTPBody.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return HTTPBody( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +}
What's the use case for this method?
swift-openapi-runtime
github_2023
others
46
apple
dnadoba
@@ -0,0 +1,535 @@ +//===----------------------------------------------------------------------===// +// +// 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 class Foundation.NSLock +import protocol Foundation.LocalizedError +import struct Foundation.Data // only for convenience initializers + +/// The type representing a request or response body. +public final class HTTPBody: @unchecked Sendable { + + /// The underlying data type. + public typealias DataType = ArraySlice<UInt8> + + /// How many times the provided sequence can be iterated. + public enum IterationBehavior: Sendable { + + /// The input sequence can only be iterated once. + /// + /// If a retry or a redirect is encountered, fail the call with + /// a descriptive error. + case single + + /// The input sequence can be iterated multiple times. + /// + /// Supports retries and redirects, as a new iterator is created each + /// time. + case multiple + } + + /// How many times the provided sequence can be iterated. + public let iterationBehavior: IterationBehavior + + /// The total length of the body, if known. + public enum Length: Sendable { + + /// Total length not known yet. + case unknown + + /// Total length is known. + case known(Int) + } + + /// The total length of the body, if known. + public let length: Length + + /// The underlying type-erased async sequence. + private let sequence: BodySequence + + /// A lock for shared mutable state. + private let lock: NSLock = { + let lock = NSLock() + lock.name = "com.apple.swift-openapi-generator.runtime.body" + return lock + }() + + /// Whether an iterator has already been created. + private var locked_iteratorCreated: Bool = false + + private init( + sequence: BodySequence, + length: Length, + iterationBehavior: IterationBehavior + ) { + self.sequence = sequence + self.length = length + self.iterationBehavior = iterationBehavior + } +} + +extension HTTPBody: Equatable { + public static func == ( + lhs: HTTPBody, + rhs: HTTPBody + ) -> Bool { + ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension HTTPBody: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +// MARK: - Creating the HTTPBody + +extension HTTPBody { + + public convenience init( + data: DataType, + length: Length + ) { + self.init( + dataChunks: [data], + length: length + ) + } + + public convenience init( + data: DataType + ) { + self.init( + dataChunks: [data], + length: .known(data.count) + ) + } + + public convenience init<S: Sequence>( + dataChunks: S, + length: Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: iterationBehavior + ) + } + + public convenience init<C: Collection>( + dataChunks: C, + length: Length + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: length, + iterationBehavior: .multiple + ) + } + + public convenience init<C: Collection>( + dataChunks: C + ) where C.Element == DataType { + self.init( + sequence: .init(WrappedSyncSequence(sequence: dataChunks)), + length: .known(dataChunks.map(\.count).reduce(0, +)), + iterationBehavior: .multiple + ) + } + + public convenience init( + stream: AsyncThrowingStream<DataType, any Error>, + length: HTTPBody.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init( + stream: AsyncStream<DataType>, + length: HTTPBody.Length + ) { + self.init( + sequence: .init(stream), + length: length, + iterationBehavior: .single + ) + } + + public convenience init<S: AsyncSequence>( + sequence: S, + length: HTTPBody.Length, + iterationBehavior: IterationBehavior + ) where S.Element == DataType { + self.init( + sequence: .init(sequence), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consuming the body + +extension HTTPBody: AsyncSequence { + public typealias Element = DataType + public typealias AsyncIterator = Iterator + public func makeAsyncIterator() -> AsyncIterator { + if iterationBehavior == .single { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + fatalError( + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + ) + } + locked_iteratorCreated = true + } + return sequence.makeAsyncIterator() + } +} + +// MARK: - Transforming the body + +extension HTTPBody { + + /// Creates a body where each chunk is transformed by the provided closure. + /// - Parameter transform: A mapping closure. + /// - Throws: If a known length was provided to this body at + /// creation time, the transform closure must not change the length of + /// each chunk. + public func mapChunks( + _ transform: @escaping @Sendable (Element) async -> Element + ) -> HTTPBody { + let validatedTransform: @Sendable (Element) async -> Element + switch length { + case .known: + validatedTransform = { element in + let transformedElement = await transform(element) + guard transformedElement.count == element.count else { + fatalError( + "OpenAPIRuntime.HTTPBody.mapChunks transform closure attempted to change the length of a chunk in a body which has a total length specified, this is not allowed." + ) + } + return transformedElement + } + case .unknown: + validatedTransform = transform + } + return HTTPBody( + sequence: map(validatedTransform), + length: length, + iterationBehavior: iterationBehavior + ) + } +} + +// MARK: - Consumption utils + +extension HTTPBody { + + /// An error thrown by the `collect` function when the body contains more + /// than the maximum allowed number of bytes. + private struct TooManyBytesError: Error, CustomStringConvertible, LocalizedError { + let maxBytes: Int + + var description: String { + "OpenAPIRuntime.HTTPBody contains more than the maximum allowed \(maxBytes) bytes." + } + + var errorDescription: String? { + description + } + } + + /// An error thrown by the `collect` function when another iteration of + /// the body is not allowed. + private struct TooManyIterationsError: Error, CustomStringConvertible, LocalizedError { + + var description: String { + "OpenAPIRuntime.HTTPBody attempted to create a second iterator, but the underlying sequence is only safe to be iterated once." + } + + var errorDescription: String? { + description + } + } + + /// Accumulates the full body in-memory into a single buffer + /// up to `maxBytes` and returns it. + /// - Parameters: + /// - maxBytes: The maximum number of bytes this method is allowed + /// to accumulate in memory before it throws an error. + /// - Throws: `TooManyBytesError` if the the sequence contains more + /// than `maxBytes`. + public func collect(upTo maxBytes: Int) async throws -> DataType { + + // As a courtesy, check if another iteration is allowed, and throw + // an error instead of fatalError here if the user is trying to + // iterate a sequence for the second time, if it's only safe to be + // iterated once. + if iterationBehavior == .single { + try { + lock.lock() + defer { + lock.unlock() + } + guard !locked_iteratorCreated else { + throw TooManyIterationsError() + } + }() + } + + var buffer = DataType.init() + for try await chunk in self { + guard buffer.count + chunk.count <= maxBytes else { + throw TooManyBytesError(maxBytes: maxBytes) + } + buffer.append(contentsOf: chunk) + } + return buffer + } +} + +// MARK: - String-based bodies + +extension StringProtocol { + fileprivate var asBodyChunk: HTTPBody.DataType {
`@inlinable` or otherwise quite slow as this is a generic over `StringProtocol`
swift-openapi-runtime
github_2023
others
24
apple
simonjbeaumont
@@ -143,6 +143,18 @@ public struct OpenAPIValueContainer: Codable, Equatable, Hashable, Sendable { try container.encode(value.map(OpenAPIValueContainer.init(validatedValue:))) case let value as [String: OpenAPIValueContainer?]: try container.encode(value.mapValues(OpenAPIValueContainer.init(validatedValue:))) + case let value as [Sendable?]: + try container.encode( + value.map { + try OpenAPIValueContainer.init(unvalidatedValue: $0) + } + ) + case let value as [String: Sendable?]: + try container.encode( + value.mapValues { + try OpenAPIValueContainer.init(unvalidatedValue: $0) + } + )
Couple of suggestions here: - We'll be landing #22 soon which means that you'll need to use existential any, i.e. `any Sendable` in place of `Sendable`, so we may as well get it right here so it doesn't need updating again. - The rest of the switch statement follows a different style of passing `init(unvalidatedValue:)` to `map` and `mapValues` directly, so could we keep it consistent with these new switch cases? ```suggestion case let value as [(any Sendable)?]: try container.encode(value.map(OpenAPIValueContainer.init(unvalidatedValue:))) case let value as [String: (any Sendable)?]: try container.encode(value.mapValues(OpenAPIValueContainer.init(unvalidatedValue:))) ```
swift-openapi-runtime
github_2023
others
24
apple
czechboy0
@@ -193,4 +193,96 @@ final class Test_OpenAPIValue: Test_Runtime { XCTAssertEqual(value[0] as? String, "one") XCTAssertEqual(value[1] as? [String: Int], ["two": 2]) } + + func testEncoding_objectNested_success() throws { + + struct Foo: Encodable { + var bar: String + var dict: OpenAPIObjectContainer = .init() + } + + do { + let value = Foo( + bar: "hi", + dict: try .init(unvalidatedValue: [ + "baz": "bar", + "number": 1, + "nestedArray": [ + 1, + [ + "k": "v" + ], + ] as [(any Sendable)?], + "nestedDict": [ + "nested": 2 + ], + ]) + ) + let encoder: JSONEncoder = .init() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let data = try encoder.encode(value) + XCTAssertEqual(
Please make it consistent with the other tests by using the utility functions that does the encoding/decoding and equality checks.
swift-openapi-runtime
github_2023
others
24
apple
czechboy0
@@ -193,4 +193,96 @@ final class Test_OpenAPIValue: Test_Runtime { XCTAssertEqual(value[0] as? String, "one") XCTAssertEqual(value[1] as? [String: Int], ["two": 2]) } + + func testEncoding_objectNested_success() throws { + + struct Foo: Encodable { + var bar: String + var dict: OpenAPIObjectContainer = .init() + } + + do {
Why is this extra do scope here?
swift-openapi-runtime
github_2023
others
24
apple
czechboy0
@@ -193,4 +193,96 @@ final class Test_OpenAPIValue: Test_Runtime { XCTAssertEqual(value[0] as? String, "one") XCTAssertEqual(value[1] as? [String: Int], ["two": 2]) } + + func testEncoding_objectNested_success() throws { + + struct Foo: Encodable { + var bar: String + var dict: OpenAPIObjectContainer = .init() + } + + do { + let value = Foo( + bar: "hi", + dict: try .init(unvalidatedValue: [ + "baz": "bar", + "number": 1, + "nestedArray": [ + 1, + [ + "k": "v" + ], + ] as [(any Sendable)?], + "nestedDict": [ + "nested": 2 + ], + ]) + ) + let encoder: JSONEncoder = .init() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let data = try encoder.encode(value) + XCTAssertEqual( + String(decoding: data, as: UTF8.self), + #""" + { + "bar" : "hi", + "dict" : { + "baz" : "bar", + "nestedArray" : [ + 1, + { + "k" : "v" + } + ], + "nestedDict" : { + "nested" : 2 + }, + "number" : 1 + } + } + """# + ) + } + } + + func testDecodeEncodeRoundTrip_objectNested_success() throws { + + struct Foo: Codable { + var bar: String + var dict: OpenAPIObjectContainer = .init() + } + + do {
Same here about the do scope.
swift-openapi-runtime
github_2023
others
45
apple
glbrntt
@@ -31,98 +31,61 @@ extension Converter { ) } - // | client | set | request path | text | string-convertible | required | renderedRequestPath | - public func renderedRequestPath( + // | client | set | request path | URI | required | renderedPath |
what's this notation?
swift-openapi-runtime
github_2023
others
41
apple
bfrearson
@@ -0,0 +1,72 @@ +//===----------------------------------------------------------------------===// +// +// 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 bag of configuration values used by the URI parser and serializer. +struct URICoderConfiguration { + + // TODO: Wrap in a struct, as this will grow. + // https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#style-values + enum Style { + case simple + case form + } + + var style: Style + var explode: Bool + var spaceEscapingCharacter: String + + private init(style: Style, explode: Bool, spaceEscapingCharacter: String) { + self.style = style + self.explode = explode + self.spaceEscapingCharacter = spaceEscapingCharacter + } + + static let formExplode: Self = .init( + style: .form, + explode: true, + spaceEscapingCharacter: "%20"
Minor point, but spaceEscapingCharacter might be better as an enum so we can be sure that we're always using the same value: ``` enum SpaceEscapingCharacter: String { case percent = "%20" case plus = "+" } ```
swift-openapi-runtime
github_2023
others
41
apple
bfrearson
@@ -0,0 +1,99 @@ +//===----------------------------------------------------------------------===// +// +// 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 type that decodes a `Decodable` objects from an URI-encoded string +/// using the rules from RFC 6570, RFC 1866, and OpenAPI 3.0.3, depending on +/// the configuration. +struct URIDecoder: Sendable { + + private let configuration: URICoderConfiguration + + init(configuration: URICoderConfiguration) { + self.configuration = configuration + } +} + +extension URIDecoder { + + /// Attempt to decode an object from an URI string. + /// + /// Under the hood, URIDecoder first parses the string into a URIParsedNode + /// using URIParser, and then uses URIValueFromNodeDecoder to decode + /// the Decodable value. + /// + /// - Parameters: + /// - type: The type to decode. + /// - key: The key of the decoded value. Only used with certain styles + /// and explode options, ignored otherwise. + /// - data: The URI-encoded string. + /// - Returns: The decoded value. + func decode<T: Decodable>( + _ type: T.Type = T.self, + forKey key: String = "", + from data: String + ) throws -> T { + try withCachedParser(from: data) { decoder in + try decoder.decode(type, forKey: key) + } + } + + /// Make multiple decode calls on the parsed URI. + /// + /// Use to avoid repeatedly reparsing the raw string. + /// - Parameters: + /// - data: The URI-encoded string. + /// - calls: The closure that contains 0 or more calls to + /// URICachedDecoder's decode method. + /// - Returns: The result of the closure invocation. + func withCachedParser<R>(
I'd be interested how much of a performance improvement this offers! Obviously optimisation is a good thing, but just curious if it makes a meaningful impact.
swift-openapi-runtime
github_2023
others
41
apple
glbrntt
@@ -0,0 +1,145 @@ +//===----------------------------------------------------------------------===// +// +// 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 node produced by `URIValueToNodeEncoder`. +enum URIEncodedNode: Equatable { + + /// No value. + case unset + + /// A single primitive value. + case primitive(Primitive) + + /// An array of nodes. + case array([Self]) + + /// A dictionary with node values. + case dictionary([String: Self]) + + /// A primitive value. + enum Primitive: Equatable { + + /// A boolean value. + case bool(Bool) + + /// A string value. + case string(String) + + /// An integer value. + case integer(Int) + + /// A floating-point value. + case double(Double) + + /// A date value. + case date(Date) + } +} + +extension URIEncodedNode { + + /// An error thrown by the methods modifying `URIEncodedNode`. + enum InsertionError: Swift.Error { + + /// The encoder encoded a second primitive value. + case settingPrimitiveValueAgain + + /// The encoder set a single value on a container. + case settingValueOnAContainer + + /// The encoder appended to a node that wasn't an array. + case appendingToNonArrayContainer + + /// The encoder inserted a value for key into a node that wasn't + /// a dictionary. + case insertingChildValueIntoNonContainer + + /// The encoder added a value to an array, but the key was not a valid + /// integer key. + case insertingChildValueIntoArrayUsingNonIntValueKey + } + + /// Sets the node to be a primitive node with the provided value. + /// - Parameter value: The primitive value to set into the node. + /// - Throws: If the node is already set. + mutating func set(_ value: Primitive) throws { + switch self { + case .unset: + self = .primitive(value) + case .primitive: + throw InsertionError.settingPrimitiveValueAgain + case .array, .dictionary: + throw InsertionError.settingValueOnAContainer + } + } + + /// Inserts a value for a key into the node, which is interpreted as a + /// dictionary. + /// - Parameters: + /// - childValue: The value to save under the provided key. + /// - key: The key to save the value for into the dictionary. + /// - Throws: If the node is already set to be anything else but a + /// dictionary. + mutating func insert<Key: CodingKey>( + _ childValue: Self, + atKey key: Key + ) throws { + switch self { + case .dictionary(var dictionary): + self = .unset + dictionary[key.stringValue] = childValue + self = .dictionary(dictionary) + case .array(var array): + // Check that this is a valid key for an unkeyed container, + // but don't actually extract the index, we only support appending + // here. + guard let intValue = key.intValue else { + throw InsertionError.insertingChildValueIntoArrayUsingNonIntValueKey + } + precondition( + intValue == array.count, + "Unkeyed container inserting at an incorrect index" + ) + self = .unset + array.append(childValue) + self = .array(array) + case .unset: + if let _ = key.intValue { + self = .array([childValue])
Should we be preconditioning that `key.intValue == 0`?
swift-openapi-runtime
github_2023
others
41
apple
glbrntt
@@ -0,0 +1,365 @@ +//===----------------------------------------------------------------------===// +// +// 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 type that allows decoding `Decodable` values from a `URIParsedNode`. +final class URIValueFromNodeDecoder { + + /// The coder used for serializing Date values. + let dateTranscoder: any DateTranscoder + + /// The underlying root node. + private let node: URIParsedNode + + /// The key of the root value in the node. + private let rootKey: URIParsedKey + + /// The variable expansion style. + private let style: URICoderConfiguration.Style + + /// The explode parameter of the expansion style. + private let explode: Bool + + /// The stack of nested values within the root node. + private var codingStack: [CodingStackEntry] + + /// Creates a new decoder. + /// - Parameters: + /// - node: The underlying root node. + /// - rootKey: The key of the root value in the node. + /// - style: The variable expansion style. + /// - explode: The explode parameter of the expansion style. + /// - dateTranscoder: The coder used for serializing Date values. + init( + node: URIParsedNode, + rootKey: URIParsedKey, + style: URICoderConfiguration.Style, + explode: Bool, + dateTranscoder: any DateTranscoder + ) { + self.node = node + self.rootKey = rootKey + self.style = style + self.explode = explode + self.dateTranscoder = dateTranscoder + self.codingStack = [] + } + + /// Decodes the provided type from the root node. + /// - Parameter type: The type to decode from the decoder. + /// - Returns: The decoded value. + /// - Throws: When a decoding error occurs. + func decodeRoot<T: Decodable>(_ type: T.Type = T.self) throws -> T { + precondition(codingStack.isEmpty) + defer { + precondition(codingStack.isEmpty) + } + + // We have to catch the special values early, otherwise we fall + // back to their Codable implementations, which don't give us + // a chance to customize the coding in the containers. + let value: T + switch type { + case is Date.Type: + value = try singleValueContainer().decode(Date.self) as! T + default: + value = try T.init(from: self) + } + return value + } +} + +extension URIValueFromNodeDecoder { + + /// A decoder error. + enum GeneralError: Swift.Error { + + /// The decoder does not support the provided type. + case unsupportedType(Any.Type) + + /// The decoder was asked to create a nested container. + case nestedContainersNotSupported + + /// The decoder was asked for more items, but it was already at the + /// end of the unkeyed container. + case reachedEndOfUnkeyedContainer + + /// The provided coding key does not have a valid integer value, but + /// it is being used for accessing items in an unkeyed container. + case codingKeyNotInt + + /// The provided coding key is out of bounds of the unkeyed container. + case codingKeyOutOfBounds + + /// The coding key is of a value not found in the keyed container. + case codingKeyNotFound + } + + /// A node materialized by the decoder. + private enum URIDecodedNode { + + /// A single value. + case single(URIParsedValue) + + /// An array of values. + case array(URIParsedValueArray) + + /// A dictionary of values. + case dictionary(URIParsedNode) + } + + /// An entry in the coding stack for `URIValueFromNodeDecoder`. + /// + /// This is used to keep track of where we are in the decode. + private struct CodingStackEntry { + + /// The key at which the entry was found. + var key: URICoderCodingKey + + /// The node at the key inside its parent. + var element: URIDecodedNode + } + + /// The element at the current head of the coding stack. + private var currentElement: URIDecodedNode { + codingStack.last?.element ?? .dictionary(node) + } + + /// Pushes a new container on top of the current stack, nesting into the + /// value at the provided key. + /// - Parameter codingKey: The coding key for the value that is then put + /// at the top of the stack. + func push(_ codingKey: URICoderCodingKey) throws { + let nextElement: URIDecodedNode + if let intValue = codingKey.intValue { + let value = try nestedValueInCurrentElementAsArray(at: intValue) + nextElement = .single(value) + } else { + let values = try nestedValuesInCurrentElementAsDictionary(forKey: codingKey.stringValue) + nextElement = .array(values) + } + codingStack.append(CodingStackEntry(key: codingKey, element: nextElement)) + } + + /// Pops the top container from the stack and restores the previously top + /// container to be the current top container. + func pop() { + codingStack.removeLast() + } + + /// Throws a type mismatch error with the provided message. + /// - Parameter message: The message to be embedded as debug description + /// inside the thrown `DecodingError`. + private func throwMismatch(_ message: String) throws -> Never {
returning `Never`, that's neat.
swift-openapi-runtime
github_2023
others
44
apple
glbrntt
@@ -0,0 +1,449 @@ +//===----------------------------------------------------------------------===// +// +// 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 type that encodes an `Encodable` objects to a string, if it conforms +/// to `CustomStringConvertible`. +struct StringEncoder: Sendable { + + /// The coder used to serialize Date values. + let dateTranscoder: any DateTranscoder +} + +extension StringEncoder { + + /// Attempt to encode a value into a string using `CustomStringConvertible`. + /// + /// - Parameters: + /// - value: The value to encode. + /// - Returns: The encoded string. + func encode(_ value: some Encodable) throws -> String { + let encoder = CustomStringConvertibleEncoder( + dateTranscoder: dateTranscoder + ) + + // We have to catch the special values early, otherwise we fall + // back to their Codable implementations, which don't give us + // a chance to customize the coding in the containers. + // We have to catch the special values early, otherwise we fall + // back to their Codable implementations, which don't give us + // a chance to customize the coding in the containers.
This comment is duplicated
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,160 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable where RawValue == String { + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + static var defaultValues: [Self] { get } +} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Equatable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Input number into quality value is out of range" + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: Comparable { + public static func < (lhs: QualityValue, rhs: QualityValue) -> Bool { + lhs.thousands > rhs.thousands
Is this intentionally backwards?
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,160 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable where RawValue == String { + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + static var defaultValues: [Self] { get } +} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Equatable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Input number into quality value is out of range" + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: Comparable { + public static func < (lhs: QualityValue, rhs: QualityValue) -> Bool { + lhs.thousands > rhs.thousands + } +} + +extension QualityValue: ExpressibleByIntegerLiteral { + public init(integerLiteral value: UInt16) { + self.thousands = value * 1000 + } +} + +extension QualityValue: ExpressibleByFloatLiteral { + public init(floatLiteral value: Double) { + self.init(doubleValue: value) + } +} + +/// A wrapper of an individual content type in the accept header. +public struct AcceptHeaderContentType<T: AcceptableProtocol>: Sendable, Equatable, Hashable { + + /// The quality value of this content type. + /// + /// Used to describe the order of priority in a comma-separated + /// list of values. + /// + /// Content types with a higher priority should be preferred by the server + /// when deciding which content type to use in the response. + /// + /// Also called the "q-factor" or "q-value". + public let quality: QualityValue + + /// The value representing the content type. + public let contentType: T
Any reason these shouldn't be `var`s?
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,160 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable where RawValue == String { + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + static var defaultValues: [Self] { get } +} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Equatable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Input number into quality value is out of range" + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: Comparable { + public static func < (lhs: QualityValue, rhs: QualityValue) -> Bool { + lhs.thousands > rhs.thousands + } +} + +extension QualityValue: ExpressibleByIntegerLiteral { + public init(integerLiteral value: UInt16) { + self.thousands = value * 1000 + } +} + +extension QualityValue: ExpressibleByFloatLiteral { + public init(floatLiteral value: Double) { + self.init(doubleValue: value) + } +} + +/// A wrapper of an individual content type in the accept header. +public struct AcceptHeaderContentType<T: AcceptableProtocol>: Sendable, Equatable, Hashable { + + /// The quality value of this content type. + /// + /// Used to describe the order of priority in a comma-separated + /// list of values. + /// + /// Content types with a higher priority should be preferred by the server + /// when deciding which content type to use in the response. + /// + /// Also called the "q-factor" or "q-value". + public let quality: QualityValue + + /// The value representing the content type. + public let contentType: T + + /// Creates a new content type from the provided parameters. + /// - Parameters: + /// - quality: The quality of the content type, between 0.0 and 1.0. + /// - value: The value representing the content type. + /// - Precondition: Priority must be in the range 0.0 and 1.0 inclusive. + public init(quality: QualityValue = 1.0, contentType: T) {
The `contentType` should come first as a required parameter.
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,160 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable where RawValue == String { + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + static var defaultValues: [Self] { get } +} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Equatable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Input number into quality value is out of range" + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: Comparable { + public static func < (lhs: QualityValue, rhs: QualityValue) -> Bool { + lhs.thousands > rhs.thousands + } +} + +extension QualityValue: ExpressibleByIntegerLiteral { + public init(integerLiteral value: UInt16) { + self.thousands = value * 1000 + } +} + +extension QualityValue: ExpressibleByFloatLiteral { + public init(floatLiteral value: Double) { + self.init(doubleValue: value) + } +} + +/// A wrapper of an individual content type in the accept header. +public struct AcceptHeaderContentType<T: AcceptableProtocol>: Sendable, Equatable, Hashable { + + /// The quality value of this content type. + /// + /// Used to describe the order of priority in a comma-separated + /// list of values. + /// + /// Content types with a higher priority should be preferred by the server + /// when deciding which content type to use in the response. + /// + /// Also called the "q-factor" or "q-value". + public let quality: QualityValue + + /// The value representing the content type. + public let contentType: T + + /// Creates a new content type from the provided parameters. + /// - Parameters: + /// - quality: The quality of the content type, between 0.0 and 1.0. + /// - value: The value representing the content type. + /// - Precondition: Priority must be in the range 0.0 and 1.0 inclusive. + public init(quality: QualityValue = 1.0, contentType: T) { + self.quality = quality + self.contentType = contentType + } + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + public static var defaultValues: [Self] { + T.defaultValues.map { .init(contentType: $0) } + } +} + +extension AcceptHeaderContentType: RawRepresentable { + public init?(rawValue: String) { + guard let validMimeType = OpenAPIMIMEType(rawValue) else { + // Invalid MIME type. + return nil + } + let quality: QualityValue + if let rawQuality = validMimeType.parameters["q"] { + guard let parsedQuality = QualityValue(rawValue: rawQuality) else { + // Invalid quality parameter. + return nil + } + quality = parsedQuality + } else { + quality = 1.0 + } + guard let typeAndSubtype = T.init(rawValue: validMimeType.kind.description.lowercased()) else {
```suggestion guard let typeAndSubtype = T(rawValue: validMimeType.kind.description.lowercased()) else { ```
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,177 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable where RawValue == String { + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + static var defaultValues: [Self] { get } +} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Equatable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Input number into quality value is out of range" + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: ExpressibleByIntegerLiteral { + public init(integerLiteral value: UInt16) { + self.thousands = value * 1000 + } +} + +extension QualityValue: ExpressibleByFloatLiteral { + public init(floatLiteral value: Double) { + self.init(doubleValue: value) + } +} + +extension Array where Element == QualityValue { + + /// Returns a sorted array of quality values, where the highest + /// priority items come first. + public func sortedByQuality() -> Self { + sorted { a, b in + a.doubleValue < b.doubleValue + } + }
Presumably this should be `a.doubleValue > b.doubleValue`?
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,177 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable where RawValue == String { + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + static var defaultValues: [Self] { get } +} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Equatable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Input number into quality value is out of range" + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable {
What do we get from this being `RawRepresentable`? It feels a bit odd having the `RawValue` be a `String`; on first though `Double` seems like a more natural fit.
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,177 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable where RawValue == String { + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + static var defaultValues: [Self] { get } +} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Equatable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Input number into quality value is out of range" + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: ExpressibleByIntegerLiteral { + public init(integerLiteral value: UInt16) { + self.thousands = value * 1000 + } +} + +extension QualityValue: ExpressibleByFloatLiteral { + public init(floatLiteral value: Double) { + self.init(doubleValue: value) + } +} + +extension Array where Element == QualityValue { + + /// Returns a sorted array of quality values, where the highest + /// priority items come first. + public func sortedByQuality() -> Self { + sorted { a, b in + a.doubleValue < b.doubleValue + } + } +} + +extension Array where Element: AcceptableProtocol { + + /// Returns the default values for the acceptable type. + public var defaultValues: Self { + Element.defaultValues + } +} + +/// A wrapper of an individual content type in the accept header. +public struct AcceptHeaderContentType<T: AcceptableProtocol>: Sendable, Equatable, Hashable {
Can we use `ContentType` instead of `T`?
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,177 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable where RawValue == String { + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + static var defaultValues: [Self] { get } +} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Equatable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Input number into quality value is out of range" + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: ExpressibleByIntegerLiteral { + public init(integerLiteral value: UInt16) { + self.thousands = value * 1000 + } +} + +extension QualityValue: ExpressibleByFloatLiteral { + public init(floatLiteral value: Double) { + self.init(doubleValue: value) + } +} + +extension Array where Element == QualityValue { + + /// Returns a sorted array of quality values, where the highest + /// priority items come first. + public func sortedByQuality() -> Self { + sorted { a, b in + a.doubleValue < b.doubleValue + } + } +} + +extension Array where Element: AcceptableProtocol { + + /// Returns the default values for the acceptable type. + public var defaultValues: Self { + Element.defaultValues + } +} + +/// A wrapper of an individual content type in the accept header. +public struct AcceptHeaderContentType<T: AcceptableProtocol>: Sendable, Equatable, Hashable { + + /// The value representing the content type. + public var contentType: T + + /// The quality value of this content type. + /// + /// Used to describe the order of priority in a comma-separated + /// list of values. + /// + /// Content types with a higher priority should be preferred by the server + /// when deciding which content type to use in the response. + /// + /// Also called the "q-factor" or "q-value". + public var quality: QualityValue + + /// Creates a new content type from the provided parameters. + /// - Parameters: + /// - value: The value representing the content type. + /// - quality: The quality of the content type, between 0.0 and 1.0. + /// - Precondition: Priority must be in the range 0.0 and 1.0 inclusive. + public init(contentType: T, quality: QualityValue = 1.0) { + self.quality = quality + self.contentType = contentType + } + + /// Returns the default set of acceptable content types for this type, in + /// the order specified in the OpenAPI document. + public static var defaultValues: [Self] { + T.defaultValues.map { .init(contentType: $0) } + } +} + +extension AcceptHeaderContentType: RawRepresentable { + public init?(rawValue: String) { + guard let validMimeType = OpenAPIMIMEType(rawValue) else { + // Invalid MIME type. + return nil + } + let quality: QualityValue + if let rawQuality = validMimeType.parameters["q"] { + guard let parsedQuality = QualityValue(rawValue: rawQuality) else { + // Invalid quality parameter. + return nil + } + quality = parsedQuality + } else { + quality = 1.0 + } + guard let typeAndSubtype = T(rawValue: validMimeType.kind.description.lowercased()) else { + // Invalid type/subtype. + return nil + } + self.init(contentType: typeAndSubtype, quality: quality) + } + + public var rawValue: String { + contentType.rawValue + (quality.isDefault ? "" : "; q=\(quality.rawValue)") + } +} + +extension AcceptHeaderContentType { + + // TODO: Can we spell this as an extension of an array?
I think the spelling would be something like: ```swift extension Array { func sortedByQuality<T: AcceptableProtocol>() -> [AcceptHeaderContentType<T>] where Element == AcceptHeaderContentType<T> { // ... } } ```
swift-openapi-runtime
github_2023
others
37
apple
gjcairo
@@ -0,0 +1,164 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable, CaseIterable
A nit, but are we explicitly listing `Hashable` _**and**_ `Equatable` on purpose? Otherwise, `Hashable` already conforms to `Equatable` so we can omit the latter.
swift-openapi-runtime
github_2023
others
37
apple
gjcairo
@@ -0,0 +1,164 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Equatable, Hashable, CaseIterable +where RawValue == String {} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Equatable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Input number into quality value is out of range" + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: ExpressibleByIntegerLiteral { + public init(integerLiteral value: UInt16) { + self.thousands = value * 1000
Feels like we should also precondition here that we're within a valid range - and multiplying by 1000 is probably unwanted too.
swift-openapi-runtime
github_2023
others
37
apple
gjcairo
@@ -0,0 +1,107 @@ +//===----------------------------------------------------------------------===// +// +// 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 XCTest +@_spi(Generated) import OpenAPIRuntime + +enum TestAcceptable: AcceptableProtocol { + case json + case other(String) + + init?(rawValue: String) { + switch rawValue { + case "application/json": + self = .json + default: + self = .other(rawValue) + } + } + + var rawValue: String { + switch self { + case .json: + return "application/json" + case .other(let string): + return string + } + } + + static var allCases: [TestAcceptable] { + [.json] + } +} + +final class Test_AcceptHeaderContentType: Test_Runtime { + func test() throws { + do { + let contentType = AcceptHeaderContentType(contentType: TestAcceptable.json) + XCTAssertEqual(contentType.contentType, .json) + XCTAssertEqual(contentType.quality, 1.0) + XCTAssertEqual(contentType.rawValue, "application/json") + XCTAssertEqual( + AcceptHeaderContentType<TestAcceptable>(rawValue: "application/json"), + contentType + ) + } + do { + let contentType = AcceptHeaderContentType( + contentType: TestAcceptable.json, + quality: 0.5 + ) + XCTAssertEqual(contentType.contentType, .json) + XCTAssertEqual(contentType.quality, 0.5) + XCTAssertEqual(contentType.rawValue, "application/json; q=0.500") + XCTAssertEqual( + AcceptHeaderContentType<TestAcceptable>(rawValue: "application/json; q=0.500"), + contentType + ) + } + do { + XCTAssertEqual( + AcceptHeaderContentType<TestAcceptable>.defaultValues, + [ + .init(contentType: .json) + ] + ) + } + do { + let unsorted: [AcceptHeaderContentType<TestAcceptable>] = [ + .init(contentType: .other("*/*"), quality: 0.3), + .init(contentType: .json, quality: 0.5), + ] + XCTAssertEqual( + unsorted.sortedByQuality(), + [ + .init(contentType: .json, quality: 0.5), + .init(contentType: .other("*/*"), quality: 0.3), + ] + ) + } + } +} + +final class Test_QualityValue: Test_Runtime { + func test() { + XCTAssertEqual(QualityValue().doubleValue, 1.0) + XCTAssertTrue(QualityValue().isDefault) + XCTAssertFalse(QualityValue(doubleValue: 0.5).isDefault) + XCTAssertEqual(QualityValue(doubleValue: 0.5).doubleValue, 0.5) + XCTAssertEqual(QualityValue(floatLiteral: 0.5).doubleValue, 0.5)
I think it would be worth adding an assertion/a test for creating a `QualityValue` from a number with 3 decimal non-zero digits, to make sure that we're preserving them properly (which is basically the whole reason why we store it as `thousands` internally)
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,167 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Hashable, CaseIterable where RawValue == String {} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Provided quality number is out of range, must be between 0.0 and 1.0, inclusive." + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: ExpressibleByIntegerLiteral {
Is this actually necessary? I assume the compiler would infer `0`/`1` to be a `Float` if this didn't exist and use the `ExpressibleByFloatLiteral` conformance.
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,167 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Hashable, CaseIterable where RawValue == String {} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() {
Without reading the docs it's not obvious that `let q = QualityValue()` would default to 1.0. From a readability perspective it might make more sense to not have a default init.
swift-openapi-runtime
github_2023
others
37
apple
glbrntt
@@ -0,0 +1,167 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// The protocol that all generated `AcceptableContentType` enums conform to. +public protocol AcceptableProtocol: RawRepresentable, Sendable, Hashable, CaseIterable where RawValue == String {} + +/// A quality value used to describe the order of priority in a comma-separated +/// list of values, such as in the Accept header. +public struct QualityValue: Sendable, Hashable { + + /// As the quality value only retains up to and including 3 decimal digits, + /// we store it in terms of the thousands. + /// + /// This allows predictable equality comparisons and sorting. + /// + /// For example, 1000 thousands is the quality value of 1.0. + private let thousands: UInt16 + + /// Creates a new quality value of the default value 1.0. + public init() { + self.thousands = 1000 + } + + /// Returns a Boolean value indicating whether the quality value is + /// at its default value 1.0. + public var isDefault: Bool { + thousands == 1000 + } + + /// Creates a new quality value from the provided floating-point number. + /// + /// - Precondition: The value must be between 0.0 and 1.0, inclusive. + public init(doubleValue: Double) { + precondition( + doubleValue >= 0.0 && doubleValue <= 1.0, + "Provided quality number is out of range, must be between 0.0 and 1.0, inclusive." + ) + self.thousands = UInt16(doubleValue * 1000) + } + + /// The value represented as a floating-point number between 0.0 and 1.0, inclusive. + public var doubleValue: Double { + Double(thousands) / 1000 + } +} + +extension QualityValue: RawRepresentable { + public init?(rawValue: String) { + guard let doubleValue = Double(rawValue) else { + return nil + } + self.init(doubleValue: doubleValue) + } + + public var rawValue: String { + String(format: "%0.3f", doubleValue) + } +} + +extension QualityValue: ExpressibleByIntegerLiteral { + public init(integerLiteral value: UInt16) { + precondition( + value >= 0 && value <= 1, + "Provided quality number is out of range, must be between 0 and 1, inclusive." + ) + self.thousands = value * 1000 + } +} + +extension QualityValue: ExpressibleByFloatLiteral { + public init(floatLiteral value: Double) { + self.init(doubleValue: value) + } +} + +extension Array { + + /// Returns the default values for the acceptable type. + public static func defaultValues<T: AcceptableProtocol>() -> [AcceptHeaderContentType<T>] + where Element == AcceptHeaderContentType<T> { + T.allCases.map { .init(contentType: $0) } + } +} + +/// A wrapper of an individual content type in the accept header. +public struct AcceptHeaderContentType<ContentType: AcceptableProtocol>: Sendable, Hashable { + + /// The value representing the content type. + public var contentType: ContentType + + /// The quality value of this content type. + /// + /// Used to describe the order of priority in a comma-separated + /// list of values. + /// + /// Content types with a higher priority should be preferred by the server + /// when deciding which content type to use in the response. + /// + /// Also called the "q-factor" or "q-value". + public var quality: QualityValue + + /// Creates a new content type from the provided parameters. + /// - Parameters: + /// - value: The value representing the content type. + /// - quality: The quality of the content type, between 0.0 and 1.0. + /// - Precondition: Priority must be in the range 0.0 and 1.0 inclusive.
```suggestion /// - Precondition: Quality must be in the range 0.0 and 1.0 inclusive. ```
swift-openapi-runtime
github_2023
others
36
apple
czechboy0
@@ -14,7 +14,7 @@ #if canImport(Darwin) import Foundation #else -@preconcurrency import Foundation +@preconcurrency import Foundation.NSLock
```suggestion @preconcurrency import class Foundation.NSLock ``` Credit goes to CI for discovering this.
swift-openapi-runtime
github_2023
others
35
apple
glbrntt
@@ -259,36 +286,65 @@ extension Converter { func setQueryItem<T>( in request: inout Request, + style: ParameterStyle?, + explode: Bool?, name: String, value: T?, convert: (T) throws -> String ) throws { guard let value else { return } - request.addQueryItem(name: name, value: try convert(value)) + let (_, resolvedExplode) = try ParameterStyle.resolvedQueryStyleAndExplode( + name: name, + style: style, + explode: explode + ) + request.addQueryItem( + name: name, + value: try convert(value), + explode: resolvedExplode + ) } func setQueryItems<T>( in request: inout Request, + style: ParameterStyle?, + explode: Bool?, name: String, values: [T]?, convert: (T) throws -> String ) throws { guard let values else { return } + let (_, resolvedExplode) = try ParameterStyle.resolvedQueryStyleAndExplode( + name: name, + style: style, + explode: explode + ) for value in values { - request.addQueryItem(name: name, value: try convert(value)) + request.addQueryItem( + name: name, + value: try convert(value), + explode: resolvedExplode + ) } } func getOptionalQueryItem<T>( in queryParameters: [URLQueryItem], + style: ParameterStyle?, + explode: Bool?, name: String, as type: T.Type, convert: (String) throws -> T ) throws -> T? { + let (_, _) = try ParameterStyle.resolvedQueryStyleAndExplode(
Are we using this just for the side effect of validation?