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
1 change: 1 addition & 0 deletions packages/Storage/Storage.Tests/Storage.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<ItemGroup>
<None Update="CreateTable\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
<None Update="LoadTable\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
<None Update="UpdateTable\Data\*.json" CopyToOutputDirectory="PreserveNewest" />
<None Update="Assets\supabase-csharp.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
Expand Down
19 changes: 19 additions & 0 deletions packages/Storage/Storage.Tests/UpdateTable/Data/TableUpdated.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"metadata-location": "s3://analytics-data/sales/events/metadata/00002-7a1f0c8e-2b4d-4e6f-9a1b-3c5d7e9f1a2b.metadata.json",
"metadata": {
"format-version": 2,
"table-uuid": "b734865e-f9a5-4654-8b0b-e15683fcb195",
"location": "s3://analytics-data/sales/events",
"last-updated-ms": 1752148819286,
"last-column-id": 3,
"last-partition-id": 1000,
"current-schema-id": 1,
"schemas": [
{ "type": "struct", "schema-id": 0, "fields": [ { "id": 1, "name": "id", "type": "long", "required": true }, { "id": 2, "name": "occurred_at", "type": "timestamptz", "required": true } ] },
{ "type": "struct", "schema-id": 1, "fields": [ { "id": 1, "name": "id", "type": "long", "required": true }, { "id": 2, "name": "occurred_at", "type": "timestamptz", "required": true }, { "id": 3, "name": "country", "type": "string", "required": false } ] }
],
"default-spec-id": 0,
"partition-specs": [ { "spec-id": 0, "fields": [ { "source-id": 2, "field-id": 1000, "name": "occurred_day", "transform": "day" } ] } ],
"properties": {}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"requirements":[],"updates":[]}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"requirements":[],"updates":[{"action":"add-spec","spec":{"fields":[{"source-id":3,"name":"country","transform":"identity"}]}},{"action":"set-default-spec","spec-id":-1}]}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"requirements":[{"type":"assert-table-uuid","uuid":"b734865e-f9a5-4654-8b0b-e15683fcb195"},{"type":"assert-default-spec-id","default-spec-id":5},{"type":"assert-last-assigned-partition-id","last-assigned-partition-id":1000}],"updates":[{"action":"add-spec","spec":{"fields":[{"source-id":3,"name":"country","transform":"identity"}]}},{"action":"set-default-spec","spec-id":-1}]}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"requirements":[{"type":"assert-table-uuid","uuid":"b734865e-f9a5-4654-8b0b-e15683fcb195"},{"type":"assert-current-schema-id","current-schema-id":4},{"type":"assert-last-assigned-field-id","last-assigned-field-id":2}],"updates":[{"action":"add-schema","schema":{"type":"struct","fields":[{"id":1,"name":"id","type":"long","required":true},{"id":3,"name":"country","type":"string","required":false}]}},{"action":"set-current-schema","schema-id":-1}]}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"requirements":[],"updates":[{"action":"add-schema","schema":{"type":"struct","fields":[{"id":1,"name":"id","type":"long","required":true},{"id":3,"name":"country","type":"string","required":false}]}},{"action":"set-current-schema","schema-id":-1}]}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Storage.Tests.Support;
using Supabase.Storage.Common;
using Supabase.Storage.UpdateTable;

namespace Storage.Tests.UpdateTable;

/// <summary>
/// Pins the exact bytes <c>UpdateTableAsync</c> puts on the wire; the approved bodies must match the Iceberg REST
/// <c>CommitTableRequest</c> that Storage forwards from <c>POST /iceberg/v1/:prefix/namespaces/:namespace/tables/:table</c>
/// (<c>requirements</c> and <c>updates</c> both required; <c>-1</c> names the schema or spec added by the same commit).
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class UpdateTableApprovalTests : RequestApprovalFixture
{
private static readonly IcebergTable Events = IcebergNamespace.Of("sales").Table("events");

private static readonly IcebergSchema Evolved = new()
{
Fields = new[]
{
new IcebergField { Id = 1, Name = "id", Type = IcebergPrimitiveType.Long, Required = true },
new IcebergField { Id = 3, Name = "country", Type = IcebergPrimitiveType.String, Required = false },
},
};

private static readonly IcebergPartitionSpec ByCountry = new()
{
Fields = new[] { new IcebergPartitionField { SourceId = 3, Name = "country", Transform = IcebergTransform.Identity } },
};

private static readonly IcebergTableMetadata Current = new()
{
TableUuid = Guid.Parse("b734865e-f9a5-4654-8b0b-e15683fcb195"),
FormatVersion = 2,
Location = "s3://analytics-data/sales/events",
LastUpdatedAt = DateTimeOffset.FromUnixTimeMilliseconds(1752062419286),
CurrentSchema = new IcebergSchema { SchemaId = 4, Fields = Array.Empty<IcebergField>() },
DefaultPartitionSpec = new IcebergPartitionSpec { SpecId = 5, Fields = Array.Empty<IcebergPartitionField>() },
LastColumnId = 2,
LastPartitionId = 1000,
Properties = new Dictionary<string, string>(),
};

[TestMethod]
public async Task UpdateTableRequest_ShouldSerializeSchemaChange()
{
this.RespondWith(Updated());
await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges { Schema = Evolved });
await this.Verify(this.EmittedRequestBody).UseDirectory("Data");
}

[TestMethod]
public async Task UpdateTableRequest_ShouldSerializePartitionSpecChange()
{
this.RespondWith(Updated());
await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges { PartitionSpec = ByCountry });
await this.Verify(this.EmittedRequestBody).UseDirectory("Data");
}

[TestMethod]
public async Task UpdateTableRequest_ShouldSerializeRequirementsOfSchemaChange_GivenBasedOn()
{
this.RespondWith(Updated());
await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges { Schema = Evolved, BasedOn = Current });
await this.Verify(this.EmittedRequestBody).UseDirectory("Data");
}

[TestMethod]
public async Task UpdateTableRequest_ShouldSerializeRequirementsOfPartitionSpecChange_GivenBasedOn()
{
this.RespondWith(Updated());
await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges { PartitionSpec = ByCountry, BasedOn = Current });
await this.Verify(this.EmittedRequestBody).UseDirectory("Data");
}

[TestMethod]
public async Task UpdateTableRequest_ShouldSerializeEmptyCommit_GivenNoChange()
{
this.RespondWith(Updated());
await this.Client.Analytics.From("analytics-data").UpdateTableAsync(Events, new IcebergTableChanges());
await this.Verify(this.EmittedRequestBody).UseDirectory("Data");
}

private static string Updated() =>
File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UpdateTable", "Data", "TableUpdated.json"));
}
184 changes: 184 additions & 0 deletions packages/Storage/Storage.Tests/UpdateTable/UpdateTableContractTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
using System;
using System.Collections.Generic;
using System.IO;
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.UpdateTable;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;

namespace Storage.Tests.UpdateTable;

/// <summary>
/// Contract tests for updating a table: the POST request the catalog puts on the wire (method, path, table and
/// namespace encoding, headers), how the table metadata after the commit is surfaced, and how each failure the Iceberg
/// route can give is surfaced. Failure bodies are pinned from the storage route source and the Iceberg REST spec, not
/// observed on a running service.
/// </summary>
[TestClass]
[TestCategory("Contract")]
public class UpdateTableContractTests
{
private const string TablePath = "/storage/v1/iceberg/v1/analytics-data/namespaces/sales/tables/events";
private static readonly IcebergTable Events = IcebergNamespace.Of("sales").Table("events");
private static readonly IcebergTableChanges NoChange = new();
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 UpdateTableAsync_ShouldPostToTheTableRoute()
{
this.Respond(TablePath, 200, Fixture("TableUpdated.json"));
await this.Catalog().UpdateTableAsync(Events, NoChange);
var request = this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!;
using (new AssertionScope())
{
request.Method.Should().Be("POST", "the Iceberg route that commits table changes is POST /:prefix/namespaces/:namespace/tables/:table");
request.Path.Should().Be(TablePath, "the bucket is the Iceberg warehouse, sent as the path prefix");
request.Headers!["Authorization"].Should().ContainSingle().Which.Should().Be("Bearer service-key");
request.Headers["Content-Type"].Should().ContainSingle().Which.Should().StartWith("application/json");
}
}

[TestMethod]
public async Task UpdateTableAsync_ShouldEscapeTheTableNameAsOneSegment()
{
this.Respond("/storage/v1/iceberg/v1/*", 200, Fixture("TableUpdated.json"));
await this.Catalog().UpdateTableAsync(IcebergNamespace.Of("sales", "europe").Table("a/b?c#d"), NoChange);
this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Url
.Should().EndWith("/namespaces/sales%1Feurope/tables/a%2Fb%3Fc%23d", "a name must not start a path segment, query or fragment");
}

[TestMethod]
public async Task UpdateTableAsync_ShouldReturnTheMetadataAfterTheCommit()
{
this.Respond(TablePath, 200, Fixture("TableUpdated.json"));
var metadata = await this.Catalog().UpdateTableAsync(Events, NoChange);
using (new AssertionScope())
{
metadata.MetadataLocation.Should().Be("s3://analytics-data/sales/events/metadata/00002-7a1f0c8e-2b4d-4e6f-9a1b-3c5d7e9f1a2b.metadata.json");
metadata.CurrentSchema.SchemaId.Should().Be(1, "the schema the commit added is now current");
metadata.CurrentSchema.Fields.Should().HaveCount(3);
metadata.LastColumnId.Should().Be(3);
}
}

[TestMethod]
public async Task UpdateTableAsync_ShouldThrowConflict_GivenTableChangedSinceBasedOn()
{
this.Respond(TablePath, 409, Envelope("Requirement failed: current schema changed: expected id 0 != 1", "CommitFailedException", 409));
var act = () => this.Catalog().UpdateTableAsync(Events, NoChange);
var exception = (await act.Should().ThrowAsync<SupabaseStorageException>()).Which;
using (new AssertionScope())
{
exception.StatusCode.Should().Be(409, "the Iceberg REST spec answers 409 when a requirement fails");
exception.Code.Should().Be("CommitFailedException", "Storage passes the catalog's error type through");
}
}

[TestMethod]
public async Task UpdateTableAsync_ShouldThrow_GivenInvalidChange()
{
this.Respond(TablePath, 400, Envelope("Cannot add field country as an identifier field: not a primitive type", "BadRequestException", 400));
var act = () => this.Catalog().UpdateTableAsync(Events, NoChange);
var exception = (await act.Should().ThrowAsync<SupabaseStorageException>()).Which;
using (new AssertionScope())
{
exception.StatusCode.Should().Be(400, "the catalog, not the SDK, validates the changes");
exception.Code.Should().Be("BadRequestException");
}
}

[TestMethod]
[DataRow("Table not found", "NoSuchTableException")]
[DataRow("Namespace not found", "NoSuchNamespaceException")]
[DataRow("Catalog name \"analytics-data\" not found", "NoSuchCatalog")]
public async Task UpdateTableAsync_ShouldThrowNotFound_GivenMissingTableNamespaceOrBucket(string message, string code)
{
this.Respond(TablePath, 404, Envelope(message, code, 404));
var act = () => this.Catalog().UpdateTableAsync(Events, NoChange);
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 UpdateTableAsync_ShouldThrow_GivenForbidden()
{
this.Respond(TablePath, 403, Envelope("Access denied: Invalid role", "AccessDenied", 403));
var act = () => this.Catalog().UpdateTableAsync(Events, NoChange);
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 UpdateTableAsync_ShouldReadHeadersAtCallTime()
{
this.Respond(TablePath, 200, Fixture("TableUpdated.json"));
var catalog = this.Catalog();
this.client.GetHeaders = () => new Dictionary<string, string> { { "apikey", "rotated" } };
await catalog.UpdateTableAsync(Events, NoChange);
this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!.Headers!["apikey"]
.Should().ContainSingle().Which.Should().Be("rotated");
}

[TestMethod]
public async Task UpdateTableAsync_ShouldHonorCancellation()
{
this.Respond(TablePath, 200, Fixture("TableUpdated.json"));
using var cts = new CancellationTokenSource();
cts.Cancel();
var act = () => this.Catalog().UpdateTableAsync(Events, NoChange, cts.Token);
await act.Should().ThrowAsync<OperationCanceledException>("the token must reach the HTTP call");
}

[TestMethod]
public void UpdateTableAsync_ShouldNotResumeOnTheCallersContext()
{
this.Respond(TablePath, 200, Fixture("TableUpdated.json"));
BlockingCaller.Completes(() => this.Catalog().UpdateTableAsync(Events, NoChange))
.Should().BeTrue("the SDK never resumes on the caller's synchronization context");
}

private static string Fixture(string name) =>
File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UpdateTable", "Data", name));

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).UsingPost())
.RespondWith(Response.Create().WithStatusCode(status).WithHeader("Content-Type", "application/json").WithBody(body));
}
53 changes: 53 additions & 0 deletions packages/Storage/Storage.Tests/UpdateTable/UpdateTableTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
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.UpdateTable;

namespace Storage.Tests.UpdateTable;

/// <summary>
/// Unit tests for the checks made before the wire when updating a table, and for the defaults of its changes.
/// The changes themselves are validated by the catalog.
/// </summary>
[TestClass]
[TestCategory("Unit")]
public class UpdateTableTests
{
private readonly Client sut = new("http://localhost:1/storage/v1");

[TestMethod]
public async Task UpdateTableAsync_ShouldThrowArgumentNullException_GivenNoTable() =>
(await FluentActions.Awaiting(() => this.sut.Analytics.From("analytics-data").UpdateTableAsync(null!, new IcebergTableChanges()))
.Should().ThrowAsync<ArgumentNullException>("there is no table to update"))
.Which.ParamName.Should().Be("table");

[TestMethod]
public async Task UpdateTableAsync_ShouldThrowArgumentNullException_GivenNoChanges() =>
(await FluentActions.Awaiting(() => this.sut.Analytics.From("analytics-data").UpdateTableAsync(IcebergNamespace.Of("sales").Table("events"), null!))
.Should().ThrowAsync<ArgumentNullException>("there are no changes to commit"))
.Which.ParamName.Should().Be("changes");

[TestMethod]
[DataRow("")]
[DataRow("..")]
public async Task UpdateTableAsync_ShouldThrowArgumentException_GivenNameThatChangesTheRoute(string name) =>
(await FluentActions.Awaiting(() => this.sut.Analytics.From("analytics-data").UpdateTableAsync(IcebergNamespace.Of("sales").Table(name), new IcebergTableChanges()))
.Should().ThrowAsync<ArgumentException>("a blank or dot-segment name would post to another route"))
.Which.ParamName.Should().Be("table");

[TestMethod]
public void IcebergTableChanges_ShouldChangeNothing_GivenNoneSet()
{
var changes = new IcebergTableChanges();
using (new AssertionScope())
{
changes.Schema.Should().BeNull();
changes.PartitionSpec.Should().BeNull();
changes.BasedOn.Should().BeNull("without it the commit asserts nothing about the table");
}
}
}
10 changes: 10 additions & 0 deletions packages/Storage/Storage/IcebergCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Supabase.Storage.Interfaces;
using Supabase.Storage.ListNamespaces;
using Supabase.Storage.ListTables;
using Supabase.Storage.UpdateTable;

namespace Supabase.Storage;

Expand Down Expand Up @@ -101,6 +102,15 @@ public async Task<IcebergTablePage> ListTablesAsync(IcebergNamespace @namespace,
return response!.ToPage(@namespace);
}

/// <inheritdoc />
public async Task<IcebergTableMetadata> UpdateTableAsync(IcebergTable table, IcebergTableChanges changes, CancellationToken cancellationToken = default)
{
RequireArgument(table, nameof(table));
RequireArgument(changes, nameof(changes));
var response = await Helpers.MakeRequestAsync<TableMetadataResponse>(this.requestClient, this.options, HttpMethod.Post, this.ResourceUrl(table.Path), UpdateTableBody.For(changes), this.headers(), cancellationToken).ConfigureAwait(false);
return response!.ToMetadata();
}

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

private async Task<bool> ResourceExistsAsync(string url, CancellationToken cancellationToken)
Expand Down
Loading