diff --git a/packages/Storage/Storage.Tests/Analytics/DeleteAnalyticsBucketPathTests.cs b/packages/Storage/Storage.Tests/Analytics/DeleteAnalyticsBucketPathTests.cs new file mode 100644 index 00000000..ca3f4123 --- /dev/null +++ b/packages/Storage/Storage.Tests/Analytics/DeleteAnalyticsBucketPathTests.cs @@ -0,0 +1,34 @@ +using System; +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Supabase.Storage.DeleteAnalyticsBucket; + +namespace Storage.Tests.Analytics; + +/// +/// Unit tests for the checks made before the wire when deleting an analytics bucket. The name format +/// itself is validated by the service; the SDK only refuses names it cannot send as one path segment. +/// +[TestClass] +[TestCategory("Unit")] +public class DeleteAnalyticsBucketPathTests +{ + [TestMethod] + [DataRow(null)] + [DataRow("")] + [DataRow(" ")] + [DataRow(".")] + [DataRow("..")] + public void For_ShouldThrowArgumentException_GivenUnusableName(string? name) => + FluentActions.Invoking(() => DeleteAnalyticsBucketPath.For("http://h/iceberg", name!)) + .Should().Throw("a null, empty or dot-segment name would reach another route") + .WithMessage("An analytics bucket name*"); + + [TestMethod] + public void For_ShouldAppendEscapedNameToBucketRoute() => + DeleteAnalyticsBucketPath.For("http://h/iceberg", "my bucket").Should().Be("http://h/iceberg/bucket/my%20bucket"); + + [TestMethod] + public void For_ShouldAcceptNamesContainingDots() => + DeleteAnalyticsBucketPath.For("http://h/iceberg", "a..b").Should().Be("http://h/iceberg/bucket/a..b"); +} diff --git a/packages/Storage/Storage.Tests/Analytics/StorageAnalyticsApiContractTests.cs b/packages/Storage/Storage.Tests/Analytics/StorageAnalyticsApiContractTests.cs new file mode 100644 index 00000000..9eee1475 --- /dev/null +++ b/packages/Storage/Storage.Tests/Analytics/StorageAnalyticsApiContractTests.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +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.Analytics; + +/// +/// Contract tests for deleting an analytics bucket: the request the client puts on the wire +/// (method, path, headers, no body) and how each response the Iceberg route can give is surfaced. +/// Failure bodies are pinned from the storage route source, not observed on a running service. +/// +[TestClass] +[TestCategory("Contract")] +public class StorageAnalyticsApiContractTests +{ + private const string BucketPath = "/storage/v1/iceberg/bucket/analytics-data"; + private WireMockServer server = null!; + private Client client = null!; + + [TestInitialize] + public void TestInitialize() + { + this.server = WireMockServer.Start(); + this.client = new Client($"{this.server.Url}/storage/v1", new Dictionary + { + { "Authorization", "Bearer service-key" } + }); + } + + [TestCleanup] + public void TestCleanup() => this.server.Stop(); + + [TestMethod] + public async Task DeleteBucketAsync_ShouldSendBodylessDeleteToIcebergBucketRoute() + { + this.Respond(BucketPath, 200, "{\"message\":\"Successfully deleted\"}"); + await this.client.Analytics.DeleteBucketAsync("analytics-data"); + var request = this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!; + using (new AssertionScope()) + { + request.Method.Should().Be("DELETE", "the Iceberg bucket route is DELETE /bucket/:bucketName"); + request.Path.Should().Be(BucketPath); + request.Body.Should().BeNullOrEmpty("the route discards any request body"); + request.Headers!["Authorization"].Should().ContainSingle().Which.Should().Be("Bearer service-key"); + } + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldEscapeTheNameAsOneSegment() + { + this.Respond("/storage/v1/iceberg/bucket/*", 200, "{}"); + await this.client.Analytics.DeleteBucketAsync("a/b?c"); + this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Url + .Should().EndWith("/storage/v1/iceberg/bucket/a%2Fb%3Fc"); + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldCompleteGivenEmptyBody() + { + this.Respond(BucketPath, 200, ""); + var act = () => this.client.Analytics.DeleteBucketAsync("analytics-data"); + await act.Should().NotThrowAsync("the acknowledgement is discarded"); + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldReadHeadersAtCallTime() + { + this.Respond(BucketPath, 200, "{}"); + var analytics = this.client.Analytics; + this.client.GetHeaders = () => new Dictionary { { "apikey", "rotated" } }; + await analytics.DeleteBucketAsync("analytics-data"); + this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Headers!["apikey"] + .Should().ContainSingle().Which.Should().Be("rotated"); + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldThrowNotFound_GivenMissingBucket() + { + this.Respond(BucketPath, 404, "{\"error\":{\"message\":\"Bucket not found\",\"type\":\"NoSuchBucket\",\"code\":404}}"); + var act = () => this.client.Analytics.DeleteBucketAsync("analytics-data"); + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be(FailureHint.Reason.NotFound); + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldReportBodyStatusCode_GivenBodyDiffersFromHttpStatus() + { + this.Respond(BucketPath, 400, "{\"statusCode\":\"404\",\"error\":\"not_found\",\"message\":\"Bucket not found\"}"); + var act = () => this.client.Analytics.DeleteBucketAsync("analytics-data"); + (await act.Should().ThrowAsync()).Which.StatusCode + .Should().Be(404, "the statusCode the service puts in its body wins over the transport status"); + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldReportHttpStatus_GivenBodyCarriesNoStatusCode() + { + this.Respond(BucketPath, 404, "{\"error\":{\"message\":\"Bucket not found\",\"type\":\"NoSuchBucket\",\"code\":404}}"); + var act = () => this.client.Analytics.DeleteBucketAsync("analytics-data"); + (await act.Should().ThrowAsync()).Which.StatusCode + .Should().Be(404, "the Iceberg error envelope has no top-level statusCode"); + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldThrowNotAuthorized_GivenUnauthorizedCaller() + { + this.Respond(BucketPath, 401, "{\"message\":\"Unauthorized\",\"statusCode\":\"401\"}"); + var act = () => this.client.Analytics.DeleteBucketAsync("analytics-data"); + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be(FailureHint.Reason.NotAuthorized); + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldThrowStorageException_GivenFeatureNotEnabled() + { + this.Respond(BucketPath, 403, "{\"error\":{\"message\":\"Iceberg buckets are not enabled for this tenant\",\"type\":\"FeatureNotEnabled\",\"code\":403}}"); + var act = () => this.client.Analytics.DeleteBucketAsync("analytics-data"); + (await act.Should().ThrowAsync()).Which.StatusCode.Should().Be(403); + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldThrowInternal_GivenServerFailure() + { + this.Respond(BucketPath, 500, "{\"error\":{\"message\":\"boom\",\"type\":\"InternalError\",\"code\":500}}"); + var act = () => this.client.Analytics.DeleteBucketAsync("analytics-data"); + (await act.Should().ThrowAsync()).Which.Reason + .Should().Be(FailureHint.Reason.Internal); + } + + [TestMethod] + public async Task DeleteBucketAsync_ShouldCancelTheRequest_GivenCanceledToken() + { + this.Respond(BucketPath, 200, "{}"); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + var act = () => this.client.Analytics.DeleteBucketAsync("analytics-data", cts.Token); + await act.Should().ThrowAsync("the token must reach the HTTP call"); + } + + private void Respond(string path, int status, string body) => + this.server.Given(Request.Create().WithPath(path).UsingDelete()) + .RespondWith(Response.Create().WithStatusCode(status).WithHeader("Content-Type", "application/json").WithBody(body)); +} diff --git a/packages/Storage/Storage/Client.cs b/packages/Storage/Storage/Client.cs index 496e0168..f0b44b10 100644 --- a/packages/Storage/Storage/Client.cs +++ b/packages/Storage/Storage/Client.cs @@ -12,6 +12,10 @@ public Client(string url, Dictionary? headers = null) : base(url public Client(string url, ClientOptions? options, Dictionary? headers = null) : base(url, options, headers) { } + /// + public IStorageAnalyticsApi Analytics => + new StorageAnalyticsApi(this.Url, this.Options, this.requestClient, () => this.Headers); + /// /// Perform a file operation in a bucket /// diff --git a/packages/Storage/Storage/DeleteAnalyticsBucket/DeleteAnalyticsBucketPath.cs b/packages/Storage/Storage/DeleteAnalyticsBucket/DeleteAnalyticsBucketPath.cs new file mode 100644 index 00000000..23dfe306 --- /dev/null +++ b/packages/Storage/Storage/DeleteAnalyticsBucket/DeleteAnalyticsBucketPath.cs @@ -0,0 +1,23 @@ +using System; + +namespace Supabase.Storage.DeleteAnalyticsBucket; + +internal static class DeleteAnalyticsBucketPath +{ + private static readonly string[] RelativeSegments = { ".", ".." }; + + internal static string For(string icebergUrl, string name) + { + RejectUnusable(name); + return $"{icebergUrl}/bucket/{Uri.EscapeDataString(name)}"; + } + + private static void RejectUnusable(string name) + { + if (string.IsNullOrWhiteSpace(name)) + throw new ArgumentException("An analytics bucket name must be provided.", nameof(name)); + + if (Array.IndexOf(RelativeSegments, name) >= 0) + throw new ArgumentException("An analytics bucket name cannot be a relative path segment.", nameof(name)); + } +} diff --git a/packages/Storage/Storage/Helpers.cs b/packages/Storage/Storage/Helpers.cs index df70c658..032d2317 100644 --- a/packages/Storage/Storage/Helpers.cs +++ b/packages/Storage/Storage/Helpers.cs @@ -145,7 +145,7 @@ HttpRequestMessage CreateRequest() if (!response.IsSuccessStatusCode) { var errorResponse = ErrorResponse.TryParse(content); - var resolvedStatus = errorResponse?.StatusCode ?? (int) response.StatusCode; + var resolvedStatus = errorResponse?.StatusCode is > 0 ? errorResponse.StatusCode : (int) response.StatusCode; errorType = resolvedStatus.ToString(); var e = new SupabaseStorageException(errorResponse?.Message ?? content) { diff --git a/packages/Storage/Storage/Interfaces/IStorageAnalyticsApi.cs b/packages/Storage/Storage/Interfaces/IStorageAnalyticsApi.cs new file mode 100644 index 00000000..29b1dcde --- /dev/null +++ b/packages/Storage/Storage/Interfaces/IStorageAnalyticsApi.cs @@ -0,0 +1,28 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Supabase.Core.Attributes; + +namespace Supabase.Storage.Interfaces; + +/// +/// Manages analytics buckets, the Apache Iceberg backed buckets of Supabase Storage. Requires a service-role key. +/// +public interface IStorageAnalyticsApi +{ + /// + /// Deletes an empty analytics bucket. + /// + /// The name of the analytics bucket to delete. + /// Token used to cancel the request. + /// The name is null, empty, or cannot be sent as a single path segment. + /// The service rejected the request, for example because the bucket does not exist or the caller is not authorized. + /// + /// + /// var storage = new Client(url, headers); + /// await storage.Analytics.DeleteBucketAsync("analytics-data"); + /// + /// + [ImplementedCapability("storage.analytics.delete_analytics_bucket")] + Task DeleteBucketAsync(string name, CancellationToken cancellationToken = default); +} diff --git a/packages/Storage/Storage/Interfaces/IStorageClient.cs b/packages/Storage/Storage/Interfaces/IStorageClient.cs index 7d58f976..bde2787b 100644 --- a/packages/Storage/Storage/Interfaces/IStorageClient.cs +++ b/packages/Storage/Storage/Interfaces/IStorageClient.cs @@ -8,6 +8,11 @@ public interface IStorageClient : IStorageBucketApi From(string id); + /// + /// Manages analytics (Apache Iceberg) buckets. Requires a service-role key. + /// + IStorageAnalyticsApi Analytics { get; } + /// /// Operations on vector buckets. /// diff --git a/packages/Storage/Storage/PublicAPI.Unshipped.txt b/packages/Storage/Storage/PublicAPI.Unshipped.txt index e8dcfd14..2964ca22 100644 --- a/packages/Storage/Storage/PublicAPI.Unshipped.txt +++ b/packages/Storage/Storage/PublicAPI.Unshipped.txt @@ -1,5 +1,9 @@ #nullable enable +Supabase.Storage.Client.Analytics.get -> Supabase.Storage.Interfaces.IStorageAnalyticsApi! Supabase.Storage.Client.Vectors.get -> Supabase.Storage.Interfaces.IStorageVectorBucketApi! +Supabase.Storage.Interfaces.IStorageAnalyticsApi +Supabase.Storage.Interfaces.IStorageAnalyticsApi.DeleteBucketAsync(string! name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Storage.Interfaces.IStorageClient.Analytics.get -> Supabase.Storage.Interfaces.IStorageAnalyticsApi! Supabase.Storage.Interfaces.IStorageClient.Vectors.get -> Supabase.Storage.Interfaces.IStorageVectorBucketApi! Supabase.Storage.Interfaces.IStorageVectorBucketApi Supabase.Storage.Interfaces.IStorageVectorBucketApi.DeleteVectorBucketAsync(string! vectorBucketName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/packages/Storage/Storage/StorageAnalyticsApi.cs b/packages/Storage/Storage/StorageAnalyticsApi.cs new file mode 100644 index 00000000..99953283 --- /dev/null +++ b/packages/Storage/Storage/StorageAnalyticsApi.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Supabase.Storage.DeleteAnalyticsBucket; +using Supabase.Storage.Interfaces; + +namespace Supabase.Storage; + +internal class StorageAnalyticsApi : IStorageAnalyticsApi +{ + private readonly string icebergUrl; + private readonly ClientOptions options; + private readonly HttpClient requestClient; + private readonly Func> headers; + + internal StorageAnalyticsApi(string storageUrl, ClientOptions options, HttpClient requestClient, Func> headers) + { + this.icebergUrl = $"{storageUrl}/iceberg"; + this.options = options; + this.requestClient = requestClient; + this.headers = headers; + } + + /// + public Task DeleteBucketAsync(string name, CancellationToken cancellationToken = default) => + Helpers.MakeRequestAsync(this.requestClient, this.options, HttpMethod.Delete, DeleteAnalyticsBucketPath.For(this.icebergUrl, name), null, this.headers(), cancellationToken); +}