Skip to content

Commit

Permalink
Fixed issue envoy/Ambassador#18.
Browse files Browse the repository at this point in the history
Connection is left open until the request has been completely read.
  • Loading branch information
tranquvis committed Jul 7, 2017
1 parent f68f06f commit 68272ef
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions Sources/HTTPConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ public final class HTTPConnection {
enum RequestState {
case parsingHeader
case readingBody
case finished
}

enum ResponseState {
case sendingHeader
case sendingBody
case finished
}

public let logger = DefaultLogger()
Expand Down Expand Up @@ -81,6 +83,8 @@ public final class HTTPConnection {
handleHeaderData(data)
case .readingBody:
handleBodyData(data)
case .finished:
return
}
}

Expand All @@ -92,10 +96,12 @@ public final class HTTPConnection {
headerElements += headerParser.feed(data)
// we only handle when there are elements in header parser
guard let lastElement = headerElements.last else {
finishRequest()
return
}
// we only handle the it when we get the end of header
guard case .end = lastElement else {
finishRequest()
return
}

Expand Down Expand Up @@ -196,6 +202,7 @@ public final class HTTPConnection {
if let length = contentLength, readDataLength >= length {
handler(Data())
inputHandler = nil
finishRequest()
}
}

Expand Down Expand Up @@ -232,9 +239,7 @@ public final class HTTPConnection {
return
}
guard data.count > 0 else {
// TODO: support keep-alive connection here?
logger.info("Finish response")
transport.close()
finishResponse()
return
}
transport.write(data: data)
Expand All @@ -252,6 +257,28 @@ public final class HTTPConnection {
callback()
}
}

private func finishRequest() {
logger.info("Finish request")
requestState = .finished
closeIfAllFinished()
}

private func finishResponse() {
logger.info("Finish response")
responseState = .finished
closeIfAllFinished()
}

private func closeIfAllFinished() {
// TODO: support keep-alive connection here?
guard requestState == .finished, responseState == .finished else {
return
}

logger.info("Finish all")
close()
}
}

extension HTTPConnection: Equatable {
Expand Down

0 comments on commit 68272ef

Please sign in to comment.