Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
41 changes: 41 additions & 0 deletions src/HotChocolate/Fusion/src/Fusion.Packaging/FusionArchive.cs
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,47 @@ Task<Stream> OpenReadSchemaAsync(CancellationToken ct)
}
}

/// <summary>
/// Removes a source schema configuration from the archive, deleting its files and
/// removing it from the archive metadata.
/// </summary>
/// <param name="schemaName">The name of the source schema to remove.</param>
/// <param name="cancellationToken">Token to cancel the operation.</param>
/// <returns>
/// <c>true</c> if the source schema was present and removed; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentException">Thrown when schemaName is null or empty.</exception>
/// <exception cref="ObjectDisposedException">Thrown when the archive has been disposed.</exception>
/// <exception cref="InvalidOperationException">Thrown when the archive is read-only.</exception>
public async Task<bool> RemoveSourceSchemaConfigurationAsync(
string schemaName,
CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(schemaName);
ObjectDisposedException.ThrowIf(_disposed, this);
EnsureMutable();

var metadata = await GetArchiveMetadataAsync(cancellationToken);

if (metadata is null || !metadata.SourceSchemas.Contains(schemaName))
{
return false;
}

_session.Delete(FileNames.GetSourceSchemaPath(schemaName));
_session.Delete(FileNames.GetSourceSchemaSettingsPath(schemaName));
_session.Delete(FileNames.GetSourceSchemaExtensionsPath(schemaName));

var updatedMetadata = metadata with
{
SourceSchemas = metadata.SourceSchemas.Remove(schemaName)
};

await SetArchiveMetadataAsync(updatedMetadata, cancellationToken);

return true;
}

/// <summary>
/// Sets the legacy archive file in the archive by copying the content from the provided stream.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,73 @@ public async Task TryGetSourceSchema_WithNonExistentSchema_ReturnsFalse()
Assert.Null(found);
}

[Fact]
public async Task RemoveSourceSchema_WithExistingSchema_RemovesSchemaAndMetadata()
{
// Arrange
var schemaContent = "type User { id: ID! }"u8.ToArray();
await using var stream = CreateStream();
var metadata = new ArchiveMetadata
{
SupportedGatewayFormats = [new Version("2.0.0")],
SourceSchemas = ["schema-a", "schema-b"]
};

using (var archive = FusionArchive.Create(stream, leaveOpen: true))
{
await archive.SetArchiveMetadataAsync(metadata, TestContext.Current.CancellationToken);
await archive.SetSourceSchemaConfigurationAsync(
"schema-a",
schemaContent,
CreateSettingsJson(),
cancellationToken: TestContext.Current.CancellationToken);
await archive.SetSourceSchemaConfigurationAsync(
"schema-b",
schemaContent,
CreateSettingsJson(),
cancellationToken: TestContext.Current.CancellationToken);
await archive.CommitAsync(TestContext.Current.CancellationToken);
}

// Act
bool removed;
stream.Position = 0;
using (var updateArchive = FusionArchive.Open(stream, FusionArchiveMode.Update, leaveOpen: true))
{
removed = await updateArchive.RemoveSourceSchemaConfigurationAsync(
"schema-b",
TestContext.Current.CancellationToken);
await updateArchive.CommitAsync(TestContext.Current.CancellationToken);
}

// Assert
stream.Position = 0;
using var readArchive = FusionArchive.Open(stream, leaveOpen: true);
var names = await readArchive.GetSourceSchemaNamesAsync(TestContext.Current.CancellationToken);
var found = await readArchive.TryGetSourceSchemaConfigurationAsync(
"schema-b",
TestContext.Current.CancellationToken);
Assert.True(removed);
Assert.Equal(["schema-a"], names);
Assert.Null(found);
}

[Fact]
public async Task RemoveSourceSchema_WithNonExistentSchema_ReturnsFalse()
{
// Arrange
await using var stream = CreateStream();
var metadata = CreateTestMetadata();

// Act & Assert
using var archive = FusionArchive.Create(stream, leaveOpen: true);
await archive.SetArchiveMetadataAsync(metadata, TestContext.Current.CancellationToken);
var removed = await archive.RemoveSourceSchemaConfigurationAsync(
"non-existent",
TestContext.Current.CancellationToken);
Assert.False(removed);
}

[Fact]
public async Task SignArchive_WithValidCertificate_CreatesSignature()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace ChilliCream.Nitro.CommandLine.Arguments;

internal sealed class FusionReplaceSourceSchemaNameArgument : Argument<string>
{
public const string ArgumentName = "OLD_SOURCE_SCHEMA_NAME";

public FusionReplaceSourceSchemaNameArgument() : base(ArgumentName)
{
Description = "The name of the source schema to replace";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace ChilliCream.Nitro.CommandLine.Arguments;

internal sealed class FusionSourceSchemaNameArgument : Argument<string>
{
public const string ArgumentName = "SOURCE_SCHEMA_NAME";

public FusionSourceSchemaNameArgument() : base(ArgumentName)
{
Description = "The name of the source schema to remove";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public FusionCommand() : base("fusion")
Subcommands.Add(new FusionPublishCommand());
Subcommands.Add(new FusionRunCommand());
Subcommands.Add(new FusionSettingsCommand());
Subcommands.Add(new FusionSourceSchemaCommand());
Subcommands.Add(new FusionValidateCommand());
Subcommands.Add(new FusionUploadCommand());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#if !NET9_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif

namespace ChilliCream.Nitro.CommandLine.Commands.Fusion;

#if !NET9_0_OR_GREATER
[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
#endif
internal sealed class FusionSourceSchemaCommand : Command
{
public FusionSourceSchemaCommand() : base("source-schema")
{
Description = "Manage source schemas in a Fusion archive.";

Subcommands.Add(new FusionSourceSchemaRemoveCommand());
Subcommands.Add(new FusionSourceSchemaReplaceCommand());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
using System.Text.Json;
using ChilliCream.Nitro.CommandLine.Helpers;
using ChilliCream.Nitro.CommandLine.Services;
using HotChocolate.Fusion;
using HotChocolate.Fusion.Packaging;

namespace ChilliCream.Nitro.CommandLine.Commands.Fusion;

internal static class FusionSourceSchemaHelpers
{
public static string ResolveExistingArchiveFile(IFileSystem fileSystem, string archiveFile)
{
if (!Path.IsPathRooted(archiveFile))
{
archiveFile = Path.Combine(fileSystem.GetCurrentDirectory(), archiveFile);
}

if (!fileSystem.FileExists(archiveFile))
{
throw new ExitException(Messages.ArchiveFileDoesNotExist(archiveFile));
}

return archiveFile;
}

/// <summary>
/// Applies a mutation to an in-memory copy of the archive, recomposes it, and only writes
/// the result back to disk when the recomposition succeeds. The on-disk archive is left
/// untouched when the mutation or the recomposition fails.
/// </summary>
public static async Task<int> ApplyAndRecomposeAsync(
string archiveFile,
Func<FusionArchive, Task> mutateAsync,
Dictionary<string, (SourceSchemaText, JsonDocument)> newSourceSchemas,
string environment,
INitroConsole console,
CancellationToken cancellationToken)
{
var bytes = await File.ReadAllBytesAsync(archiveFile, cancellationToken);

var buffer = new MemoryStream();
buffer.Write(bytes, 0, bytes.Length);
buffer.Position = 0;

Comment thread
tobias-tengler marked this conversation as resolved.
Resolved
using var archive = FusionArchive.Open(buffer, FusionArchiveMode.Update, leaveOpen: true);

await mutateAsync(archive);

await using var composeActivity = console.StartActivity(
"Composing new configuration",
"Failed to compose new configuration.");

var (result, compositionLog) = await FusionPublishHelpers.ComposeAsync(
archive,
environment,
newSourceSchemas,
compositionSettings: null,
legacyArchive: null,
cancellationToken);

if (result.IsSuccess)
{
buffer.Position = 0;
await File.WriteAllBytesAsync(archiveFile, buffer.ToArray(), cancellationToken);

composeActivity.Success("Composed new configuration.");

return ExitCodes.Success;
}
else
{
await composeActivity.FailAllAsync();

console.WriteLine();
console.WriteLine("## Composition log");
console.WriteLine();

FusionComposeCommand.WriteCompositionLog(
compositionLog,
console.Out,
false);

foreach (var error in result.Errors)
{
console.Error.WriteErrorLine(error.Message);
}

throw new ExitException();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
#if !NET9_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
using ChilliCream.Nitro.CommandLine.Arguments;
using ChilliCream.Nitro.CommandLine.Helpers;
using ChilliCream.Nitro.CommandLine.Services;
using HotChocolate.Fusion.Packaging;

namespace ChilliCream.Nitro.CommandLine.Commands.Fusion;

#if !NET9_0_OR_GREATER
[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
#endif
internal sealed class FusionSourceSchemaRemoveCommand : Command
{
public FusionSourceSchemaRemoveCommand() : base("remove")
{
Description =
"Remove a source schema from a Fusion archive and recompose the remaining source schemas.";

Arguments.Add(Opt<FusionSourceSchemaNameArgument>.Instance);

Options.Add(Opt<FusionArchiveFileOption>.Instance);
Options.Add(Opt<FusionEnvironmentOption>.Instance);

this.AddGlobalNitroOptions();

this.AddExamples(
"""
fusion source-schema remove reviews \
--archive ./gateway.far
""");

this.SetActionWithExceptionHandling(ExecuteAsync);
}

private static async Task<int> ExecuteAsync(
ICommandServices services,
ParseResult parseResult,
CancellationToken cancellationToken)
{
var console = services.GetRequiredService<INitroConsole>();
var fileSystem = services.GetRequiredService<IFileSystem>();
var environmentVariables = services.GetRequiredService<IEnvironmentVariableProvider>();

var sourceSchemaName = parseResult.GetRequiredValue(Opt<FusionSourceSchemaNameArgument>.Instance);
var archiveFile = parseResult.GetRequiredValue(Opt<FusionArchiveFileOption>.Instance);
var environment = parseResult.GetValue(Opt<FusionEnvironmentOption>.Instance);

archiveFile = FusionSourceSchemaHelpers.ResolveExistingArchiveFile(fileSystem, archiveFile);

environment ??= environmentVariables.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";

return await FusionSourceSchemaHelpers.ApplyAndRecomposeAsync(
archiveFile,
MutateAsync,
[],
environment,
console,
cancellationToken);

async Task MutateAsync(FusionArchive archive)
{
var names = (await archive.GetSourceSchemaNamesAsync(cancellationToken)).ToList();

if (!names.Contains(sourceSchemaName))
{
throw new ExitException(
Messages.SourceSchemaDoesNotExistInArchive(sourceSchemaName, archiveFile));
}

if (names.Count == 1)
{
throw new ExitException(Messages.CannotRemoveLastSourceSchema(sourceSchemaName));
}

await archive.RemoveSourceSchemaConfigurationAsync(sourceSchemaName, cancellationToken);
}
}
}
Loading
Loading