diff --git a/packages/Storage/Storage.Tests/AccessToken/StorageAccessTokenTests.cs b/packages/Storage/Storage.Tests/AccessToken/StorageAccessTokenTests.cs index 0c9715f04..d24eb3728 100644 --- a/packages/Storage/Storage.Tests/AccessToken/StorageAccessTokenTests.cs +++ b/packages/Storage/Storage.Tests/AccessToken/StorageAccessTokenTests.cs @@ -255,6 +255,14 @@ public void Download_ShouldComplete_GivenLocalFileAndCallerBlockingAndTokenRetri public void Download_ShouldComplete_GivenLocalFileAndCallerBlockingAndTokenRetrievedAtOnce() => this.CompletesWhileCallerBlocksDownloadingToFile(RetrievedAtOnce); + [TestMethod] + public void DownloadStreamAsync_ShouldComplete_GivenCallerBlockingAndTokenRetrievedLater() => + this.CompletesWhileCallerBlocks(() => this.client.From(Bucket).DownloadStreamAsync("a.bin"), RetrievedLater); + + [TestMethod] + public void DownloadStreamAsync_ShouldComplete_GivenCallerBlockingAndTokenRetrievedAtOnce() => + this.CompletesWhileCallerBlocks(() => this.client.From(Bucket).DownloadStreamAsync("a.bin"), RetrievedAtOnce); + private void CompletesWhileCallerBlocksDownloadingToFile(Func> retrieval) { var localPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.bin"); diff --git a/packages/Storage/Storage.Tests/FileBuckets/DownloadStream/DownloadStreamContractTests.cs b/packages/Storage/Storage.Tests/FileBuckets/DownloadStream/DownloadStreamContractTests.cs new file mode 100644 index 000000000..29caf734a --- /dev/null +++ b/packages/Storage/Storage.Tests/FileBuckets/DownloadStream/DownloadStreamContractTests.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using FluentAssertions.Execution; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Storage; +using Supabase.Storage.Exceptions; +using WireMock.RequestBuilders; +using WireMock.ResponseBuilders; +using WireMock.Server; + +namespace Storage.Tests.FileBuckets.DownloadStream; + +/// +/// Contract tests for DownloadStreamAsync and the FileDownload it returns. +/// +[TestClass] +[TestCategory("Contract")] +public class DownloadStreamContractTests +{ + private const string Bucket = "videos"; + private const string ObjectPath = "movies/trailer.mp4"; + private const string ObjectRoute = "/storage/v1/object/videos/movies/trailer.mp4"; + private const string Authorization = "Bearer service-role-key"; + private const string Body = "streamed-body"; + private const string ETag = "\"version-1\""; + private const string ContentRange = "bytes 0-12/100"; + private static readonly byte[] Payload = Encoding.UTF8.GetBytes(Body); + + private WireMockServer server = null!; + private Client client = null!; + private string directory = null!; + + [TestInitialize] + public void TestInitialize() + { + this.server = WireMockServer.Start(); + this.client = new Client($"{this.server.Url}/storage/v1", new Dictionary { { "Authorization", Authorization } }); + this.directory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())).FullName; + } + + [TestCleanup] + public void TestCleanup() + { + this.server.Stop(); + Directory.Delete(this.directory, true); + } + + [TestMethod] + public async Task DownloadStreamAsync_ShouldExposeTheStatusHeadersAndBody_GivenPartialContent() + { + this.server.Given(Request.Create().WithPath(ObjectRoute).WithHeader("Authorization", Authorization).UsingGet()) + .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.PartialContent) + .WithHeader("ETag", ETag).WithHeader("Content-Range", ContentRange).WithBody(Payload)); + using var download = await this.client.From(Bucket).DownloadStreamAsync(ObjectPath); + using var reader = new StreamReader(download.Content); + using (new AssertionScope()) + { + download.StatusCode.Should().Be(HttpStatusCode.PartialContent, "206 is a success like any other 2xx status"); + download.Headers.ETag!.Tag.Should().Be(ETag); + download.ContentHeaders.ContentRange!.ToString().Should().Be(ContentRange); + (await reader.ReadToEndAsync()).Should().Be(Body); + } + } + + [TestMethod] + public async Task DownloadStreamAsync_ShouldThrowTheEnvelopeError_GivenAnErrorEnvelope() + { + this.server.Given(Request.Create().WithPath(ObjectRoute).UsingGet()) + .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.BadRequest).WithHeader("Content-Type", "application/json") + .WithBody("""{"statusCode":"404","error":"not_found","message":"Object not found","code":"NoSuchKey"}""")); + var thrown = (await FluentActions.Awaiting(() => this.client.From(Bucket).DownloadStreamAsync(ObjectPath)) + .Should().ThrowAsync("the error is raised by the call, before a stream is returned")).Which; + using (new AssertionScope()) + { + thrown.StatusCode.Should().Be((int) HttpStatusCode.NotFound, "the statusCode the service puts in its body wins over the transport status"); + thrown.Code.Should().Be("NoSuchKey"); + thrown.Message.Should().Be("Object not found"); + } + } + + [TestMethod] + public async Task DownloadStreamAsync_ShouldRequestTheRenderRoute_GivenTransformOptions() + { + this.server.Given(Request.Create().WithPath("/storage/v1/render/image/authenticated/videos/movies/trailer.mp4").WithParam("width", "100").UsingGet()) + .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.OK).WithBody(Payload)); + using var download = await this.client.From(Bucket).DownloadStreamAsync(ObjectPath, new TransformOptions { Width = 100 }); + (await download.ReadAsBytesAsync()).Should().Equal(Payload); + } + + [TestMethod] + public async Task DownloadStreamAsync_ShouldNotSendTheRequest_GivenACancelledToken() + { + await FluentActions.Awaiting(() => this.client.From(Bucket).DownloadStreamAsync(ObjectPath, cancellationToken: new CancellationToken(true))) + .Should().ThrowAsync(); + this.server.LogEntries.Should().BeEmpty("a cancelled call never reaches the service"); + } + + [TestMethod] + public async Task ReadAsBytesAsync_ShouldReturnTheBody_GivenACapOfExactlyItsSize() + { + this.RespondWithPayload(); + using var download = await this.client.From(Bucket).DownloadStreamAsync(ObjectPath); + (await download.ReadAsBytesAsync(Payload.Length)).Should().Equal(Payload); + } + + [TestMethod] + public async Task SaveAsync_ShouldCreateTheFile_GivenNoFileAtThePath() + { + var destination = Path.Combine(this.directory, "trailer.mp4"); + this.RespondWithPayload(); + using var download = await this.client.From(Bucket).DownloadStreamAsync(ObjectPath); + await download.SaveAsync(destination); + this.FilesInDirectory().Should().Equal(new Dictionary { [destination] = Body }); + } + + [TestMethod] + public async Task SaveAsync_ShouldReplaceTheFile_GivenAFileAtThePath() + { + var destination = Path.Combine(this.directory, "trailer.mp4"); + await File.WriteAllTextAsync(destination, "previous-body"); + this.RespondWithPayload(); + using var download = await this.client.From(Bucket).DownloadStreamAsync(ObjectPath); + await download.SaveAsync(destination); + this.FilesInDirectory().Should().Equal(new Dictionary { [destination] = Body }, "no temporary file is left"); + } + + private void RespondWithPayload() => + this.server.Given(Request.Create().WithPath(ObjectRoute).UsingGet()) + .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.OK).WithBody(Payload)); + + private Dictionary FilesInDirectory() => + Directory.GetFiles(this.directory).ToDictionary(file => file, File.ReadAllText); +} diff --git a/packages/Storage/Storage.Tests/FileBuckets/DownloadStream/DownloadStreamUnfinishedBodyTests.cs b/packages/Storage/Storage.Tests/FileBuckets/DownloadStream/DownloadStreamUnfinishedBodyTests.cs new file mode 100644 index 000000000..7a9272df2 --- /dev/null +++ b/packages/Storage/Storage.Tests/FileBuckets/DownloadStream/DownloadStreamUnfinishedBodyTests.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using FluentAssertions.Execution; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Storage; +using Supabase.Storage.Exceptions; +using Supabase.Storage.FileBuckets.DownloadStream; +using Supabase.TestSupport; + +namespace Storage.Tests.FileBuckets.DownloadStream; + +/// +/// Contract tests for a download whose body is cut short. +/// +[TestClass] +[TestCategory("Contract")] +public class DownloadStreamUnfinishedBodyTests +{ + private const string Bucket = "videos"; + private const string ObjectPath = "movies/trailer.mp4"; + private const long DeclaredLength = 100; + private static readonly string Head = $"HTTP/1.1 200 OK\r\nContent-Length: {DeclaredLength}\r\n\r\n"; + private const string PartialBody = "hello"; + private const long Cap = 4; + private const string PreviousBody = "previous-body"; + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + + private TcpListener listener = null!; + private Client client = null!; + private TcpClient connection = null!; + private NetworkStream wire = null!; + private string directory = null!; + + [TestInitialize] + public void TestInitialize() + { + this.listener = new TcpListener(IPAddress.Loopback, 0); + this.listener.Start(); + var port = ((IPEndPoint) this.listener.LocalEndpoint).Port; + this.client = new Client($"http://127.0.0.1:{port}/storage/v1", new Dictionary { { "Authorization", "Bearer service-role-key" } }); + this.directory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())).FullName; + } + + [TestCleanup] + public void TestCleanup() + { + this.connection?.Dispose(); + this.listener.Stop(); + Directory.Delete(this.directory, true); + } + + [TestMethod] + public async Task DownloadStreamAsync_ShouldReturn_GivenOnlyTheHeadHasArrived() + { + using var download = await this.DownloadAfterSendingAsync(Head); + download.ContentHeaders.ContentLength.Should().Be(DeclaredLength, "the call returns with the head and reads no byte of the body"); + } + + [TestMethod] + public async Task Content_ShouldThrowHttpRequestException_GivenTheConnectionDrops() + { + using var download = await this.DownloadAfterSendingAsync(Head + PartialBody); + using var reader = new StreamReader(download.Content); + this.connection.Close(); + FluentActions.Invoking(() => reader.ReadToEnd()).Should().Throw( + "a dropped connection is a network error"); + } + + [TestMethod] + public async Task ReadAsBytesAsync_ShouldThrow_GivenMoreBytesThanTheCap() + { + using var download = await this.DownloadAfterSendingAsync(Head + PartialBody); + var thrown = await FluentActions.Awaiting(() => download.ReadAsBytesAsync(Cap)).Should().ThrowAsync(); + using (new AssertionScope()) + { + thrown.WithMessage($"*{Cap} bytes*"); + (await this.IsClosedAsync()).Should().BeTrue("the SDK stops reading and closes the connection once the cap is passed"); + } + } + + [TestMethod] + public async Task SaveAsync_ShouldLeaveTheFileAsItWas_GivenTheConnectionDrops() + { + var destination = await this.ExistingFileAsync(); + using var download = await this.DownloadAfterSendingAsync(Head + PartialBody); + this.connection.Close(); + await FluentActions.Awaiting(() => download.SaveAsync(destination)).Should().ThrowAsync(); + this.FilesInDirectory().Should().Equal(new Dictionary { [destination] = PreviousBody }, + "the destination never holds a partial body and the temporary file is deleted"); + } + + [TestMethod] + public async Task SaveAsync_ShouldCloseTheConnection_GivenCancellation() + { + using var download = await this.DownloadAfterSendingAsync(Head + PartialBody); + using var cancellation = new CancellationTokenSource(); + var save = download.SaveAsync(Path.Combine(this.directory, "trailer.mp4"), cancellation.Token); + cancellation.Cancel(); + await FluentActions.Awaiting(() => save).Should().ThrowAsync(); + (await this.IsClosedAsync()).Should().BeTrue("cancelling the read closes the connection"); + } + + [TestMethod] + public async Task ReadAsBytesAsync_ShouldComplete_GivenACallerBlockingOnIt() + { + using var download = await this.DownloadAfterSendingAsync(Head); + BlockingCaller.Completes(() => this.AfterSendingTheBody(download.ReadAsBytesAsync())) + .Should().BeTrue("the SDK never resumes on the caller's synchronization context"); + } + + [TestMethod] + public async Task SaveAsync_ShouldComplete_GivenACallerBlockingOnIt() + { + using var download = await this.DownloadAfterSendingAsync(Head); + BlockingCaller.Completes(() => this.AfterSendingTheBody(download.SaveAsync(Path.Combine(this.directory, "trailer.mp4")))) + .Should().BeTrue("the SDK never resumes on the caller's synchronization context"); + } + + private Task AfterSendingTheBody(Task reading) + { + this.wire.Write(new byte[DeclaredLength]); + return reading; + } + + private async Task DownloadAfterSendingAsync(string response) + { + var download = this.client.From(Bucket).DownloadStreamAsync(ObjectPath); + this.connection = await this.listener.AcceptTcpClientAsync(); + this.wire = this.connection.GetStream(); + await this.SkipRequestHeadAsync(); + await this.wire.WriteAsync(Encoding.ASCII.GetBytes(response)); + return await download.WaitAsync(Timeout); + } + + private async Task SkipRequestHeadAsync() + { + using var reader = new StreamReader(this.wire, leaveOpen: true); + var line = await reader.ReadLineAsync(); + while (!string.IsNullOrEmpty(line)) + line = await reader.ReadLineAsync(); + } + + private async Task ExistingFileAsync() + { + var destination = Path.Combine(this.directory, "trailer.mp4"); + await File.WriteAllTextAsync(destination, PreviousBody); + return destination; + } + + private Dictionary FilesInDirectory() => + Directory.GetFiles(this.directory).ToDictionary(file => file, File.ReadAllText); + + private async Task IsClosedAsync() + { + try + { + return await this.wire.ReadAsync(new byte[1]).AsTask().WaitAsync(Timeout) == 0; + } + catch (IOException) + { + return true; + } + } +} diff --git a/packages/Storage/Storage.Tests/FileBuckets/DownloadStream/FileStreamDownloadTests.cs b/packages/Storage/Storage.Tests/FileBuckets/DownloadStream/FileStreamDownloadTests.cs new file mode 100644 index 000000000..2af021d3e --- /dev/null +++ b/packages/Storage/Storage.Tests/FileBuckets/DownloadStream/FileStreamDownloadTests.cs @@ -0,0 +1,37 @@ +using System; +using System.Text; +using System.Threading.Tasks; +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Storage.Exceptions; + +namespace Storage.Tests.FileBuckets.DownloadStream; + +/// +/// End-to-end tests for DownloadStreamAsync against the local stack, on a uniquely named private bucket +/// that tears down. +/// +[TestClass] +[TestCategory("E2E")] +public class FileStreamDownloadTests : StorageE2EFixture +{ + [TestMethod] + public async Task DownloadStreamAsync_ShouldStreamTheUploadedBytes() + { + var bucket = this.Storage.From(await this.NewBucket()); + var name = $"{Guid.NewGuid()}.txt"; + var uploaded = Encoding.UTF8.GetBytes("streamed body"); + await bucket.Upload(uploaded, name); + using var download = await bucket.DownloadStreamAsync(name); + (await download.ReadAsBytesAsync()).Should().Equal(uploaded); + } + + [TestMethod] + public async Task DownloadStreamAsync_ShouldThrowNotFound_GivenAMissingObject() + { + var bucket = this.Storage.From(await this.NewBucket()); + (await FluentActions.Awaiting(() => bucket.DownloadStreamAsync($"{Guid.NewGuid()}.txt")) + .Should().ThrowAsync()) + .Which.Reason.Should().Be(FailureHint.Reason.NotFound); + } +} diff --git a/packages/Storage/Storage.Tests/Observability/ObservabilityContractTests.cs b/packages/Storage/Storage.Tests/Observability/ObservabilityContractTests.cs index 432f08330..e84eafffe 100644 --- a/packages/Storage/Storage.Tests/Observability/ObservabilityContractTests.cs +++ b/packages/Storage/Storage.Tests/Observability/ObservabilityContractTests.cs @@ -146,6 +146,32 @@ public async Task Download_ShouldCarryTheTransferAttributes() }, "a transfer is a whole upload or download rather than one HTTP request, so it keeps its own metrics and attributes"); } + [TestMethod] + public async Task DownloadStream_ShouldRecordTheTransferWithoutASize() + { + this.server.Given(Request.Create().WithPath($"/storage/v1/object/{Bucket}/file.txt").UsingGet()) + .RespondWith(Response.Create().WithStatusCode(200).WithBody("payload")); + using var download = await this.client.From(Bucket).DownloadStreamAsync("file.txt"); + using (new AssertionScope()) + { + var span = this.SingleSpan($"GET /storage/v1/object/{Bucket}/file.txt"); + span.GetTagItem("storage.transfer.direction").Should().Be("download"); + span.GetTagItem("http.response.status_code").Should().Be(200); + this.measurements.Should().ContainSingle(m => m.Name == "supabase.storage.transfer.duration"); + this.measurements.Should().NotContain(m => m.Name == "supabase.storage.transfer.size", + "the size is unknown when the call returns"); + } + } + + [TestMethod] + public async Task DownloadStream_ShouldMarkTheSpanAsError_GivenTheServiceIsUnreachable() + { + this.server.Stop(); + await FluentActions.Awaiting(() => this.client.From(Bucket).DownloadStreamAsync("file.txt")) + .Should().ThrowAsync(); + this.SingleSpan($"GET /storage/v1/object/{Bucket}/file.txt").Status.Should().Be(ActivityStatusCode.Error); + } + [TestMethod] public async Task Upload_ShouldTagTheSpanAndRecordTheTransferSize() { diff --git a/packages/Storage/Storage/Extensions/HttpClientProgress.cs b/packages/Storage/Storage/Extensions/HttpClientProgress.cs index b35607481..544314d20 100644 --- a/packages/Storage/Storage/Extensions/HttpClientProgress.cs +++ b/packages/Storage/Storage/Extensions/HttpClientProgress.cs @@ -27,7 +27,7 @@ internal static class HttpClientProgress /// size (80 KB). Kept just under the 85,000-byte Large Object Heap threshold so the buffer /// stays on the gen-0 heap. This is set to the default expected value. /// - private const int CopyBufferSize = 81920; + internal const int CopyBufferSize = 81920; public static async Task DownloadDataAsync( @@ -116,6 +116,46 @@ float GetProgressPercentage(float totalBytes, float currentBytes) => (totalBytes / currentBytes) * 100f; } + public static async Task OpenDownloadAsync( + this HttpClient client, + Uri uri, + Dictionary headers, + CancellationToken cancellationToken, + TracePropagation tracePropagation + ) + { + using var activity = StorageInstrumentation.StartHttpActivity(HttpMethod.Get, uri, StorageInstrumentation.DirectionDownload); + var message = BuildDownloadRequest(uri, headers, tracePropagation); + var startTimestamp = Stopwatch.GetTimestamp(); + int? statusCode = null; + string? errorType = null; + + try + { + var response = await client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + statusCode = (int) response.StatusCode; + activity.SetHttpResponseTags(statusCode.Value); + + if (response.IsSuccessStatusCode) + return response; + + // Stryker disable once Boolean : an earlier await left the caller's context + var error = await HandleResponseError(response).ConfigureAwait(false); + errorType = error.StatusCode.ToString(); + throw error; + } + catch (Exception e) when (!(e is SupabaseStorageException)) + { + errorType = e.GetType().FullName; + activity.SetFailure(e); + throw; + } + finally + { + StorageInstrumentation.RecordTransfer(StorageInstrumentation.DirectionDownload, HttpMethod.Get, uri, null, statusCode, errorType, startTimestamp); + } + } + private static HttpRequestMessage BuildDownloadRequest(Uri uri, Dictionary? headers, TracePropagation tracePropagation) { var message = new HttpRequestMessage(HttpMethod.Get, uri); diff --git a/packages/Storage/Storage/FileBuckets/DownloadStream/DownloadBodyStream.cs b/packages/Storage/Storage/FileBuckets/DownloadStream/DownloadBodyStream.cs new file mode 100644 index 000000000..71defee43 --- /dev/null +++ b/packages/Storage/Storage/FileBuckets/DownloadStream/DownloadBodyStream.cs @@ -0,0 +1,72 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace Supabase.Storage.FileBuckets.DownloadStream; + +internal sealed class DownloadBodyStream(Stream body) : Stream +{ + public override bool CanRead => body.CanRead; + + [ExcludeFromCodeCoverage] + public override bool CanSeek => false; + + [ExcludeFromCodeCoverage] + public override bool CanWrite => false; + + [ExcludeFromCodeCoverage] + public override long Length => throw new NotSupportedException(); + + [ExcludeFromCodeCoverage] + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + try + { + return body.Read(buffer, offset, count); + } + catch (IOException e) + { + throw ConnectionFailure(e); + } + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + this.ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + try + { + return await body.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + } + catch (IOException e) + { + throw ConnectionFailure(e); + } + } + + [ExcludeFromCodeCoverage] + public override void Flush() + { + } + + [ExcludeFromCodeCoverage] + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + [ExcludeFromCodeCoverage] + public override void SetLength(long value) => throw new NotSupportedException(); + + [ExcludeFromCodeCoverage] + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + private static HttpRequestException ConnectionFailure(IOException e) => new(e.Message, e); +} diff --git a/packages/Storage/Storage/FileBuckets/DownloadStream/FileDownload.cs b/packages/Storage/Storage/FileBuckets/DownloadStream/FileDownload.cs new file mode 100644 index 000000000..a407c6ccc --- /dev/null +++ b/packages/Storage/Storage/FileBuckets/DownloadStream/FileDownload.cs @@ -0,0 +1,101 @@ +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +using Supabase.Storage.Exceptions; +using Supabase.Storage.Extensions; + +namespace Supabase.Storage.FileBuckets.DownloadStream; + +/// +/// A file download whose body is read as it arrives. +/// +public sealed class FileDownload : IDisposable +{ + private readonly HttpResponseMessage response; + + internal FileDownload(HttpResponseMessage response, Stream body) + { + this.response = response; + this.Content = new DownloadBodyStream(body); + } + + /// + /// Gets the HTTP status code. + /// + public HttpStatusCode StatusCode => this.response.StatusCode; + + /// + /// Gets the response headers, such as ETag. + /// + public HttpResponseHeaders Headers => this.response.Headers; + + /// + /// Gets the content headers, such as Content-Length and Content-Range. + /// + public HttpContentHeaders ContentHeaders => this.response.Content.Headers; + + /// + /// Gets the body, which can be read once. + /// + public Stream Content { get; } + + /// + /// Reads the body into memory, up to bytes when given. + /// + public async Task ReadAsBytesAsync(long? maxBytes = null, CancellationToken cancellationToken = default) + { + using (this) + { + using var collected = new MemoryStream(); + var buffer = new byte[HttpClientProgress.CopyBufferSize]; + int read; + while ((read = await this.Content.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) > 0) + { + if (collected.Length + read > maxBytes) + throw new SupabaseStorageException($"The download exceeds {maxBytes} bytes."); + collected.Write(buffer, 0, read); + } + + return collected.ToArray(); + } + } + + /// + /// Saves the body to , replacing it only once the whole body has arrived. + /// + public async Task SaveAsync(string path, CancellationToken cancellationToken = default) + { + var temporaryPath = Path.Combine(Path.GetDirectoryName(Path.GetFullPath(path))!, $"{Path.GetFileName(path)}.{Guid.NewGuid():N}.download"); + using (this) + { + try + { + using (var file = File.Create(temporaryPath)) + await this.Content.CopyToAsync(file, cancellationToken).ConfigureAwait(false); + MoveOver(temporaryPath, path); + } + catch + { + File.Delete(temporaryPath); + throw; + } + } + } + + /// + /// Closes the connection. + /// + public void Dispose() => this.response.Dispose(); + + private static void MoveOver(string temporaryPath, string path) + { + if (File.Exists(path)) + File.Replace(temporaryPath, path, null); + else + File.Move(temporaryPath, path); + } +} diff --git a/packages/Storage/Storage/Interfaces/IStorageFileApi.cs b/packages/Storage/Storage/Interfaces/IStorageFileApi.cs index fbf3ed3db..eaebfae7c 100644 --- a/packages/Storage/Storage/Interfaces/IStorageFileApi.cs +++ b/packages/Storage/Storage/Interfaces/IStorageFileApi.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using Supabase.Storage.FileBuckets.DownloadStream; namespace Supabase.Storage.Interfaces; @@ -53,6 +54,16 @@ Task Download( /// /// Task DownloadVersionAsync(string supabasePath, string versionId, CancellationToken cancellationToken = default); + /// + /// Downloads a file as a stream. + /// + /// + /// + /// + Task DownloadStreamAsync(string supabasePath, TransformOptions? transformOptions = null, CancellationToken cancellationToken = default); Task DownloadPublicFile( string supabasePath, TransformOptions? transformOptions = null, diff --git a/packages/Storage/Storage/PublicAPI.Unshipped.txt b/packages/Storage/Storage/PublicAPI.Unshipped.txt index 60521e358..2e9fa7d9a 100644 --- a/packages/Storage/Storage/PublicAPI.Unshipped.txt +++ b/packages/Storage/Storage/PublicAPI.Unshipped.txt @@ -1,13 +1,23 @@ #nullable enable +Supabase.Storage.FileBuckets.DownloadStream.FileDownload +Supabase.Storage.FileBuckets.DownloadStream.FileDownload.Content.get -> System.IO.Stream! +Supabase.Storage.FileBuckets.DownloadStream.FileDownload.ContentHeaders.get -> System.Net.Http.Headers.HttpContentHeaders! +Supabase.Storage.FileBuckets.DownloadStream.FileDownload.Dispose() -> void +Supabase.Storage.FileBuckets.DownloadStream.FileDownload.Headers.get -> System.Net.Http.Headers.HttpResponseHeaders! +Supabase.Storage.FileBuckets.DownloadStream.FileDownload.ReadAsBytesAsync(long? maxBytes = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Storage.FileBuckets.DownloadStream.FileDownload.SaveAsync(string! path, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Storage.FileBuckets.DownloadStream.FileDownload.StatusCode.get -> System.Net.HttpStatusCode Supabase.Storage.FileObjectV2.ArchivedAt.get -> System.DateTimeOffset? Supabase.Storage.FileObjectV2.ArchivedAt.set -> void Supabase.Storage.FileObjectV2.IsDeleteMarker.get -> bool? Supabase.Storage.FileObjectV2.IsDeleteMarker.set -> void Supabase.Storage.FileObjectV2.IsVersioned.get -> bool? Supabase.Storage.FileObjectV2.IsVersioned.set -> void -Supabase.Storage.Interfaces.IStorageFileApi.ExistsAsync(string! path, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Storage.Interfaces.IStorageFileApi.DownloadStreamAsync(string! supabasePath, Supabase.Storage.TransformOptions? transformOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.Interfaces.IStorageFileApi.GetVersionInfoAsync(string! path, string! versionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.Interfaces.IStorageFileApi.RemoveVersionAsync(string! path, string! versionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Storage.StorageFileApi.DownloadStreamAsync(string! supabasePath, Supabase.Storage.TransformOptions? transformOptions = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Storage.Interfaces.IStorageFileApi.ExistsAsync(string! path, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.StorageFileApi.ExistsAsync(string! path, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.StorageFileApi.GetVersionInfoAsync(string! path, string! versionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! Supabase.Storage.StorageFileApi.RemoveVersionAsync(string! path, string! versionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/packages/Storage/Storage/StorageFileApi.cs b/packages/Storage/Storage/StorageFileApi.cs index 06112a889..05800c914 100644 --- a/packages/Storage/Storage/StorageFileApi.cs +++ b/packages/Storage/Storage/StorageFileApi.cs @@ -14,6 +14,7 @@ using Supabase.Storage.Common; using Supabase.Storage.Exceptions; using Supabase.Storage.Extensions; +using Supabase.Storage.FileBuckets.DownloadStream; using Supabase.Storage.Interfaces; using Supabase.Storage.Responses; @@ -781,6 +782,17 @@ public Task DownloadVersionAsync(string supabasePath, string versionId, return this.DownloadBytes(url, cancellationToken: cancellationToken, versionId: versionId); } + /// + [ImplementedCapability("storage.file_buckets.download_as_stream")] + public async Task DownloadStreamAsync(string supabasePath, TransformOptions? transformOptions = null, CancellationToken cancellationToken = default) + { + var uri = DownloadUri(this.DownloadUrl(supabasePath, transformOptions), transformOptions); + var headers = await Helpers.AuthorizeAsync(this.Options, this.Headers, cancellationToken).ConfigureAwait(false); + var response = await this.downloadClient.OpenDownloadAsync(uri, headers, cancellationToken, this.Options.TracePropagation).ConfigureAwait(false); + // Stryker disable once Boolean : an earlier await left the caller's context + return new FileDownload(response, await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); + } + /// /// Downloads a public file to the filesystem. This method DOES NOT VERIFY that the file is actually public. ///