Skip to content
Closed
Show file tree
Hide file tree
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
@@ -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;

/// <summary>
/// Contract tests for <c>DownloadStreamAsync</c> and the <c>FileDownload</c> it returns.
/// </summary>
[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<string, string> { { "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<SupabaseStorageException>("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<OperationCanceledException>();
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<string, string> { [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<string, string> { [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<string, string> FilesInDirectory() =>
Directory.GetFiles(this.directory).ToDictionary(file => file, File.ReadAllText);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
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;

namespace Storage.Tests.FileBuckets.DownloadStream;

/// <summary>
/// Contract tests for a download whose body is cut short.
/// </summary>
[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<string, string> { { "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<HttpRequestException>(
"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<SupabaseStorageException>();
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<HttpRequestException>();
this.FilesInDirectory().Should().Equal(new Dictionary<string, string> { [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<OperationCanceledException>();
(await this.IsClosedAsync()).Should().BeTrue("cancelling the read closes the connection");
}

private async Task<FileDownload> 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<string> ExistingFileAsync()
{
var destination = Path.Combine(this.directory, "trailer.mp4");
await File.WriteAllTextAsync(destination, PreviousBody);
return destination;
}

private Dictionary<string, string> FilesInDirectory() =>
Directory.GetFiles(this.directory).ToDictionary(file => file, File.ReadAllText);

private async Task<bool> IsClosedAsync()
{
try
{
return await this.wire.ReadAsync(new byte[1]).AsTask().WaitAsync(Timeout) == 0;
}
catch (IOException)
{
return true;
}
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// End-to-end tests for <c>DownloadStreamAsync</c> against the local stack, on a uniquely named private bucket
/// that <see cref="StorageE2EFixture"/> tears down.
/// </summary>
[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<SupabaseStorageException>())
.Which.Reason.Should().Be(FailureHint.Reason.NotFound);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,22 @@ 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())
{
this.SingleSpan($"GET /storage/v1/object/{Bucket}/file.txt")
.GetTagItem("storage.transfer.direction").Should().Be("download");
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 Upload_ShouldTagTheSpanAndRecordTheTransferSize()
{
Expand Down
Loading
Loading