Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Last active December 19, 2024 16:38
Show Gist options
  • Save davidfowl/d544f054c147c054b5149fd91e47b91c to your computer and use it in GitHub Desktop.
Save davidfowl/d544f054c147c054b5149fd91e47b91c to your computer and use it in GitHub Desktop.
Wait to start command
using Microsoft.Extensions.DependencyInjection;
var builder = DistributedApplication.CreateBuilder(args);
builder.AddContainer("redis", "redis").WithExplicitStart();
builder.Build().Run();
public static class ExplicitStartupExtensions
{
public static IResourceBuilder<T> WithExplicitStart<T>(this IResourceBuilder<T> builder)
where T : IResource
{
// This will block the resource from starting until the start command is executed
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
builder.ApplicationBuilder.Eventing.Subscribe<BeforeResourceStartedEvent>(builder.Resource, async (evt, ct) =>
{
var rns = evt.Services.GetRequiredService<ResourceNotificationService>();
var startCommand = evt.Resource.Annotations.OfType<ResourceCommandAnnotation>().FirstOrDefault(c => c.Type == "resource-start");
if (startCommand is null)
{
return;
}
evt.Resource.Annotations.Remove(startCommand);
// Create a new command that clones the start command
var newCommand = new ResourceCommandAnnotation(
"resource-start",
startCommand.DisplayName,
context =>
{
if (!tcs.Task.IsCompleted)
{
return ResourceCommandState.Enabled;
}
return startCommand.UpdateState(context);
},
context =>
{
if (!tcs.Task.IsCompleted)
{
tcs.SetResult();
return Task.FromResult(CommandResults.Success());
}
return startCommand.ExecuteCommand(context);
},
startCommand.DisplayDescription,
startCommand.Parameter,
startCommand.ConfirmationMessage,
startCommand.IconName,
startCommand.IconVariant,
startCommand.IsHighlighted);
evt.Resource.Annotations.Add(newCommand);
await rns.PublishUpdateAsync(evt.Resource, s => s with { State = new(KnownResourceStates.Waiting, KnownResourceStateStyles.Info) });
await tcs.Task.WaitAsync(ct);
});
return builder;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment