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
217 changes: 217 additions & 0 deletions packages/Storage/Storage.Tests/ListTables/ListTablesContractTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Execution;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Storage.Tests.Support;
using Supabase.Storage;
using Supabase.Storage.Common;
using Supabase.Storage.Exceptions;
using Supabase.Storage.Interfaces;
using Supabase.Storage.ListTables;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;

namespace Storage.Tests.ListTables;

/// <summary>
/// Contract tests for listing the tables of a namespace: the GET request the catalog puts on the wire (method, path,
/// namespace encoding, paging query, headers, no body), how the page in the response is mapped, and how each failure
/// 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 ListTablesContractTests
{
private const string TablesPath = "/storage/v1/iceberg/v1/analytics-data/namespaces/sales/tables";
private const string Listed = "{\"identifiers\":[{\"namespace\":[\"sales\"],\"name\":\"events\"},{\"namespace\":[\"sales\"],\"name\":\"orders\"}]}";
private static readonly IcebergNamespace Sales = IcebergNamespace.Of("sales");
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 ListTablesAsync_ShouldSendBodylessGetToTheTablesRouteOfTheNamespace()
{
this.Respond(TablesPath, 200, Listed);
await this.Catalog().ListTablesAsync(Sales);
var request = this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!;
using (new AssertionScope())
{
request.Method.Should().Be("GET", "the Iceberg route that lists tables is GET /:prefix/namespaces/:namespace/tables");
request.Path.Should().Be(TablesPath, "the bucket is the Iceberg warehouse, sent as the path prefix");
request.Body.Should().BeNullOrEmpty();
request.Headers!["Authorization"].Should().ContainSingle().Which.Should().Be("Bearer service-key");
}
}

[TestMethod]
public async Task ListTablesAsync_ShouldSendNoPagingParameter_GivenNoOptions()
{
this.Respond(TablesPath, 200, Listed);
await this.Catalog().ListTablesAsync(Sales);
this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Query
.Should().BeNullOrEmpty("an option left unset is not sent");
}

[TestMethod]
public async Task ListTablesAsync_ShouldSendPageSizeAndToken_GivenOptions()
{
this.Respond(TablesPath, 200, Listed);
await this.Catalog().ListTablesAsync(Sales, new ListTablesOptions { PageSize = 2, PageToken = "next/page token" });
var query = this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Query!;
using (new AssertionScope())
{
query["pageSize"].Should().Equal(new[] { "2" }, "the Iceberg REST spec names it pageSize");
query["pageToken"].Should().Equal(new[] { "next/page token" }, "the Iceberg REST spec names it pageToken");
}
}

[TestMethod]
public async Task ListTablesAsync_ShouldJoinNamespaceLevelsWithTheUnitSeparator()
{
this.Respond("/storage/v1/iceberg/v1/*", 200, Listed);
await this.Catalog().ListTablesAsync(IcebergNamespace.Of("sales", "europe"));
this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Url
.Should().Contain("/namespaces/sales%1Feurope/tables", "the Iceberg REST spec joins levels with the 0x1F separator");
}

[TestMethod]
public async Task ListTablesAsync_ShouldReturnTheListedTablesInOrder()
{
this.Respond(TablesPath, 200, Listed);
(await this.Catalog().ListTablesAsync(Sales)).Tables
.Should().Equal(Sales.Table("events"), Sales.Table("orders"));
}

[TestMethod]
public async Task ListTablesAsync_ShouldReturnTheNamespaceTheServiceSent()
{
this.Respond(TablesPath, 200, "{\"identifiers\":[{\"namespace\":[\"sales\",\"europe\"],\"name\":\"events\"}]}");
(await this.Catalog().ListTablesAsync(Sales)).Tables
.Should().ContainSingle().Which.Should().Be(IcebergNamespace.Of("sales", "europe").Table("events"));
}

[TestMethod]
[DataRow("{\"identifiers\":[{\"name\":\"events\"}]}")]
[DataRow("{\"identifiers\":[{\"namespace\":[],\"name\":\"events\"}]}")]
public async Task ListTablesAsync_ShouldReturnTheListedNamespace_GivenIdentifierWithoutNamespace(string body)
{
this.Respond(TablesPath, 200, body);
(await this.Catalog().ListTablesAsync(Sales)).Tables
.Should().ContainSingle().Which.Should().Be(Sales.Table("events"));
}

[TestMethod]
public async Task ListTablesAsync_ShouldReturnNoTable_GivenResponseOmitsIdentifiers()
{
this.Respond(TablesPath, 200, "{}");
(await this.Catalog().ListTablesAsync(Sales)).Tables.Should().BeEmpty();
}

[TestMethod]
public async Task ListTablesAsync_ShouldReturnTheNextPageToken()
{
this.Respond(TablesPath, 200, "{\"identifiers\":[],\"next-page-token\":\"page-2\"}");
(await this.Catalog().ListTablesAsync(Sales)).NextPageToken.Should().Be("page-2");
}

[TestMethod]
public async Task ListTablesAsync_ShouldReturnNoNextPageToken_GivenLastPage()
{
this.Respond(TablesPath, 200, Listed);
(await this.Catalog().ListTablesAsync(Sales)).NextPageToken.Should().BeNull("Storage never sends one today");
}

[TestMethod]
[DataRow("Namespace not found", "NoSuchNamespaceException")]
[DataRow("Catalog name \"analytics-data\" not found", "NoSuchCatalog")]
public async Task ListTablesAsync_ShouldThrowNotFound_GivenMissingNamespaceOrBucket(string message, string code)
{
this.Respond(TablesPath, 404, Envelope(message, code, 404));
var act = () => this.Catalog().ListTablesAsync(Sales);
var exception = (await act.Should().ThrowAsync<SupabaseStorageException>()).Which;
using (new AssertionScope())
{
exception.Reason.Should().Be(FailureHint.Reason.NotFound);
exception.Code.Should().Be(code);
}
}

[TestMethod]
public async Task ListTablesAsync_ShouldThrow_GivenNegativePageSize()
{
this.Respond(TablesPath, 400, Envelope("querystring/pageSize must be >= 0", "InvalidRequest", 400));
var act = () => this.Catalog().ListTablesAsync(Sales, new ListTablesOptions { PageSize = -1 });
(await act.Should().ThrowAsync<SupabaseStorageException>("the service, not the SDK, validates the page size"))
.Which.StatusCode.Should().Be(400);
}

[TestMethod]
public async Task ListTablesAsync_ShouldThrow_GivenForbidden()
{
this.Respond(TablesPath, 403, Envelope("Access denied: Invalid role", "AccessDenied", 403));
var act = () => this.Catalog().ListTablesAsync(Sales);
var exception = (await act.Should().ThrowAsync<SupabaseStorageException>()).Which;
using (new AssertionScope())
{
exception.StatusCode.Should().Be(403, "only the service role may use the catalog");
exception.Code.Should().Be("AccessDenied");
}
}

[TestMethod]
public async Task ListTablesAsync_ShouldReadHeadersAtCallTime()
{
this.Respond(TablesPath, 200, Listed);
var catalog = this.Catalog();
this.client.GetHeaders = () => new Dictionary<string, string> { { "apikey", "rotated" } };
await catalog.ListTablesAsync(Sales);
this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Headers!["apikey"]
.Should().ContainSingle().Which.Should().Be("rotated");
}

[TestMethod]
public async Task ListTablesAsync_ShouldHonorCancellation()
{
this.Respond(TablesPath, 200, Listed);
using var cts = new CancellationTokenSource();
cts.Cancel();
var act = () => this.Catalog().ListTablesAsync(Sales, null, cts.Token);
await act.Should().ThrowAsync<OperationCanceledException>("the token must reach the HTTP call");
}

[TestMethod]
public void ListTablesAsync_ShouldNotResumeOnTheCallersContext()
{
this.Respond(TablesPath, 200, Listed);
BlockingCaller.Completes(() => this.Catalog().ListTablesAsync(Sales))
.Should().BeTrue("the SDK never resumes on the caller's synchronization context");
}

private static string Envelope(string message, string type, int code) =>
$"{{\"error\":{{\"message\":{JsonSerializer.Serialize(message)},\"type\":\"{type}\",\"code\":{code}}}}}";

private IIcebergCatalog Catalog() => this.client.Analytics.From("analytics-data");

private void Respond(string path, int status, string body) =>
this.server.Given(Request.Create().WithPath(path).UsingGet())
.RespondWith(Response.Create().WithStatusCode(status).WithHeader("Content-Type", "application/json").WithBody(body));
}
48 changes: 48 additions & 0 deletions packages/Storage/Storage.Tests/ListTables/ListTablesTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Execution;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Supabase.Storage;
using Supabase.Storage.Common;
using Supabase.Storage.ListTables;

namespace Storage.Tests.ListTables;

/// <summary>
/// Unit tests for the checks made before the wire when listing the tables of a namespace, and for the defaults of its
/// options and page.
/// </summary>
[TestClass]
[TestCategory("Unit")]
public class ListTablesTests
{
private readonly Client sut = new("http://localhost:1/storage/v1");

[TestMethod]
public async Task ListTablesAsync_ShouldThrowArgumentNullException_GivenNoNamespace() =>
(await FluentActions.Awaiting(() => this.sut.Analytics.From("analytics-data").ListTablesAsync(null!))
.Should().ThrowAsync<ArgumentNullException>("there is no namespace to list"))
.Which.ParamName.Should().Be("namespace");

[TestMethod]
public async Task ListTablesAsync_ShouldThrowArgumentException_GivenRelativeSegmentNamespace() =>
await FluentActions.Awaiting(() => this.sut.Analytics.From("analytics-data").ListTablesAsync(IcebergNamespace.Of("..")))
.Should().ThrowAsync<ArgumentException>("a dot-segment namespace would reach another route")
.WithMessage("A namespace cannot be a relative path segment.*");

[TestMethod]
public void ListTablesOptions_ShouldSendNothing_GivenNoneSet()
{
var options = new ListTablesOptions();
using (new AssertionScope())
{
options.PageSize.Should().BeNull("the service owns the default page size");
options.PageToken.Should().BeNull("the first page needs no token");
}
}

[TestMethod]
public void IcebergTablePage_ShouldHaveNoTable_GivenNoneSet() =>
new IcebergTablePage().Tables.Should().BeEmpty();
}
11 changes: 11 additions & 0 deletions packages/Storage/Storage/Common/QueryString.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;

namespace Supabase.Storage.Common;

internal static class QueryString
{
internal static string Append(string url, IEnumerable<string> parameters) => $"{url}?{string.Join("&", parameters)}";

internal static string Parameter(string name, string value) => $"{name}={Uri.EscapeDataString(value)}";
}
10 changes: 10 additions & 0 deletions packages/Storage/Storage/IcebergCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Supabase.Storage.Exceptions;
using Supabase.Storage.Interfaces;
using Supabase.Storage.ListNamespaces;
using Supabase.Storage.ListTables;

namespace Supabase.Storage;

Expand Down Expand Up @@ -91,6 +92,15 @@ public Task DeleteTableAsync(IcebergTable table, DeleteTableOptions? options = n
return Helpers.MakeRequestAsync(this.requestClient, this.options, HttpMethod.Delete, DeleteTableQuery.For(this.ResourceUrl(table.Path), options), null, this.headers(), cancellationToken);
}

/// <inheritdoc />
public async Task<IcebergTablePage> ListTablesAsync(IcebergNamespace @namespace, ListTablesOptions? options = null, CancellationToken cancellationToken = default)
{
RequireArgument(@namespace, nameof(@namespace));
var url = ListTablesQuery.For(this.ResourceUrl($"{@namespace.Path}/tables"), options);
var response = await Helpers.MakeRequestAsync<ListTablesResponse>(this.requestClient, this.options, HttpMethod.Get, url, null, this.headers(), cancellationToken).ConfigureAwait(false);
return response!.ToPage(@namespace);
}

private string ResourceUrl(string path) => $"{this.catalogUrl}/{path}";

private async Task<bool> ResourceExistsAsync(string url, CancellationToken cancellationToken)
Expand Down
27 changes: 27 additions & 0 deletions packages/Storage/Storage/Interfaces/IIcebergCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Supabase.Storage.CreateTable;
using Supabase.Storage.DeleteTable;
using Supabase.Storage.ListNamespaces;
using Supabase.Storage.ListTables;

namespace Supabase.Storage.Interfaces;

Expand Down Expand Up @@ -213,4 +214,30 @@ public interface IIcebergCatalog
/// </example>
[ImplementedCapability("storage.analytics.delete_table")]
Task DeleteTableAsync(IcebergTable table, DeleteTableOptions? options = null, CancellationToken cancellationToken = default);

/// <summary>
/// Lists the tables of a namespace, one page at a time. Storage applies the page size as a limit and ignores the
/// page token today: it returns the first tables in creation order, without a next-page token.
/// </summary>
/// <param name="namespace">The namespace whose tables to list.</param>
/// <param name="options">Page size and page token, following the Iceberg REST Catalog spec. When null, none is sent.</param>
/// <param name="cancellationToken">Token used to cancel the request.</param>
/// <returns>One page of tables. Empty when the namespace holds none.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="namespace"/> is null.</exception>
/// <exception cref="System.ArgumentException">The namespace is a relative path segment.</exception>
/// <exception cref="Exceptions.SupabaseStorageException">
/// The service refused the call, for example because the namespace or its bucket does not exist (status 404,
/// <c>Code</c> <c>NoSuchNamespaceException</c> or <c>NoSuchCatalog</c>), the page size is negative (status 400) or
/// the caller is not authorized.
/// </exception>
/// <example>
/// <code>
/// var catalog = storage.Analytics.From("analytics-data");
/// var page = await catalog.ListTablesAsync(IcebergNamespace.Of("sales"));
/// foreach (var table in page.Tables)
/// Console.WriteLine(table.Name);
/// </code>
/// </example>
[ImplementedCapability("storage.analytics.list_tables")]
Task<IcebergTablePage> ListTablesAsync(IcebergNamespace @namespace, ListTablesOptions? options = null, CancellationToken cancellationToken = default);
}
12 changes: 5 additions & 7 deletions packages/Storage/Storage/ListNamespaces/ListNamespacesQuery.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Supabase.Storage.Common;

namespace Supabase.Storage.ListNamespaces;

internal static class ListNamespacesQuery
{
internal static string For(string namespacesUrl, ListNamespacesOptions? options) =>
$"{namespacesUrl}?{string.Join("&", ParametersOf(options ?? new ListNamespacesOptions()))}";
QueryString.Append(namespacesUrl, ParametersOf(options ?? new ListNamespacesOptions()));

private static IEnumerable<string> ParametersOf(ListNamespacesOptions options)
{
if (options.Parent is { } parent)
yield return Parameter("parent", parent.Joined());
yield return QueryString.Parameter("parent", parent.Joined());

if (options.PageToken is { } pageToken)
yield return Parameter("pageToken", pageToken);
yield return QueryString.Parameter("pageToken", pageToken);

if (options.PageSize is { } pageSize)
yield return Parameter("pageSize", pageSize.ToString(CultureInfo.InvariantCulture));
yield return QueryString.Parameter("pageSize", pageSize.ToString(CultureInfo.InvariantCulture));
}

private static string Parameter(string name, string value) => $"{name}={Uri.EscapeDataString(value)}";
}
17 changes: 17 additions & 0 deletions packages/Storage/Storage/ListTables/IcebergTablePage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using Supabase.Storage.Common;

namespace Supabase.Storage.ListTables;

/// <summary>
/// One page of the tables of a namespace.
/// </summary>
public sealed record IcebergTablePage
{
/// <summary>The tables of this page, in the order the service listed them.</summary>
public IReadOnlyList<IcebergTable> Tables { get; init; } = Array.Empty<IcebergTable>();

/// <summary>The token that requests the next page, or null when this page is the last.</summary>
public string? NextPageToken { get; init; }
}
Loading