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
@@ -0,0 +1,34 @@
using System;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Storage.DeleteAnalyticsBucket;

namespace Storage.Tests.Analytics;

/// <summary>
/// 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.
/// </summary>
[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<ArgumentException>("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");
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
[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<string, string>
{
{ "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<string, string> { { "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<SupabaseStorageException>()).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<SupabaseStorageException>()).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<SupabaseStorageException>()).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<SupabaseStorageException>()).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<SupabaseStorageException>()).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<SupabaseStorageException>()).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<OperationCanceledException>("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));
}
4 changes: 4 additions & 0 deletions packages/Storage/Storage/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ public Client(string url, Dictionary<string, string>? headers = null) : base(url
public Client(string url, ClientOptions? options, Dictionary<string, string>? headers = null) : base(url, options, headers)
{ }

/// <inheritdoc />
public IStorageAnalyticsApi Analytics =>
new StorageAnalyticsApi(this.Url, this.Options, this.requestClient, () => this.Headers);

/// <summary>
/// Perform a file operation in a bucket
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -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));
}
}
2 changes: 1 addition & 1 deletion packages/Storage/Storage/Helpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
28 changes: 28 additions & 0 deletions packages/Storage/Storage/Interfaces/IStorageAnalyticsApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Supabase.Core.Attributes;

namespace Supabase.Storage.Interfaces;

/// <summary>
/// Manages analytics buckets, the Apache Iceberg backed buckets of Supabase Storage. Requires a service-role key.
/// </summary>
public interface IStorageAnalyticsApi
{
/// <summary>
/// Deletes an empty analytics bucket.
/// </summary>
/// <param name="name">The name of the analytics bucket to delete.</param>
/// <param name="cancellationToken">Token used to cancel the request.</param>
/// <exception cref="ArgumentException">The name is null, empty, or cannot be sent as a single path segment.</exception>
/// <exception cref="Exceptions.SupabaseStorageException">The service rejected the request, for example because the bucket does not exist or the caller is not authorized.</exception>
/// <example>
/// <code>
/// var storage = new Client(url, headers);
/// await storage.Analytics.DeleteBucketAsync("analytics-data");
/// </code>
/// </example>
[ImplementedCapability("storage.analytics.delete_analytics_bucket")]
Task DeleteBucketAsync(string name, CancellationToken cancellationToken = default);
}
5 changes: 5 additions & 0 deletions packages/Storage/Storage/Interfaces/IStorageClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ public interface IStorageClient<TBucket, TFileObject> : IStorageBucketApi<TBucke
{
IStorageFileApi<TFileObject> From(string id);

/// <summary>
/// Manages analytics (Apache Iceberg) buckets. Requires a service-role key.
/// </summary>
IStorageAnalyticsApi Analytics { get; }

/// <summary>
/// Operations on vector buckets.
/// </summary>
Expand Down
4 changes: 4 additions & 0 deletions packages/Storage/Storage/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -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<TBucket, TFileObject>.Analytics.get -> Supabase.Storage.Interfaces.IStorageAnalyticsApi!
Supabase.Storage.Interfaces.IStorageClient<TBucket, TFileObject>.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!
29 changes: 29 additions & 0 deletions packages/Storage/Storage/StorageAnalyticsApi.cs
Original file line number Diff line number Diff line change
@@ -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<Dictionary<string, string>> headers;

internal StorageAnalyticsApi(string storageUrl, ClientOptions options, HttpClient requestClient, Func<Dictionary<string, string>> headers)
{
this.icebergUrl = $"{storageUrl}/iceberg";
this.options = options;
this.requestClient = requestClient;
this.headers = headers;
}

/// <inheritdoc />
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);
}