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 | 35 | apple | gjcairo | @@ -320,23 +383,49 @@ extension Converter {
func getOptionalQueryItems<T>(
in queryParameters: [URLQueryItem],
+ style: ParameterStyle?,
+ explode: Bool?,
name: String,
as type: [T].Type,
convert: (String) throws -> T
) throws -> [T]? {
- let untypedValues = queryParameters.filter { $0.name == name }
- return try untypedValues.map { try convert($0.value ?? "") }
+ let (_, resolvedExplode) = try ParameterStyle.resolvedQueryStyleAndExplode(
+ name: name,
+ style: style,
+ explode: explode
+ )
+ let untypedValues =
+ queryParameters
+ .filter { $0.name == name }
+ .map { $0.value ?? "" }
+ // If explode is false, some of the items might have multiple
+ // comma-separate values, so we need to split them here.
+ let processedValues: [String]
+ if resolvedExplode {
+ processedValues = untypedValues
+ } else {
+ processedValues = untypedValues.flatMap { multiValue in
+ multiValue
+ .split(separator: ",", omittingEmptySubsequences: false) | I'm sorry for the late comment, but in theory I assume it would be possible to have values with commas in them. Would the commas be escaped or percent-encoded in this case? Just want to make sure this split doesn't split the string at incorrect places. |
swift-openapi-runtime | github_2023 | others | 29 | apple | gjcairo | @@ -17,31 +17,68 @@ extension Converter {
// MARK: Miscs
- /// Validates that the Content-Type header field (if present)
- /// is compatible with the provided content-type substring.
+ /// Returns the content-type header from the provided header fields, if
+ /// present.
+ /// - Parameter headerFields: The header fields to inspect for the content
+ /// type header.
+ /// - Returns: The content type value, or nil if not found.
+ public func extractContentTypeIfPresent(in headerFields: [HeaderField]) -> String? {
+ headerFields.firstValue(name: "content-type")
+ }
+
+ /// Checks whether a concrete content type matches an expected content type.
///
- /// Succeeds if no Content-Type header is found in the response headers.
+ /// The concrete content type can contain parameters, such as `charset`, but
+ /// they are ignored in the equality comparison.
///
+ /// The expected content type can contain wildcards, such as */* and text/*.
/// - Parameters:
- /// - headerFields: Header fields to inspect for a content type.
- /// - substring: Expected content type.
- /// - Throws: If the response's Content-Type value is not compatible with the provided substring.
- public func validateContentTypeIfPresent(
- in headerFields: [HeaderField],
- substring: String
- ) throws {
+ /// - received: The concrete content type to validate against the other.
+ /// - expected: The expected content type, can be a wildcard. | Nit:
```suggestion
/// - expected: The expected content type, can contain wildcards.
``` |
swift-openapi-runtime | github_2023 | others | 29 | apple | simonjbeaumont | @@ -17,31 +17,53 @@ extension Converter {
// MARK: Miscs
- /// Validates that the Content-Type header field (if present)
- /// is compatible with the provided content-type substring.
+ /// Returns the MIME type from the content-type header, if present.
+ /// - Parameter headerFields: The header fields to inspect for the content
+ /// type header.
+ /// - Returns: The content type value, or nil if not found or invalid.
+ public func extractContentTypeIfPresent(in headerFields: [HeaderField]) -> MIMEType? {
+ guard let rawValue = headerFields.firstValue(name: "content-type") else {
+ return nil
+ }
+ return MIMEType(rawValue)
+ }
+
+ /// Checks whether a concrete content type matches an expected content type.
///
- /// Succeeds if no Content-Type header is found in the response headers.
+ /// The concrete content type can contain parameters, such as `charset`, but
+ /// they are ignored in the equality comparison.
///
+ /// The expected content type can contain wildcards, such as */* and text/*.
/// - Parameters:
- /// - headerFields: Header fields to inspect for a content type.
- /// - substring: Expected content type.
- /// - Throws: If the response's Content-Type value is not compatible with the provided substring.
- public func validateContentTypeIfPresent(
- in headerFields: [HeaderField],
- substring: String
- ) throws {
- guard
- let contentType = try getOptionalHeaderFieldAsText(
- in: headerFields,
- name: "content-type",
- as: String.self
- )
- else {
- return
+ /// - received: The concrete content type to validate against the other.
+ /// - expected: The expected content type, can contain wildcards.
+ /// - Returns: A Boolean value representing whether the concrete content
+ /// type matches the expected one.
+ public func isValidContentType(received: MIMEType?, expected: String) -> Bool { | Nit: This is called `isValidContentType` but it's really a test that matches. It's not really about validity of the received content type? Really it's `validateContentTypeMatches(...)` or similar? |
swift-openapi-runtime | github_2023 | others | 29 | apple | simonjbeaumont | @@ -17,31 +17,53 @@ extension Converter {
// MARK: Miscs
- /// Validates that the Content-Type header field (if present)
- /// is compatible with the provided content-type substring.
+ /// Returns the MIME type from the content-type header, if present.
+ /// - Parameter headerFields: The header fields to inspect for the content
+ /// type header.
+ /// - Returns: The content type value, or nil if not found or invalid.
+ public func extractContentTypeIfPresent(in headerFields: [HeaderField]) -> MIMEType? {
+ guard let rawValue = headerFields.firstValue(name: "content-type") else {
+ return nil
+ }
+ return MIMEType(rawValue)
+ }
+
+ /// Checks whether a concrete content type matches an expected content type.
///
- /// Succeeds if no Content-Type header is found in the response headers.
+ /// The concrete content type can contain parameters, such as `charset`, but
+ /// they are ignored in the equality comparison.
///
+ /// The expected content type can contain wildcards, such as */* and text/*.
/// - Parameters:
- /// - headerFields: Header fields to inspect for a content type.
- /// - substring: Expected content type.
- /// - Throws: If the response's Content-Type value is not compatible with the provided substring.
- public func validateContentTypeIfPresent(
- in headerFields: [HeaderField],
- substring: String
- ) throws {
- guard
- let contentType = try getOptionalHeaderFieldAsText(
- in: headerFields,
- name: "content-type",
- as: String.self
- )
- else {
- return
+ /// - received: The concrete content type to validate against the other.
+ /// - expected: The expected content type, can contain wildcards.
+ /// - Returns: A Boolean value representing whether the concrete content
+ /// type matches the expected one.
+ public func isValidContentType(received: MIMEType?, expected: String) -> Bool {
+ guard let received else {
+ return false
}
- guard contentType.localizedCaseInsensitiveContains(substring) else {
- throw RuntimeError.unexpectedContentTypeHeader(contentType)
+ let receivedContentType = received
+ guard let expectedContentType = MIMEType(expected) else {
+ return false | So this is going to return false if the expected input to the function is not a valid mimetype? Can't we just have this function take a `MIMEType` for `expected`? |
swift-openapi-runtime | github_2023 | others | 29 | apple | simonjbeaumont | @@ -0,0 +1,156 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 container for a parsed, valid MIME type.
+@_spi(Generated)
+public struct MIMEType: Equatable {
+
+ /// The value of the type or subtype in the MIME type.
+ public enum Token: Equatable {
+
+ /// Any value, represented as `*`.
+ case wildcard
+
+ /// A concrete value.
+ case concrete(String)
+
+ public static func == (lhs: Token, rhs: Token) -> Bool {
+ // Case-insensitive
+ lhs.description.lowercased() == rhs.description.lowercased()
+ }
+ }
+
+ /// The type – the first token.
+ public var type: Token | In the RFC, this does have some more structure. Maybe we don't care about this at this time, but there are at least codified special values:
https://datatracker.ietf.org/doc/html/rfc2045#section-5.1 |
swift-openapi-runtime | github_2023 | others | 29 | apple | simonjbeaumont | @@ -0,0 +1,156 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 container for a parsed, valid MIME type.
+@_spi(Generated)
+public struct MIMEType: Equatable {
+
+ /// The value of the type or subtype in the MIME type.
+ public enum Token: Equatable {
+
+ /// Any value, represented as `*`.
+ case wildcard
+
+ /// A concrete value.
+ case concrete(String)
+
+ public static func == (lhs: Token, rhs: Token) -> Bool {
+ // Case-insensitive
+ lhs.description.lowercased() == rhs.description.lowercased()
+ }
+ }
+
+ /// The type – the first token.
+ public var type: Token
+
+ /// The subtype – the second token.
+ public var subtype: Token
+
+ /// Any optional parameters.
+ public var parameters: [String: String]
+
+ /// Creates a new MIME type.
+ /// - Parameters:
+ /// - type: The type – the first token.
+ /// - subtype: The subtype – the second token.
+ /// - parameters: Any optional parameters.
+ public init(type: Token, subtype: Token, parameters: [String: String] = [:]) {
+ self.type = type
+ self.subtype = subtype
+ self.parameters = parameters
+ }
+
+ public static func == (lhs: MIMEType, rhs: MIMEType) -> Bool {
+ guard lhs.type == rhs.type else {
+ return false
+ }
+ guard lhs.subtype == rhs.subtype else {
+ return false
+ }
+ // Parameter names are case-insensitive, parameter values are
+ // case-sensitive.
+ guard lhs.parameters.count == rhs.parameters.count else {
+ return false
+ }
+ func normalizeKeyValue(key: String, value: String) -> (String, String) {
+ (key.lowercased(), value)
+ }
+ let normalizedLeftParams = Dictionary(
+ uniqueKeysWithValues: lhs.parameters.map(normalizeKeyValue)
+ )
+ let normalizedRightParams = Dictionary(
+ uniqueKeysWithValues: rhs.parameters.map(normalizeKeyValue)
+ )
+ return normalizedLeftParams == normalizedRightParams
+ }
+}
+
+extension MIMEType.Token: LosslessStringConvertible {
+ public init?(_ description: String) {
+ if description == "*" {
+ self = .wildcard
+ } else {
+ self = .concrete(description)
+ }
+ }
+
+ public var description: String {
+ switch self {
+ case .wildcard:
+ return "*"
+ case .concrete(let string):
+ return string
+ }
+ }
+}
+
+extension MIMEType: LosslessStringConvertible {
+ public init?(_ description: String) {
+ var components =
+ description
+ // Split by semicolon
+ .split(separator: ";")
+ .map(String.init)
+ // Trim leading/trailing spaces
+ .map { $0.soar_trimmingLeadingAndTrailingSpaces }
+ guard !components.isEmpty else {
+ return nil
+ }
+ let firstComponent = components.removeFirst()
+ let typeAndSubtype =
+ firstComponent
+ .split(separator: "/")
+ .map(String.init)
+ .compactMap(MIMEType.Token.init)
+ guard typeAndSubtype.count == 2 else {
+ return nil
+ }
+ func parseParameter(_ string: String) -> (String, String)? {
+ let components =
+ string
+ .split(separator: "=")
+ .map(String.init)
+ guard components.count == 2 else {
+ return nil
+ }
+ return (components[0], components[1])
+ }
+ let parameters =
+ components
+ .compactMap(parseParameter)
+ self.init(
+ type: typeAndSubtype[0],
+ subtype: typeAndSubtype[1],
+ parameters: Dictionary(
+ parameters,
+ uniquingKeysWith: { a, _ in a }
+ )
+ )
+ }
+
+ public var description: String {
+ (["\(type.description)/\(subtype.description)"]
+ + parameters
+ .sorted(by: { a, b in a.key < b.key })
+ .map { "\($0)=\($1)" })
+ .joined(separator: "; ")
+ }
+}
+
+extension String {
+ fileprivate var soar_trimmingLeadingAndTrailingSpaces: Self { | If it's `fileprivate` why do we need it to be `soar_` prefixed? |
swift-openapi-runtime | github_2023 | others | 29 | apple | simonjbeaumont | @@ -0,0 +1,156 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 container for a parsed, valid MIME type.
+@_spi(Generated)
+public struct MIMEType: Equatable {
+
+ /// The value of the type or subtype in the MIME type.
+ public enum Token: Equatable {
+
+ /// Any value, represented as `*`.
+ case wildcard
+
+ /// A concrete value.
+ case concrete(String)
+
+ public static func == (lhs: Token, rhs: Token) -> Bool {
+ // Case-insensitive
+ lhs.description.lowercased() == rhs.description.lowercased()
+ }
+ }
+
+ /// The type – the first token.
+ public var type: Token
+
+ /// The subtype – the second token.
+ public var subtype: Token
+
+ /// Any optional parameters.
+ public var parameters: [String: String]
+
+ /// Creates a new MIME type.
+ /// - Parameters:
+ /// - type: The type – the first token.
+ /// - subtype: The subtype – the second token.
+ /// - parameters: Any optional parameters.
+ public init(type: Token, subtype: Token, parameters: [String: String] = [:]) {
+ self.type = type
+ self.subtype = subtype
+ self.parameters = parameters
+ }
+
+ public static func == (lhs: MIMEType, rhs: MIMEType) -> Bool {
+ guard lhs.type == rhs.type else {
+ return false
+ }
+ guard lhs.subtype == rhs.subtype else {
+ return false
+ }
+ // Parameter names are case-insensitive, parameter values are
+ // case-sensitive.
+ guard lhs.parameters.count == rhs.parameters.count else {
+ return false
+ }
+ func normalizeKeyValue(key: String, value: String) -> (String, String) {
+ (key.lowercased(), value)
+ }
+ let normalizedLeftParams = Dictionary(
+ uniqueKeysWithValues: lhs.parameters.map(normalizeKeyValue)
+ )
+ let normalizedRightParams = Dictionary(
+ uniqueKeysWithValues: rhs.parameters.map(normalizeKeyValue)
+ )
+ return normalizedLeftParams == normalizedRightParams
+ }
+}
+
+extension MIMEType.Token: LosslessStringConvertible {
+ public init?(_ description: String) {
+ if description == "*" {
+ self = .wildcard
+ } else {
+ self = .concrete(description)
+ }
+ }
+
+ public var description: String {
+ switch self {
+ case .wildcard:
+ return "*"
+ case .concrete(let string):
+ return string
+ }
+ }
+}
+
+extension MIMEType: LosslessStringConvertible {
+ public init?(_ description: String) {
+ var components =
+ description
+ // Split by semicolon
+ .split(separator: ";")
+ .map(String.init)
+ // Trim leading/trailing spaces
+ .map { $0.soar_trimmingLeadingAndTrailingSpaces }
+ guard !components.isEmpty else {
+ return nil
+ }
+ let firstComponent = components.removeFirst()
+ let typeAndSubtype =
+ firstComponent
+ .split(separator: "/")
+ .map(String.init)
+ .compactMap(MIMEType.Token.init)
+ guard typeAndSubtype.count == 2 else {
+ return nil
+ }
+ func parseParameter(_ string: String) -> (String, String)? {
+ let components =
+ string
+ .split(separator: "=")
+ .map(String.init)
+ guard components.count == 2 else {
+ return nil
+ }
+ return (components[0], components[1])
+ }
+ let parameters =
+ components
+ .compactMap(parseParameter)
+ self.init(
+ type: typeAndSubtype[0],
+ subtype: typeAndSubtype[1],
+ parameters: Dictionary(
+ parameters,
+ uniquingKeysWith: { a, _ in a }
+ ) | Are we being overly permissive here? I skimmed the RFC and it the only thing I can interpret requirements about uniqueness of parameters is this:
> After the media type and subtype names, the remainder
of the header field is simply a set of parameters, specified in an
attribute=value notation. The ordering of parameters is not
significant.
The use of insignificant order and term "set", I infer uniqueness. Should we be rejecting MIMETypes with duplicates as it can only lead to confusion.
Additionally it makes this not LosslessStringConvertible because a round trip may lose some duplicate parameters.
I think we should be returning `nil` here, WDYT? |
swift-openapi-runtime | github_2023 | others | 29 | apple | simonjbeaumont | @@ -0,0 +1,102 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+
+final class Test_MIMEType: Test_Runtime {
+ func test() throws {
+ let cases: [(String, MIMEType?, String?)] = [
+
+ // Common
+ (
+ "application/json",
+ MIMEType(
+ type: .concrete("application"),
+ subtype: .concrete("json")
+ ),
+ "application/json"
+ ),
+
+ // Subtype wildcard
+ (
+ "application/*",
+ MIMEType(
+ type: .concrete("application"),
+ subtype: .wildcard
+ ),
+ "application/*"
+ ),
+
+ // Type wildcard
+ (
+ "*/*",
+ MIMEType(
+ type: .wildcard,
+ subtype: .wildcard
+ ),
+ "*/*"
+ ),
+
+ // Common with a parameter
+ (
+ "application/json; charset=UTF-8",
+ MIMEType(
+ type: .concrete("application"),
+ subtype: .concrete("json"),
+ parameters: [
+ "charset": "UTF-8"
+ ]
+ ),
+ "application/json; charset=UTF-8"
+ ),
+
+ // Common with two parameters
+ (
+ "application/json; charset=UTF-8; boundary=1234",
+ MIMEType(
+ type: .concrete("application"),
+ subtype: .concrete("json"),
+ parameters: [
+ "charset": "UTF-8",
+ "boundary": "1234",
+ ]
+ ),
+ "application/json; boundary=1234; charset=UTF-8"
+ ),
+
+ // Common case preserving, but case insensitive equality
+ (
+ "APPLICATION/JSON;CHARSET=UTF-8",
+ MIMEType(
+ type: .concrete("application"),
+ subtype: .concrete("json"),
+ parameters: [
+ "charset": "UTF-8"
+ ]
+ ),
+ "APPLICATION/JSON; CHARSET=UTF-8"
+ ),
+
+ // Invalid
+ ("application", nil, nil),
+ ("application/foo/bar", nil, nil),
+ ("", nil, nil), | Is it possible to construct `*/json` currently? If so, should it be possible? |
swift-openapi-runtime | github_2023 | others | 29 | apple | simonjbeaumont | @@ -0,0 +1,170 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 container for a parsed, valid MIME type.
+@_spi(Generated)
+public struct OpenAPIMIMEType: Equatable {
+
+ /// The kind of the MIME type.
+ public enum Kind: Equatable {
+
+ /// Any, spelled as `*/*`.
+ case any
+
+ /// Any subtype of a concrete type, spelled as `type/*`.
+ case anySubtype(type: String)
+
+ /// A concrete value, spelled as `type/subtype`.
+ case concrete(type: String, subtype: String)
+
+ public static func == (lhs: Kind, rhs: Kind) -> Bool {
+ switch (lhs, rhs) {
+ case (.any, .any):
+ return true
+ case let (.anySubtype(lhsType), .anySubtype(rhsType)):
+ return lhsType.lowercased() == rhsType.lowercased()
+ case let (.concrete(lhsType, lhsSubtype), .concrete(rhsType, rhsSubtype)):
+ return lhsType.lowercased() == rhsType.lowercased()
+ && lhsSubtype.lowercased() == rhsSubtype.lowercased()
+ default:
+ return false
+ }
+ }
+ }
+
+ /// The kind of the MIME type.
+ public var kind: Kind
+
+ /// Any optional parameters.
+ public var parameters: [String: String]
+
+ /// Creates a new MIME type.
+ /// - Parameters:
+ /// - kind: The kind of the MIME type.
+ /// - parameters: Any optional parameters.
+ public init(kind: Kind, parameters: [String: String] = [:]) {
+ self.kind = kind
+ self.parameters = parameters
+ }
+
+ public static func == (lhs: OpenAPIMIMEType, rhs: OpenAPIMIMEType) -> Bool {
+ guard lhs.kind == rhs.kind else {
+ return false
+ }
+ // Parameter names are case-insensitive, parameter values are
+ // case-sensitive.
+ guard lhs.parameters.count == rhs.parameters.count else {
+ return false
+ }
+ func normalizeKeyValue(key: String, value: String) -> (String, String) {
+ (key.lowercased(), value)
+ }
+ let normalizedLeftParams = Dictionary(
+ uniqueKeysWithValues: lhs.parameters.map(normalizeKeyValue)
+ )
+ let normalizedRightParams = Dictionary(
+ uniqueKeysWithValues: rhs.parameters.map(normalizeKeyValue)
+ )
+ return normalizedLeftParams == normalizedRightParams
+ }
+}
+
+extension OpenAPIMIMEType.Kind: LosslessStringConvertible {
+ public init?(_ description: String) {
+ let typeAndSubtype =
+ description
+ .split(separator: "/") | Nit: could use maxSplits here. |
swift-openapi-runtime | github_2023 | others | 25 | apple | simonjbeaumont | @@ -139,9 +139,9 @@ public struct OpenAPIValueContainer: Codable, Equatable, Hashable, Sendable {
try container.encode(value)
case let value as String:
try container.encode(value)
- case let value as [OpenAPIValueContainer?]:
+ case let value as [Sendable?]:
try container.encode(value.map(OpenAPIValueContainer.init(validatedValue:)))
- case let value as [String: OpenAPIValueContainer?]:
+ case let value as [String: Sendable?]: | ```suggestion
case let value as [String: (any Sendable)?]:
```
And elsewhere |
swift-openapi-runtime | github_2023 | others | 22 | apple | FranzBusch | @@ -229,10 +229,11 @@ public protocol ClientMiddleware: Sendable {
/// - operationID: The identifier of the OpenAPI operation.
/// - next: A closure that calls the next middleware, or the transport.
/// - Returns: An HTTP response.
+ @preconcurrency | We should not add this and any of the other `@preconcurrency` attributes. Just marking the closure as `@Sendable` seems all we need. |
swift-openapi-runtime | github_2023 | others | 22 | apple | FranzBusch | @@ -47,20 +82,12 @@ extension HeaderField {
/// Use this to avoid leaking sensitive tokens into application logs.
public static var redactedHeaderFields: Set<String> { | This is actually a bit surprising to me. This is a global static which can be set to redact header fields? This sounds to be like something that should be rather passed in a configuration struct. @czechboy0 @simonjbeaumont is this something you considered before? |
swift-openapi-runtime | github_2023 | others | 22 | apple | simonjbeaumont | @@ -17,6 +17,40 @@ import Foundation
@preconcurrency import Foundation
#endif
+/// A protected-by-locks storage for ``redactedHeaderFields``.
+private class RedactedHeadersStorage: @unchecked Sendable {
+ /// The underlying storage of ``redactedHeaderFields``,
+ /// protected by a lock.
+ private var _locked_redactedHeaderFields: Set<String> = HeaderField.defaultRedactedHeaderFields
+
+ /// The header fields to be redacted.
+ var redactedHeaderFields: Set<String> {
+ get {
+ lock.lock()
+ defer {
+ lock.unlock()
+ }
+ return _locked_redactedHeaderFields
+ }
+ set {
+ lock.lock()
+ defer {
+ lock.unlock()
+ }
+ _locked_redactedHeaderFields = newValue
+ }
+ }
+
+ /// The lock used for protecting access to `_locked_redactedHeaderFields`.
+ private let lock: NSLock = {
+ let lock = NSLock()
+ lock.name = "com.apple.swift-openapi-runtime.lock.redactedHeaderFields"
+ return lock
+ }()
+
+ init() {} | ```suggestion
```
Isn't this implicit? |
swift-openapi-runtime | github_2023 | others | 22 | apple | simonjbeaumont | @@ -30,7 +30,7 @@ services:
test:
<<: *common
- command: /bin/bash -xcl "swift $${SWIFT_TEST_VERB-test} $${WARN_AS_ERROR_ARG-} $${SANITIZER_ARG-} $${IMPORT_CHECK_ARG-}"
+ command: /bin/bash -xcl "swift $${SWIFT_TEST_VERB-test} $${WARN_AS_ERROR_ARG-} $${SANITIZER_ARG-} $${IMPORT_CHECK_ARG-} -Xswiftc -strict-concurrency=complete" | To follow the convention here we should probably replace this with...
```suggestion
command: /bin/bash -xcl "swift $${SWIFT_TEST_VERB-test} $${WARN_AS_ERROR_ARG-} $${SANITIZER_ARG-} $${IMPORT_CHECK_ARG-} $${STRICT_CONCURRENCY_ARG-}"
```
...and then specify it in:
- `docker/docker-compose.2204.58.yaml`
- `docker/docker-compose.2204.59.yaml`
If you look in those files, that's how `-Xswiftc -warnings-as-errors` is passed.
|
swift-openapi-runtime | github_2023 | others | 22 | apple | FranzBusch | @@ -11,7 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
+#if canImport(Darwin)
import Foundation
+#else
+@preconcurrency import Foundation | For all the places where we do this could we specify what type we are importing here by doing `import struct Foundation.URL`. This way we know what we need to make `Sendable` and it narrows down the preconcurrency import a bit more |
swift-openapi-runtime | github_2023 | others | 22 | apple | czechboy0 | @@ -327,7 +327,7 @@ public struct OpenAPIObjectContainer: Codable, Equatable, Hashable, Sendable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
- try container.encode(value.mapValues(OpenAPIValueContainer.init))
+ try container.encode(value.mapValues(OpenAPIValueContainer.init(unvalidatedValue:))) | Can you confirm that before this change, this is also the initializer that was picked? I have a suspicion that we previously used the validated initializer, but would have to double check. |
swift-openapi-runtime | github_2023 | others | 22 | apple | czechboy0 | @@ -13,6 +13,7 @@ services:
environment:
- WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors
- IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error
+ - STRICT_CONCURRENCY_ARG=-Xswiftc -strict-concurrency=complete | 👏 |
swift-openapi-runtime | github_2023 | others | 22 | apple | simonjbeaumont | @@ -19,7 +19,7 @@ RUN echo 'export PATH="$HOME/.tools:$PATH"' >> $HOME/.profile
# swift-format
ARG swiftformat_version=508.0.0
RUN git clone --branch $swiftformat_version --depth 1 https://github.com/apple/swift-format $HOME/.tools/swift-format-source
-RUN cd $HOME/.tools/swift-format-source && swift build -c release
+RUN cd $HOME/.tools/swift-format-source && swift build -c release -Xswiftc -strict-concurrency=complete | This is us building `swift-format` for the formatting we do in the CI pipeline. This isn't where we want to be adding this.
This should be added to the `docker-compose.yaml` for the `integration-test` "service". |
swift-openapi-runtime | github_2023 | others | 19 | apple | czechboy0 | @@ -207,7 +207,7 @@ public protocol ClientTransport: Sendable {
/// ) async throws -> Response {
/// var request = request
/// request.headerFields.append(.init(
-/// name: "Authorization", value: "Bearer \(token)"
+/// name: "Authorization", value: "Bearer \(self.bearerToken)" | ```suggestion
/// name: "Authorization", value: "Bearer \(bearerToken)"
```
We generally omit the `self.` unless required by the compiler. |
swift-openapi-runtime | github_2023 | others | 18 | apple | czechboy0 | @@ -17,7 +17,7 @@ import PackageDescription
let package = Package(
name: "swift-openapi-runtime",
platforms: [
- .macOS(.v13), .iOS(.v16), .tvOS(.v16), .watchOS(.v9),
+ .macOS(.v10_15), .iOS(.v12), .tvOS(.v13), .watchOS(.v6), | ```suggestion
.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6),
```
Let's keep the OS versions aligned. |
swift-openapi-runtime | github_2023 | others | 18 | apple | czechboy0 | @@ -22,11 +22,21 @@ extension Converter {
) throws -> String {
var renderedString = template
for parameter in parameters {
- renderedString.replace(
- "{}",
- with: parameter.description,
- maxReplacements: 1
- )
+ if #available(iOS 16.0, macOS 13.0, *) { | Please check aligned watchOS and tvOS versions as well. |
swift-openapi-runtime | github_2023 | others | 18 | apple | czechboy0 | @@ -22,11 +22,21 @@ extension Converter {
) throws -> String {
var renderedString = template
for parameter in parameters {
- renderedString.replace(
- "{}",
- with: parameter.description,
- maxReplacements: 1
- )
+ if #available(macOS 13, iOS 16.0, tvOS 16, watchOS 9, *) {
+ renderedString.replace(
+ "{}",
+ with: parameter.description,
+ maxReplacements: 1
+ )
+ } else {
+ if let range = renderedString.range(of: "{}") {
+ renderedString = renderedString.replacingOccurrences(
+ of: "{}",
+ with: parameter.description,
+ range: range
+ )
+ }
+ } | ```suggestion
if let range = renderedString.range(of: "{}") {
renderedString = renderedString.replacingOccurrences(
of: "{}",
with: parameter.description,
range: range
)
}
```
Actually, let's just use the implementation that supports the older OS's, to further simplify this. |
swift-openapi-runtime | github_2023 | others | 17 | apple | czechboy0 | @@ -0,0 +1,48 @@
+#!/usr/bin/env bash
+##===----------------------------------------------------------------------===##
+##
+## 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
+##
+##===----------------------------------------------------------------------===##
+set -euo pipefail
+
+log() { printf -- "** %s\n" "$*" >&2; }
+error() { printf -- "** ERROR: %s\n" "$*" >&2; }
+fatal() { error "$@"; exit 1; }
+
+log "Checking required executables..."
+SWIFT_BIN=${SWIFT_BIN:-$(command -v swift || xcrun -f swift)} || fatal "SWIFT_BIN unset and no swift on PATH"
+JQ_BIN=${JQ_BIN:-$(command -v jq)} || fatal "JQ_BIN unset and no jq on PATH"
+
+CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
+TMP_DIR=$(mktemp -d "${PWD}/tmp.$(basename "$0").XXXXXXXXXX.noindex")
+
+PACKAGE_PATH=${PACKAGE_PATH:-${REPO_ROOT}}
+
+SWIFT_OPENAPI_GENERATOR_REPO_URL="${SWIFT_OPENAPI_GENERATOR_REPO_URL:-https://github.com/apple/swift-openapi-generator}"
+SWIFT_OPENAPI_GENERATOR_REPO_CLONE_DIR="${TMP_DIR}/$(basename "${SWIFT_OPENAPI_GENERATOR_REPO_URL}")"
+INTEGRATION_TEST_PACKAGE_PATH="${SWIFT_OPENAPI_GENERATOR_REPO_CLONE_DIR}/IntegrationTest"
+
+log "Cloning ${SWIFT_OPENAPI_GENERATOR_REPO_URL} to ${SWIFT_OPENAPI_GENERATOR_REPO_CLONE_DIR}"
+git clone --depth=1 "${SWIFT_OPENAPI_GENERATOR_REPO_URL}" "${SWIFT_OPENAPI_GENERATOR_REPO_CLONE_DIR}" | We have a few options here:
- clone main (the behavior proposed in this PR)
- clone the latest release
- clone the oldest "compatible" release (probably could be computed by taking the major.minor from latest release, and setting patch to 0) |
swift-openapi-runtime | github_2023 | others | 12 | apple | simonjbeaumont | @@ -281,17 +285,32 @@ public extension Converter {
/// - Parameters:
/// - type: Type used to decode the data.
/// - data: Encoded body data.
+ /// - strategy: A hint about which coding strategy to use.
/// - transform: Closure for transforming the Decodable type into a final type.
/// - Returns: Deserialized body value.
func bodyGetRequired<T: Decodable, C>(
_ type: T.Type,
from data: Data?,
+ strategy: CodingStrategy,
transforming transform: (T) -> C
) throws -> C {
guard let data else {
throw RuntimeError.missingRequiredRequestBody
}
- let decoded = try decoder.decode(type, from: data)
+ let decoded: T
+ if let myType = T.self as? _StringParameterConvertible.Type,
+ strategy == .string
+ {
+ guard
+ let stringValue = String(data: data, encoding: .utf8),
+ let decodedValue = myType.init(stringValue)
+ else {
+ throw RuntimeError.failedToDecodeBody(type: T.self)
+ }
+ decoded = decodedValue as! T
+ } else {
+ decoded = try decoder.decode(type, from: data)
+ } | Should we consider changing the semantics here to be stricter?
Specifically, if `bodyGetRequired(...)` is called with `strategy: .string` then I think it should attempt to use that strategy and fail if that wasn't the right choice.
Right now it looks like if we ask for `.string` but the type is not `_StringParameterConvertible` we fallback to using Codable.
Maybe what we want is something like
```swift
switch strategy {
case .string:
guard let stringConvertibleType = T.self as? _StringParameterConvertible.Type else {
preconditionFailure("...")
}
guard
let stringValue = String(data: data, encoding: .utf8),
let decodedValue = myType.init(stringValue)
else {
throw RuntimeError.failedToDecodeBody(type: T.self)
}
decoded = decodedValue as! T
case .json:
decoded = try decoder.decode(type, from: data)
}
```
|
swift-openapi-runtime | github_2023 | others | 12 | apple | simonjbeaumont | @@ -83,20 +83,25 @@ extension Converter {
/// - Parameters:
/// - type: Type used to decode the data.
/// - data: Encoded body data.
- /// - transform: Closure for transforming the Decodable type into a final type.
+ /// - strategy: A hint about which coding strategy to use.
+ /// - transform: Closure for transforming the Decodable type into a final
+ /// type.
/// - Returns: Deserialized body value.
public func bodyGet<T: Decodable, C>(
_ type: T.Type,
from data: Data,
+ strategy: BodyCodingStrategy,
transforming transform: (T) -> C
) throws -> C {
let decoded: T
- if let myType = T.self as? _StringParameterConvertible.Type {
+ if let myType = T.self as? _StringParameterConvertible.Type,
+ strategy == .string
+ { | AFAICT this still has fallback semantics if called with `.string` when `T` does _not_ conform to `_StringParameterConvertible`, which IMO would be a bug in our generated code. As we discussed in the other thread, we think this method should be stricter since we have the more lenient method for backwards compatibility still. |
swift-openapi-runtime | github_2023 | others | 12 | apple | simonjbeaumont | @@ -139,9 +144,11 @@ extension Converter {
) throws -> Data {
let body = transform(value)
headerFields.add(name: "content-type", value: body.contentType)
- if let value = value as? _StringParameterConvertible {
+ if let value = value as? _StringParameterConvertible,
+ body.strategy == .string
+ { | Ditto about strictness. |
swift-openapi-runtime | github_2023 | others | 9 | apple | simonjbeaumont | @@ -90,7 +90,18 @@ extension Converter {
from data: Data,
transforming transform: (T) -> C
) throws -> C {
- let decoded = try decoder.decode(type, from: data)
+ let decoded: T
+ if let myType = T.self as? _StringParameterConvertible.Type {
+ guard
+ let stringValue = String(data: data, encoding: .utf8),
+ let decodedValue = myType.init(stringValue)
+ else {
+ throw RuntimeError.failedToDecodePrimitiveBodyFromData
+ }
+ decoded = decodedValue as! T
+ } else {
+ decoded = try decoder.decode(type, from: data)
+ } | So I think you can put this back the way it was and avoid all the dynamic type checking by using an overload with a generic where clause like this:
```swift
public func bodyGet<T: Decodable, C>(
_ type: T.Type,
from data: Data,
transforming transform: (T) -> C
) throws -> C where T: _StringParameterConvertible {
guard
let stringValue = String(data: data, encoding: .utf8),
let decodedValue = T(stringValue)
else {
throw RuntimeError.failedToDecodePrimitiveBodyFromData
}
return transform(decodedValue)
}
```
I think you can probably play a similar trick in the other places in this PR where we're currently doing some `as?` and `as!`. |
swift-openapi-runtime | github_2023 | others | 9 | apple | weissi | @@ -90,7 +90,18 @@ extension Converter {
from data: Data,
transforming transform: (T) -> C
) throws -> C {
- let decoded = try decoder.decode(type, from: data)
+ let decoded: T
+ if let myType = T.self as? _StringParameterConvertible.Type {
+ guard
+ let stringValue = String(data: data, encoding: .utf8), | Please avoid String(data:encoding:), especially in networked software as it has 2 failure modes (return nil or insert replacement characters for invalid UTF8 -- which one it chooses depends on what's broken).
The correct and faster way is `String(decoding: data, as: UTF8.self)` which also doesn't require Foundation and is not fallible |
swift-openapi-runtime | github_2023 | others | 9 | apple | weissi | @@ -128,6 +139,12 @@ extension Converter {
) throws -> Data {
let body = transform(value)
headerFields.add(name: "content-type", value: body.contentType)
+ if let value = value as? _StringParameterConvertible {
+ guard let data = value.description.data(using: .utf8) else { | Same here, the correct and fast way is `Data(value.utf8)` which can't fail and is faster. You should audit your code to make sure `String(data` and `data(using` aren't present |
swift-openapi-runtime | github_2023 | others | 10 | apple | czechboy0 | @@ -90,19 +90,27 @@ extension Converter {
from data: Data,
transforming transform: (T) -> C
) throws -> C {
- let decoded: T
- if let myType = T.self as? _StringParameterConvertible.Type {
- guard
- let stringValue = String(data: data, encoding: .utf8),
- let decodedValue = myType.init(stringValue)
- else {
- throw RuntimeError.failedToDecodePrimitiveBodyFromData
- }
- decoded = decodedValue as! T
- } else {
- decoded = try decoder.decode(type, from: data)
+ return transform(try decoder.decode(type, from: data))
+ }
+
+ /// Gets a deserialized value from body data.
+ /// - Parameters:
+ /// - type: Type used to decode the data.
+ /// - data: Encoded body data.
+ /// - transform: Closure for transforming the Decodable type into a final type.
+ /// - Returns: Deserialized body value.
+ public func bodyGet<T: Decodable & _StringParameterConvertible, C: _StringParameterConvertible>( | ```suggestion
public func bodyGet<T: Decodable & _StringParameterConvertible, C>(
``` |
swift-openapi-runtime | github_2023 | others | 10 | apple | czechboy0 | @@ -126,6 +134,27 @@ extension Converter {
)
}
+ /// Provides an optional serialized value for the body value.
+ /// - Parameters:
+ /// - value: Encodable value to turn into data.
+ /// - headerFields: Headers container where to add the Content-Type header.
+ /// - transform: Closure for transforming the Encodable value into body content.
+ /// - Returns: Data for the serialized body value, or nil if `value` was nil.
+ public func bodyAddOptional<T: Encodable & _StringParameterConvertible, C: _StringParameterConvertible>( | ```suggestion
public func bodyAddOptional<T: Encodable & _StringParameterConvertible, C>(
``` |
swift-openapi-runtime | github_2023 | others | 10 | apple | czechboy0 | @@ -139,15 +168,28 @@ extension Converter {
) throws -> Data {
let body = transform(value)
headerFields.add(name: "content-type", value: body.contentType)
- if let value = value as? _StringParameterConvertible {
- guard let data = value.description.data(using: .utf8) else {
- throw RuntimeError.failedToEncodePrimitiveBodyIntoData
- }
- return data
- }
return try encoder.encode(body.value)
}
+ /// Provides a required serialized value for the body value.
+ /// - Parameters:
+ /// - value: Encodable value to turn into data.
+ /// - headerFields: Headers container where to add the Content-Type header.
+ /// - transform: Closure for transforming the Encodable value into body content.
+ /// - Returns: Data for the serialized body value.
+ public func bodyAddRequired<T: Encodable & _StringParameterConvertible, C: _StringParameterConvertible>( | ```suggestion
public func bodyAddRequired<T: Encodable & _StringParameterConvertible, C>(
``` |
swift-openapi-runtime | github_2023 | others | 10 | apple | czechboy0 | @@ -139,15 +168,28 @@ extension Converter {
) throws -> Data {
let body = transform(value)
headerFields.add(name: "content-type", value: body.contentType)
- if let value = value as? _StringParameterConvertible {
- guard let data = value.description.data(using: .utf8) else {
- throw RuntimeError.failedToEncodePrimitiveBodyIntoData
- }
- return data
- }
return try encoder.encode(body.value)
}
+ /// Provides a required serialized value for the body value.
+ /// - Parameters:
+ /// - value: Encodable value to turn into data.
+ /// - headerFields: Headers container where to add the Content-Type header.
+ /// - transform: Closure for transforming the Encodable value into body content.
+ /// - Returns: Data for the serialized body value.
+ public func bodyAddRequired<T: Encodable & _StringParameterConvertible, C: _StringParameterConvertible>(
+ _ value: C,
+ headerFields: inout [HeaderField],
+ transforming transform: (C) -> EncodableBodyContent<T>
+ ) throws -> Data where C: _StringParameterConvertible { | ```suggestion
) throws -> Data {
``` |
swift-openapi-runtime | github_2023 | others | 4 | apple | simonjbeaumont | @@ -23,6 +23,7 @@ CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)"
swift package --package-path "${REPO_ROOT}" plugin generate-documentation \
+ --product OpenAPIRuntime \ | So that we can use the same script in other repos, I suggest we make this a parameter to the script, preferably as an environment variable...
```bash
log "Checking required environment variables..."
test -n "${DOCC_TARGET:-}" || fatal "DOCC_TARGET unset"
```
Then if we need this to run for multiple targets (which we don't at the moment) we can just have either two invocations in soundness.
Maybe also worth exploring if we can get a tool in our Docker image that we could use to extract the targets from the `.spi.yml`. |
swift-openapi-runtime | github_2023 | others | 3 | apple | simonjbeaumont | @@ -1,9 +1,34 @@
# Swift OpenAPI Generator Runtime
-This library provides common abstractions and helper functions used by all
-client and server code generated by [Swift OpenAPI Generator][0].
+This library provides common abstractions and helper functions used by all client and server code generated by [Swift OpenAPI Generator][0].
-To get started, check out the [documentation][1].
+## Supported use cases
+
+1. Use the types from this library to instantiate your generated client and server code. To learn more, review the adoption guides in the [Swift OpenAPI Generator documentation][1].
+2. Implement a custom transport or middleware to extend your generated client and server. For client code, check out `ClientTransport` and `ClientMiddleware`. For server code, check out `ServerTransport` and `ServerMiddleware`. | This isn't quite right. You don't use the types here to instantiate the client or the server. The `Client` and `Server` types are generated. It's more that this library is a dependency of those types.
```suggestion
This library contains the common types and abstractions required by projects adopting [Swift OpenAPI Generator][0].
It contains:
- Common types used in the code generated by the `swift-openapi-generator` package plugin.
- Protocol definitions for pluggable layers, including `ClientTransport`, `ServerTransport`, and middleware.
``` |
swift-openapi-runtime | github_2023 | others | 3 | apple | simonjbeaumont | @@ -1,9 +1,34 @@
# Swift OpenAPI Generator Runtime
-This library provides common abstractions and helper functions used by all
-client and server code generated by [Swift OpenAPI Generator][0].
+This library provides common abstractions and helper functions used by all client and server code generated by [Swift OpenAPI Generator][0].
-To get started, check out the [documentation][1].
+## Supported use cases
+
+1. Use the types from this library to instantiate your generated client and server code. To learn more, review the adoption guides in the [Swift OpenAPI Generator documentation][1].
+2. Implement a custom transport or middleware to extend your generated client and server. For client code, check out `ClientTransport` and `ClientMiddleware`. For server code, check out `ServerTransport` and `ServerMiddleware`.
+
+## Getting started
+
+To depend on the runtime API package, add the dependency in your `Package.swift`:
+
+```swift
+.package(url: "https://github.com/apple/swift-openapi-runtime", from: "0.1.0"),
+```
+
+and in your target, add `OpenAPIRuntime` to your dependencies:
+
+```swift
+.target(name: "MyTarget", dependencies: [
+ .product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"),
+],
+```
+
+Now you can use the library as described in [Supported use cases](#Supported-use-cases). | Do you think it makes sense to include this snippet because this is not an intended use case. I think we should show the generator plugin in here too (maybe without a transport, e.g. for a project that just generates the types? |
swift-openapi-runtime | github_2023 | others | 3 | apple | simonjbeaumont | @@ -1,9 +1,34 @@
# Swift OpenAPI Generator Runtime
-This library provides common abstractions and helper functions used by all
-client and server code generated by [Swift OpenAPI Generator][0].
+This library provides common abstractions and helper functions used by all client and server code generated by [Swift OpenAPI Generator][0].
-To get started, check out the [documentation][1].
+## Supported use cases
+
+1. Use the types from this library to instantiate your generated client and server code. To learn more, review the adoption guides in the [Swift OpenAPI Generator documentation][1].
+2. Implement a custom transport or middleware to extend your generated client and server. For client code, check out `ClientTransport` and `ClientMiddleware`. For server code, check out `ServerTransport` and `ServerMiddleware`.
+
+## Getting started
+
+To depend on the runtime API package, add the dependency in your `Package.swift`:
+
+```swift
+.package(url: "https://github.com/apple/swift-openapi-runtime", from: "0.1.0"),
+```
+
+and in your target, add `OpenAPIRuntime` to your dependencies:
+
+```swift
+.target(name: "MyTarget", dependencies: [
+ .product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"),
+],
+```
+
+Now you can use the library as described in [Supported use cases](#Supported-use-cases).
+
+## Documentation
+
+To learn more, check out the full [documentation][2]. | 👍 |
swift-openapi-runtime | github_2023 | others | 3 | apple | simonjbeaumont | @@ -4,14 +4,31 @@ Use and extend your client and server code generated by Swift OpenAPI Generato
## Overview
-
This library provides common abstractions and helper functions used by all client and server code generated by [Swift OpenAPI Generator][0].
-### Supported Use Cases
+### Supported use cases
1. Use the types from this library to instantiate your generated client and server code. To learn more, review the adoption guides in the [Swift OpenAPI Generator documentation][1].
2. Implement a custom transport or middleware to extend your generated client and server. For client code, check out ``ClientTransport`` and ``ClientMiddleware``. For server code, check out ``ServerTransport`` and ``ServerMiddleware``.
+### Getting started
+
+To depend on the runtime API package, add the dependency in your `Package.swift`: | Does the style guide suggest something more directive, e.g.:
```suggestion
Add the package dependency in your `Package.swift`:
``` |
swift-openapi-runtime | github_2023 | others | 3 | apple | simonjbeaumont | @@ -1,9 +1,38 @@
# Swift OpenAPI Generator Runtime
-This library provides common abstractions and helper functions used by all
-client and server code generated by [Swift OpenAPI Generator][0].
+This library provides common abstractions and helper functions used by all client and server code generated by [Swift OpenAPI Generator][0]. | ```suggestion
This library provides common abstractions and helper functions used by the client and server code generated by [Swift OpenAPI Generator][0].
``` |
swift-openapi-runtime | github_2023 | others | 3 | apple | simonjbeaumont | @@ -1,9 +1,38 @@
# Swift OpenAPI Generator Runtime
-This library provides common abstractions and helper functions used by all
-client and server code generated by [Swift OpenAPI Generator][0].
+This library provides common abstractions and helper functions used by all client and server code generated by [Swift OpenAPI Generator][0].
-To get started, check out the [documentation][1].
+## Overview
+
+It contains:
+- Common types used in the code generated by the `swift-openapi-generator` package plugin.
+- Protocol definitions for pluggable layers, including `ClientTransport`, `ServerTransport`, and middleware.
+
+## Usage
+
+Add the package dependency in your `Package.swift`:
+
+```swift
+.package(url: "https://github.com/apple/swift-openapi-runtime", from: "0.1.0"),
+```
+
+and in your target, add `OpenAPIRuntime` to your dependencies:
+
+```swift
+.target(name: "MyTarget", dependencies: [
+ .product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"),
+],
+```
+
+Next step depends on your use case:
+
+1. Use the types from this library with your generated client and server code. To learn more, review the adoption guides in the [Swift OpenAPI Generator documentation][1], which explains how the packages fit together.
+2. Implement a custom transport or middleware to extend your generated client and server. For client code, check out `ClientTransport` and `ClientMiddleware`. For server code, check out `ServerTransport` and `ServerMiddleware`. You can also publish your transport or middleware to allow others to use it with their generated code. | I think these paragraphs are dense because you're using the numbered list. Can we break them out into nested headings?
```suggestion
The next step depends on your use case.
### Using Swift OpenAPI Generator for code generation
The generated code depends on types from this library. Check out the adoption guides in the [Swift OpenAPI Generator documentation][1] to see how the packages fit together.
### Implementing transports and middlewares
Swift OpenAPI Generator generates client and server code that is designed to be used with pluggable transports and middlewares.
Implement a new transport or middleware by providing a type that adopts one of the protocols from the runtime library:
* `ClientTransport`
* `ClientMiddleware`
* `ServerTransport`
* `ServerMiddleware`
You can also publish your transport or middleware as a Swift package to allow others to use it with their generated code.
``` |
app-store-server-library-swift | github_2023 | others | 84 | apple | izanger | @@ -1,5 +1,15 @@
# Changelog
+## Version 3.0.0
+- Incorporate changes for App Store Server API v1.15 and App Store Server Notifications v2.15 [https://github.com/apple/app-store-server-library-swift/pull/82]
+- Add verified chain caching to improve performance [https://github.com/apple/app-store-server-library-swift/pull/80]
+- Rename Environment -> AppStoreEnvironment to [https://github.com/apple/app-store-server-library-swift/pull/81] | Extra "to" |
app-store-server-library-swift | github_2023 | others | 84 | apple | izanger | @@ -1,5 +1,15 @@
# Changelog
+## Version 3.0.0
+- Incorporate changes for App Store Server API v1.15 and App Store Server Notifications v2.15 [https://github.com/apple/app-store-server-library-swift/pull/82]
+- Add verified chain caching to improve performance [https://github.com/apple/app-store-server-library-swift/pull/80]
+- Rename Environment -> AppStoreEnvironment to [https://github.com/apple/app-store-server-library-swift/pull/81]
+- Rename Data -> NotificationDate to deconflict with Foundation.Data [https://github.com/apple/app-store-server-library-swift/pull/79] | NotificationDate -> NotificationData |
app-store-server-library-swift | github_2023 | others | 84 | apple | izanger | @@ -1,5 +1,15 @@
# Changelog
+## Version 3.0.0
+- Incorporate changes for App Store Server API v1.15 and App Store Server Notifications v2.15 [https://github.com/apple/app-store-server-library-swift/pull/82]
+- Add verified chain caching to improve performance [https://github.com/apple/app-store-server-library-swift/pull/80]
+- Rename Environment -> AppStoreEnvironment to [https://github.com/apple/app-store-server-library-swift/pull/81]
+- Rename Data -> NotificationDate to deconflict with Foundation.Data [https://github.com/apple/app-store-server-library-swift/pull/79]
+- Move to Swift and Swift Tools Version 6 [https://github.com/apple/app-store-server-library-swift/pull/78]
+ - This change is a breaking change
+- Update to JWTKit5 [https://github.com/apple/app-store-server-library-swift/pull/68] from @dimitribouniol
+- Made data models conform to Sendable [https://github.com/apple/app-store-server-library-swift/pull/82] from @shimastripe | - Wrong link
- Suggest Made -> Make to match tense of other bullets |
app-store-server-library-swift | github_2023 | others | 58 | apple | dimitribouniol | @@ -1,5 +1,10 @@
# Changelog
+## Version 2.1.0 | 😉
```suggestion
## Version 2.2.0
``` |
app-store-server-library-swift | github_2023 | others | 38 | apple | izanger | @@ -1,13 +1,20 @@
# Changelog
+## Version 1.1.0
+- Support App Store Server Notifications v2.10 [https://github.com/apple/app-store-server-library-swift/pull/37]
+- Require appAppleId in SignedDataVerifier for the Production environment [https://github.com/apple/app-store-server-library-swift/pull/35]
+
+## Version 1.0.2
+- Limit platforms to supported platforms [https://github.com/apple/app-store-server-library-swift/pull/29]
+
## Version 1.0.1
-- Add public constructors to all models [#26]
+- Add public constructors to all models [https://github.com/apple/app-store-server-library-swift/pull/26]
## Version 1.0.0
-- Add status field to the data model [#7]
-- Adding new error codes from App Store Server API v1.9 [#9]
-- Adding new fields from App Store Server API v1.10 [#10]
-- Migrate to AsyncHTTPClient [#15]
-- Add support for LocalTesting and Xcode environments [#19]
-- Allow reading unknown enum values [#20]
-- Add errorMessage to APIException [#21]
+- Add status field to the data model [https://github.com/apple/app-store-server-library-swift/pull/7]
+- Adding new error codes from App Store Server API v1.9 [https://github.com/apple/app-store-server-library-swift/pull/9]
+- Adding new fields from App Store Server API v1.10 [https://github.com/apple/app-store-server-library-swift/pull/10] | Wrong link |
app-store-server-library-swift | github_2023 | others | 38 | apple | izanger | @@ -1,13 +1,20 @@
# Changelog
+## Version 1.1.0
+- Support App Store Server Notifications v2.10 [https://github.com/apple/app-store-server-library-swift/pull/37]
+- Require appAppleId in SignedDataVerifier for the Production environment [https://github.com/apple/app-store-server-library-swift/pull/35] | Add a shoutout |
app-store-server-library-swift | github_2023 | others | 35 | apple | alexanderjordanbaker | @@ -57,11 +57,12 @@ import AppStoreServerLibrary
let bundleId = "com.example"
let appleRootCAs = loadRootCAs() // Specific implementation may vary
+let appAppleId: String? = nil // For production environments, it's required | This is an Int64?, also could you please use the phrase "appAppleId must be provided for the Production environment" |
app-store-server-library-swift | github_2023 | others | 21 | apple | izanger | @@ -318,63 +318,282 @@ public class AppStoreServerAPIClient {
public enum APIResult<T> {
case success(response: T)
- case failure(statusCode: Int?, rawApiError: Int64?, apiError: APIError?, causedBy: Error?)
+ case failure(statusCode: Int?, rawApiError: Int64?, apiError: APIError?, errorMessage: String?, causedBy: Error?)
}
public enum APIError: Int64 {
+ ///An error that indicates an invalid request.
+ ///
+ ///[GeneralBadRequestError](https://developer.apple.com/documentation/appstoreserverapi/generalbadrequesterror)
case generalBadRequest = 4000000
+
+ ///An error that indicates an invalid app identifier.
+ ///
+ ///[InvalidAppIdentifierError](https://developer.apple.com/documentation/appstoreserverapi/invalidappidentifiererror)
case invalidAppIdentifier = 4000002
+
+ ///An error that indicates an invalid request revision.
+ ///
+ ///[InvalidRequestRevisionError](https://developer.apple.com/documentation/appstoreserverapi/invalidrequestrevisionerror)
case invalidRequestRevision = 4000005
+
+ ///An error that indicates an invalid transaction identifier.
+ ///
+ ///[InvalidTransactionIdError](https://developer.apple.com/documentation/appstoreserverapi/invalidtransactioniderror)
case invalidTransactionId = 4000006
+
+ ///An error that indicates an invalid original transaction identifier.
+ ///
+ ///[InvalidOriginalTransactionIdError](https://developer.apple.com/documentation/appstoreserverapi/invalidoriginaltransactioniderror)
case invalidOriginalTransactionId = 4000008
+
+ ///An error that indicates an invalid extend-by-days value.
+ ///
+ ///[InvalidExtendByDaysError](https://developer.apple.com/documentation/appstoreserverapi/invalidextendbydayserror)
case invalidExtendByDays = 4000009
+
+ ///An error that indicates an invalid reason code.
+ ///
+ ///[InvalidExtendReasonCodeError](https://developer.apple.com/documentation/appstoreserverapi/invalidextendreasoncodeerror)
case invalidExtendReasonCode = 4000010
+
+ ///An error that indicates an invalid request identifier.
+ ///
+ ///[InvalidRequestIdentifierError](https://developer.apple.com/documentation/appstoreserverapi/invalidrequestidentifiererror)
case invalidIdentifier = 4000011 | Suggest a rename to `invalidRequestIdentifier` |
app-store-server-library-swift | github_2023 | others | 15 | apple | alexanderjordanbaker | @@ -150,31 +149,22 @@ final class AppStoreOIDPolicy: VerifierPolicy {
final class Requester: OCSPRequester {
func query(request: [UInt8], uri: String) async -> X509.OCSPRequesterQueryResult {
- let url = URL(string: uri)!
- var urlRequest = URLRequest(url: url)
- urlRequest.httpMethod = "POST"
- urlRequest.setValue("application/ocsp-request", forHTTPHeaderField: "Content-Type")
- urlRequest.httpBody = Foundation.Data(request)
-
do {
- let data: Foundation.Data = try await withCheckedThrowingContinuation() { c in
- let urlSessionDataTask = URLSession.shared.dataTask(with: urlRequest) {data, response, error in
- if let e = error {
- c.resume(throwing: e)
- return
- }
- guard let unwrappedData = data else {
- c.resume(throwing: OCSPFetchError())
- return
- }
- c.resume(returning: unwrappedData)
- }
- urlSessionDataTask.resume()
+ let httpClient = HTTPClient()
+ defer {
+ try? httpClient.syncShutdown()
+ }
+ var urlRequest = HTTPClientRequest(url: uri)
+ urlRequest.method = .POST
+ urlRequest.headers.add(name: "Content-Type", value: "application/ocsp-request")
+ urlRequest.body = .bytes(request)
+ let response = try await httpClient.execute(urlRequest, timeout: .seconds(30))
+ var body = try await response.body.collect(upTo: 1024 * 1024)
+ guard let data = body.readData(length: body.readableBytes) else {
+ return .nonTerminalError(OCSPFetchError()) | Why is this not a terminalError? If we are unable to read data from the OCSP response, wouldn't that be an unrecoverable error? |
app-store-server-library-node | github_2023 | others | 199 | apple | alexanderjordanbaker | @@ -134,6 +134,14 @@ const signature = signatureCreator.createSignature(productId, subscriptionOfferI
console.log(signature)
```
+## Local Development | @hakusai22 Sorry for the slow reply, could we remove this piece? To provide contribution instructions, we'd need to do a fuller type of description and make sure it is applicable across all the languages, reference the contribution guidelines, etc. |
app-store-server-library-node | github_2023 | others | 164 | apple | mnMomma | @@ -76,7 +76,8 @@ const verifiedNotification = await verifier.verifyAndDecodeNotification(notifica
console.log(verifiedNotification)
```
-### Receipt Usage
+### Receipt Usage (For Legacy App Receipts)
+If you use an App Receipt from [Original StoreKit](https://developer.apple.com/documentation/storekit/in-app_purchase/original_api_for_in-app_purchase/validating_receipts_with_the_app_store), you can utilize `ReceiptUtility` to verify the legacy receipt. | Help with running this |
app-store-server-library-node | github_2023 | others | 115 | apple | riyazpanjwani | @@ -26,6 +26,15 @@ yarn add @apple/app-store-server-library
[Documentation](https://apple.github.io/app-store-server-library-node/)
[WWDC Video](https://developer.apple.com/videos/play/wwdc2023/10143/)
+
+### Obtaining an In-App Purchase key from App Store Connect
+
+To use the App Store Server API or creation promotional offer signatures, a signing key downloaded from App Store Connect is required. To obtain this key, you must have the Admin role. Go to Users and Access > Integrations > In-App Purchase. Here you can create and manage keys, as well as find your issuer id. When using a key, you'll need the key id and issuer id as well. | nit: create? or of? |
app-store-server-library-node | github_2023 | others | 62 | apple | alexanderjordanbaker | @@ -1,6 +1,6 @@
{
"name": "@apple/app-store-server-library",
- "version": "1.0.0",
+ "version": "1.0.1", | If you are going to bump the version, please also bump the version in the user agent string as well |
app-store-server-library-node | github_2023 | others | 40 | apple | izanger | @@ -58,7 +58,7 @@ try {
### Verification Usage
```typescript
-import { SignedDataVerifier } from "@apple/app-store-server-library/dist/jwt_verification"
+import { SignedDataVerifier } from from "@apple/app-store-server-library" | Double `from`? |
app-store-server-library-node | github_2023 | typescript | 23 | apple | alexanderjordanbaker | @@ -367,48 +367,312 @@ export class APIException extends Error {
}
}
+/**
+ * Error codes that App Store Server API responses return.
+ *
+ * {@link https://developer.apple.com/documentation/appstoreserverapi/error_codes Error Codes} | Please update this to use a lowercase c to match the documentation |
swift-openapi-urlsession | github_2023 | others | 50 | apple | czechboy0 | @@ -193,7 +193,18 @@ extension URLRequest {
}
self.init(url: url)
self.httpMethod = request.method.rawValue
- for header in request.headerFields { setValue(header.value, forHTTPHeaderField: header.name.canonicalName) } | Would it also get fixed if we used the `addValue` API instead? https://developer.apple.com/documentation/foundation/urlrequest/2011522-addvalue |
swift-openapi-urlsession | github_2023 | others | 38 | apple | simonjbeaumont | @@ -10,12 +10,12 @@ Use the transport with client code generated by [Swift OpenAPI Generator](https:
### Supported platforms and minimum versions
-| macOS | Linux | iOS | tvOS | watchOS |
-| :-: | :-: | :-: | :-: | :-: |
-| ✅ 10.15+ | ✅ | ✅ 13+ | ✅ 13+ | ✅ 6+ |
+| macOS | Linux | iOS | tvOS | watchOS | visionOS |
+| :-: | :-: | :-: | :-: | :-: | :-: |
+| ✅ 10.15+ | ✅ | ✅ 13+ | ✅ 13+ | ✅ 6+ | ✅ 1+ |
-Note: Streaming support only available on macOS 12+, iOS 15+, tvOS 15+, and
-watchOS 8+.For streaming support on Linux, please use the [AsyncHTTPClient
+Note: Streaming support only available on macOS 12+, iOS 15+, tvOS 15+,
+watchOS 8+, and visionOS 1+.For streaming support on Linux, please use the [AsyncHTTPClient | ```suggestion
Note: Streaming support only available on macOS 12+, iOS 15+, tvOS 15+,
watchOS 8+, and visionOS 1+. For streaming support on Linux, please use the [AsyncHTTPClient
``` |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -0,0 +1,162 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+#if canImport(FoundationNetworking)
+@preconcurrency import struct FoundationNetworking.URLRequest
+@preconcurrency import class FoundationNetworking.URLSession
+@preconcurrency import class FoundationNetworking.URLResponse
+@preconcurrency import class FoundationNetworking.HTTPURLResponse
+#endif
+
+/// Delegate that supports bidirectional streaming of request and response bodies.
+///
+/// While URLSession provides a high-level API that returns an async sequence of
+/// bytes, `bytes(for:delegate:)`, but does not provide an API that takes an async sequence
+/// as a request body. For instance, `upload(for:delegate:)` and `upload(fromFile:delegate:)`
+/// both buffer the entire response body and return `Data`.
+///
+/// Additionally, bridging `URLSession.AsyncBytes`, which is an `AsyncSequence<UInt8>` to
+/// `OpenAPIRuntime.HTTPBody`, an `AsyncSequence<ByteChunk>`, is problematic and will
+/// incur an allocation for every byte.
+///
+/// This delegate vends the response body as a `HTTBody` with one chunk for each
+/// `urlSession(_:didReceive data:)` callback. It also provides backpressure, which will
+/// suspend and resume the URLSession task based on a configurable high and low watermark.
+///
+/// When performing requests without a body, this delegate should be used with a
+/// `URLSessionDataTask` to stream the response body.
+///
+/// When performing requests with a body, this delegate should be used with a
+/// `URLSessionUploadTask` using `uploadTask(withStreamedRequest:delegate:)`, which will
+/// ask the delegate for a `InputStream` for the request body via the
+/// `urlSession(_:needNewBodyStreamForTask:)` callback.
+///
+/// The `urlSession(_:needNewBodyStreamForTask:)` callback will create a pair of bound
+/// streams, bridge the `HTTPBody` request body to the `OutputStream` and return the
+/// `InputStream` to URLSession. Backpressure for the request body stream is provided
+/// as an implementation detail of how URLSession reads from the `InputStream`.
+///
+/// Note that `urlSession(_:needNewBodyStreamForTask:)` may be called more than once, e.g.
+/// when performing a HTTP redirect, upon which the delegate is expected to create a new
+/// `InputStream` for the request body. This is only possible if the underlying `HTTPBody`
+/// request body can be iterated multiple times, i.e. `iterationBehavior == .multiple`.
+/// If the request body cannot be iterated multiple times, then the URLSession task will be cancelled.
+final class BidirectionalStreamingURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
+
+ let requestBody: HTTPBody?
+ var hasAlreadyIteratedRequestBody: Bool
+ var hasSuspendedURLSessionTask: Bool
+ let requestStreamBufferSize: Int
+ var requestStream: HTTPBodyOutputStreamBridge?
+
+ typealias ResponseContinuation = CheckedContinuation<URLResponse, any Error>
+ var responseContinuation: ResponseContinuation?
+
+ typealias ResponseBodyStream = AsyncBackpressuredStream<HTTPBody.ByteChunk, any Error>
+ var responseBodyStream: ResponseBodyStream
+ var responseBodyStreamSource: ResponseBodyStream.Source
+
+ /// Use `bidirectionalStreamingRequest(for:baseURL:requestBody:requestStreamBufferSize:responseStreamWatermarks:)`
+ init(requestBody: HTTPBody?, requestStreamBufferSize: Int, responseStreamWatermarks: (low: Int, high: Int)) {
+ self.requestBody = requestBody
+ self.hasAlreadyIteratedRequestBody = false
+ self.hasSuspendedURLSessionTask = false
+ self.requestStreamBufferSize = requestStreamBufferSize
+ (self.responseBodyStream, self.responseBodyStreamSource) = AsyncBackpressuredStream.makeStream(
+ backPressureStrategy: .highLowWatermarkWithElementCounts(
+ lowWatermark: responseStreamWatermarks.low,
+ highWatermark: responseStreamWatermarks.high
+ )
+ )
+ }
+
+ func urlSession(_ session: URLSession, needNewBodyStreamForTask task: URLSessionTask) async -> InputStream? {
+ debug("Task delegate: needNewBodyStreamForTask")
+ // If the HTTP body cannot be iterated multiple times then bad luck; the only thing
+ // we can do is cancel the task and return nil.
+ if hasAlreadyIteratedRequestBody {
+ guard requestBody!.iterationBehavior == .multiple else {
+ debug("Task delegate: Cannot rewind request body, canceling task") | Will this result in an error visible to the adopter? |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -0,0 +1,162 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+#if canImport(FoundationNetworking)
+@preconcurrency import struct FoundationNetworking.URLRequest
+@preconcurrency import class FoundationNetworking.URLSession
+@preconcurrency import class FoundationNetworking.URLResponse
+@preconcurrency import class FoundationNetworking.HTTPURLResponse
+#endif
+
+/// Delegate that supports bidirectional streaming of request and response bodies.
+///
+/// While URLSession provides a high-level API that returns an async sequence of
+/// bytes, `bytes(for:delegate:)`, but does not provide an API that takes an async sequence
+/// as a request body. For instance, `upload(for:delegate:)` and `upload(fromFile:delegate:)`
+/// both buffer the entire response body and return `Data`.
+///
+/// Additionally, bridging `URLSession.AsyncBytes`, which is an `AsyncSequence<UInt8>` to
+/// `OpenAPIRuntime.HTTPBody`, an `AsyncSequence<ByteChunk>`, is problematic and will
+/// incur an allocation for every byte.
+///
+/// This delegate vends the response body as a `HTTBody` with one chunk for each
+/// `urlSession(_:didReceive data:)` callback. It also provides backpressure, which will
+/// suspend and resume the URLSession task based on a configurable high and low watermark.
+///
+/// When performing requests without a body, this delegate should be used with a
+/// `URLSessionDataTask` to stream the response body.
+///
+/// When performing requests with a body, this delegate should be used with a
+/// `URLSessionUploadTask` using `uploadTask(withStreamedRequest:delegate:)`, which will
+/// ask the delegate for a `InputStream` for the request body via the
+/// `urlSession(_:needNewBodyStreamForTask:)` callback.
+///
+/// The `urlSession(_:needNewBodyStreamForTask:)` callback will create a pair of bound
+/// streams, bridge the `HTTPBody` request body to the `OutputStream` and return the
+/// `InputStream` to URLSession. Backpressure for the request body stream is provided
+/// as an implementation detail of how URLSession reads from the `InputStream`.
+///
+/// Note that `urlSession(_:needNewBodyStreamForTask:)` may be called more than once, e.g.
+/// when performing a HTTP redirect, upon which the delegate is expected to create a new
+/// `InputStream` for the request body. This is only possible if the underlying `HTTPBody`
+/// request body can be iterated multiple times, i.e. `iterationBehavior == .multiple`.
+/// If the request body cannot be iterated multiple times, then the URLSession task will be cancelled.
+final class BidirectionalStreamingURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
+
+ let requestBody: HTTPBody?
+ var hasAlreadyIteratedRequestBody: Bool
+ var hasSuspendedURLSessionTask: Bool
+ let requestStreamBufferSize: Int
+ var requestStream: HTTPBodyOutputStreamBridge?
+
+ typealias ResponseContinuation = CheckedContinuation<URLResponse, any Error>
+ var responseContinuation: ResponseContinuation?
+
+ typealias ResponseBodyStream = AsyncBackpressuredStream<HTTPBody.ByteChunk, any Error>
+ var responseBodyStream: ResponseBodyStream
+ var responseBodyStreamSource: ResponseBodyStream.Source
+
+ /// Use `bidirectionalStreamingRequest(for:baseURL:requestBody:requestStreamBufferSize:responseStreamWatermarks:)`
+ init(requestBody: HTTPBody?, requestStreamBufferSize: Int, responseStreamWatermarks: (low: Int, high: Int)) {
+ self.requestBody = requestBody
+ self.hasAlreadyIteratedRequestBody = false
+ self.hasSuspendedURLSessionTask = false
+ self.requestStreamBufferSize = requestStreamBufferSize
+ (self.responseBodyStream, self.responseBodyStreamSource) = AsyncBackpressuredStream.makeStream(
+ backPressureStrategy: .highLowWatermarkWithElementCounts(
+ lowWatermark: responseStreamWatermarks.low,
+ highWatermark: responseStreamWatermarks.high
+ )
+ )
+ }
+
+ func urlSession(_ session: URLSession, needNewBodyStreamForTask task: URLSessionTask) async -> InputStream? {
+ debug("Task delegate: needNewBodyStreamForTask")
+ // If the HTTP body cannot be iterated multiple times then bad luck; the only thing
+ // we can do is cancel the task and return nil.
+ if hasAlreadyIteratedRequestBody {
+ guard requestBody!.iterationBehavior == .multiple else { | Is it guaranteed that `requestBody` isn't nil here? |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -0,0 +1,162 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+#if canImport(FoundationNetworking)
+@preconcurrency import struct FoundationNetworking.URLRequest
+@preconcurrency import class FoundationNetworking.URLSession
+@preconcurrency import class FoundationNetworking.URLResponse
+@preconcurrency import class FoundationNetworking.HTTPURLResponse
+#endif
+
+/// Delegate that supports bidirectional streaming of request and response bodies.
+///
+/// While URLSession provides a high-level API that returns an async sequence of
+/// bytes, `bytes(for:delegate:)`, but does not provide an API that takes an async sequence
+/// as a request body. For instance, `upload(for:delegate:)` and `upload(fromFile:delegate:)`
+/// both buffer the entire response body and return `Data`.
+///
+/// Additionally, bridging `URLSession.AsyncBytes`, which is an `AsyncSequence<UInt8>` to
+/// `OpenAPIRuntime.HTTPBody`, an `AsyncSequence<ByteChunk>`, is problematic and will
+/// incur an allocation for every byte.
+///
+/// This delegate vends the response body as a `HTTBody` with one chunk for each
+/// `urlSession(_:didReceive data:)` callback. It also provides backpressure, which will
+/// suspend and resume the URLSession task based on a configurable high and low watermark.
+///
+/// When performing requests without a body, this delegate should be used with a
+/// `URLSessionDataTask` to stream the response body.
+///
+/// When performing requests with a body, this delegate should be used with a
+/// `URLSessionUploadTask` using `uploadTask(withStreamedRequest:delegate:)`, which will
+/// ask the delegate for a `InputStream` for the request body via the
+/// `urlSession(_:needNewBodyStreamForTask:)` callback.
+///
+/// The `urlSession(_:needNewBodyStreamForTask:)` callback will create a pair of bound
+/// streams, bridge the `HTTPBody` request body to the `OutputStream` and return the
+/// `InputStream` to URLSession. Backpressure for the request body stream is provided
+/// as an implementation detail of how URLSession reads from the `InputStream`.
+///
+/// Note that `urlSession(_:needNewBodyStreamForTask:)` may be called more than once, e.g.
+/// when performing a HTTP redirect, upon which the delegate is expected to create a new
+/// `InputStream` for the request body. This is only possible if the underlying `HTTPBody`
+/// request body can be iterated multiple times, i.e. `iterationBehavior == .multiple`.
+/// If the request body cannot be iterated multiple times, then the URLSession task will be cancelled.
+final class BidirectionalStreamingURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
+
+ let requestBody: HTTPBody?
+ var hasAlreadyIteratedRequestBody: Bool
+ var hasSuspendedURLSessionTask: Bool
+ let requestStreamBufferSize: Int
+ var requestStream: HTTPBodyOutputStreamBridge?
+
+ typealias ResponseContinuation = CheckedContinuation<URLResponse, any Error>
+ var responseContinuation: ResponseContinuation?
+
+ typealias ResponseBodyStream = AsyncBackpressuredStream<HTTPBody.ByteChunk, any Error>
+ var responseBodyStream: ResponseBodyStream
+ var responseBodyStreamSource: ResponseBodyStream.Source
+
+ /// Use `bidirectionalStreamingRequest(for:baseURL:requestBody:requestStreamBufferSize:responseStreamWatermarks:)`
+ init(requestBody: HTTPBody?, requestStreamBufferSize: Int, responseStreamWatermarks: (low: Int, high: Int)) {
+ self.requestBody = requestBody
+ self.hasAlreadyIteratedRequestBody = false
+ self.hasSuspendedURLSessionTask = false
+ self.requestStreamBufferSize = requestStreamBufferSize
+ (self.responseBodyStream, self.responseBodyStreamSource) = AsyncBackpressuredStream.makeStream(
+ backPressureStrategy: .highLowWatermarkWithElementCounts(
+ lowWatermark: responseStreamWatermarks.low,
+ highWatermark: responseStreamWatermarks.high
+ )
+ )
+ }
+
+ func urlSession(_ session: URLSession, needNewBodyStreamForTask task: URLSessionTask) async -> InputStream? {
+ debug("Task delegate: needNewBodyStreamForTask")
+ // If the HTTP body cannot be iterated multiple times then bad luck; the only thing
+ // we can do is cancel the task and return nil.
+ if hasAlreadyIteratedRequestBody {
+ guard requestBody!.iterationBehavior == .multiple else {
+ debug("Task delegate: Cannot rewind request body, canceling task")
+ task.cancel()
+ return nil
+ }
+ }
+
+ // Create a fresh pair of streams.
+ let (inputStream, outputStream) = createStreamPair(withBufferSize: requestStreamBufferSize)
+
+ // Bridge the output stream to the request body and open the output stream.
+ requestStream = HTTPBodyOutputStreamBridge(outputStream, requestBody!, openOutputStream: true)
+
+ // Return the new input stream (unopened, it gets opened by URLSession).
+ return inputStream
+ }
+
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+ debug("Task delegate: didReceive data (numBytes: \(data.count), dataTask.state: \(dataTask.state))")
+ do {
+ switch try responseBodyStreamSource.write(contentsOf: [ArraySlice(data)]) {
+ case .produceMore: break
+ case .enqueueCallback(let writeToken):
+ if self.hasSuspendedURLSessionTask {
+ debug("Task delegate: already suspended task, not enqueing another writer callback")
+ break
+ }
+ debug("Task delegate: response stream backpressure, suspending URLSession task and enqueing callback")
+ dataTask.suspend()
+ self.hasSuspendedURLSessionTask = true | What's the threading story here? Do we not need locks because the delegate calls are guaranteed to be called on a serial queue? |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -0,0 +1,162 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+#if canImport(FoundationNetworking)
+@preconcurrency import struct FoundationNetworking.URLRequest
+@preconcurrency import class FoundationNetworking.URLSession
+@preconcurrency import class FoundationNetworking.URLResponse
+@preconcurrency import class FoundationNetworking.HTTPURLResponse
+#endif
+
+/// Delegate that supports bidirectional streaming of request and response bodies.
+///
+/// While URLSession provides a high-level API that returns an async sequence of
+/// bytes, `bytes(for:delegate:)`, but does not provide an API that takes an async sequence
+/// as a request body. For instance, `upload(for:delegate:)` and `upload(fromFile:delegate:)`
+/// both buffer the entire response body and return `Data`.
+///
+/// Additionally, bridging `URLSession.AsyncBytes`, which is an `AsyncSequence<UInt8>` to
+/// `OpenAPIRuntime.HTTPBody`, an `AsyncSequence<ByteChunk>`, is problematic and will
+/// incur an allocation for every byte.
+///
+/// This delegate vends the response body as a `HTTBody` with one chunk for each
+/// `urlSession(_:didReceive data:)` callback. It also provides backpressure, which will
+/// suspend and resume the URLSession task based on a configurable high and low watermark.
+///
+/// When performing requests without a body, this delegate should be used with a
+/// `URLSessionDataTask` to stream the response body.
+///
+/// When performing requests with a body, this delegate should be used with a
+/// `URLSessionUploadTask` using `uploadTask(withStreamedRequest:delegate:)`, which will
+/// ask the delegate for a `InputStream` for the request body via the
+/// `urlSession(_:needNewBodyStreamForTask:)` callback.
+///
+/// The `urlSession(_:needNewBodyStreamForTask:)` callback will create a pair of bound
+/// streams, bridge the `HTTPBody` request body to the `OutputStream` and return the
+/// `InputStream` to URLSession. Backpressure for the request body stream is provided
+/// as an implementation detail of how URLSession reads from the `InputStream`.
+///
+/// Note that `urlSession(_:needNewBodyStreamForTask:)` may be called more than once, e.g.
+/// when performing a HTTP redirect, upon which the delegate is expected to create a new
+/// `InputStream` for the request body. This is only possible if the underlying `HTTPBody`
+/// request body can be iterated multiple times, i.e. `iterationBehavior == .multiple`.
+/// If the request body cannot be iterated multiple times, then the URLSession task will be cancelled.
+final class BidirectionalStreamingURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
+
+ let requestBody: HTTPBody?
+ var hasAlreadyIteratedRequestBody: Bool
+ var hasSuspendedURLSessionTask: Bool
+ let requestStreamBufferSize: Int
+ var requestStream: HTTPBodyOutputStreamBridge?
+
+ typealias ResponseContinuation = CheckedContinuation<URLResponse, any Error>
+ var responseContinuation: ResponseContinuation?
+
+ typealias ResponseBodyStream = AsyncBackpressuredStream<HTTPBody.ByteChunk, any Error>
+ var responseBodyStream: ResponseBodyStream
+ var responseBodyStreamSource: ResponseBodyStream.Source
+
+ /// Use `bidirectionalStreamingRequest(for:baseURL:requestBody:requestStreamBufferSize:responseStreamWatermarks:)`
+ init(requestBody: HTTPBody?, requestStreamBufferSize: Int, responseStreamWatermarks: (low: Int, high: Int)) {
+ self.requestBody = requestBody
+ self.hasAlreadyIteratedRequestBody = false
+ self.hasSuspendedURLSessionTask = false
+ self.requestStreamBufferSize = requestStreamBufferSize
+ (self.responseBodyStream, self.responseBodyStreamSource) = AsyncBackpressuredStream.makeStream(
+ backPressureStrategy: .highLowWatermarkWithElementCounts(
+ lowWatermark: responseStreamWatermarks.low,
+ highWatermark: responseStreamWatermarks.high
+ )
+ )
+ }
+
+ func urlSession(_ session: URLSession, needNewBodyStreamForTask task: URLSessionTask) async -> InputStream? {
+ debug("Task delegate: needNewBodyStreamForTask")
+ // If the HTTP body cannot be iterated multiple times then bad luck; the only thing
+ // we can do is cancel the task and return nil.
+ if hasAlreadyIteratedRequestBody {
+ guard requestBody!.iterationBehavior == .multiple else {
+ debug("Task delegate: Cannot rewind request body, canceling task")
+ task.cancel()
+ return nil
+ }
+ }
+
+ // Create a fresh pair of streams.
+ let (inputStream, outputStream) = createStreamPair(withBufferSize: requestStreamBufferSize)
+
+ // Bridge the output stream to the request body and open the output stream.
+ requestStream = HTTPBodyOutputStreamBridge(outputStream, requestBody!, openOutputStream: true)
+
+ // Return the new input stream (unopened, it gets opened by URLSession).
+ return inputStream
+ }
+
+ func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
+ debug("Task delegate: didReceive data (numBytes: \(data.count), dataTask.state: \(dataTask.state))")
+ do {
+ switch try responseBodyStreamSource.write(contentsOf: [ArraySlice(data)]) {
+ case .produceMore: break
+ case .enqueueCallback(let writeToken):
+ if self.hasSuspendedURLSessionTask {
+ debug("Task delegate: already suspended task, not enqueing another writer callback")
+ break
+ }
+ debug("Task delegate: response stream backpressure, suspending URLSession task and enqueing callback")
+ dataTask.suspend()
+ self.hasSuspendedURLSessionTask = true
+ responseBodyStreamSource.enqueueCallback(writeToken: writeToken) { result in
+ switch result {
+ case .success:
+ debug("Task delegate: response stream callback, resuming URLSession task")
+ dataTask.resume()
+ self.hasSuspendedURLSessionTask = false
+ case .failure(let error):
+ debug("Task delegate: response stream callback, cancelling URLSession task, error: \(error)") | Will we surface this error to the adopter? |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -0,0 +1,162 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+#if canImport(FoundationNetworking)
+@preconcurrency import struct FoundationNetworking.URLRequest
+@preconcurrency import class FoundationNetworking.URLSession
+@preconcurrency import class FoundationNetworking.URLResponse
+@preconcurrency import class FoundationNetworking.HTTPURLResponse
+#endif | Do we need this if we're inside the `#if canImport(Darwin)` here? |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -0,0 +1,286 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+#if canImport(FoundationNetworking)
+@preconcurrency import struct FoundationNetworking.URLRequest
+@preconcurrency import class FoundationNetworking.URLSession
+@preconcurrency import class FoundationNetworking.URLResponse
+@preconcurrency import class FoundationNetworking.HTTPURLResponse
+#endif | Same as in the previous file, will these Linux imports be used if we're `#if` on Darwin? |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -0,0 +1,286 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+#if canImport(FoundationNetworking)
+@preconcurrency import struct FoundationNetworking.URLRequest
+@preconcurrency import class FoundationNetworking.URLSession
+@preconcurrency import class FoundationNetworking.URLResponse
+@preconcurrency import class FoundationNetworking.HTTPURLResponse
+#endif
+
+final class HTTPBodyOutputStreamBridge: NSObject, StreamDelegate {
+ static let streamQueue = DispatchQueue(label: "HTTPBodyStreamDelegate", autoreleaseFrequency: .workItem)
+
+ let httpBody: HTTPBody
+ let outputStream: OutputStream
+ private(set) var state: State {
+ didSet { debug("Output stream delegate state transition: \(oldValue) -> \(state)") }
+ }
+
+ init(_ outputStream: OutputStream, _ httpBody: HTTPBody, openOutputStream: Bool = true) {
+ self.httpBody = httpBody
+ self.outputStream = outputStream
+ self.state = .initial
+ super.init()
+ self.outputStream.delegate = self
+ CFWriteStreamSetDispatchQueue(self.outputStream as CFWriteStream, Self.streamQueue)
+ if openOutputStream { self.outputStream.open() }
+ }
+
+ deinit { debug("Output stream delegate deinit") }
+
+ func performAction(_ action: State.Action) {
+ debug("Output stream delegate performing action from state machine: \(action)")
+ dispatchPrecondition(condition: .onQueue(Self.streamQueue))
+ switch action {
+ case .none: return
+ case .resumeProducer(let producerContinuation):
+ producerContinuation.resume()
+ performAction(self.state.resumedProducer())
+ case .writeBytes(let chunk): writePendingBytes(chunk)
+ case .cancelProducerAndCloseStream(let producerContinuation):
+ producerContinuation.resume(throwing: CancellationError())
+ outputStream.close()
+ case .cancelProducer(let producerContinuation): producerContinuation.resume(throwing: CancellationError())
+ case .closeStream: outputStream.close()
+ }
+ }
+
+ func startWriterTask() {
+ dispatchPrecondition(condition: .onQueue(Self.streamQueue))
+ let task = Task {
+ dispatchPrecondition(condition: .notOnQueue(Self.streamQueue))
+ for try await chunk in httpBody {
+ try await withCheckedThrowingContinuation { continuation in
+ Self.streamQueue.async {
+ debug("Output stream delegate produced chunk and suspended producer.")
+ self.performAction(self.state.producedChunkAndSuspendedProducer(chunk, continuation))
+ }
+ }
+ }
+ Self.streamQueue.async {
+ debug("Output stream delegate wrote final chunk.")
+ self.performAction(self.state.wroteFinalChunk())
+ }
+ }
+ self.performAction(self.state.startedProducerTask(task))
+ }
+
+ private func writePendingBytes(_ bytesToWrite: Chunk) {
+ dispatchPrecondition(condition: .onQueue(Self.streamQueue))
+ precondition(!bytesToWrite.isEmpty)
+ guard outputStream.streamStatus == .open else {
+ debug("Output stream closed unexpectedly.")
+ performAction(self.state.wroteBytes(numBytesWritten: 0, streamStillHasSpaceAvailable: false))
+ return
+ }
+ switch bytesToWrite.withUnsafeBytes({ outputStream.write($0.baseAddress!, maxLength: bytesToWrite.count) }) {
+ case 0:
+ debug("Output stream delegate reached end of stream when writing.")
+ performAction(self.state.endEncountered())
+ case -1:
+ debug("Output stream delegate encountered error writing to stream: \(outputStream.streamError!).")
+ performAction(self.state.errorOccurred(outputStream.streamError!))
+ case let written where written > 0:
+ debug("Output stream delegate wrote \(written) bytes to stream.")
+ performAction(
+ self.state.wroteBytes(
+ numBytesWritten: written,
+ streamStillHasSpaceAvailable: outputStream.hasSpaceAvailable
+ )
+ )
+ default: preconditionFailure() | Can you add a string to the crash (here and in the rest of the file)? |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -0,0 +1,286 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+#if canImport(FoundationNetworking)
+@preconcurrency import struct FoundationNetworking.URLRequest
+@preconcurrency import class FoundationNetworking.URLSession
+@preconcurrency import class FoundationNetworking.URLResponse
+@preconcurrency import class FoundationNetworking.HTTPURLResponse
+#endif
+
+final class HTTPBodyOutputStreamBridge: NSObject, StreamDelegate {
+ static let streamQueue = DispatchQueue(label: "HTTPBodyStreamDelegate", autoreleaseFrequency: .workItem)
+
+ let httpBody: HTTPBody
+ let outputStream: OutputStream
+ private(set) var state: State {
+ didSet { debug("Output stream delegate state transition: \(oldValue) -> \(state)") }
+ }
+
+ init(_ outputStream: OutputStream, _ httpBody: HTTPBody, openOutputStream: Bool = true) {
+ self.httpBody = httpBody
+ self.outputStream = outputStream
+ self.state = .initial
+ super.init()
+ self.outputStream.delegate = self
+ CFWriteStreamSetDispatchQueue(self.outputStream as CFWriteStream, Self.streamQueue)
+ if openOutputStream { self.outputStream.open() }
+ }
+
+ deinit { debug("Output stream delegate deinit") }
+
+ func performAction(_ action: State.Action) {
+ debug("Output stream delegate performing action from state machine: \(action)")
+ dispatchPrecondition(condition: .onQueue(Self.streamQueue))
+ switch action {
+ case .none: return
+ case .resumeProducer(let producerContinuation):
+ producerContinuation.resume()
+ performAction(self.state.resumedProducer())
+ case .writeBytes(let chunk): writePendingBytes(chunk)
+ case .cancelProducerAndCloseStream(let producerContinuation):
+ producerContinuation.resume(throwing: CancellationError())
+ outputStream.close()
+ case .cancelProducer(let producerContinuation): producerContinuation.resume(throwing: CancellationError())
+ case .closeStream: outputStream.close()
+ }
+ }
+
+ func startWriterTask() {
+ dispatchPrecondition(condition: .onQueue(Self.streamQueue))
+ let task = Task {
+ dispatchPrecondition(condition: .notOnQueue(Self.streamQueue))
+ for try await chunk in httpBody {
+ try await withCheckedThrowingContinuation { continuation in
+ Self.streamQueue.async {
+ debug("Output stream delegate produced chunk and suspended producer.")
+ self.performAction(self.state.producedChunkAndSuspendedProducer(chunk, continuation))
+ }
+ }
+ }
+ Self.streamQueue.async {
+ debug("Output stream delegate wrote final chunk.")
+ self.performAction(self.state.wroteFinalChunk())
+ }
+ }
+ self.performAction(self.state.startedProducerTask(task))
+ }
+
+ private func writePendingBytes(_ bytesToWrite: Chunk) {
+ dispatchPrecondition(condition: .onQueue(Self.streamQueue))
+ precondition(!bytesToWrite.isEmpty)
+ guard outputStream.streamStatus == .open else {
+ debug("Output stream closed unexpectedly.")
+ performAction(self.state.wroteBytes(numBytesWritten: 0, streamStillHasSpaceAvailable: false))
+ return
+ }
+ switch bytesToWrite.withUnsafeBytes({ outputStream.write($0.baseAddress!, maxLength: bytesToWrite.count) }) {
+ case 0:
+ debug("Output stream delegate reached end of stream when writing.")
+ performAction(self.state.endEncountered())
+ case -1:
+ debug("Output stream delegate encountered error writing to stream: \(outputStream.streamError!).")
+ performAction(self.state.errorOccurred(outputStream.streamError!))
+ case let written where written > 0:
+ debug("Output stream delegate wrote \(written) bytes to stream.")
+ performAction(
+ self.state.wroteBytes(
+ numBytesWritten: written,
+ streamStillHasSpaceAvailable: outputStream.hasSpaceAvailable
+ )
+ )
+ default: preconditionFailure()
+ }
+ }
+
+ func stream(_ stream: Stream, handle event: Stream.Event) {
+ dispatchPrecondition(condition: .onQueue(Self.streamQueue))
+ debug("Output stream delegate received event: \(event).")
+ switch event {
+ case .openCompleted:
+ guard case .initial = state else {
+ debug("Output stream delegate ignroing duplicate openCompleted event.") | ```suggestion
debug("Output stream delegate ignoring duplicate openCompleted event.")
``` |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -73,8 +73,21 @@ public struct URLSessionTransport: ClientTransport {
/// Creates a new configuration with the provided session.
/// - Parameter session: The URLSession used for performing HTTP operations.
- /// If none is provided, the system uses the shared URLSession.
- public init(session: URLSession = .shared) { self.session = session }
+ /// If none is provided, the system uses the shared URLSession.
+ public init(session: URLSession = .shared) { self.init(session: session, implementation: .platformDefault) }
+
+ enum Implementation {
+ case buffered
+ case streaming(requestBodyStreamBufferSize: Int, responseBodyStreamWatermarks: (low: Int, high: Int))
+ } | 👍 |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -73,8 +73,21 @@ public struct URLSessionTransport: ClientTransport {
/// Creates a new configuration with the provided session.
/// - Parameter session: The URLSession used for performing HTTP operations.
- /// If none is provided, the system uses the shared URLSession.
- public init(session: URLSession = .shared) { self.session = session }
+ /// If none is provided, the system uses the shared URLSession.
+ public init(session: URLSession = .shared) { self.init(session: session, implementation: .platformDefault) }
+
+ enum Implementation {
+ case buffered
+ case streaming(requestBodyStreamBufferSize: Int, responseBodyStreamWatermarks: (low: Int, high: Int))
+ }
+
+ var implemenation: Implementation
+
+ init(session: URLSession = .shared, implementation: Implementation = .platformDefault) { | ```suggestion
init(session: URLSession = .shared, implementation: Implementation) {
```
This way `.init()` won't be ambiguous. |
swift-openapi-urlsession | github_2023 | others | 24 | apple | czechboy0 | @@ -205,6 +218,69 @@ extension URLSessionTransportError: CustomStringConvertible {
case .notHTTPResponse(let response):
return "Received a non-HTTP response, of type: \(String(describing: type(of: response)))"
case .noResponse(let url): return "Received a nil response for \(url?.absoluteString ?? "<nil URL>")"
+ case .streamingNotSupported: return "Streaming is not supported on this platform"
}
}
}
+
+var debugLoggingEnabled: Bool = false
+func debug(_ items: Any..., separator: String = " ", terminator: String = "\n") {
+ assert(
+ {
+ if debugLoggingEnabled { print(items, separator: separator, terminator: terminator) }
+ return true
+ }()
+ )
+}
+
+extension URLSession {
+ func bufferedRequest(for request: HTTPRequest, baseURL: URL, requestBody: HTTPBody?) async throws -> (
+ HTTPResponse, HTTPBody?
+ ) {
+ var urlRequest = try URLRequest(request, baseURL: baseURL)
+ if let requestBody { urlRequest.httpBody = try await Data(collecting: requestBody, upTo: .max) }
+
+ /// Use `dataTask(with:completionHandler:)` here because `data(for:[delegate:]) async` is only available on
+ /// Darwin platforms newer than our minimum deployment target, and not at all on Linux.
+ let (response, maybeResponseBodyData): (URLResponse, Data?) = try await withCheckedThrowingContinuation {
+ continuation in
+ let task = self.dataTask(with: urlRequest) { [urlRequest] data, response, error in
+ if let error {
+ continuation.resume(throwing: error)
+ return
+ }
+ guard let response else {
+ continuation.resume(throwing: URLSessionTransportError.noResponse(url: urlRequest.url))
+ return
+ }
+ continuation.resume(with: .success((response, data)))
+ }
+ task.resume()
+ }
+
+ let maybeResponseBody = maybeResponseBodyData.map { data in
+ HTTPBody(data, length: HTTPBody.Length(from: response), iterationBehavior: .multiple)
+ }
+ return (try HTTPResponse(response), maybeResponseBody)
+ }
+}
+
+extension URLSessionTransport.Configuration.Implementation {
+ static var platformSupportsStreaming: Bool {
+ #if canImport(Darwin)
+ guard #available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) else { return false }
+ _ = URLSession.bidirectionalStreamingRequest | Why is this here? |
swift-openapi-urlsession | github_2023 | others | 24 | apple | guoye-zhang | @@ -0,0 +1,286 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+
+final class HTTPBodyOutputStreamBridge: NSObject, StreamDelegate {
+ static let streamQueue = DispatchQueue(label: "HTTPBodyStreamDelegate", autoreleaseFrequency: .workItem)
+
+ let httpBody: HTTPBody
+ let outputStream: OutputStream
+ private(set) var state: State {
+ didSet { debug("Output stream delegate state transition: \(oldValue) -> \(state)") }
+ }
+
+ init(_ outputStream: OutputStream, _ httpBody: HTTPBody, openOutputStream: Bool = true) { | Is `openOutputStream` still useful? I think it's always true now |
swift-openapi-urlsession | github_2023 | others | 24 | apple | guoye-zhang | @@ -73,8 +73,23 @@ public struct URLSessionTransport: ClientTransport {
/// Creates a new configuration with the provided session.
/// - Parameter session: The URLSession used for performing HTTP operations.
- /// If none is provided, the system uses the shared URLSession.
- public init(session: URLSession = .shared) { self.session = session }
+ /// If none is provided, the system uses the shared URLSession.
+ public init(session: URLSession = .shared) { self.init(session: session, implementation: .platformDefault) }
+
+ enum Implementation {
+ case buffering
+ case streaming(requestBodyStreamBufferSize: Int, responseBodyStreamWatermarks: (low: Int, high: Int)) | My preference is to not expose `requestBodyStreamBufferSize`. It is an extremely confusing parameter that does not reflect buffering done in CFNetwork and Network framework. We could have gotten away with not using bounded stream pair if NSStream subclassing were easier in Swift, and it will likely be unnecessary in the future.
We'd like to retain the ability to fine tune these values on our platforms without needing developers to change their code, e.g. reducing the buffer size on low memory devices like Apple Watch, or even adjusting it dynamically based on memory pressure / app state. Most developers are not equipped to decide the best buffer size to use.
Would they be better as environment variables for advanced use cases that we don't need to commit as APIs? |
swift-openapi-urlsession | github_2023 | others | 24 | apple | guoye-zhang | @@ -0,0 +1,191 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+
+/// Delegate that supports bidirectional streaming of request and response bodies.
+///
+/// While URLSession provides a high-level API that returns an async sequence of
+/// bytes, `bytes(for:delegate:)`, but does not provide an API that takes an async sequence
+/// as a request body. For instance, `upload(for:delegate:)` and `upload(fromFile:delegate:)`
+/// both buffer the entire response body and return `Data`.
+///
+/// Additionally, bridging `URLSession.AsyncBytes`, which is an `AsyncSequence<UInt8>` to
+/// `OpenAPIRuntime.HTTPBody`, an `AsyncSequence<ByteChunk>`, is problematic and will
+/// incur an allocation for every byte.
+///
+/// This delegate vends the response body as a `HTTBody` with one chunk for each
+/// `urlSession(_:didReceive data:)` callback. It also provides backpressure, which will
+/// suspend and resume the URLSession task based on a configurable high and low watermark.
+///
+/// When performing requests without a body, this delegate should be used with a
+/// `URLSessionDataTask` to stream the response body.
+///
+/// When performing requests with a body, this delegate should be used with a
+/// `URLSessionUploadTask` using `uploadTask(withStreamedRequest:delegate:)`, which will
+/// ask the delegate for a `InputStream` for the request body via the
+/// `urlSession(_:needNewBodyStreamForTask:)` callback.
+///
+/// The `urlSession(_:needNewBodyStreamForTask:)` callback will create a pair of bound
+/// streams, bridge the `HTTPBody` request body to the `OutputStream` and return the
+/// `InputStream` to URLSession. Backpressure for the request body stream is provided
+/// as an implementation detail of how URLSession reads from the `InputStream`.
+///
+/// Note that `urlSession(_:needNewBodyStreamForTask:)` may be called more than once, e.g.
+/// when performing a HTTP redirect, upon which the delegate is expected to create a new
+/// `InputStream` for the request body. This is only possible if the underlying `HTTPBody`
+/// request body can be iterated multiple times, i.e. `iterationBehavior == .multiple`.
+/// If the request body cannot be iterated multiple times, then the URLSession task will be cancelled.
+final class BidirectionalStreamingURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
+
+ let requestBody: HTTPBody?
+ var hasAlreadyIteratedRequestBody: Bool
+ var hasSuspendedURLSessionTask: Bool
+ let requestStreamBufferSize: Int
+ var requestStream: HTTPBodyOutputStreamBridge?
+
+ typealias ResponseContinuation = CheckedContinuation<URLResponse, any Error>
+ var responseContinuation: ResponseContinuation?
+
+ typealias ResponseBodyStream = AsyncBackpressuredStream<HTTPBody.ByteChunk, any Error>
+ var responseBodyStream: ResponseBodyStream
+ var responseBodyStreamSource: ResponseBodyStream.Source
+
+ /// This lock is taken for the duration of all delegate callbacks to protect the mutable delegate state.
+ ///
+ /// Although all the delegate callbacks are performed on the session's `delegateQueue`, there is no guarantee that
+ /// this is a _serial_ queue.
+ ///
+ /// Regardless of the type of delegate queue, URLSession will attempt to order the callbacks for each task in a
+ /// sensible way, but it cannot be guaranteed, specifically when the URLSession task is cancelled.
+ ///
+ /// Therefore, even though the `suspend()`, `resume()`, and `cancel()` URLSession methods are thread-safe, we need
+ /// to protect any mutable state within the delegate itself.
+ let callbackLock = NSLock() | Do we prefer NSLock or NIOLock? I think both are used in some files |
swift-openapi-urlsession | github_2023 | others | 24 | apple | guoye-zhang | @@ -0,0 +1,191 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 OpenAPIRuntime
+import HTTPTypes
+#if canImport(Darwin)
+import Foundation
+
+/// Delegate that supports bidirectional streaming of request and response bodies.
+///
+/// While URLSession provides a high-level API that returns an async sequence of
+/// bytes, `bytes(for:delegate:)`, but does not provide an API that takes an async sequence
+/// as a request body. For instance, `upload(for:delegate:)` and `upload(fromFile:delegate:)`
+/// both buffer the entire response body and return `Data`.
+///
+/// Additionally, bridging `URLSession.AsyncBytes`, which is an `AsyncSequence<UInt8>` to
+/// `OpenAPIRuntime.HTTPBody`, an `AsyncSequence<ByteChunk>`, is problematic and will
+/// incur an allocation for every byte.
+///
+/// This delegate vends the response body as a `HTTBody` with one chunk for each
+/// `urlSession(_:didReceive data:)` callback. It also provides backpressure, which will
+/// suspend and resume the URLSession task based on a configurable high and low watermark.
+///
+/// When performing requests without a body, this delegate should be used with a
+/// `URLSessionDataTask` to stream the response body.
+///
+/// When performing requests with a body, this delegate should be used with a
+/// `URLSessionUploadTask` using `uploadTask(withStreamedRequest:delegate:)`, which will
+/// ask the delegate for a `InputStream` for the request body via the
+/// `urlSession(_:needNewBodyStreamForTask:)` callback.
+///
+/// The `urlSession(_:needNewBodyStreamForTask:)` callback will create a pair of bound
+/// streams, bridge the `HTTPBody` request body to the `OutputStream` and return the
+/// `InputStream` to URLSession. Backpressure for the request body stream is provided
+/// as an implementation detail of how URLSession reads from the `InputStream`.
+///
+/// Note that `urlSession(_:needNewBodyStreamForTask:)` may be called more than once, e.g.
+/// when performing a HTTP redirect, upon which the delegate is expected to create a new
+/// `InputStream` for the request body. This is only possible if the underlying `HTTPBody`
+/// request body can be iterated multiple times, i.e. `iterationBehavior == .multiple`.
+/// If the request body cannot be iterated multiple times, then the URLSession task will be cancelled.
+final class BidirectionalStreamingURLSessionDelegate: NSObject, URLSessionTaskDelegate, URLSessionDataDelegate {
+
+ let requestBody: HTTPBody?
+ var hasAlreadyIteratedRequestBody: Bool
+ var hasSuspendedURLSessionTask: Bool
+ let requestStreamBufferSize: Int
+ var requestStream: HTTPBodyOutputStreamBridge?
+
+ typealias ResponseContinuation = CheckedContinuation<URLResponse, any Error>
+ var responseContinuation: ResponseContinuation?
+
+ typealias ResponseBodyStream = AsyncBackpressuredStream<HTTPBody.ByteChunk, any Error>
+ var responseBodyStream: ResponseBodyStream
+ var responseBodyStreamSource: ResponseBodyStream.Source
+
+ /// This lock is taken for the duration of all delegate callbacks to protect the mutable delegate state.
+ ///
+ /// Although all the delegate callbacks are performed on the session's `delegateQueue`, there is no guarantee that
+ /// this is a _serial_ queue.
+ ///
+ /// Regardless of the type of delegate queue, URLSession will attempt to order the callbacks for each task in a
+ /// sensible way, but it cannot be guaranteed, specifically when the URLSession task is cancelled.
+ ///
+ /// Therefore, even though the `suspend()`, `resume()`, and `cancel()` URLSession methods are thread-safe, we need
+ /// to protect any mutable state within the delegate itself.
+ let callbackLock = NSLock()
+
+ /// In addition to the callback lock, there is one point of rentrancy, where the response stream callback gets fired
+ /// immediately, for this we have a different lock, which protects `hasSuspendedURLSessionTask`.
+ let hasSuspendedURLSessionTaskLock = NSLock()
+
+ /// Use `bidirectionalStreamingRequest(for:baseURL:requestBody:requestStreamBufferSize:responseStreamWatermarks:)`.
+ init(requestBody: HTTPBody?, requestStreamBufferSize: Int, responseStreamWatermarks: (low: Int, high: Int)) {
+ self.requestBody = requestBody
+ self.hasAlreadyIteratedRequestBody = false
+ self.hasSuspendedURLSessionTask = false
+ self.requestStreamBufferSize = requestStreamBufferSize
+ (self.responseBodyStream, self.responseBodyStreamSource) = AsyncBackpressuredStream.makeStream(
+ backPressureStrategy: .highLowWatermarkWithElementCounts(
+ lowWatermark: responseStreamWatermarks.low,
+ highWatermark: responseStreamWatermarks.high
+ )
+ )
+ }
+
+ func urlSession(_ session: URLSession, needNewBodyStreamForTask task: URLSessionTask) async -> InputStream? {
+ callbackLock.withLock {
+ debug("Task delegate: needNewBodyStreamForTask")
+ // If the HTTP body cannot be iterated multiple times then bad luck; the only thing
+ // we can do is cancel the task and return nil.
+ if hasAlreadyIteratedRequestBody {
+ guard requestBody!.iterationBehavior == .multiple else {
+ debug("Task delegate: Cannot rewind request body, cancelling task")
+ task.cancel() | Returning nil is sufficient, no need to do both |
swift-openapi-urlsession | github_2023 | others | 19 | apple | glbrntt | @@ -37,6 +43,13 @@ for SCRIPT_PATH in "${SCRIPT_PATHS[@]}"; do
fi
done
+log "Running swift-format..."
+bash ${CURRENT_SCRIPT_DIR}/run-swift-format.sh $FIX_FORMAT > /dev/null | ```suggestion
bash "${CURRENT_SCRIPT_DIR}"/run-swift-format.sh $FIX_FORMAT > /dev/null
``` |
swift-openapi-urlsession | github_2023 | others | 28 | apple | czechboy0 | @@ -164,7 +164,8 @@ final class BidirectionalStreamingURLSessionDelegate: NSObject, URLSessionTaskDe
{
callbackLock.withLock {
debug("Task delegate: didReceive response")
- self.responseContinuation?.resume(returning: response)
+ responseContinuation?.resume(returning: response)
+ responseContinuation = nil | I remember someone recently mentioning that we should be careful about resuming continuations within locked sections. I wonder if we could make this a little safer by returning the continuation from `withLock` and resuming it outside the locked section? Same below.
Still approving the PR, just a thought in case you haven't considered this. |
swift-openapi-urlsession | github_2023 | others | 26 | apple | czechboy0 | @@ -230,10 +231,17 @@ var debugLoggingEnabled: Bool {
get { _debugLoggingEnabled.withLockedValue { $0 } }
set { _debugLoggingEnabled.withLockedValue { $0 = newValue } }
}
-func debug(_ items: Any..., separator: String = " ", terminator: String = "\n") {
+private let _standardErrorLock = LockStorage.create(value: FileHandle.standardError) | Where's the `LockStorage` type coming from? |
swift-openapi-urlsession | github_2023 | others | 15 | apple | simonjbeaumont | @@ -138,40 +145,74 @@ internal enum URLSessionTransportError: Error {
case noResponse(url: URL?)
}
-extension OpenAPIRuntime.Response {
- init(from urlResponse: URLResponse, body: Data) throws {
+extension HTTPResponse {
+ static func response( | The guidance suggests that type-preserving conversions are `init(...)`. |
swift-openapi-urlsession | github_2023 | others | 15 | apple | simonjbeaumont | @@ -138,40 +145,74 @@ internal enum URLSessionTransportError: Error {
case noResponse(url: URL?)
}
-extension OpenAPIRuntime.Response {
- init(from urlResponse: URLResponse, body: Data) throws {
+extension HTTPResponse {
+ static func response(
+ method: HTTPRequest.Method,
+ urlResponse: URLResponse,
+ data: Data
+ ) throws -> (HTTPResponse, HTTPBody?) {
guard let httpResponse = urlResponse as? HTTPURLResponse else {
throw URLSessionTransportError.notHTTPResponse(urlResponse)
}
- let headerFields: [HeaderField] = httpResponse
- .allHeaderFields
- .compactMap { headerName, headerValue in
- guard let name = headerName as? String, let value = headerValue as? String else {
- return nil
- }
- return HeaderField(name: name, value: value)
+ var headerFields = HTTPFields()
+ for (headerName, headerValue) in httpResponse.allHeaderFields {
+ guard
+ let rawName = headerName as? String,
+ let name = HTTPField.Name(rawName),
+ let value = headerValue as? String
+ else {
+ continue | Is this the right thing to do when we cannot convert the header? Should we instead throw? |
swift-openapi-urlsession | github_2023 | others | 15 | apple | simonjbeaumont | @@ -138,40 +145,74 @@ internal enum URLSessionTransportError: Error {
case noResponse(url: URL?)
}
-extension OpenAPIRuntime.Response {
- init(from urlResponse: URLResponse, body: Data) throws {
+extension HTTPResponse {
+ static func response(
+ method: HTTPRequest.Method,
+ urlResponse: URLResponse,
+ data: Data
+ ) throws -> (HTTPResponse, HTTPBody?) {
guard let httpResponse = urlResponse as? HTTPURLResponse else {
throw URLSessionTransportError.notHTTPResponse(urlResponse)
}
- let headerFields: [HeaderField] = httpResponse
- .allHeaderFields
- .compactMap { headerName, headerValue in
- guard let name = headerName as? String, let value = headerValue as? String else {
- return nil
- }
- return HeaderField(name: name, value: value)
+ var headerFields = HTTPFields()
+ for (headerName, headerValue) in httpResponse.allHeaderFields {
+ guard
+ let rawName = headerName as? String,
+ let name = HTTPField.Name(rawName),
+ let value = headerValue as? String
+ else {
+ continue
}
- self.init(statusCode: httpResponse.statusCode, headerFields: headerFields, body: body)
+ headerFields[name] = value
+ }
+ let body: HTTPBody?
+ switch method {
+ case .head, .connect, .trace:
+ body = nil
+ default:
+ body = .init(data)
+ } | I realise we left room in the transport API to provide a nil body. But we should consider which of these is more important:
- URLSessionTransport should have the same semantics as if I used URLSession directly.
- All transports should have similar semantics.
The latter is hard to police. Consequently, should this method just provide the data in all cases, if that's what URLSession does? |
swift-openapi-urlsession | github_2023 | others | 15 | apple | simonjbeaumont | @@ -138,40 +145,74 @@ internal enum URLSessionTransportError: Error {
case noResponse(url: URL?)
}
-extension OpenAPIRuntime.Response {
- init(from urlResponse: URLResponse, body: Data) throws {
+extension HTTPResponse {
+ static func response(
+ method: HTTPRequest.Method,
+ urlResponse: URLResponse,
+ data: Data
+ ) throws -> (HTTPResponse, HTTPBody?) {
guard let httpResponse = urlResponse as? HTTPURLResponse else {
throw URLSessionTransportError.notHTTPResponse(urlResponse)
}
- let headerFields: [HeaderField] = httpResponse
- .allHeaderFields
- .compactMap { headerName, headerValue in
- guard let name = headerName as? String, let value = headerValue as? String else {
- return nil
- }
- return HeaderField(name: name, value: value)
+ var headerFields = HTTPFields()
+ for (headerName, headerValue) in httpResponse.allHeaderFields {
+ guard
+ let rawName = headerName as? String,
+ let name = HTTPField.Name(rawName),
+ let value = headerValue as? String
+ else {
+ continue
}
- self.init(statusCode: httpResponse.statusCode, headerFields: headerFields, body: body)
+ headerFields[name] = value
+ }
+ let body: HTTPBody?
+ switch method {
+ case .head, .connect, .trace:
+ body = nil
+ default:
+ body = .init(data)
+ }
+ return (
+ HTTPResponse(
+ status: .init(code: httpResponse.statusCode),
+ headerFields: headerFields
+ ),
+ body
+ )
}
}
extension URLRequest {
- init(_ request: OpenAPIRuntime.Request, baseURL: URL) throws {
- guard var baseUrlComponents = URLComponents(string: baseURL.absoluteString) else {
- throw URLSessionTransportError.invalidRequestURL(request: request, baseURL: baseURL)
+ init(_ request: HTTPRequest, body: HTTPBody?, baseURL: URL) async throws {
+ guard
+ var baseUrlComponents = URLComponents(string: baseURL.absoluteString),
+ let requestUrlComponents = URLComponents(string: request.path ?? "")
+ else {
+ throw URLSessionTransportError.invalidRequestURL(
+ path: request.path ?? "<nil>",
+ method: request.method,
+ baseURL: baseURL
+ )
}
- baseUrlComponents.percentEncodedPath += request.path
- baseUrlComponents.percentEncodedQuery = request.query
+
+ let path = requestUrlComponents.percentEncodedPath
+ baseUrlComponents.percentEncodedPath += path
+ baseUrlComponents.percentEncodedQuery = requestUrlComponents.percentEncodedQuery
guard let url = baseUrlComponents.url else {
- throw URLSessionTransportError.invalidRequestURL(request: request, baseURL: baseURL)
+ throw URLSessionTransportError.invalidRequestURL(
+ path: path,
+ method: request.method,
+ baseURL: baseURL
+ )
}
self.init(url: url)
- self.httpMethod = request.method.name
+ self.httpMethod = request.method.rawValue
for header in request.headerFields {
- self.addValue(header.value, forHTTPHeaderField: header.name)
+ self.setValue(header.value, forHTTPHeaderField: header.name.canonicalName) | Isn't it this `.canonicalName` that's causing the conversion that meant you needed to change the tests? ISTR that they had other properties that didn't do this? |
swift-openapi-urlsession | github_2023 | others | 15 | apple | simonjbeaumont | @@ -27,41 +27,54 @@ import Foundation
@preconcurrency import class FoundationNetworking.URLSessionConfiguration
#endif
@testable import OpenAPIURLSession
+import HTTPTypes
class URLSessionTransportTests: XCTestCase {
- func testRequestConversion() throws {
- let request = OpenAPIRuntime.Request(
- path: "/hello%20world/Maria",
- query: "greeting=Howdy",
+ func testRequestConversion() async throws {
+ let request = HTTPRequest(
method: .post,
+ scheme: nil,
+ authority: nil,
+ path: "/hello%20world/Maria?greeting=Howdy",
headerFields: [
- .init(name: "X-Mumble", value: "mumble")
- ],
- body: Data("👋".utf8)
+ .init("x-mumble2")!: "mumble"
+ ]
+ )
+ let body: HTTPBody = "👋"
+ let urlRequest = try await URLRequest(
+ request,
+ body: body,
+ baseURL: URL(string: "http://example.com/api")!
)
- let urlRequest = try URLRequest(request, baseURL: URL(string: "http://example.com/api")!)
XCTAssertEqual(urlRequest.url, URL(string: "http://example.com/api/hello%20world/Maria?greeting=Howdy"))
XCTAssertEqual(urlRequest.httpMethod, "POST")
- XCTAssertEqual(urlRequest.allHTTPHeaderFields, ["X-Mumble": "mumble"]) | Can't we move the `.canonicalName` to the test when doing the conversion as a normalization before the equality check? |
swift-openapi-urlsession | github_2023 | others | 7 | apple | czechboy0 | @@ -18,7 +18,7 @@ import PackageDescription
let package = Package(
name: "swift-openapi-urlsession",
platforms: [
- .macOS(.v13), .iOS(.v16), .tvOS(.v16), .watchOS(.v9),
+ .macOS(.v11), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), | For consistency, did you try bumping macOS back to `10.15`, so that all the OS's are aligned? |
swift-openapi-urlsession | github_2023 | others | 7 | apple | czechboy0 | @@ -90,7 +90,18 @@ public struct URLSessionTransport: ClientTransport {
}
private func invokeSession(_ urlRequest: URLRequest) async throws -> (Data, URLResponse) {
- #if canImport(FoundationNetworking)
+ #if canImport(FoundationNetworking)
+ return try await performDataTask(with: urlRequest)
+ #else
+ if #available(iOS 15.0, *) { | Should this also include the macOS, tvOS, and watchOS versions aligned with iOS 15? |
swift-openapi-urlsession | github_2023 | others | 7 | apple | simonjbeaumont | @@ -90,7 +90,18 @@ public struct URLSessionTransport: ClientTransport {
}
private func invokeSession(_ urlRequest: URLRequest) async throws -> (Data, URLResponse) {
- #if canImport(FoundationNetworking)
+ #if canImport(FoundationNetworking)
+ return try await performDataTask(with: urlRequest)
+ #else
+ if #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) {
+ return try await configuration.session.data(for: urlRequest)
+ } else {
+ return try await performDataTask(with: urlRequest)
+ }
+ #endif
+ }
+
+ private func performDataTask(with urlRequest: URLRequest) async throws -> (Data, URLResponse) { | I'm not sure I understand the motivation behind this method selection, but I might have misunderstood something.
Firstly, [`URLSession.dataTask(with:completionHandler:)`](https://developer.apple.com/documentation/foundation/urlsession/1407613-datatask) is not deprecated and is available back to macOS 10.9.
Secondly, [`URLSession.data(for:)`](https://developer.apple.com/documentation/foundation/urlsession/3919872-data) looks to be available back to macOS 10.15.
So based on the goal of making this package deployable on `.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6)`, it looks like we could use either method unilaterally.
WDYT @czechboy0? |
swift-openapi-urlsession | github_2023 | others | 7 | apple | czechboy0 | @@ -4,6 +4,11 @@ A client transport that uses the [URLSession](https://developer.apple.com/docume
Use the transport with client code generated by [Swift OpenAPI Generator](https://github.com/apple/swift-openapi-generator).
+## Supported platforms and minimum versions
+ | macOS | Linux | iOS | tvOS | watchOS |
+ | :-: | :-: | :-: | :-: | :-: |
+ | ✅ 10.15+ | ✅ | ✅ 13+ | ✅ 13+ | ✅ 6+ |
+ | Good catch – can you please also add this to https://github.com/apple/swift-openapi-urlsession/blob/main/Sources/OpenAPIURLSession/Documentation.docc/Documentation.md? |
swift-openapi-urlsession | github_2023 | others | 7 | apple | czechboy0 | @@ -178,6 +178,8 @@ extension URLSessionTransportError: CustomStringConvertible {
"Invalid request URL from request path: \(request.path), query: \(request.query ?? "<nil>") relative to base URL: \(baseURL.absoluteString)"
case .notHTTPResponse(let response):
return "Received a non-HTTP response, of type: \(String(describing: type(of: response)))"
+ case .noResponse(let url):
+ return "Received a nil response for \(url?.absoluteString ?? "")" | ```suggestion
return "Received a nil response for \(url?.absoluteString ?? "<nil URL>")"
```
Nit: to make it easier to catch when the URL is nil. |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -86,3 +91,178 @@ def query_iterator_indices(block_mask_map: np.ndarray, *, padding: int = 0) -> K
kv_block_offset=jnp.asarray(index_offset),
kv_block_offset_size=jnp.asarray(index_offset_size),
)
+
+
+class BaseFlashAttention(Configurable):
+ """Common interface for FlashAttention for all backends."""
+
+ @config_class
+ class Config(Configurable.Config):
+ """Configures BaseFlashAttention.
+
+ Attributes:
+ is_decoding: Whether we're in decoding/inference mode.
+ softmax_scale: Scale factor to apply to QK.
+ dropout_rate: Dropout rate for attention probs.
+ interpret: Whether to use interpret mode for Pallas kernels.
+ tpu_block_size: Block size for TPU pallas kernels.
+ gpu_block_size: Block size for GPU pallas kernels.
+ """
+
+ is_decoding: bool = False | Keep some of these as required? `is_decoding=False` doesn't seem like a universal default. |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -86,3 +91,178 @@ def query_iterator_indices(block_mask_map: np.ndarray, *, padding: int = 0) -> K
kv_block_offset=jnp.asarray(index_offset),
kv_block_offset_size=jnp.asarray(index_offset_size),
)
+
+
+class BaseFlashAttention(Configurable):
+ """Common interface for FlashAttention for all backends."""
+
+ @config_class
+ class Config(Configurable.Config):
+ """Configures BaseFlashAttention.
+
+ Attributes:
+ is_decoding: Whether we're in decoding/inference mode.
+ softmax_scale: Scale factor to apply to QK.
+ dropout_rate: Dropout rate for attention probs.
+ interpret: Whether to use interpret mode for Pallas kernels.
+ tpu_block_size: Block size for TPU pallas kernels.
+ gpu_block_size: Block size for GPU pallas kernels.
+ """
+
+ is_decoding: bool = False
+ softmax_scale: float = 1.0
+ dropout_rate: float = 0.0
+ interpret: bool = False
+ tpu_block_size: int = 512
+ gpu_block_size: int = 128
+
+ def __init__(self, cfg):
+ super().__init__(cfg)
+ # Keep a typed copy of self.config.
+ self.cfg: BaseFlashAttention.Config = self.config
+
+ def name(self) -> str:
+ """Returns the class name."""
+ return self.__class__.__name__
+
+ def _log_unsupported(self, reason: str):
+ logging.warning("Not using %s because %s", self.name(), reason)
+ return False | ```suggestion
``` |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -86,3 +91,178 @@ def query_iterator_indices(block_mask_map: np.ndarray, *, padding: int = 0) -> K
kv_block_offset=jnp.asarray(index_offset),
kv_block_offset_size=jnp.asarray(index_offset_size),
)
+
+
+class BaseFlashAttention(Configurable):
+ """Common interface for FlashAttention for all backends."""
+
+ @config_class
+ class Config(Configurable.Config):
+ """Configures BaseFlashAttention.
+
+ Attributes:
+ is_decoding: Whether we're in decoding/inference mode.
+ softmax_scale: Scale factor to apply to QK.
+ dropout_rate: Dropout rate for attention probs.
+ interpret: Whether to use interpret mode for Pallas kernels.
+ tpu_block_size: Block size for TPU pallas kernels.
+ gpu_block_size: Block size for GPU pallas kernels.
+ """
+
+ is_decoding: bool = False
+ softmax_scale: float = 1.0
+ dropout_rate: float = 0.0
+ interpret: bool = False
+ tpu_block_size: int = 512
+ gpu_block_size: int = 128
+
+ def __init__(self, cfg):
+ super().__init__(cfg)
+ # Keep a typed copy of self.config.
+ self.cfg: BaseFlashAttention.Config = self.config
+
+ def name(self) -> str:
+ """Returns the class name."""
+ return self.__class__.__name__
+
+ def _log_unsupported(self, reason: str):
+ logging.warning("Not using %s because %s", self.name(), reason)
+ return False
+
+ def _check_block_size(self, *, query: Tensor, key: Tensor, block_size: int) -> bool:
+ q_seq_len = query.shape[1]
+ k_seq_len = key.shape[1]
+ if q_seq_len % block_size != 0 or k_seq_len % block_size != 0:
+ self._log_unsupported(f"{q_seq_len=} or {k_seq_len=} is not divisible by {block_size=}")
+ return False
+ return True
+
+ def is_supported(
+ self, query: Tensor, key: Tensor, value: Tensor, bias: BaseAttentionBias | ```suggestion
self, *, query: Tensor, key: Tensor, value: Tensor, bias: BaseAttentionBias
``` |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -86,3 +91,178 @@ def query_iterator_indices(block_mask_map: np.ndarray, *, padding: int = 0) -> K
kv_block_offset=jnp.asarray(index_offset),
kv_block_offset_size=jnp.asarray(index_offset_size),
)
+
+
+class BaseFlashAttention(Configurable):
+ """Common interface for FlashAttention for all backends."""
+
+ @config_class
+ class Config(Configurable.Config):
+ """Configures BaseFlashAttention.
+
+ Attributes:
+ is_decoding: Whether we're in decoding/inference mode.
+ softmax_scale: Scale factor to apply to QK.
+ dropout_rate: Dropout rate for attention probs.
+ interpret: Whether to use interpret mode for Pallas kernels.
+ tpu_block_size: Block size for TPU pallas kernels.
+ gpu_block_size: Block size for GPU pallas kernels.
+ """
+
+ is_decoding: bool = False
+ softmax_scale: float = 1.0
+ dropout_rate: float = 0.0
+ interpret: bool = False
+ tpu_block_size: int = 512
+ gpu_block_size: int = 128
+
+ def __init__(self, cfg):
+ super().__init__(cfg)
+ # Keep a typed copy of self.config.
+ self.cfg: BaseFlashAttention.Config = self.config
+
+ def name(self) -> str:
+ """Returns the class name."""
+ return self.__class__.__name__
+
+ def _log_unsupported(self, reason: str):
+ logging.warning("Not using %s because %s", self.name(), reason)
+ return False
+
+ def _check_block_size(self, *, query: Tensor, key: Tensor, block_size: int) -> bool:
+ q_seq_len = query.shape[1]
+ k_seq_len = key.shape[1]
+ if q_seq_len % block_size != 0 or k_seq_len % block_size != 0:
+ self._log_unsupported(f"{q_seq_len=} or {k_seq_len=} is not divisible by {block_size=}")
+ return False
+ return True
+
+ def is_supported(
+ self, query: Tensor, key: Tensor, value: Tensor, bias: BaseAttentionBias
+ ) -> bool:
+ """Returns whether the attention kernel supports the given configuration.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ bias: Attention bias to apply.
+
+ Returns:
+ True if the current configuration is supported. False otherwise.
+
+ Raises:
+ ValueError: If the given configuration doesn't logically make sense, e.g. if the
+ shapes of q/k/v do not satisfy the requirement of a standard attention.
+ """
+ del bias
+ if key.shape != value.shape:
+ raise ValueError(f"Expects {query.shape=} to be equal to {key.shape=}")
+ if query.shape[0] != key.shape[0]:
+ raise ValueError(
+ f"Expects query batch size {query.shape[0]} to be equal to key batch size "
+ f"{key.shape[0]}"
+ )
+ if query.shape[-1] != key.shape[-1]:
+ raise ValueError(
+ f"Expects query head dim {query.shape[-1]} to be equal to key head dim "
+ f"{key.shape[-1]}"
+ )
+ if query.shape[2] % key.shape[2] != 0:
+ raise ValueError(
+ f"Expects query num heads {query.shape[2]} to be divisible by num key heads "
+ f"{key.shape[2]}"
+ )
+ return True
+
+ def __call__(
+ self, | ```suggestion
self,
*,
```
(If kwargs are prohibited somewhere, please leave a comment.) |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -86,3 +91,178 @@ def query_iterator_indices(block_mask_map: np.ndarray, *, padding: int = 0) -> K
kv_block_offset=jnp.asarray(index_offset),
kv_block_offset_size=jnp.asarray(index_offset_size),
)
+
+
+class BaseFlashAttention(Configurable):
+ """Common interface for FlashAttention for all backends."""
+
+ @config_class
+ class Config(Configurable.Config):
+ """Configures BaseFlashAttention.
+
+ Attributes:
+ is_decoding: Whether we're in decoding/inference mode.
+ softmax_scale: Scale factor to apply to QK.
+ dropout_rate: Dropout rate for attention probs.
+ interpret: Whether to use interpret mode for Pallas kernels.
+ tpu_block_size: Block size for TPU pallas kernels.
+ gpu_block_size: Block size for GPU pallas kernels.
+ """
+
+ is_decoding: bool = False
+ softmax_scale: float = 1.0
+ dropout_rate: float = 0.0
+ interpret: bool = False
+ tpu_block_size: int = 512
+ gpu_block_size: int = 128
+
+ def __init__(self, cfg):
+ super().__init__(cfg)
+ # Keep a typed copy of self.config.
+ self.cfg: BaseFlashAttention.Config = self.config
+
+ def name(self) -> str:
+ """Returns the class name."""
+ return self.__class__.__name__
+
+ def _log_unsupported(self, reason: str):
+ logging.warning("Not using %s because %s", self.name(), reason)
+ return False
+
+ def _check_block_size(self, *, query: Tensor, key: Tensor, block_size: int) -> bool:
+ q_seq_len = query.shape[1]
+ k_seq_len = key.shape[1]
+ if q_seq_len % block_size != 0 or k_seq_len % block_size != 0:
+ self._log_unsupported(f"{q_seq_len=} or {k_seq_len=} is not divisible by {block_size=}")
+ return False
+ return True
+
+ def is_supported(
+ self, query: Tensor, key: Tensor, value: Tensor, bias: BaseAttentionBias
+ ) -> bool:
+ """Returns whether the attention kernel supports the given configuration.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ bias: Attention bias to apply.
+
+ Returns:
+ True if the current configuration is supported. False otherwise.
+
+ Raises:
+ ValueError: If the given configuration doesn't logically make sense, e.g. if the
+ shapes of q/k/v do not satisfy the requirement of a standard attention.
+ """
+ del bias
+ if key.shape != value.shape:
+ raise ValueError(f"Expects {query.shape=} to be equal to {key.shape=}")
+ if query.shape[0] != key.shape[0]:
+ raise ValueError(
+ f"Expects query batch size {query.shape[0]} to be equal to key batch size "
+ f"{key.shape[0]}"
+ )
+ if query.shape[-1] != key.shape[-1]:
+ raise ValueError(
+ f"Expects query head dim {query.shape[-1]} to be equal to key head dim "
+ f"{key.shape[-1]}"
+ )
+ if query.shape[2] % key.shape[2] != 0:
+ raise ValueError(
+ f"Expects query num heads {query.shape[2]} to be divisible by num key heads "
+ f"{key.shape[2]}"
+ )
+ return True
+
+ def __call__(
+ self,
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: BaseAttentionBias,
+ prng_key: Optional[Tensor] = None,
+ ) -> Tensor:
+ """Computes attention context.
+
+ Warning: The dtype of key and value may differ from the dtype of query.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ bias: Attention bias to apply.
+ prng_key: PRNG key for dropout. Only needed when dropout_rate > 0.0.
+
+ Returns:
+ The context tensor of shape [batch_size, target_length, num_heads, per_head_dim].
+ """
+ raise NotImplementedError()
+
+
+class BaseSingleStepDecoding(BaseFlashAttention): | Here we can define a `default_config` which sets `is_decoding=True`. |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -86,3 +91,178 @@ def query_iterator_indices(block_mask_map: np.ndarray, *, padding: int = 0) -> K
kv_block_offset=jnp.asarray(index_offset),
kv_block_offset_size=jnp.asarray(index_offset_size),
)
+
+
+class BaseFlashAttention(Configurable):
+ """Common interface for FlashAttention for all backends."""
+
+ @config_class
+ class Config(Configurable.Config):
+ """Configures BaseFlashAttention.
+
+ Attributes:
+ is_decoding: Whether we're in decoding/inference mode.
+ softmax_scale: Scale factor to apply to QK.
+ dropout_rate: Dropout rate for attention probs.
+ interpret: Whether to use interpret mode for Pallas kernels.
+ tpu_block_size: Block size for TPU pallas kernels.
+ gpu_block_size: Block size for GPU pallas kernels.
+ """
+
+ is_decoding: bool = False
+ softmax_scale: float = 1.0
+ dropout_rate: float = 0.0
+ interpret: bool = False
+ tpu_block_size: int = 512
+ gpu_block_size: int = 128
+
+ def __init__(self, cfg):
+ super().__init__(cfg)
+ # Keep a typed copy of self.config.
+ self.cfg: BaseFlashAttention.Config = self.config
+
+ def name(self) -> str:
+ """Returns the class name."""
+ return self.__class__.__name__
+
+ def _log_unsupported(self, reason: str):
+ logging.warning("Not using %s because %s", self.name(), reason)
+ return False
+
+ def _check_block_size(self, *, query: Tensor, key: Tensor, block_size: int) -> bool:
+ q_seq_len = query.shape[1]
+ k_seq_len = key.shape[1]
+ if q_seq_len % block_size != 0 or k_seq_len % block_size != 0:
+ self._log_unsupported(f"{q_seq_len=} or {k_seq_len=} is not divisible by {block_size=}")
+ return False
+ return True
+
+ def is_supported(
+ self, query: Tensor, key: Tensor, value: Tensor, bias: BaseAttentionBias
+ ) -> bool:
+ """Returns whether the attention kernel supports the given configuration.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ bias: Attention bias to apply.
+
+ Returns:
+ True if the current configuration is supported. False otherwise.
+
+ Raises:
+ ValueError: If the given configuration doesn't logically make sense, e.g. if the
+ shapes of q/k/v do not satisfy the requirement of a standard attention.
+ """
+ del bias
+ if key.shape != value.shape:
+ raise ValueError(f"Expects {query.shape=} to be equal to {key.shape=}")
+ if query.shape[0] != key.shape[0]:
+ raise ValueError(
+ f"Expects query batch size {query.shape[0]} to be equal to key batch size "
+ f"{key.shape[0]}"
+ )
+ if query.shape[-1] != key.shape[-1]:
+ raise ValueError(
+ f"Expects query head dim {query.shape[-1]} to be equal to key head dim "
+ f"{key.shape[-1]}"
+ )
+ if query.shape[2] % key.shape[2] != 0:
+ raise ValueError(
+ f"Expects query num heads {query.shape[2]} to be divisible by num key heads "
+ f"{key.shape[2]}"
+ )
+ return True
+
+ def __call__(
+ self,
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ bias: BaseAttentionBias,
+ prng_key: Optional[Tensor] = None,
+ ) -> Tensor:
+ """Computes attention context.
+
+ Warning: The dtype of key and value may differ from the dtype of query.
+
+ Args:
+ query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
+ key: Key of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ value: Value of shape [batch_size, source_length, num_kv_heads, per_head_dim].
+ bias: Attention bias to apply.
+ prng_key: PRNG key for dropout. Only needed when dropout_rate > 0.0.
+
+ Returns:
+ The context tensor of shape [batch_size, target_length, num_heads, per_head_dim].
+ """
+ raise NotImplementedError()
+
+
+class BaseSingleStepDecoding(BaseFlashAttention):
+ """Wraps the common checks for single step decoding kernels."""
+
+ def is_supported(self, query, key, value, bias): | Retain typing/returns and add a docstring referring users to the parent.
(Please apply elsewhere.) |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -772,63 +789,168 @@ def call_kernel(
flash_attention.defvjp(_mha_forward, _mha_backward)
-# Interface to cuDNN's dot product attention.
-# TODO(kelvin-zou): Add support for segment IDs.
-def cudnn_dot_product_attention(
- query: Tensor,
- key: Tensor,
- value: Tensor,
- bias: Optional[Tensor] = None,
- mask: Optional[Tensor] = None,
- causal: bool = False,
- *,
- softmax_scale: float = 1.0,
- seed: int = 42,
- dropout_rate: float = 0.0,
- qkv_layout: str = "BTNH",
-):
- """Computes dot-product attention given query (Q), key (K), and value (V).
+class CuDNNGPUFlashAttention(BaseFlashAttention):
+ """Wraps cuDNN FlashAttention and disallows explicit bias.
- If provided, bias, segment_ids, and any causal mask are applied on top of one another.
+ We disallow folding `mask_fn` and segment ids into explicit bias to allow Pallas implementation
+ to be used when possible.
- Reference implementation:
- https://github.com/google/jax/blob/f4158ace933482844c145a6b919bf5dc86e084ba/jax/_src/cudnn/fused_attention_stablehlo.py#L927.
- https://github.com/openxla/xla/blob/536ba0b7d74f6637a7a772471a99ecf4f578aef2/xla/service/gpu/cublas_cudnn.cc#L77.
+ Note on sliding window condition (quoted from an error message):
+ "Sliding window attention is only supported with padding_mask=False, causal_mask=True,
+ is_dropout=False, is_bias=False, is_ragged=False"
+ """
- Args:
- query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
- key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
- value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
- bias: Optional logit biases of shape [batch_size, num_heads, target_length, source_length].
- mask: Optional logit mask of shape [batch_size, num_heads, target_length, source_length].
- softmax_scale: Optional scale to apply to softmax. Defaults to 1.
- seed: Random seed for dropout.
- dropout_rate: Dropout rate.
- qkv_layout: Layout string, with supported formats being BTNH, BNTH, BSNH,
- BNSH. Now it only supports BTNH.
+ _allow_explicit_bias = False | Why do we need the attribute? |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -772,63 +789,168 @@ def call_kernel(
flash_attention.defvjp(_mha_forward, _mha_backward)
-# Interface to cuDNN's dot product attention.
-# TODO(kelvin-zou): Add support for segment IDs.
-def cudnn_dot_product_attention(
- query: Tensor,
- key: Tensor,
- value: Tensor,
- bias: Optional[Tensor] = None,
- mask: Optional[Tensor] = None,
- causal: bool = False,
- *,
- softmax_scale: float = 1.0,
- seed: int = 42,
- dropout_rate: float = 0.0,
- qkv_layout: str = "BTNH",
-):
- """Computes dot-product attention given query (Q), key (K), and value (V).
+class CuDNNGPUFlashAttention(BaseFlashAttention):
+ """Wraps cuDNN FlashAttention and disallows explicit bias.
- If provided, bias, segment_ids, and any causal mask are applied on top of one another.
+ We disallow folding `mask_fn` and segment ids into explicit bias to allow Pallas implementation
+ to be used when possible.
- Reference implementation:
- https://github.com/google/jax/blob/f4158ace933482844c145a6b919bf5dc86e084ba/jax/_src/cudnn/fused_attention_stablehlo.py#L927.
- https://github.com/openxla/xla/blob/536ba0b7d74f6637a7a772471a99ecf4f578aef2/xla/service/gpu/cublas_cudnn.cc#L77.
+ Note on sliding window condition (quoted from an error message):
+ "Sliding window attention is only supported with padding_mask=False, causal_mask=True,
+ is_dropout=False, is_bias=False, is_ragged=False"
+ """
- Args:
- query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
- key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
- value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
- bias: Optional logit biases of shape [batch_size, num_heads, target_length, source_length].
- mask: Optional logit mask of shape [batch_size, num_heads, target_length, source_length].
- softmax_scale: Optional scale to apply to softmax. Defaults to 1.
- seed: Random seed for dropout.
- dropout_rate: Dropout rate.
- qkv_layout: Layout string, with supported formats being BTNH, BNTH, BSNH,
- BNSH. Now it only supports BTNH.
+ _allow_explicit_bias = False
+
+ def is_supported(self, query, key, value, bias):
+ if not super().is_supported(query, key, value, bias):
+ return False
+ if self.cfg.is_decoding:
+ if query.shape[1] > 1:
+ return self._log_unsupported("multi-step decoding is not supported.") | nit --
```suggestion
self._log_unsupported("Multi-step decoding is not supported.")
return False
``` |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -772,63 +789,168 @@ def call_kernel(
flash_attention.defvjp(_mha_forward, _mha_backward)
-# Interface to cuDNN's dot product attention.
-# TODO(kelvin-zou): Add support for segment IDs.
-def cudnn_dot_product_attention(
- query: Tensor,
- key: Tensor,
- value: Tensor,
- bias: Optional[Tensor] = None,
- mask: Optional[Tensor] = None,
- causal: bool = False,
- *,
- softmax_scale: float = 1.0,
- seed: int = 42,
- dropout_rate: float = 0.0,
- qkv_layout: str = "BTNH",
-):
- """Computes dot-product attention given query (Q), key (K), and value (V).
+class CuDNNGPUFlashAttention(BaseFlashAttention):
+ """Wraps cuDNN FlashAttention and disallows explicit bias.
- If provided, bias, segment_ids, and any causal mask are applied on top of one another.
+ We disallow folding `mask_fn` and segment ids into explicit bias to allow Pallas implementation
+ to be used when possible.
- Reference implementation:
- https://github.com/google/jax/blob/f4158ace933482844c145a6b919bf5dc86e084ba/jax/_src/cudnn/fused_attention_stablehlo.py#L927.
- https://github.com/openxla/xla/blob/536ba0b7d74f6637a7a772471a99ecf4f578aef2/xla/service/gpu/cublas_cudnn.cc#L77.
+ Note on sliding window condition (quoted from an error message):
+ "Sliding window attention is only supported with padding_mask=False, causal_mask=True,
+ is_dropout=False, is_bias=False, is_ragged=False"
+ """
- Args:
- query: Query of shape [batch_size, target_length, num_heads, per_head_dim].
- key: Key of shape [batch_size, source_length, num_heads, per_head_dim].
- value: Value of shape [batch_size, source_length, num_heads, per_head_dim].
- bias: Optional logit biases of shape [batch_size, num_heads, target_length, source_length].
- mask: Optional logit mask of shape [batch_size, num_heads, target_length, source_length].
- softmax_scale: Optional scale to apply to softmax. Defaults to 1.
- seed: Random seed for dropout.
- dropout_rate: Dropout rate.
- qkv_layout: Layout string, with supported formats being BTNH, BNTH, BSNH,
- BNSH. Now it only supports BTNH.
+ _allow_explicit_bias = False
+
+ def is_supported(self, query, key, value, bias):
+ if not super().is_supported(query, key, value, bias):
+ return False
+ if self.cfg.is_decoding:
+ if query.shape[1] > 1:
+ return self._log_unsupported("multi-step decoding is not supported.")
+ if not key.shape[1] % 2 == 0:
+ return self._log_unsupported(f"key sequence length {key.shape[1]} is not even.")
+ else:
+ if not self._check_block_size(query=query, key=key, block_size=2): | Comment on block size in relation to gpu_block_size? |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -177,7 +177,7 @@ def _compute_attention(
backend=backend,
softmax_scale=1.0,
is_decoding=is_decoding,
- block_size=cfg.tpu_block_size,
+ tpu_block_size=cfg.tpu_block_size, | Can we leave a TODO to decouple the naming from specific platforms? |
axlearn | github_2023 | python | 1,058 | apple | markblee | @@ -214,3 +218,37 @@ def _mha_backward(
flash_attention.defvjp(_mha_forward, _mha_backward)
+
+
+class NeuronFlashAttention(BaseFlashAttention):
+ """Wraps the Neuron attention kernel."""
+
+ def is_supported(self, query, key, value, bias):
+ # TODO(hanzhi-zhou): neuron may error out for unsupported sequence length and head size.
+ # Should we add checks for them and fallback to XLA? | What is the reason not to do so? |
axlearn | github_2023 | python | 1,041 | apple | changlan | @@ -168,10 +169,160 @@ class ForwardMode(enum.Enum):
class KVState(NamedTuple):
- """Represents key/value projections, of shape [batch, source_length, num_kv_heads, head_dim]."""
+ """Represents key/value projections.
+
+ Fields:
+ k_proj: [batch, source_length, num_kv_heads, per_head_dim], Projected key tensor.
+ v_proj: [batch, source_length, num_kv_heads, per_head_dim], Projected value tensor.
+ key_positions: [batch, source_length], Positions of the keys in the batch.
+ """
k_proj: Tensor
v_proj: Tensor
+ key_positions: Tensor
+
+
+class BaseKVCache(BaseLayer):
+ """Abstract base class for KV cache."""
+
+ @config_class
+ class Config(BaseLayer.Config):
+ """Configures BaseKVCache."""
+
+ # Autoregressive cache dtype. Should match the step dtype.
+ # Needs to match the forward dtype for Repeated layers. If None, infer as BaseLayer.dtype().
+ cache_dtype: Optional[jnp.dtype] = None
+
+ class Output(KVState):
+ pass
+
+ class Shape(NamedTuple):
+ """Shape of BaseKVCache.
+
+ Fields:
+ batch_size: int, batch size.
+ kv_len: int, KV Cache size.
+ num_kv_heads: int, the number of KV heads.
+ per_head_dim: int, the dimension per head.
+ """
+
+ batch_size: int
+ kv_len: int
+ num_kv_heads: int
+ per_head_dim: int
+
+ def _cache_dtype(self, dtype: jnp.dtype):
+ # Default to activation dtype for initialization if cache_dtype is None.
+ dtype = self.config.cache_dtype or dtype
+ assert dtype is not None
+ return dtype
+
+ def init_states(self, shape: Shape, *, dtype: jnp.dtype) -> Nested[Tensor]:
+ """Initializes KV cache.
+
+ Args:
+ shape: Shape, [batch, kv_len, num_kv_heads, per_head_dim].
+ dtype: dtype for KV Cache.
+
+ Returns:
+ init_state: A `Nested[Tensor]` object containing KV cache such as key and value.
+ """
+ raise NotImplementedError(type(self))
+
+ def extend_step(
+ self,
+ cached_states: Nested[Tensor],
+ *,
+ k_proj: Tensor,
+ v_proj: Tensor,
+ proj_positions: Tensor,
+ paddings: Optional[Tensor] = None,
+ ) -> tuple[Nested[Tensor], Output]:
+ """Updates the KV cache per extend step.
+
+ The input k_proj/v_proj are generated by `i_proj.forward()` from the input tokens.
+ The output k_proj/v_proj will have the `kv_cache` concatenated and will be used
+ in the current attention operation.
+
+ Args:
+ cached_states: A `Nested[Tensor]` object containing KV cache such as key and value.
+ k_proj: [batch, source_length, num_kv_heads, per_head_dim], Projected key tensor.
+ v_proj: [batch, source_length, num_kv_heads, per_head_dim], Projected value tensor.
+ proj_positions: [batch, source_length], Positions of the k_proj, int32.
+ paddings: [batch, source_length], An optional paddings of the k_proj, k_proj dtype. | nit: Could you please add more details on the semantics of paddings? |
axlearn | github_2023 | python | 1,041 | apple | changlan | @@ -168,10 +169,160 @@ class ForwardMode(enum.Enum):
class KVState(NamedTuple):
- """Represents key/value projections, of shape [batch, source_length, num_kv_heads, head_dim]."""
+ """Represents key/value projections.
+
+ Fields:
+ k_proj: [batch, source_length, num_kv_heads, per_head_dim], Projected key tensor.
+ v_proj: [batch, source_length, num_kv_heads, per_head_dim], Projected value tensor.
+ key_positions: [batch, source_length], Positions of the keys in the batch.
+ """
k_proj: Tensor
v_proj: Tensor
+ key_positions: Tensor
+
+
+class BaseKVCache(BaseLayer):
+ """Abstract base class for KV cache."""
+
+ @config_class
+ class Config(BaseLayer.Config):
+ """Configures BaseKVCache."""
+
+ # Autoregressive cache dtype. Should match the step dtype.
+ # Needs to match the forward dtype for Repeated layers. If None, infer as BaseLayer.dtype().
+ cache_dtype: Optional[jnp.dtype] = None
+
+ class Output(KVState):
+ pass
+
+ class Shape(NamedTuple):
+ """Shape of BaseKVCache.
+
+ Fields:
+ batch_size: int, batch size.
+ kv_len: int, KV Cache size.
+ num_kv_heads: int, the number of KV heads.
+ per_head_dim: int, the dimension per head.
+ """
+
+ batch_size: int
+ kv_len: int
+ num_kv_heads: int
+ per_head_dim: int
+
+ def _cache_dtype(self, dtype: jnp.dtype):
+ # Default to activation dtype for initialization if cache_dtype is None.
+ dtype = self.config.cache_dtype or dtype
+ assert dtype is not None
+ return dtype
+
+ def init_states(self, shape: Shape, *, dtype: jnp.dtype) -> Nested[Tensor]:
+ """Initializes KV cache.
+
+ Args:
+ shape: Shape, [batch, kv_len, num_kv_heads, per_head_dim].
+ dtype: dtype for KV Cache.
+
+ Returns:
+ init_state: A `Nested[Tensor]` object containing KV cache such as key and value.
+ """
+ raise NotImplementedError(type(self))
+
+ def extend_step(
+ self,
+ cached_states: Nested[Tensor],
+ *,
+ k_proj: Tensor,
+ v_proj: Tensor,
+ proj_positions: Tensor,
+ paddings: Optional[Tensor] = None,
+ ) -> tuple[Nested[Tensor], Output]:
+ """Updates the KV cache per extend step.
+
+ The input k_proj/v_proj are generated by `i_proj.forward()` from the input tokens.
+ The output k_proj/v_proj will have the `kv_cache` concatenated and will be used
+ in the current attention operation.
+
+ Args:
+ cached_states: A `Nested[Tensor]` object containing KV cache such as key and value.
+ k_proj: [batch, source_length, num_kv_heads, per_head_dim], Projected key tensor.
+ v_proj: [batch, source_length, num_kv_heads, per_head_dim], Projected value tensor.
+ proj_positions: [batch, source_length], Positions of the k_proj, int32. | Is this same as `key_positions`? Why use different names? |
axlearn | github_2023 | python | 1,041 | apple | changlan | @@ -2013,16 +2003,46 @@ def init_states(
query and .probs is of shape [batch, num_heads, target_length, source_length].
Otherwise, if initializing cache from scratch, output will be None.
"""
- return self._forward_for_mode(
+ if key is not None:
+ if query.shape[1] != key.shape[1]:
+ raise ValueError("Cross-attention extend_step is not supported.")
+ init_states = dict(time_step=jnp.zeros([query.shape[0]], dtype=jnp.int32))
+
+ # TODO(dhwang2): init_states without prefilling cannot determine whether KV sharing occurs,
+ # so a config option or additional argument should be added.
+ kv_sharing = kv_state is not None
+ if not kv_sharing:
+ kv_shape = KVCache.Shape(
+ batch_size=query.shape[0],
+ kv_len=query.shape[1],
+ num_kv_heads=self.i_proj.num_kv_heads,
+ per_head_dim=self.per_head_dim(),
+ )
+ init_states.update(
+ kv_cache=self.kv_cache.init_states(shape=kv_shape, dtype=query.dtype),
+ )
+
+ if time_step is None:
+ # init_states without prefilling branch.
+ return init_states, None
+
+ # Prefill branch.
+ # TODO(dhwang2): Optimize it by passing only the valid parts of the query. Currently,
+ # prefill has a complexity of O(max_len²), but this can be easily reduced to | Is this true when we use splash attention? |
axlearn | github_2023 | python | 1,041 | apple | changlan | @@ -1758,6 +1734,7 @@ def _forward_for_mode(
query: A Tensor or TensorSpec of shape [batch, target_length, target_dim].
key: An optional Tensor of shape [batch, source_length, source_dim].
value: An optional Tensor of shape [batch, source_length, source_dim].
+ paddings: An optional Tensor of shape [batch, target_dim] for query paddings. | nit: add more comments on the semantics of paddings? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.