diff --git a/packages/Storage/Storage.Tests/Files/StorageFileApiContractTests.cs b/packages/Storage/Storage.Tests/Files/StorageFileApiContractTests.cs index 7fb2c3b3..9541b96e 100644 --- a/packages/Storage/Storage.Tests/Files/StorageFileApiContractTests.cs +++ b/packages/Storage/Storage.Tests/Files/StorageFileApiContractTests.cs @@ -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; @@ -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!; @@ -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()).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(); + } + + [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(); + } + + 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(); diff --git a/packages/Storage/Storage.Tests/Files/StorageFileTests.cs b/packages/Storage/Storage.Tests/Files/StorageFileTests.cs index 044f6a37..c34ae15b 100644 --- a/packages/Storage/Storage.Tests/Files/StorageFileTests.cs +++ b/packages/Storage/Storage.Tests/Files/StorageFileTests.cs @@ -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 UploadThreeNumbered() { var names = new[] diff --git a/packages/Storage/Storage/Interfaces/IStorageFileApi.cs b/packages/Storage/Storage/Interfaces/IStorageFileApi.cs index 3f3bed9d..fbf3ed3d 100644 --- a/packages/Storage/Storage/Interfaces/IStorageFileApi.cs +++ b/packages/Storage/Storage/Interfaces/IStorageFileApi.cs @@ -175,5 +175,19 @@ Task UploadToSignedUrl( /// /// Task PurgeCache(string path, PurgeCacheOptions? options = null, CancellationToken cancellationToken = default); -} + /// Checks whether a file exists by reading its metadata. + /// + /// Returns false only for the NoSuchKey error code or an HTTP 404 without an error code. + /// Other failures, including InvalidJWT, NoSuchBucket and network errors, throw. + /// + /// The file path within the bucket, including the file name (for example, folder/image.png). + /// A token to cancel the operation. + /// true if the file exists, false if the key does not exist. + /// + /// + /// + Task ExistsAsync(string path, CancellationToken cancellationToken = default); +} diff --git a/packages/Storage/Storage/PublicAPI.Unshipped.txt b/packages/Storage/Storage/PublicAPI.Unshipped.txt index 5a474fd2..60521e35 100644 --- a/packages/Storage/Storage/PublicAPI.Unshipped.txt +++ b/packages/Storage/Storage/PublicAPI.Unshipped.txt @@ -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.ExistsAsync(string! path, 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.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 03edae09..06112a88 100644 --- a/packages/Storage/Storage/StorageFileApi.cs +++ b/packages/Storage/Storage/StorageFileApi.cs @@ -315,7 +315,9 @@ public async Task CreateSignedUrl( /// /// [ImplementedCapability("storage.file_buckets.file_info")] - public async Task Info(string path) + public Task Info(string path) => this.Info(path, CancellationToken.None); + + private async Task Info(string path, CancellationToken cancellationToken) { var response = await Helpers.MakeRequestAsync( this.requestClient, @@ -323,7 +325,8 @@ public async Task CreateSignedUrl( HttpMethod.Get, $"{this.Url}/object/info/{this.EscapeForRequestUrl(path, nameof(path))}", null, - this.Headers + this.Headers, + cancellationToken ).ConfigureAwait(false); return response; @@ -913,6 +916,22 @@ public async Task CreateUploadSignedUrl(string supabasePath) return Helpers.MakeRequestAsync(this.requestClient, this.Options, HttpMethod.Delete, url, null, this.Headers, cancellationToken); } + /// + [ImplementedCapability("storage.file_buckets.file_exists")] + public async Task 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 UploadOrUpdate( string localPath, string supabasePath,