Skip to content

Commit

Permalink
Fix stack overflows generated when streaming requests (#538)
Browse files Browse the repository at this point in the history
  • Loading branch information
adam-fowler authored Mar 7, 2023
1 parent cf1c872 commit 787be99
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
4 changes: 3 additions & 1 deletion Sources/SotoCore/HTTP/S3StreamReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,9 @@ final class S3ChunkedStreamReader: StreamReader {
// if there are still bytes left to read then call _fillBuffer again, otherwise succeed with the
// contents of the working buffer
if self.bytesLeftToRead > 0 {
_fillBuffer()
eventLoop.execute {
_fillBuffer()
}
} else {
promise.succeed(self.workingBuffer)
}
Expand Down
12 changes: 10 additions & 2 deletions Sources/SotoCore/HTTP/StreamWriter+write.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,26 @@ extension AsyncHTTPClient.HTTPClient.Body.StreamWriter {
// should never reach here as HTTPClient throws HTTPClientError.bodyLengthMismatch
promise.fail(AWSClient.ClientError.tooMuchData)
} else {
_write(newAmountLeft)
_write(newAmountLeft, on: eventLoop)
}
} else {
_write(nil)
}
return promise.futureResult
}.cascadeFailure(to: promise)
} else {
_write(newAmountLeft)
_write(newAmountLeft, on: eventLoop)
}
}.cascadeFailure(to: promise)
}

// execute write in eventLoop. Use to avoid stack overflows
func _write(_ amountLeft: Int?, on eventLoop: EventLoop) {
eventLoop.execute {
_write(amountLeft)
}
}

_write(reader.contentSize)

return promise.futureResult
Expand Down
14 changes: 14 additions & 0 deletions Tests/SotoCoreTests/AWSClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,20 @@ class AWSClientTests: XCTestCase {
XCTAssertNoThrow(try self.testRequestStreaming(config: config, client: client, server: awsServer, bufferSize: 65552, blockSize: 65552))
}

func testRequestStreamingAvoidStackOverflow() {
let awsServer = AWSTestServer(serviceProtocol: .json)
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
let config = createServiceConfig(service: "s3", endpoint: awsServer.address)
let client = createAWSClient(credentialProvider: .static(accessKeyId: "foo", secretAccessKey: "bar"), httpClientProvider: .shared(httpClient))
defer {
XCTAssertNoThrow(try client.syncShutdown())
XCTAssertNoThrow(try awsServer.stop())
XCTAssertNoThrow(try httpClient.syncShutdown())
}

XCTAssertNoThrow(try self.testRequestStreaming(config: config, client: client, server: awsServer, bufferSize: 16 * 1024, blockSize: 8))
}

func testRequestStreamingWithPayload(_ payload: AWSPayload) throws {
struct Input: AWSEncodableShape & AWSShapeWithPayload {
static var _payloadPath: String = "payload"
Expand Down

0 comments on commit 787be99

Please sign in to comment.