Skip to content
Merged
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
Expand Up @@ -6,6 +6,7 @@
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Execution;
Expand All @@ -32,6 +33,7 @@ namespace Storage.Tests.Files;
public class StorageFileApiContractTests
{
private const string Bucket = "bucket";
private const string InfoPath = "/storage/v1/object/info/" + Bucket + "/a.png";

private WireMockServer server = null!;
private Client client = null!;
Expand Down Expand Up @@ -612,6 +614,84 @@ public async Task From_ShouldReuseTheConnection_GivenASecondCall()
}
}

[TestMethod]
public async Task ExistsAsync_ShouldReturnTrue_GivenExistingFile()
{
this.Respond(InfoPath, "GET", 200, "{\"name\":\"a.png\"}");
(await this.client.From(Bucket).ExistsAsync("a.png")).Should().BeTrue();
}

[TestMethod]
public async Task ExistsAsync_ShouldRequestTheObjectInfoRoute()
{
this.Respond(InfoPath, "GET", 200, "{\"name\":\"a.png\"}");
await this.client.From(Bucket).ExistsAsync("a.png");
using (new AssertionScope())
{
this.SingleRequest().Method.Should().Be("GET");
this.SingleRequest().Path.Should().Be(InfoPath);
}
}

[TestMethod]
public async Task ExistsAsync_ShouldReturnTrue_GivenNullJsonSuccess()
{
this.Respond(InfoPath, "GET", 200, "null");
(await this.client.From(Bucket).ExistsAsync("a.png")).Should().BeTrue();
}

[TestMethod]
public async Task ExistsAsync_ShouldReturnFalse_GivenNoSuchKey()
{
this.Respond(InfoPath, "GET", 404, "{\"statusCode\":\"404\",\"code\":\"NoSuchKey\",\"message\":\"Object not found\"}");
(await this.client.From(Bucket).ExistsAsync("a.png")).Should().BeFalse();
}

[TestMethod]
public async Task ExistsAsync_ShouldReturnFalse_GivenNotFoundWithoutErrorCode()
{
this.Respond(InfoPath, "GET", 404, "{\"message\":\"Not found\"}");
(await this.client.From(Bucket).ExistsAsync("a.png")).Should().BeFalse();
}

[TestMethod]
[DataRow(HttpStatusCode.Unauthorized, "Unauthorized")]
[DataRow(HttpStatusCode.Forbidden, "AccessDenied")]
[DataRow(HttpStatusCode.NotFound, "NoSuchBucket")]
[DataRow(HttpStatusCode.InternalServerError, "InternalError")]
public async Task ExistsAsync_ShouldThrow_GivenAnErrorOtherThanMissingKey(HttpStatusCode status, string code)
{
this.Respond(InfoPath, "GET", (int) status, $"{{\"statusCode\":\"{(int) status}\",\"code\":\"{code}\",\"message\":\"Service error\"}}");
var act = () => this.client.From(Bucket).ExistsAsync("a.png");
(await act.Should().ThrowAsync<SupabaseStorageException>()).Which.Code.Should().Be(code);
}

[TestMethod]
public async Task ExistsAsync_ShouldThrow_GivenCancelledToken()
{
this.Respond(InfoPath, "GET", 200, "{\"name\":\"a.png\"}");
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
var act = () => this.client.From(Bucket).ExistsAsync("a.png", cancellation.Token);
await act.Should().ThrowAsync<OperationCanceledException>();
}

[TestMethod]
public async Task ExistsAsync_ShouldThrow_GivenUnreachableServer()
{
var act = () => new Client($"http://127.0.0.1:{FreePort()}/storage/v1").From(Bucket).ExistsAsync("a.png");
await act.Should().ThrowAsync<HttpRequestException>();
}

private static int FreePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint) listener.LocalEndpoint).Port;
listener.Stop();
return port;
}

private static async Task AnswerGetRequests(TcpClient connection)
{
var stream = connection.GetStream();
Expand Down
11 changes: 11 additions & 0 deletions packages/Storage/Storage.Tests/Files/StorageFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,17 @@ public async Task List_ShouldReturnFilesDescending_GivenCreatedAtColumnAndOrderD
list!.Select(item => item.Name).Should().Equal(names[2], names[1], names[0]);
}

[TestMethod]
public async Task ExistsAsync_ShouldReturnTrue_GivenExistingFile()
{
var names = await this.UploadThreeNumbered();
(await this.bucket.ExistsAsync(names[0])).Should().BeTrue();
}

[TestMethod]
public async Task ExistsAsync_ShouldReturnFalse_GivenNonExistingFile() =>
(await this.bucket.ExistsAsync($"{Guid.NewGuid()}.png")).Should().BeFalse();

private async Task<string[]> UploadThreeNumbered()
{
var names = new[]
Expand Down
16 changes: 15 additions & 1 deletion packages/Storage/Storage/Interfaces/IStorageFileApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,5 +175,19 @@ Task<string> UploadToSignedUrl(
/// </code>
/// </example>
Task<GenericResponse?> PurgeCache(string path, PurgeCacheOptions? options = null, CancellationToken cancellationToken = default);
}

/// <summary>Checks whether a file exists by reading its metadata.</summary>
/// <remarks>
/// Returns <c>false</c> only for the <c>NoSuchKey</c> error code or an HTTP 404 without an error code.
/// Other failures, including <c>InvalidJWT</c>, <c>NoSuchBucket</c> and network errors, throw.
/// </remarks>
/// <param name="path">The file path within the bucket, including the file name (for example, <c>folder/image.png</c>).</param>
/// <param name="cancellationToken">A token to cancel the operation.</param>
/// <returns><c>true</c> if the file exists, <c>false</c> if the key does not exist.</returns>
/// <example>
/// <code><![CDATA[
/// var exists = await storage.From("avatars").ExistsAsync("folder/avatar.png");
/// ]]></code>
/// </example>
Task<bool> ExistsAsync(string path, CancellationToken cancellationToken = default);
}
2 changes: 2 additions & 0 deletions packages/Storage/Storage/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ 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<TFileObject>.ExistsAsync(string! path, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<bool>!
Supabase.Storage.Interfaces.IStorageFileApi<TFileObject>.GetVersionInfoAsync(string! path, string! versionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Storage.FileObjectV2?>!
Supabase.Storage.Interfaces.IStorageFileApi<TFileObject>.RemoveVersionAsync(string! path, string! versionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<TFileObject?>!
Supabase.Storage.StorageFileApi.ExistsAsync(string! path, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<bool>!
Supabase.Storage.StorageFileApi.GetVersionInfoAsync(string! path, string! versionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Storage.FileObjectV2?>!
Supabase.Storage.StorageFileApi.RemoveVersionAsync(string! path, string! versionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Supabase.Storage.FileObject?>!
23 changes: 21 additions & 2 deletions packages/Storage/Storage/StorageFileApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -315,15 +315,18 @@ public async Task<string> CreateSignedUrl(
/// <param name="path"></param>
/// <returns></returns>
[ImplementedCapability("storage.file_buckets.file_info")]
public async Task<FileObjectV2?> Info(string path)
public Task<FileObjectV2?> Info(string path) => this.Info(path, CancellationToken.None);

private async Task<FileObjectV2?> Info(string path, CancellationToken cancellationToken)
{
var response = await Helpers.MakeRequestAsync<FileObjectV2>(
this.requestClient,
this.Options,
HttpMethod.Get,
$"{this.Url}/object/info/{this.EscapeForRequestUrl(path, nameof(path))}",
null,
this.Headers
this.Headers,
cancellationToken
).ConfigureAwait(false);

return response;
Expand Down Expand Up @@ -913,6 +916,22 @@ public async Task<UploadSignedUrl> CreateUploadSignedUrl(string supabasePath)
return Helpers.MakeRequestAsync<GenericResponse>(this.requestClient, this.Options, HttpMethod.Delete, url, null, this.Headers, cancellationToken);
}

/// <inheritdoc />
[ImplementedCapability("storage.file_buckets.file_exists")]
public async Task<bool> ExistsAsync(string path, CancellationToken cancellationToken = default)
{
try
{
await this.Info(path, cancellationToken).ConfigureAwait(false);
return true;
}
catch (SupabaseStorageException ex) when (
ex.Code == "NoSuchKey" || ((int?) ex.Response?.StatusCode == 404 && ex.Code == null))
{
return false;
}
}

private async Task<string> UploadOrUpdate(
string localPath,
string supabasePath,
Expand Down
Loading