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 @@
{"vectorBucketName":"embeddings-prod","indexName":"docs-v1"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Storage.Tests.Support;

namespace Storage.Tests.DeleteVectorIndex;

/// <summary>
/// Pins the exact bytes <c>Vectors.From(...).DeleteIndexAsync</c> puts on the wire; the approved body must
/// match the service's <c>DeleteIndex</c> schema (<c>vectorBucketName</c> and <c>indexName</c>, camelCase).
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class DeleteVectorIndexApprovalTests : RequestApprovalFixture
{
[TestMethod]
public async Task DeleteIndexRequest_ShouldSerializeToExpectedPayload()
{
this.RespondWith("");
await this.Client.Vectors.From("embeddings-prod").DeleteIndexAsync("docs-v1");
await this.Verify(this.EmittedRequestBody).UseDirectory("Data");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
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.DeleteVectorIndex;

/// <summary>
/// Contract tests for <c>Vectors.From(bucket).DeleteIndexAsync</c>: the request it sends to
/// <c>POST /vector/DeleteIndex</c> and how each service answer maps to the caller's result.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class DeleteVectorIndexContractTests
{
private const string Path = "/storage/v1/vector/DeleteIndex";
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-role-key" } });
}

[TestCleanup]
public void TestCleanup() => this.server.Stop();

[TestMethod]
public async Task DeleteIndexAsync_ShouldPostTheBucketAndIndexNamesToTheVectorRoute()
{
this.Respond(200, string.Empty);
await this.client.Vectors.From("embeddings-prod").DeleteIndexAsync("docs-v1");
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\",\"indexName\":\"docs-v1\"}");
request.Headers!["Authorization"].Should().ContainSingle().Which.Should().Be("Bearer service-role-key");
}
}

[TestMethod]
public void From_ShouldNotSendARequest()
{
this.client.Vectors.From("embeddings-prod");
this.server.LogEntries.Should().BeEmpty("scoping to a bucket is local; only an operation reaches the service");
}

[TestMethod]
[DataRow(400, "InvalidRequest", "the service rejects a malformed index name")]
[DataRow(404, "S3VectorNotFoundException", "the bucket or the index does not exist")]
[DataRow(500, "InternalError", "the service failed internally")]
public async Task DeleteIndexAsync_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.From("embeddings-prod").DeleteIndexAsync("docs-v1"))
.Should().ThrowAsync<SupabaseStorageException>(because);
using (new AssertionScope())
{
thrown.Which.StatusCode.Should().Be(status);
thrown.Which.Code.Should().Be(code);
}
}

[TestMethod]
public async Task DeleteIndexAsync_ShouldClassifyAsNotAuthorized_GivenANonServiceRoleCaller()
{
this.Respond(403, "{\"statusCode\":\"403\",\"error\":\"Unauthorized\",\"message\":\"Invalid compact JWS\"}");
(await FluentActions.Awaiting(() => this.client.Vectors.From("embeddings-prod").DeleteIndexAsync("docs-v1"))
.Should().ThrowAsync<SupabaseStorageException>())
.Which.Reason.Should().Be(FailureHint.Reason.NotAuthorized);
}

[TestMethod]
public async Task DeleteIndexAsync_ShouldThrowStorageException_GivenTheVectorServiceIsNotEnabled()
{
this.Respond(404, "{\"statusCode\":\"404\",\"error\":\"Not Found\",\"message\":\"Route POST:/vector/DeleteIndex not found\"}");
(await FluentActions.Awaiting(() => this.client.Vectors.From("embeddings-prod").DeleteIndexAsync("docs-v1"))
.Should().ThrowAsync<SupabaseStorageException>())
.Which.StatusCode.Should().Be(404);
}

[TestMethod]
public async Task DeleteIndexAsync_ShouldCancel_GivenACanceledToken()
{
this.Respond(200, string.Empty);
using var source = new CancellationTokenSource();
source.Cancel();
await FluentActions.Awaiting(() => this.client.Vectors.From("embeddings-prod").DeleteIndexAsync("docs-v1", source.Token))
.Should().ThrowAsync<OperationCanceledException>("the token must reach the HTTP call");
}

[TestMethod]
public async Task DeleteIndexAsync_ShouldSendDynamicHeaders_GivenGetHeadersOnTheClient()
{
this.Respond(200, string.Empty);
this.client.GetHeaders = () => new Dictionary<string, string> { { "X-Dynamic", "fresh" } };
await this.client.Vectors.From("embeddings-prod").DeleteIndexAsync("docs-v1");
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));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
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.DeleteVectorIndex;

/// <summary>
/// Unit tests for the checks <c>Vectors.From(bucket).DeleteIndexAsync</c> makes before it touches the wire.
/// </summary>
[TestClass]
[TestCategory("Unit")]
public class DeleteVectorIndexTests
{
[TestMethod]
[DataRow(null)]
[DataRow("")]
[DataRow(" ")]
public void From_ShouldThrowArgumentException_GivenABlankBucketName(string? name)
{
var sut = new Client("http://localhost:1/storage/v1");
var thrown = FluentActions.Invoking(() => sut.Vectors.From(name!))
.Should().Throw<ArgumentException>("a blank bucket name can never address a bucket");
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]
[DataRow(null)]
[DataRow("")]
[DataRow(" ")]
public async Task DeleteIndexAsync_ShouldThrowArgumentException_GivenABlankIndexName(string? name)
{
var sut = new Client("http://localhost:1/storage/v1");
var thrown = await FluentActions.Awaiting(() => sut.Vectors.From("embeddings-prod").DeleteIndexAsync(name!))
.Should().ThrowAsync<ArgumentException>("a blank index name can never address an index and must not reach the service");
using (new AssertionScope())
{
thrown.Which.ParamName.Should().Be("indexName");
thrown.Which.Message.Should().Contain("null, empty or whitespace", "the caller needs to know why the name was refused");
}
}

[TestMethod]
public async Task DeleteIndexAsync_ShouldNotSendARequest_GivenABlankIndexName()
{
var handler = Substitute.For<HttpMessageHandler>();
var sut = new Client("http://localhost:1/storage/v1", new ClientOptions { HttpRequestClient = new HttpClient(handler) });
await FluentActions.Awaiting(() => sut.Vectors.From("embeddings-prod").DeleteIndexAsync(" ")).Should().ThrowAsync<ArgumentException>();
handler.ReceivedCalls().Should().BeEmpty("validation happens before any I/O");
}
}
32 changes: 32 additions & 0 deletions packages/Storage/Storage/Common/VectorService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Supabase.Storage.Common;

internal sealed class VectorService
{
private readonly string url;
private readonly ClientOptions options;
private readonly HttpClient requestClient;
private readonly Func<Dictionary<string, string>> headers;

internal VectorService(string storageUrl, ClientOptions options, HttpClient requestClient, Func<Dictionary<string, string>> headers)
{
this.url = $"{storageUrl.TrimEnd('/')}/vector";
this.options = options;
this.requestClient = requestClient;
this.headers = headers;
}

internal Task Post(string operation, object body, CancellationToken cancellationToken) =>
Helpers.MakeRequestAsync(this.requestClient, this.options, HttpMethod.Post, $"{this.url}/{operation}", body, this.headers(), cancellationToken);

internal static void RequireName(string value, string parameterName)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("The value cannot be null, empty or whitespace.", parameterName);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System.Text.Json.Serialization;

namespace Supabase.Storage.DeleteVectorIndex;

internal sealed class DeleteVectorIndexBody
{
internal DeleteVectorIndexBody(string vectorBucketName, string indexName)
{
this.VectorBucketName = vectorBucketName;
this.IndexName = indexName;
}

[JsonPropertyName("vectorBucketName")]
public string VectorBucketName { get; }

[JsonPropertyName("indexName")]
public string IndexName { get; }
}
15 changes: 15 additions & 0 deletions packages/Storage/Storage/Interfaces/IStorageVectorBucketApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@ namespace Supabase.Storage.Interfaces;
/// </summary>
public interface IStorageVectorBucketApi
{
/// <summary>
/// Scopes the following operations to one vector bucket. Nothing is sent to the service.
/// </summary>
/// <param name="vectorBucketName">The name of the vector bucket.</param>
/// <returns>A client for the operations that act inside that bucket.</returns>
/// <exception cref="System.ArgumentException">
/// <paramref name="vectorBucketName"/> is null, empty or whitespace.
/// </exception>
/// <example>
/// <code>
/// var bucket = storage.Vectors.From("embeddings-prod");
/// </code>
/// </example>
IVectorBucket From(string vectorBucketName);

/// <summary>
/// Deletes an empty vector bucket. The service rejects the call while the bucket still has
/// indexes. Requires a service-role key.
Expand Down
31 changes: 31 additions & 0 deletions packages/Storage/Storage/Interfaces/IVectorBucket.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Threading;
using System.Threading.Tasks;
using Supabase.Core.Attributes;

namespace Supabase.Storage.Interfaces;

/// <summary>
/// Operations scoped to one vector bucket, obtained from <see cref="IStorageVectorBucketApi.From"/>.
/// </summary>
public interface IVectorBucket
{
/// <summary>
/// Deletes a vector index from this bucket, together with its vectors. Requires a service-role key.
/// </summary>
/// <param name="indexName">The name of the index to delete.</param>
/// <param name="cancellationToken">Token used to cancel the request.</param>
/// <exception cref="System.ArgumentException">
/// <paramref name="indexName"/> is null, empty or whitespace.
/// </exception>
/// <exception cref="Exceptions.SupabaseStorageException">
/// The service refused the call, for example because the bucket or the index does not exist
/// (<c>Code</c> <c>S3VectorNotFoundException</c>).
/// </exception>
/// <example>
/// <code>
/// await storage.Vectors.From("embeddings-prod").DeleteIndexAsync("docs-v1");
/// </code>
/// </example>
[ImplementedCapability("storage.vector_buckets.delete_index")]
Task DeleteIndexAsync(string indexName, CancellationToken cancellationToken = default);
}
3 changes: 3 additions & 0 deletions packages/Storage/Storage/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ Supabase.Storage.Client.Vectors.get -> Supabase.Storage.Interfaces.IStorageVecto
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!
Supabase.Storage.Interfaces.IStorageVectorBucketApi.From(string! vectorBucketName) -> Supabase.Storage.Interfaces.IVectorBucket!
Supabase.Storage.Interfaces.IVectorBucket
Supabase.Storage.Interfaces.IVectorBucket.DeleteIndexAsync(string! indexName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!
31 changes: 11 additions & 20 deletions packages/Storage/Storage/StorageVectorBucketApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,39 +3,30 @@
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Supabase.Storage.Common;
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<Dictionary<string, string>> headers;
private readonly VectorService service;

internal StorageVectorBucketApi(string storageUrl, ClientOptions options, HttpClient requestClient, Func<Dictionary<string, string>> headers)
{
this.url = $"{storageUrl.TrimEnd('/')}/vector";
this.options = options;
this.requestClient = requestClient;
this.headers = headers;
}
internal StorageVectorBucketApi(string storageUrl, ClientOptions options, HttpClient requestClient, Func<Dictionary<string, string>> headers) =>
this.service = new VectorService(storageUrl, options, requestClient, headers);

/// <inheritdoc />
public Task DeleteVectorBucketAsync(string vectorBucketName, CancellationToken cancellationToken = default)
public IVectorBucket From(string vectorBucketName)
{
RequireName(vectorBucketName, nameof(vectorBucketName));
return this.Post("DeleteVectorBucket", new DeleteVectorBucketBody(vectorBucketName), cancellationToken);
VectorService.RequireName(vectorBucketName, nameof(vectorBucketName));
return new VectorBucket(vectorBucketName, this.service);
}

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)
/// <inheritdoc />
public Task DeleteVectorBucketAsync(string vectorBucketName, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentException("The value cannot be null, empty or whitespace.", parameterName);
VectorService.RequireName(vectorBucketName, nameof(vectorBucketName));
return this.service.Post("DeleteVectorBucket", new DeleteVectorBucketBody(vectorBucketName), cancellationToken);
}
}
26 changes: 26 additions & 0 deletions packages/Storage/Storage/VectorBucket.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Threading;
using System.Threading.Tasks;
using Supabase.Storage.Common;
using Supabase.Storage.DeleteVectorIndex;
using Supabase.Storage.Interfaces;

namespace Supabase.Storage;

internal sealed class VectorBucket : IVectorBucket
{
private readonly string vectorBucketName;
private readonly VectorService service;

internal VectorBucket(string vectorBucketName, VectorService service)
{
this.vectorBucketName = vectorBucketName;
this.service = service;
}

/// <inheritdoc />
public Task DeleteIndexAsync(string indexName, CancellationToken cancellationToken = default)
{
VectorService.RequireName(indexName, nameof(indexName));
return this.service.Post("DeleteIndex", new DeleteVectorIndexBody(this.vectorBucketName, indexName), cancellationToken);
}
}