diff --git a/packages/Storage/Storage.Tests/DeleteVectorBucket/Data/DeleteVectorBucketApprovalTests.DeleteVectorBucketRequest_ShouldSerializeToExpectedPayload.verified.txt b/packages/Storage/Storage.Tests/DeleteVectorBucket/Data/DeleteVectorBucketApprovalTests.DeleteVectorBucketRequest_ShouldSerializeToExpectedPayload.verified.txt new file mode 100644 index 00000000..b3e1fe38 --- /dev/null +++ b/packages/Storage/Storage.Tests/DeleteVectorBucket/Data/DeleteVectorBucketApprovalTests.DeleteVectorBucketRequest_ShouldSerializeToExpectedPayload.verified.txt @@ -0,0 +1 @@ +{"vectorBucketName":"embeddings-prod"} \ No newline at end of file diff --git a/packages/Storage/Storage.Tests/DeleteVectorBucket/DeleteVectorBucketApprovalTests.cs b/packages/Storage/Storage.Tests/DeleteVectorBucket/DeleteVectorBucketApprovalTests.cs new file mode 100644 index 00000000..ffd9777d --- /dev/null +++ b/packages/Storage/Storage.Tests/DeleteVectorBucket/DeleteVectorBucketApprovalTests.cs @@ -0,0 +1,22 @@ +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Storage.Tests.Support; + +namespace Storage.Tests.DeleteVectorBucket; + +/// +/// Pins the exact bytes Vectors.DeleteVectorBucketAsync puts on the wire; the approved body must +/// match the service's DeleteVectorBucket schema (vectorBucketName, camelCase). +/// +[TestClass] +[TestCategory("Contract")] +public class DeleteVectorBucketApprovalTests : RequestApprovalFixture +{ + [TestMethod] + public async Task DeleteVectorBucketRequest_ShouldSerializeToExpectedPayload() + { + this.RespondWith(""); + await this.Client.Vectors.DeleteVectorBucketAsync("embeddings-prod"); + await this.Verify(this.EmittedRequestBody).UseDirectory("Data"); + } +} diff --git a/packages/Storage/Storage.Tests/DeleteVectorBucket/DeleteVectorBucketContractTests.cs b/packages/Storage/Storage.Tests/DeleteVectorBucket/DeleteVectorBucketContractTests.cs new file mode 100644 index 00000000..4b610aa3 --- /dev/null +++ b/packages/Storage/Storage.Tests/DeleteVectorBucket/DeleteVectorBucketContractTests.cs @@ -0,0 +1,126 @@ +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.DeleteVectorBucket; + +/// +/// Contract tests for Vectors.DeleteVectorBucketAsync: the request it sends to +/// POST /vector/DeleteVectorBucket and how each service answer maps to the caller's result. +/// +[TestClass] +[TestCategory("Contract")] +public class DeleteVectorBucketContractTests +{ + private const string Path = "/storage/v1/vector/DeleteVectorBucket"; + 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-role-key" } }); + } + + [TestCleanup] + public void TestCleanup() => this.server.Stop(); + + [TestMethod] + public async Task DeleteVectorBucketAsync_ShouldPostTheBucketNameToTheVectorRoute() + { + this.Respond(200, string.Empty); + await this.client.Vectors.DeleteVectorBucketAsync("embeddings-prod"); + var request = this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!; + using (new AssertionScope()) + { + request.Method.Should().Be("POST"); + request.Path.Should().Be(Path); + request.Body.Should().Be("{\"vectorBucketName\":\"embeddings-prod\"}"); + request.Headers!["Authorization"].Should().ContainSingle().Which.Should().Be("Bearer service-role-key"); + } + } + + [TestMethod] + public async Task DeleteVectorBucketAsync_ShouldComplete_GivenAnEmptyBody() + { + this.Respond(200, string.Empty); + await this.client.Vectors.DeleteVectorBucketAsync("embeddings-prod"); + } + + [TestMethod] + public async Task DeleteVectorBucketAsync_ShouldPostToTheVectorRoute_GivenAUrlWithATrailingSlash() + { + this.Respond(200, string.Empty); + await new Client($"{this.server.Url}/storage/v1/").Vectors.DeleteVectorBucketAsync("embeddings-prod"); + this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Path.Should().Be(Path); + } + + [TestMethod] + [DataRow(400, "S3VectorBucketNotEmpty", "the service refuses to delete a bucket that still has indexes")] + [DataRow(404, "S3VectorNotFoundException", "the bucket does not exist")] + [DataRow(500, "InternalError", "the service failed internally")] + public async Task DeleteVectorBucketAsync_ShouldThrowStorageException_GivenAServiceError(int status, string code, string because) + { + this.Respond(status, $"{{\"statusCode\":\"{status}\",\"code\":\"{code}\",\"message\":\"refused\"}}"); + var thrown = await FluentActions.Awaiting(() => this.client.Vectors.DeleteVectorBucketAsync("embeddings-prod")) + .Should().ThrowAsync(because); + using (new AssertionScope()) + { + thrown.Which.StatusCode.Should().Be(status); + thrown.Which.Code.Should().Be(code); + } + } + + [TestMethod] + public async Task DeleteVectorBucketAsync_ShouldClassifyAsNotAuthorized_GivenANonServiceRoleCaller() + { + this.Respond(403, "{\"statusCode\":\"403\",\"error\":\"Unauthorized\",\"message\":\"Invalid compact JWS\"}"); + (await FluentActions.Awaiting(() => this.client.Vectors.DeleteVectorBucketAsync("embeddings-prod")) + .Should().ThrowAsync()) + .Which.Reason.Should().Be(FailureHint.Reason.NotAuthorized); + } + + [TestMethod] + public async Task DeleteVectorBucketAsync_ShouldThrowStorageException_GivenTheVectorServiceIsNotEnabled() + { + this.Respond(404, "{\"statusCode\":\"404\",\"error\":\"Not Found\",\"message\":\"Route DELETE:/vector/DeleteVectorBucket not found\"}"); + (await FluentActions.Awaiting(() => this.client.Vectors.DeleteVectorBucketAsync("embeddings-prod")) + .Should().ThrowAsync()) + .Which.StatusCode.Should().Be(404); + } + + [TestMethod] + public async Task DeleteVectorBucketAsync_ShouldCancel_GivenACanceledToken() + { + this.Respond(200, string.Empty); + using var source = new CancellationTokenSource(); + source.Cancel(); + await FluentActions.Awaiting(() => this.client.Vectors.DeleteVectorBucketAsync("embeddings-prod", source.Token)) + .Should().ThrowAsync("the token must reach the HTTP call"); + } + + [TestMethod] + public async Task DeleteVectorBucketAsync_ShouldSendDynamicHeaders_GivenGetHeadersOnTheClient() + { + this.Respond(200, string.Empty); + this.client.GetHeaders = () => new Dictionary { { "X-Dynamic", "fresh" } }; + await this.client.Vectors.DeleteVectorBucketAsync("embeddings-prod"); + this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Headers!["X-Dynamic"] + .Should().ContainSingle().Which.Should().Be("fresh"); + } + + private void Respond(int statusCode, string body) => + this.server.Given(Request.Create().WithPath(Path).UsingPost()) + .RespondWith(Response.Create().WithStatusCode(statusCode) + .WithHeader("Content-Type", "application/json").WithBody(body)); +} diff --git a/packages/Storage/Storage.Tests/DeleteVectorBucket/DeleteVectorBucketTests.cs b/packages/Storage/Storage.Tests/DeleteVectorBucket/DeleteVectorBucketTests.cs new file mode 100644 index 00000000..90feac17 --- /dev/null +++ b/packages/Storage/Storage.Tests/DeleteVectorBucket/DeleteVectorBucketTests.cs @@ -0,0 +1,43 @@ +using System; +using System.Net.Http; +using System.Threading.Tasks; +using FluentAssertions; +using FluentAssertions.Execution; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; +using Supabase.Storage; + +namespace Storage.Tests.DeleteVectorBucket; + +/// +/// Unit tests for the checks Vectors.DeleteVectorBucketAsync makes before it touches the wire. +/// +[TestClass] +[TestCategory("Unit")] +public class DeleteVectorBucketTests +{ + [TestMethod] + [DataRow(null)] + [DataRow("")] + [DataRow(" ")] + public async Task DeleteVectorBucketAsync_ShouldThrowArgumentException_GivenABlankName(string? name) + { + var sut = new Client("http://localhost:1/storage/v1"); + var thrown = await FluentActions.Awaiting(() => sut.Vectors.DeleteVectorBucketAsync(name!)) + .Should().ThrowAsync("a blank name can never address a bucket and must not reach the service"); + using (new AssertionScope()) + { + thrown.Which.ParamName.Should().Be("vectorBucketName"); + thrown.Which.Message.Should().Contain("null, empty or whitespace", "the caller needs to know why the name was refused"); + } + } + + [TestMethod] + public async Task DeleteVectorBucketAsync_ShouldNotSendARequest_GivenABlankName() + { + var handler = Substitute.For(); + var sut = new Client("http://localhost:1/storage/v1", new ClientOptions { HttpRequestClient = new HttpClient(handler) }); + await FluentActions.Awaiting(() => sut.Vectors.DeleteVectorBucketAsync(" ")).Should().ThrowAsync(); + handler.ReceivedCalls().Should().BeEmpty("validation happens before any I/O"); + } +} diff --git a/packages/Storage/Storage/Client.cs b/packages/Storage/Storage/Client.cs index 257b18c7..496e0168 100644 --- a/packages/Storage/Storage/Client.cs +++ b/packages/Storage/Storage/Client.cs @@ -20,4 +20,8 @@ public Client(string url, ClientOptions? options, Dictionary? he [ImplementedCapability("storage.file_buckets.access_bucket")] public IStorageFileApi From(string id) => new StorageFileApi(this.Url, id, this.Options, this.Headers, this.requestClient, this.uploadClient, this.downloadClient); + + /// + public IStorageVectorBucketApi Vectors => + new StorageVectorBucketApi(this.Url, this.Options, this.requestClient, () => this.Headers); } diff --git a/packages/Storage/Storage/DeleteVectorBucket/DeleteVectorBucketBody.cs b/packages/Storage/Storage/DeleteVectorBucket/DeleteVectorBucketBody.cs new file mode 100644 index 00000000..5f2a7571 --- /dev/null +++ b/packages/Storage/Storage/DeleteVectorBucket/DeleteVectorBucketBody.cs @@ -0,0 +1,11 @@ +using System.Text.Json.Serialization; + +namespace Supabase.Storage.DeleteVectorBucket; + +internal sealed class DeleteVectorBucketBody +{ + internal DeleteVectorBucketBody(string vectorBucketName) => this.VectorBucketName = vectorBucketName; + + [JsonPropertyName("vectorBucketName")] + public string VectorBucketName { get; } +} diff --git a/packages/Storage/Storage/Interfaces/IStorageClient.cs b/packages/Storage/Storage/Interfaces/IStorageClient.cs index 682d873b..7d58f976 100644 --- a/packages/Storage/Storage/Interfaces/IStorageClient.cs +++ b/packages/Storage/Storage/Interfaces/IStorageClient.cs @@ -1,11 +1,15 @@ -using Supabase.Core.Interfaces; +using Supabase.Core.Interfaces; -namespace Supabase.Storage.Interfaces +namespace Supabase.Storage.Interfaces; + +public interface IStorageClient : IStorageBucketApi, IGettableHeaders + where TBucket : Bucket + where TFileObject : FileObject { - public interface IStorageClient : IStorageBucketApi, IGettableHeaders - where TBucket : Bucket - where TFileObject : FileObject - { - IStorageFileApi From(string id); - } -} \ No newline at end of file + IStorageFileApi From(string id); + + /// + /// Operations on vector buckets. + /// + IStorageVectorBucketApi Vectors { get; } +} diff --git a/packages/Storage/Storage/Interfaces/IStorageVectorBucketApi.cs b/packages/Storage/Storage/Interfaces/IStorageVectorBucketApi.cs new file mode 100644 index 00000000..e4dc901b --- /dev/null +++ b/packages/Storage/Storage/Interfaces/IStorageVectorBucketApi.cs @@ -0,0 +1,32 @@ +using System.Threading; +using System.Threading.Tasks; +using Supabase.Core.Attributes; + +namespace Supabase.Storage.Interfaces; + +/// +/// Operations on vector buckets, which hold the vector indexes of the Storage vector service. +/// +public interface IStorageVectorBucketApi +{ + /// + /// Deletes an empty vector bucket. The service rejects the call while the bucket still has + /// indexes. Requires a service-role key. + /// + /// The name of the vector bucket to delete. + /// Token used to cancel the request. + /// + /// is null, empty or whitespace. + /// + /// + /// The service refused the call, for example because the bucket does not exist + /// (Code S3VectorNotFoundException) or is not empty (Code S3VectorBucketNotEmpty). + /// + /// + /// + /// await storage.Vectors.DeleteVectorBucketAsync("embeddings-prod"); + /// + /// + [ImplementedCapability("storage.vector_buckets.delete_vector_bucket")] + Task DeleteVectorBucketAsync(string vectorBucketName, CancellationToken cancellationToken = default); +} diff --git a/packages/Storage/Storage/PublicAPI.Unshipped.txt b/packages/Storage/Storage/PublicAPI.Unshipped.txt index 7dc5c581..e8dcfd14 100644 --- a/packages/Storage/Storage/PublicAPI.Unshipped.txt +++ b/packages/Storage/Storage/PublicAPI.Unshipped.txt @@ -1 +1,5 @@ #nullable enable +Supabase.Storage.Client.Vectors.get -> Supabase.Storage.Interfaces.IStorageVectorBucketApi! +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/StorageVectorBucketApi.cs b/packages/Storage/Storage/StorageVectorBucketApi.cs new file mode 100644 index 00000000..fd9453f4 --- /dev/null +++ b/packages/Storage/Storage/StorageVectorBucketApi.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Supabase.Storage.DeleteVectorBucket; +using Supabase.Storage.Interfaces; + +namespace Supabase.Storage; + +internal sealed class StorageVectorBucketApi : IStorageVectorBucketApi +{ + private readonly string url; + private readonly ClientOptions options; + private readonly HttpClient requestClient; + private readonly Func> headers; + + internal StorageVectorBucketApi(string storageUrl, ClientOptions options, HttpClient requestClient, Func> headers) + { + this.url = $"{storageUrl.TrimEnd('/')}/vector"; + this.options = options; + this.requestClient = requestClient; + this.headers = headers; + } + + /// + public Task DeleteVectorBucketAsync(string vectorBucketName, CancellationToken cancellationToken = default) + { + RequireName(vectorBucketName, nameof(vectorBucketName)); + return this.Post("DeleteVectorBucket", new DeleteVectorBucketBody(vectorBucketName), cancellationToken); + } + + private Task Post(string operation, object body, CancellationToken cancellationToken) => + Helpers.MakeRequestAsync(this.requestClient, this.options, HttpMethod.Post, $"{this.url}/{operation}", body, this.headers(), cancellationToken); + + private static void RequireName(string value, string parameterName) + { + if (string.IsNullOrWhiteSpace(value)) + throw new ArgumentException("The value cannot be null, empty or whitespace.", parameterName); + } +}