Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -286,9 +286,17 @@ abstract class AbstractCurlBackend[F[_]](_monad: MonadError[F], verbose: Boolean
curl.option(HeaderData, spaces.headersResp)
curl.option(Url, request.uri.toString)
setMethod(curl, request.method)
setRequestBody(curl, request.body, request.method).flatMap { _ =>
// the try block below frees the native resources only once the transfer starts, so earlier failures free them here
cleanupOnError(setRequestBody(curl, request.body, request.method)) {
curl.cleanup()
freeSpaces(spaces)
}.flatMap { _ =>
val multi = CurlApi.multiInit
liftM(multi.addHandle(curl)).flatMap { _ =>
cleanupOnError(liftM(multi.addHandle(curl))) {
multi.cleanup()
curl.cleanup()
freeSpaces(spaces)
}.flatMap { _ =>
// Track whether native resources (multi, curl, spaces) have already been cleaned up —
// either by transferring ownership to CurlMultiInputStream or by explicit freeing in a fallback path.
// When true, the outer catch block must NOT attempt to free them (would double-free).
Expand Down Expand Up @@ -518,6 +526,13 @@ abstract class AbstractCurlBackend[F[_]](_monad: MonadError[F], verbose: Boolean
buffer.toByteArray
}

/** Runs `cleanup` if `fa` fails, including when evaluating `fa` throws. */
private def cleanupOnError[A](fa: => F[A])(cleanup: => Unit): F[A] =
monad.handleError(monad.suspend(fa)) { case e =>
cleanup
monad.error(e)
}

private def liftM(code: CurlMCode.CurlMCode): F[CurlMCode.CurlMCode] =
code match {
case CurlMCode.Ok => monad.unit(code)
Expand Down
Loading