Skip to content

Commit

Permalink
Add timeout configuration if the connection does not receive a respon…
Browse files Browse the repository at this point in the history
…se (#101)
  • Loading branch information
madsodgaard committed Feb 1, 2021
1 parent ce8213a commit 03e83e2
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 14 deletions.
6 changes: 5 additions & 1 deletion Sources/APNSwift/APNSwiftConfiguration.swift
Expand Up @@ -168,6 +168,8 @@ public struct APNSwiftConfiguration {
public var topic: String
public var environment: Environment
internal var logger: Logger?
/// Optional timeout time if the connection does not receive a response.
public var timeout: TimeAmount? = nil

public var url: URL {
switch environment {
Expand Down Expand Up @@ -197,7 +199,8 @@ public struct APNSwiftConfiguration {
authenticationMethod: AuthenticationMethod,
topic: String,
environment: APNSwiftConfiguration.Environment,
logger: Logger? = nil
logger: Logger? = nil,
timeout: TimeAmount? = nil
) {
self.topic = topic
self.authenticationMethod = authenticationMethod
Expand All @@ -206,6 +209,7 @@ public struct APNSwiftConfiguration {
logger[metadataKey: "origin"] = "APNSwift"
self.logger = logger
}
self.timeout = timeout
}
}

Expand Down
45 changes: 34 additions & 11 deletions Sources/APNSwift/APNSwiftConnection.swift
Expand Up @@ -200,20 +200,43 @@ public final class APNSwiftConnection: APNSwiftClient {
request: payload,
responsePromise: responsePromise
)

streamPromise.futureResult.cascadeFailure(to: responsePromise)
return streamPromise.futureResult.flatMap { stream in
logger?.info("Send - sending")
return stream.writeAndFlush(context).flatMapErrorThrowing { error in
logger?.info("Send - sending - failed - \(error)")
responsePromise.fail(error)
throw error

let timeoutPromise = self.channel.eventLoop.makePromise(of: Void.self)
responsePromise.futureResult.cascade(to: timeoutPromise)
timeoutPromise.futureResult.cascadeFailure(to: responsePromise)
var timeoutTask: Scheduled<Any>? = nil
let timeoutTime = configuration.timeout

return streamPromise.futureResult
.flatMap { stream in
logger?.info("Send - sending")
if let timeoutTime = timeoutTime {
timeoutTask = stream.eventLoop.scheduleTask(in: timeoutTime) {
logger?.warning("Send - sending - failed - No response was received within the timeout.")
return timeoutPromise.fail(NoResponseWithinTimeoutError())
}
} else {
timeoutPromise.succeed(())
}

return stream.writeAndFlush(context).flatMapErrorThrowing { error in
logger?.info("Send - sending - failed - \(error)")
responsePromise.fail(error)
throw error
}
}
.flatMap {
responsePromise
.futureResult
.and(timeoutPromise.futureResult)
.map { _ in () }
}
.always { _ in
timeoutTask?.cancel()
}
}.flatMap {
responsePromise.futureResult
}
}

var onClose: EventLoopFuture<Void> {
logger?.debug("Connection - closed")
return self.channel.closeFuture
Expand Down
2 changes: 2 additions & 0 deletions Sources/APNSwift/APNSwiftErrors.swift
Expand Up @@ -18,6 +18,8 @@ import Foundation
public struct NoResponseReceivedBeforeConnectionEnded: Error, Equatable {}
/// An error where a request was made to Apple, but the response body buffer was nil
public struct NoResponseBodyFromApple: Error, Equatable {}
/// An error where no the connection received no response within the timeout period
public struct NoResponseWithinTimeoutError: Error, Equatable {}

public struct APNSwiftError: Equatable {
public enum ResponseError: Error, Equatable {
Expand Down
4 changes: 3 additions & 1 deletion Tests/APNSwiftTests/APNSwiftConfigurationTests.swift
Expand Up @@ -27,7 +27,8 @@ class APNSwiftConfigurationTests: XCTestCase {
teamIdentifier: "MY_TEAM_ID"
),
topic: "MY_TOPIC",
environment: environment
environment: environment,
timeout: .seconds(5)
)

switch environment {
Expand All @@ -46,6 +47,7 @@ class APNSwiftConfigurationTests: XCTestCase {
XCTFail("expected JWT auth method")
}
XCTAssertEqual(apnsConfiguration.topic, "MY_TOPIC")
XCTAssertEqual(apnsConfiguration.timeout, .seconds(5))

}

Expand Down
1 change: 0 additions & 1 deletion Tests/APNSwiftTests/APNSwiftRequestTests.swift
Expand Up @@ -304,7 +304,6 @@ final class APNSwiftRequestTests: XCTestCase {
// Should have changed
XCTAssertFalse(newCachedToken == bearerToken.currentBearerToken)
bearerToken.cancel()

}

let validAuthKey = """
Expand Down

0 comments on commit 03e83e2

Please sign in to comment.