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.
ConfirmationMessageshows 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.
