Skip to content

Commit

Permalink
Revert "Revert main to v0.5.4" (#149) (#153)
Browse files Browse the repository at this point in the history
  • Loading branch information
waahm7 committed Feb 1, 2023
1 parent 49dec94 commit c38f4f7
Show file tree
Hide file tree
Showing 39 changed files with 1,553 additions and 177 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -170,21 +170,24 @@ extension CredentialsProvider.Source {
/// (by default ~/.aws/profile and ~/.aws/credentials)
///
/// - Parameters:
/// - bootstrap: Connection bootstrap to use for any network connections made while sourcing credentials.
/// - configFileNameOverride: (Optional) Override path to the profile config file (~/.aws/config by default)
/// - profileFileNameOverride: (Optional) Override of what profile to use to source credentials from ('default' by default)
/// - credentialsFileNameOverride: (Optional) Override path to the profile credentials file (~/.aws/credentials by default)
/// - shutdownCallback: (Optional) shutdown callback
/// - allocator: (Optional) allocator to override
/// - Returns: `CredentialsProvider`
/// - Throws: CommonRuntimeError.crtError
public static func `profile`(configFileNameOverride: String? = nil,
public static func `profile`(bootstrap: ClientBootstrap,
configFileNameOverride: String? = nil,
profileFileNameOverride: String? = nil,
credentialsFileNameOverride: String? = nil,
shutdownCallback: ShutdownCallback? = nil,
allocator: Allocator = defaultAllocator) -> Self {
Self { allocator in
let shutdownCallbackCore = ShutdownCallbackCore(shutdownCallback)
var profileOptionsC = aws_credentials_provider_profile_options()
profileOptionsC.bootstrap = bootstrap.rawValue
profileOptionsC.shutdown_options = shutdownCallbackCore.getRetainedCredentialProviderShutdownOptions()
guard let provider: UnsafeMutablePointer<aws_credentials_provider> = withByteCursorFromStrings(
configFileNameOverride,
Expand Down
16 changes: 9 additions & 7 deletions Source/AwsCommonRuntimeKit/auth/signing/Signer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ public class Signer {
/// - `Throws`: An error of type `AwsCommonRuntimeError` which will pull last error found in the CRT
/// - `Returns`: Returns a signed http request `HttpRequest`
public static func signRequest(
request: HTTPRequest,
request: HTTPRequestBase,
config: SigningConfig,
allocator: Allocator = defaultAllocator) async throws -> HTTPRequest {
allocator: Allocator = defaultAllocator) async throws -> HTTPRequestBase {

guard let signable = aws_signable_new_http_request(allocator.rawValue, request.rawValue) else {
throw CommonRunTimeError.crtError(.makeFromLastError())
Expand All @@ -41,7 +41,9 @@ public class Signer {
aws_signable_destroy(signable)
}

return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<HTTPRequest, Error>) in
return try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<
HTTPRequestBase,
Error>) in
let signRequestCore = SignRequestCore(request: request,
continuation: continuation,
shouldSignHeader: config.shouldSignHeader,
Expand Down Expand Up @@ -74,11 +76,11 @@ public class Signer {

class SignRequestCore {
let allocator: Allocator
let request: HTTPRequest
var continuation: CheckedContinuation<HTTPRequest, Error>
let request: HTTPRequestBase
var continuation: CheckedContinuation<HTTPRequestBase, Error>
let shouldSignHeader: ((String) -> Bool)?
init(request: HTTPRequest,
continuation: CheckedContinuation<HTTPRequest, Error>,
init(request: HTTPRequestBase,
continuation: CheckedContinuation<HTTPRequestBase, Error>,
shouldSignHeader: ((String) -> Bool)? = nil,
allocator: Allocator) {
self.allocator = allocator
Expand Down
2 changes: 1 addition & 1 deletion Source/AwsCommonRuntimeKit/crt/Allocator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public final class TracingAllocator: Allocator {
* - Parameter framesPerStack: How many frames to record for each allocation
* (8 as usually a good default to start with).
*/
public convenience init(tracingStacksOf allocator: Allocator, framesPerStack: Int = 16) {
public convenience init(tracingStacksOf allocator: Allocator, framesPerStack: Int = 10) {
self.init(allocator, level: .stacks, framesPerStack: framesPerStack)
}

Expand Down
42 changes: 41 additions & 1 deletion Source/AwsCommonRuntimeKit/crt/CStruct.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,47 @@ func withOptionalCStructPointer<Arg1Type: CStruct,
return withOptionalCStructPointer(arg1, arg2) { arg1Pointer, arg2Pointer in
return withOptionalCStructPointer(arg3, arg4) { arg3Pointer, arg4Pointer in
return withOptionalCStructPointer(to: arg5) { arg5Pointer in
return body(arg1Pointer, arg2Pointer, arg3Pointer, arg4Pointer, arg5Pointer)
return body(
arg1Pointer,
arg2Pointer,
arg3Pointer,
arg4Pointer,
arg5Pointer)
}
}
}
}

func withOptionalCStructPointer<Arg1Type: CStruct,
Arg2Type: CStruct,
Arg3Type: CStruct,
Arg4Type: CStruct,
Arg5Type: CStruct,
Arg6Type: CStruct,
Result>(
_ arg1: Arg1Type?,
_ arg2: Arg2Type?,
_ arg3: Arg3Type?,
_ arg4: Arg4Type?,
_ arg5: Arg5Type?,
_ arg6: Arg6Type?,
_ body: (UnsafePointer<Arg1Type.RawType>?,
UnsafePointer<Arg2Type.RawType>?,
UnsafePointer<Arg3Type.RawType>?,
UnsafePointer<Arg4Type.RawType>?,
UnsafePointer<Arg5Type.RawType>?,
UnsafePointer<Arg6Type.RawType>?) -> Result
) -> Result {
return withOptionalCStructPointer(arg1, arg2) { arg1Pointer, arg2Pointer in
return withOptionalCStructPointer(arg3, arg4) { arg3Pointer, arg4Pointer in
return withOptionalCStructPointer(arg5, arg6) { arg5Pointer, arg6Pointer in
return body(
arg1Pointer,
arg2Pointer,
arg3Pointer,
arg4Pointer,
arg5Pointer,
arg6Pointer)
}
}
}
Expand Down
16 changes: 16 additions & 0 deletions Source/AwsCommonRuntimeKit/crt/Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,25 @@ extension Data {
}
}

func withAWSByteCursorPointer<Result>(_ body: (UnsafeMutablePointer<aws_byte_cursor>) -> Result) -> Result {
let count = self.count
return self.withUnsafeBytes { rawBufferPointer -> Result in
var cursor = aws_byte_cursor_from_array(rawBufferPointer.baseAddress, count)
return withUnsafeMutablePointer(to: &cursor) {
body($0)
}
}
}

public func encodeToHexString() -> String {
map { String(format: "%02x", $0) }.joined()
}

func chunked(into size: Int) -> [Data] {
return stride(from: 0, to: count, by: size).map {
self[$0 ..< Swift.min($0 + size, count)]
}
}
}

extension aws_date_time {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ public struct EventStreamHeader {

/// value.count can not be greater than EventStreamHeader.maxValueLength for supported types.
public var value: EventStreamHeaderValue

public init(name: String, value: EventStreamHeaderValue) {
self.name = name
self.value = value
}
}

public enum EventStreamHeaderValue: Equatable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ public struct EventStreamMessage {
var payload: Data = Data()
var allocator: Allocator = defaultAllocator

public init(headers: [EventStreamHeader] = [EventStreamHeader](),
payload: Data = Data(),
allocator: Allocator = defaultAllocator) {
self.headers = headers
self.payload = payload
self.allocator = allocator
}

/// Get the binary format of this message (i.e. for sending across the wire manually)
/// - Returns: binary Data.
public func getEncoded() throws -> Data {
Expand Down
23 changes: 23 additions & 0 deletions Source/AwsCommonRuntimeKit/http/HTTP1Stream.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0.
import AwsCHttp
import Foundation

/// An HTTP1Stream represents a single HTTP/1.1 specific Http Request/Response.
public class HTTP1Stream: HTTPStream {
/// Stream keeps a reference to HttpConnection to keep it alive
private let httpConnection: HTTPClientConnection

// Called by HTTPClientConnection
init(
httpConnection: HTTPClientConnection,
options: aws_http_make_request_options,
callbackData: HTTPStreamCallbackCore) throws {
guard let rawValue = withUnsafePointer(
to: options, { aws_http_connection_make_request(httpConnection.rawValue, $0) }) else {
throw CommonRunTimeError.crtError(.makeFromLastError())
}
self.httpConnection = httpConnection
super.init(rawValue: rawValue, callbackData: callbackData)
}
}
126 changes: 126 additions & 0 deletions Source/AwsCommonRuntimeKit/http/HTTP2ClientConnection.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0.

import AwsCHttp
import AwsCIo
import Foundation

public class HTTP2ClientConnection: HTTPClientConnection {

/// Creates a new http2 stream from the `HTTPRequestOptions` given.
/// - Parameter requestOptions: An `HTTPRequestOptions` struct containing callbacks on
/// the different events from the stream
/// - Returns: An `HTTP2Stream`
override public func makeRequest(requestOptions: HTTPRequestOptions) throws -> HTTPStream {
let httpStreamCallbackCore = HTTPStreamCallbackCore(requestOptions: requestOptions)
do {
return try HTTP2Stream(httpConnection: self,
options: httpStreamCallbackCore.getRetainedHttpMakeRequestOptions(),
callbackData: httpStreamCallbackCore)
} catch {
httpStreamCallbackCore.release()
throw error
}
}

/// Send a SETTINGS frame (HTTP/2 only).
/// SETTINGS will be applied locally when settings ACK is received from peer.
/// - Parameter setting: The settings to change
public func updateSetting(setting: HTTP2Settings) async throws {
try await withCheckedThrowingContinuation({ (continuation: CheckedContinuation<(), Error>) in
let continuationCore = ContinuationCore(continuation: continuation)
setting.withCStruct { settingList in
let count = settingList.count
settingList.withUnsafeBufferPointer { pointer in
guard aws_http2_connection_change_settings(
rawValue,
pointer.baseAddress!,
count,
onChangeSettingsComplete,
continuationCore.passRetained()) == AWS_OP_SUCCESS else {
continuationCore.release()
continuation.resume(throwing: CommonRunTimeError.crtError(.makeFromLastError()))
return
}
}
}
})
}

/// Send a PING frame. Round-trip-time is calculated when PING ACK is received from peer.
/// - Parameter data: (Optional) 8 Bytes data with the PING frame. Data count must be exact 8 bytes.
/// - Returns: The round trip time in nanoseconds for the connection.
public func sendPing(data: Data = Data()) async throws -> UInt64 {
try await withCheckedThrowingContinuation({ (continuation: CheckedContinuation<UInt64, Error>) in
let continuationCore = ContinuationCore(continuation: continuation)
data.withAWSByteCursorPointer { dataPointer in
guard aws_http2_connection_ping(
rawValue,
data.isEmpty ? nil : dataPointer,
onPingComplete,
continuationCore.passRetained()) == AWS_OP_SUCCESS
else {
continuationCore.release()
continuation.resume(throwing: CommonRunTimeError.crtError(.makeFromLastError()))
return
}
}
})
}

/// Send a custom GOAWAY frame.
///
/// Note that the connection automatically attempts to send a GOAWAY during
/// shutdown (unless a GOAWAY with a valid Last-Stream-ID has already been sent).
///
/// This call can be used to gracefully warn the peer of an impending shutdown
/// (error=0, allowMoreStreams=true), or to customize the final GOAWAY
/// frame that is sent by this connection.
///
/// The other end may not receive the goaway, if the connection already closed.
///
/// - Parameters:
/// - error: The HTTP/2 error code to send.
/// - allowMoreStreams: If true, new peer-initiated streams will continue to be acknowledged and the GOAWAY's Last-Stream-ID will
/// be set to a max value. If false, new peer-initiated streams will be ignored and the GOAWAY's
/// Last-Stream-ID will be set to the latest acknowledged stream.
/// - debugData: (Optional) debug data to send. Size must not exceed 16KB.
public func sendGoAway(error: HTTP2Error, allowMoreStreams: Bool, debugData: Data = Data()) {
debugData.withAWSByteCursorPointer { dataPointer in
aws_http2_connection_send_goaway(
rawValue,
error.rawValue,
allowMoreStreams,
dataPointer)
}
}
}

private func onChangeSettingsComplete(connection: UnsafeMutablePointer<aws_http_connection>?,
errorCode: Int32,
userData: UnsafeMutableRawPointer!) {
let continuation = Unmanaged<ContinuationCore<()>>.fromOpaque(userData).takeRetainedValue().continuation

guard errorCode == AWS_OP_SUCCESS else {
continuation.resume(throwing: CommonRunTimeError.crtError(CRTError(code: errorCode)))
return
}

// SUCCESS
continuation.resume()
}

private func onPingComplete(connection: UnsafeMutablePointer<aws_http_connection>?,
roundTripTimeNs: UInt64,
errorCode: Int32,
userData: UnsafeMutableRawPointer!) {
let continuation = Unmanaged<ContinuationCore<UInt64>>.fromOpaque(userData).takeRetainedValue().continuation

guard errorCode == AWS_OP_SUCCESS else {
continuation.resume(throwing: CommonRunTimeError.crtError(CRTError(code: errorCode)))
return
}

// SUCCESS
continuation.resume(returning: roundTripTimeNs)
}
19 changes: 19 additions & 0 deletions Source/AwsCommonRuntimeKit/http/HTTP2Error.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0.

/// Error codes that may be present in HTTP/2 RST_STREAM and GOAWAY frames (RFC-7540 7).
public enum HTTP2Error: UInt32 {
case protocolError = 1
case internalError = 2
case flowControlError = 3
case settingsTimeout = 4
case streamClosed = 5
case frameSizeError = 6
case refusedStream = 7
case cancel = 8
case compressionError = 9
case connectError = 10
case enhanceYourCalm = 11
case inadequateSecurity = 12
case HTTP_1_1_Required = 13
}
Loading

0 comments on commit c38f4f7

Please sign in to comment.