aws-sdk-net: TransferUtil.UploadAsync does not work with unseekable streams or zero length streams

Expected Behavior

Things should behave, I should be able to pass through a stream that has no length / zero length and at least get decent exceptions, preferably it should be handled for the user. Any other scenario requires us to buffer the full upload in a stream that can do it all (seeking, accurate report of length etc) before we can give the stream to the s3 sdk, not nice for using it in a webserver and feels like we have to babysit the aws sdk so it behaves…

Current Behavior

Request terminates with NotSupported exception as S3 tries to access the length somewhere without catching the exception. The stacktrace is posted under Stacktrace for length NotSupported exception:

Steps to Reproduce (for bugs)

Create aspnet project, add a post endpoint for a simple upload transfer (just binary, no form data),

What also helps, as a non seekable stream is not always practical, is to add this line, this is a helper that spools the request body to disk once it reaches a threshold

HttpContext.Request.EnableRewind(3145728); // 3 MB max in mem before spooling to disk

Problems is that with that method the S3 client hangs and finally responds/times-out with the exception seen at the bottom Stacktrace for length 0 case:

Your Environment

  • AWSSDK.Core version used: 3.3.1.2
  • Targeted .NET platform: netcoreapp 1.1
  • Output of dotnet --info:
.NET Command Line Tools (1.0.4)

Product Information:
 Version:            1.0.4
 Commit SHA-1 hash:  af1e6684fd

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.12
 OS Platform: Darwin
 RID:         osx.10.12-x64
 Base Path:   /usr/local/share/dotnet/sdk/1.0.4

Context:

Most streams don’t allow you to set length, and both of these streams can’t do length tracking in a reliable way as they sometimes don’t know it yet (think chunked requests)

these streams are no exception to that, that is why you probably put quite a few consumers of your sdk in a tough spot by trying to read out a ContentLength for your own S3 request from the stream. That should be re-evaluated, either by allowing us to pass in a ContentLength ourselves somewhere or doing something like a chunked upload so you don’t need to set a Content-Length header and thus have no need for a ContentLength from the stream.

Also apparently something is completely blowing up if the stream length that was passed in is 0 as I could easily achieve, that should be something to check out irrespective of your decision or the outcome of this issue.

Stacktrace for length NotSupported exception:

      An unhandled exception has occurred: Specified method is not supported.
System.NotSupportedException: Specified method is not supported.
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameRequestStream.get_Length()
   at Amazon.S3.Transfer.TransferUtilityUploadRequest.get_ContentLength()
   at Amazon.S3.Transfer.TransferUtility.IsMultipartUpload(TransferUtilityUploadRequest request)
   at Amazon.S3.Transfer.TransferUtility.GetUploadCommand(TransferUtilityUploadRequest request, SemaphoreSlim asyncThrottler)
   at Amazon.S3.Transfer.TransferUtility.UploadAsync(Stream stream, String bucketName, String key, CancellationToken cancellationToken)
... our code ...

Stacktrace for length 0 case (it took many seconds before it responds with this error):

      An unhandled exception has occurred: The provided 'x-amz-content-sha256' header does not match what was computed.
Amazon.S3.AmazonS3Exception: The provided 'x-amz-content-sha256' header does not match what was computed. ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown.
   at Amazon.Runtime.HttpWebRequestMessage.<GetResponseAsync>d__20.MoveNext() in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\HttpHandler\_mobile\HttpRequestMessageFactory.cs:line 404
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.HttpHandler`1.<InvokeAsync>d__9`1.MoveNext() in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\HttpHandler\HttpHandler.cs:line 175
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.RedirectHandler.<InvokeAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.Unmarshaller.<InvokeAsync>d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.S3.Internal.AmazonS3ResponseHandler.<InvokeAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.ErrorHandler.<InvokeAsync>d__5`1.MoveNext()
   --- End of inner exception stack trace ---
   at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\ErrorHandler\HttpErrorResponseExceptionHandler.cs:line 60
   at Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext executionContext, Exception exception) in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\ErrorHandler\ErrorHandler.cs:line 212
   at Amazon.Runtime.Internal.ErrorHandler.<InvokeAsync>d__5`1.MoveNext() in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\ErrorHandler\ErrorHandler.cs:line 104
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Amazon.Runtime.Internal.RetryHandler.<InvokeAsync>d__10`1.MoveNext() in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\RetryHandler\RetryHandler.cs:line 131
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.S3.Internal.AmazonS3ExceptionHandler.<InvokeAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.ErrorCallbackHandler.<InvokeAsync>d__5`1.MoveNext() in E:\JenkinsWorkspaces\v3-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\Handlers\ErrorCallbackHandler.cs:line 58
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.Runtime.Internal.MetricsHandler.<InvokeAsync>d__1`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Amazon.S3.Transfer.Internal.SimpleUploadCommand.<ExecuteAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
... our code ...

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 11
  • Comments: 36 (8 by maintainers)

Most upvoted comments

I hope this issue is still in the backlog, and that there are still intentions of resolving it. We hit the same problem.

What’s the status here? it’s been another 10 months. This is an absolute must have.

S3 is the service to store large files, right?

Why does this API not allow a simple unseekable stream? I want to pass incoming request body (of my API) as a stream directly into S3.

Alternatively, I wouldn’t mind if you exposed an API where you open a writeable stream for me that I copy data into. This would be even cleaner. Maybe like this:

            using var stream = await s3.OpenPutObjectAsync(new OpenPutObjectRequest
            {
                BucketName = bucketName,
                Key = key,
                ContentType = contentType,
                ContentLength = contentLength,
            });

           // Let me write whatever I want.

At this point in time you’re forcing me to to either:

  • stream to FS, then upload to S3 or
  • write a stream wrapper that makes this awkward API happy.

Because of the same reason 😉 kestrel (.net core web server) for instance doesn’t do buffering for performance reasons. And the buffering stream that I linked to also doesn’t report it due to unreliable internals (it only starts buffering after the first read for instance) It is just something that is hard to rely on, however we always know the file size or content length from our incoming request to pass a valid content-length to the sdk.

We just don’t always have control over the type of input streams. If you think it shouldn’t be in the sdk we’ll just have to pass some wrapper stream that takes a stream and a length, an unnecessary allocation but so be it.

Besides all this, a content-length != a stream length, these two could have completely separate meanings and should be able to be set separately from each other.

The problem is not the fact that we don’t know the Content-Length but that the sdk assumes the stream actually has and knows that length. This assumption is wrong and the behavior unidiomatic. There should be a way to give a content length to the sdk as an argument separate from the stream. Currently as far as I could tell most of this is internal and just pokes the stream for its length.

We suffer the same problem - particularly if we are dealing with encrypted or compressed streams. We can’t read the size from the stream, or seek. We have a kinda workaround which is if we use the simple PUT object for these types AND are told up front how big the file is we can support them - but obviously the PUT request has a max size limit of 5GB which isn’t ideal. A solution for multi-part uploads would help us significantly.

Note, we are also behind an abstraction, and S3 is only ONE of the concrete implementations.

BTW our use case is a follows:

  1. It is ASP.NET Core API
  2. API accepts a request stream. Images, media files (sometimes big)
  3. We do some internal logic with data from headers/cookies and figure out the target bucket name and key. We don’t read the body and avoid full buffering.
  4. After that we forward the request body to S3. And would be happy if S3 SDK could do the upload also without full buffering.

Has there been any traction on this? Its been almost 2 years.

I’ve added this as a feature request in our backlog. We’ll report back once we have more news regarding this work. I appreciate the the detailed report, repro, and the discussion.

@jecc1982 @Nijasbijilyrawther @NinoFloris @dave-yotta @jpestanota @AlainH @tapmantwo @Svisstack @tburnett80 @TommyN @peswallstreet @mrogunlana @p-selivanov @aron-truvian

This feature has been released in S3 Version 3.7.202. I’m going to leave this issue open for a couple more days just in case there are any issues.

I’m looking forward to seeing this implemented

We gave up waiting and now use Minio https://github.com/minio/minio which supports not only specifying a length separately in the upload call, but also supports length -1 meaning “stream it out, I don’t know how big it’ll be”.

Aspnet or IIS willl protect you with a maximum body size limit for gigantic uploads anyway. This is perfect for APIs that want to proxy uploads after validation and upload destination is retrieved from config.

This was queued up as a Priority 2 item internally so hasn’t gotten much attention, but this feature request has been implemented and will go out in our next manual release. Appreciate the patience and will post here when the feature is out.

I dunno what the last two comments are related to, but the issue reported here is related to non-seekable input streams.

FYI, just in case it helps, I got a pointer to this tool and examples and they seem promising: https://github.com/mlhpdx/s3-upload-stream

Same problem but in my case I need to calculate the SHA512 on the fly so I need to wrap the FileStream into CryptoStream which is not seekable of course (as it calculating the SHA512 in the fly)

I’m running into this very same problem, and it’s disappointing that Amazon hasn’t given a solution for this yet.

My use case is that I’m taking zip files from one S3 bucket, and decompressing them into another S3 bucket via a lambda function. However, this won’t work, since the stream(s) from the zip archive are not seekable.

Here you go https://github.com/NinoFloris/awsrepro675

EDIT: Just tested the FileBufferingReadStream and a non seekable stream with PutObjectRequest as well, same exact errors