Skip to main content

Bending Aspire to your will - Reset your application state with one command

I spend a lot of time testing and debugging APIs, and so do my AI agents. Lately I notice that my agents lose time and tokens on it. They look for the right port, guess at endpoints, fight with a terminal, and try to get the database back into a known state. Every run starts with the same detective work.

So for this series of posts I picked one scenario and I’m sticking with it: the API-testing loop. The goal is to adapt Aspire so that I (and my agents) can debug and test easily and efficiently.

The third step of my API-testing loop: tests leave data behind. A clean, repeatable run means flushing Redis and recreating the catalog database. By hand, that is a Redis CLI command and a database drop-and-seed, in the right order. For me that's annoying. For an agent, it's one more thing to figure out on every run.

Note: this post is part of a series about the demos from my session “Bending Aspire to your will”.

In aspire-shop, state lives in two places: the PostgreSQL catalog database (seeded by the catalog DB manager) and the Redis basket cache. The goal is a single "Reset Shop State" command that clears both.

I build it in three steps: two building blocks and one composite command.

Building block 1: expose an existing endpoint as a command

The catalog DB manager already has the logic. It has a development-only /reset-db endpoint that deletes and recreates the database:

app.MapPost("/reset-db", async (CatalogDbContext dbContext, CatalogDbInitializer dbInitializer, CancellationToken cancellationToken) =>
{
    // Delete and recreate the database. This is useful for development scenarios to reset the database to its initial state.
    await dbContext.Database.EnsureDeletedAsync(cancellationToken);
    await dbInitializer.InitializeDatabaseAsync(dbContext, cancellationToken);
}).RequireCors("OpenApi");

When the service already has an endpoint, you don't have to write a command. WithHttpCommand turns it into one:

catalogDbManager.WithHttpCommand("/reset-db", "Reset Database",
    commandName: "reset-db",
    commandOptions: new() { IconName = "DatabaseLightning", ResultMode = HttpCommandResultMode.Auto, IsHighlighted = true });

Remark: the endpoint is only mapped when the environment is Development. That is exactly what you want for a destructive endpoint, but it also means the command fails in any other environment.

Building block 2: write a command once, reuse it everywhere

Redis has no HTTP endpoint I can call. So this time I write the command myself. Instead of putting a lambda in the AppHost, I put it in an extension method on the resource type:

internal static class RedisResourceBuilderExtensions
{
    public static IResourceBuilder<RedisResource> WithClearCommand(
        this IResourceBuilder<RedisResource> builder)
    {
        var commandOptions = new CommandOptions
        {
            UpdateState = OnUpdateResourceState,
            IconName = "AnimalRabbitOff",
            IconVariant = IconVariant.Filled,
            Visibility = ResourceCommandVisibility.Api | ResourceCommandVisibility.UI
        };

        builder.WithCommand(
            name: "clear-cache",
            displayName: "Clear Cache",
            executeCommand: context => OnRunClearCacheCommandAsync(builder, context),
            commandOptions: commandOptions);

        return builder;
    }

    private static async Task<ExecuteCommandResult> OnRunClearCacheCommandAsync(
        IResourceBuilder<RedisResource> builder,
        ExecuteCommandContext context)
    {
        var connectionString = await builder.Resource.GetConnectionStringAsync() ??
            throw new InvalidOperationException(
                $"Unable to get the '{context.ResourceName}' connection string.");

        await using var connection = ConnectionMultiplexer.Connect(connectionString);
        var database = connection.GetDatabase();
        await database.ExecuteAsync("FLUSHALL");

        return CommandResults.Success();
    }

    private static ResourceCommandState OnUpdateResourceState(UpdateCommandStateContext context)
    {
        return context.ResourceSnapshot.HealthStatus is HealthStatus.Healthy
            ? ResourceCommandState.Enabled
            : ResourceCommandState.Disabled;
    }
}

I left out the logging in OnUpdateResourceState. The command gets the connection string from the resource itself and runs FLUSHALL. As with the export command in Part 1, it is only enabled when the resource is healthy.

In the AppHost, using it looks like this:

var basketCache = builder.AddRedis("basketcache")
    .WithDataVolume()
    .WithRedisCommander()
    .WithClearCommand();

WithClearCommand() reads like a built-in feature. That is the point. Every Redis resource in every AppHost of my team can get this command with one line.

Remark: FLUSHALL removes the keys of all Redis databases, not only the ones of the basket service. That is fine for a local dev container. It is not something you want to expose against a shared instance.

Tip: Visibility = ResourceCommandVisibility.Api | ResourceCommandVisibility.UI controls where the command shows up. Here it is visible in the dashboard and available via the API, so it can be called from other surfaces too.

Compose commands, confirm the destructive ones

Now I combine both. A command can call other commands through ResourceCommandService:

builder.AddProject<Projects.AspireShop_Frontend>("frontend")
    // ...
    .WithCommand(
        name: "reset-shop-state",
        displayName: "Reset Shop State",
        executeCommand: async context =>
        {
            var commands = context.Services.GetRequiredService<ResourceCommandService>();
            var clearCacheResult = await commands.ExecuteCommandAsync(
                basketCache.Resource.Name,
                "clear-cache",
                context.CancellationToken);
            if (!clearCacheResult.Success)
            {
                return clearCacheResult;
            }

            return await commands.ExecuteCommandAsync(
                catalogDbManager.Resource.Name,
                "reset-db",
                context.CancellationToken);
        },
        commandOptions: new()
        {
            IconName = "ArrowReset",
            IsHighlighted = true,
            ConfirmationMessage = "This clears the Redis cache and deletes and recreates the catalog database. Continue?"
        })

A few choices I made in here:

  • Clear the cache first, then reset the database. If clearing the cache fails, I return that result and stop. I don't want a half-reset state.
  • The command lives on the frontend. It is the resource that represents the whole shop, so it's where I look for it. Which resource a command belongs to is a design choice.
  • ConfirmationMessage shows a dialog before anything runs. The message says exactly what will be destroyed.

Remark: name a destructive command for what it destroys, and never rely on a disabled button as your only guard. UpdateState is a convenience for the UI. It is not a safety mechanism.

That's it! One click (or one call) and the shop is back to a known state: empty basket, freshly seeded catalog. Combined with the export and test call commands from Part 1 and 2, the loop is almost closed. What's missing is one place to browse and try the API. For that, I build a custom resource in the next part.

More information

Popular posts from this blog

Podman– Command execution failed with exit code 125

After updating WSL on one of the developer machines, Podman failed to work. When we took a look through Podman Desktop, we noticed that Podman had stopped running and returned the following error message: Error: Command execution failed with exit code 125 Here are the steps we tried to fix the issue: We started by running podman info to get some extra details on what could be wrong: >podman info OS: windows/amd64 provider: wsl version: 5.3.1 Cannot connect to Podman. Please verify your connection to the Linux system using `podman system connection list`, or try `podman machine init` and `podman machine start` to manage a new Linux VM Error: unable to connect to Podman socket: failed to connect: dial tcp 127.0.0.1:2655: connectex: No connection could be made because the target machine actively refused it. That makes sense as the podman VM was not running. Let’s check the VM: >podman machine list NAME         ...

Cache stampede: when our cache turned against us

While investigating some performance issues, we ran into an ASP.NET Core API that cached a fairly expensive aggregation query for 60 seconds. Under normal load, that was fine: one request rebuilds the cache, everyone else reads from it. Under peak load, dozens of requests would arrive in that same expiry window, all see a cache miss, and all fire the same expensive query in parallel. The database didn't like that. That was the moment when our caching layer stopped helping and started hurting. A burst of requests comes in at the same time, all miss the cache, and all go hammer the database or the downstream API at once. That's a cache stampede . The cache was supposed to protect our backend, and for a few hundred milliseconds it did the opposite. Why this happens IMemoryCache.GetOrCreate (and its async sibling) looks like it protects you, but it doesn't add any locking on its own. Look at the naive version: public async Task<Report> GetReportAsync(string key) ...

VS Code Planning mode

After the introduction of Plan mode in Visual Studio , it now also found its way into VS Code. Planning mode, or as I like to call it 'Hannibal mode', extends GitHub Copilot's Agent Mode capabilities to handle larger, multi-step coding tasks with a structured approach. Instead of jumping straight into code generation, Planning mode creates a detailed execution plan. If you want more details, have a look at my previous post . Putting plan mode into action VS Code takes a different approach compared to Visual Studio when using plan mode. Instead of a configuration setting that you can activate but have limited control over, planning is available as a separate chat mode/agent: I like this approach better than how Visual Studio does it as you have explicit control when plan mode is activated. Instead of immediately diving into execution, the plan agent creates a plan and asks some follow up questions: You can further edit the plan by clicking on ‘Open in Editor’: ...