Skip to content

Conversation

@martinothamar
Copy link
Contributor

@martinothamar martinothamar commented Oct 28, 2025

Description

I think we want to gracefull shutdown in Staging++ (which means tt02 and prod mostly).
If we want to have process/next locks: Altinn/altinn-studio#16669
this means we can make it more unlikely to hit timeout/cancellation-related cases during rolling upgrades and such (let process/next complete and release any locks held in Storage)

image

Related Issue(s)

Verification

  • Your code builds clean without any errors or warnings
  • Manual testing done (required)
  • Relevant automated test added (if you find this hard, leave it and we'll help out)
  • All tests run green

Documentation

  • User documentation is updated with a separate linked PR in altinn-studio-docs. (if applicable)

Summary by CodeRabbit

  • New Features
    • Added graceful shutdown handling with configurable delays and timeout configuration.
    • Application now responds appropriately to system shutdown signals.
    • Improved application stability during shutdown sequences.

@martinothamar martinothamar added other A PR that should be in release notes, but as a chore backport-ignore This PR is a new feature and should not be cherry-picked onto release branches labels Oct 28, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 28, 2025

📝 Walkthrough

Walkthrough

The changes introduce graceful shutdown handling for the Altinn.App.Api application. A new AppHostLifetime class is created to intercept POSIX signals (SIGINT, SIGQUIT, SIGTERM) and execute graceful shutdown with configurable delays. The ServiceCollectionExtensions class registers this new lifetime handler during application service setup.

Changes

Cohort / File(s) Change Summary
Graceful Shutdown Infrastructure
src/Altinn.App.Api/Extensions/ServiceCollectionExtensions.cs, src/Altinn.App.Api/Infrastructure/Lifetime/AppHostLifetime.cs
Adds new using directive for Altinn.App.Api.Infrastructure.Lifetime. Introduces ConfigureGracefulShutdown method to register custom AppHostLifetime as singleton IHostLifetime with configurable shutdownDelay and shutdownTimeout. Creates new sealed AppHostLifetime class implementing IHostLifetime and IDisposable that registers POSIX signal handlers for graceful shutdown, logs signals, applies configured delays, and triggers host shutdown via IHostApplicationLifetime.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Signal handler registration and disposal logic requires careful verification for proper cleanup
  • Graceful shutdown delay and timeout configuration logic needs validation for edge cases
  • Dependency injection setup in service collection should be verified for correct lifecycle management

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Gracefully shutdown app" is directly and fully related to the main changes in the pull request. The PR introduces graceful shutdown functionality by adding signal handlers and shutdown delay logic through a new AppHostLifetime class and ConfigureGracefulShutdown configuration method. The title is concise, clear, and specific enough that teammates scanning the commit history would immediately understand this PR implements graceful shutdown behavior for the application. The title avoids vague terms, excessive detail, and noise, making it an effective summary of the primary change.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/graceful-shutdown

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@martinothamar
Copy link
Contributor Author

/publish

@github-actions
Copy link

github-actions bot commented Oct 28, 2025

PR release:

⚙️ Building...
✅ Done!

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
src/Altinn.App.Api/Infrastructure/Lifetime/AppHostLifetime.cs (3)

1-1: Remove unused using

System.Runtime.InteropServices isn’t used.

-using System.Runtime.InteropServices;

18-30: Add OS guard to avoid PlatformNotSupported on Windows

Only register POSIX signals on non-Windows OS. Keeps dev/test on Windows safe.

-    public Task WaitForStartAsync(CancellationToken cancellationToken)
+    public Task WaitForStartAsync(CancellationToken cancellationToken)
     {
-        if (!_environment.IsDevelopment())
+        if (!_environment.IsDevelopment() && !OperatingSystem.IsWindows())
         {
             _disposables =
             [
                 PosixSignalRegistration.Create(PosixSignal.SIGINT, HandleSignal),
                 PosixSignalRegistration.Create(PosixSignal.SIGQUIT, HandleSignal),
                 PosixSignalRegistration.Create(PosixSignal.SIGTERM, HandleSignal),
             ];
         }
         return Task.CompletedTask;
     }

32-42: Prevent multiple StopApplication calls and prefer async/await over ContinueWith

Make shutdown trigger idempotent and avoid ContinueWith; run the delayed stop on the thread pool.

-    private void HandleSignal(PosixSignalContext ctx)
+    private void HandleSignal(PosixSignalContext ctx)
     {
         _logger.LogInformation("Received shutdown signal: {Signal}, delaying shutdown", ctx.Signal);
         ctx.Cancel = true; // Signal intercepted here, we are now responsible for calling `StopApplication`
-        Task.Delay(_delay)
-            .ContinueWith(t =>
-            {
-                _logger.LogInformation("Starting host shutdown...");
-                _applicationLifetime.StopApplication();
-            });
+        _ = Task.Run(async () =>
+        {
+            await Task.Delay(_delay).ConfigureAwait(false);
+            if (Interlocked.Exchange(ref _stopRequested, 1) == 0)
+            {
+                _logger.LogInformation("Starting host shutdown...");
+                _applicationLifetime.StopApplication();
+            }
+        });
     }

Add this field near the top of the class:

private int _stopRequested;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4986803 and c472cc3.

📒 Files selected for processing (2)
  • src/Altinn.App.Api/Extensions/ServiceCollectionExtensions.cs (3 hunks)
  • src/Altinn.App.Api/Infrastructure/Lifetime/AppHostLifetime.cs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.cs

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.cs: Use internal accessibility on types by default
Use sealed for classes unless inheritance is a valid use-case
Dispose IDisposable/IAsyncDisposable instances
Do not use .GetAwaiter().GetResult(), .Result(), .Wait(), or other blocking APIs on Task
Do not use the Async suffix for async methods
Write efficient code; avoid unnecessary allocations (e.g., avoid repeated ToString calls; consider for-loops over LINQ when appropriate)
Do not invoke the same async operation multiple times in the same code path unless necessary
Avoid awaiting async operations inside tight loops; prefer batching with a sensible upper bound on parallelism
Use CSharpier for formatting (required before commits; formatting also runs on build via CSharpier.MSBuild)

Files:

  • src/Altinn.App.Api/Infrastructure/Lifetime/AppHostLifetime.cs
  • src/Altinn.App.Api/Extensions/ServiceCollectionExtensions.cs
**/*.{cs,csproj}

📄 CodeRabbit inference engine (CLAUDE.md)

Use Nullable Reference Types

Files:

  • src/Altinn.App.Api/Infrastructure/Lifetime/AppHostLifetime.cs
  • src/Altinn.App.Api/Extensions/ServiceCollectionExtensions.cs
src/{Altinn.App.Api,Altinn.App.Core}/**/*.cs

📄 CodeRabbit inference engine (CLAUDE.md)

src/{Altinn.App.Api,Altinn.App.Core}/**/*.cs: Types meant to be implemented by apps should be marked with the ImplementableByApps attribute
For HTTP APIs, define DTOs with ...Request and ...Response naming

Files:

  • src/Altinn.App.Api/Infrastructure/Lifetime/AppHostLifetime.cs
  • src/Altinn.App.Api/Extensions/ServiceCollectionExtensions.cs
🧬 Code graph analysis (1)
src/Altinn.App.Api/Extensions/ServiceCollectionExtensions.cs (1)
src/Altinn.App.Api/Infrastructure/Lifetime/AppHostLifetime.cs (1)
  • AppHostLifetime (7-49)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Analyze (csharp)
  • GitHub Check: Run dotnet build and test (macos-latest)
  • GitHub Check: Run dotnet build and test (ubuntu-latest)
  • GitHub Check: Static code analysis
  • GitHub Check: Run dotnet build and test (windows-latest)
🔇 Additional comments (1)
src/Altinn.App.Api/Extensions/ServiceCollectionExtensions.cs (1)

9-9: LGTM on namespace import

Import is correct and scoped to the new lifetime type.

Comment on lines +128 to +129
ConfigureGracefulShutdown(services);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Do not override ConsoleLifetime in Development; gate registration to tt02/prod

Registering a custom IHostLifetime unconditionally replaces ConsoleLifetime, which can break Ctrl+C handling locally. Limit registration to staging++ (tt02) and prod, and pass env to the helper.

Apply:

-        ConfigureGracefulShutdown(services);
+        ConfigureGracefulShutdown(services, env);

And update the helper signature and gating (see diff on the method below).

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/Altinn.App.Api/Extensions/ServiceCollectionExtensions.cs around lines
128-129, ConfigureGracefulShutdown(services) is registering a custom
IHostLifetime unconditionally which overrides ConsoleLifetime in Development;
change the call to accept the current environment and only register the custom
lifetime when the environment is tt02 or Production. Update the
ConfigureGracefulShutdown helper signature to accept IHostEnvironment (or
environment name) and move the conditional there so that in Development the
default ConsoleLifetime remains untouched while in tt02/prod the custom
IHostLifetime is added to the services.

Comment on lines +552 to +581

private static void ConfigureGracefulShutdown(IServiceCollection services)
{
// Need to coordinate graceful shutdown (let's assume k8s as the scheduler/runtime):
// - deployment is configured with a terminationGracePeriod of 30s (default timeout before SIGKILL)
// - k8s flow of information is eventually consistent.
// it takes time for knowledge of SIGTERM on the worker node to propagate to e.g. networking layers
// (k8s Service -> Endspoints rotation. It takes time to be taken out of Endpoint rotation)
// - we want to gracefully drain ASP.NET core for requests, leaving some time for active requests to complete
// This leaves us with the following sequence of events
// - container receives SIGTERM
// - `AppHostLifetime` intercepts SIGTERM and delays for `shutdownDelay`
// - `AppHostLifetime` calls `IHostApplicationLifetime.StopApplication`, to start ASP.NET Core shutdown process
// - ASP.NET Core will spend a maximum of `shutdownTimeout` trying to drain active requests
// (cancelable requests can combine cancellation tokens with `IHostApplicationLifetime.ApplicationStopping`)
// - If ASP.NET Core completes shutdown within `shutdownTimeout`, everything is fine
// - If ASP.NET Core is stuck or in some way can't terminate, kubelet will eventually SIGKILL
var shutdownDelay = TimeSpan.FromSeconds(5);
var shutdownTimeout = TimeSpan.FromSeconds(20);

services.AddSingleton<IHostLifetime>(serviceProvider =>
{
var logger = serviceProvider.GetRequiredService<ILogger<AppHostLifetime>>();
var env = serviceProvider.GetRequiredService<IHostEnvironment>();
var lifetime = serviceProvider.GetRequiredService<IHostApplicationLifetime>();
return new AppHostLifetime(logger, env, lifetime, shutdownDelay);
});

services.Configure<HostOptions>(options => options.ShutdownTimeout = shutdownTimeout);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Gate by environment; make idempotent values configurable; fix typo

  • Gate lifetime registration to staging++ (tt02) and Production only.
  • Consider configuring delay/timeout from config.
  • Minor: “Endspoints” -> “Endpoints”.
-    private static void ConfigureGracefulShutdown(IServiceCollection services)
+    private static void ConfigureGracefulShutdown(IServiceCollection services, IHostEnvironment env)
     {
-        // Need to coordinate graceful shutdown (let's assume k8s as the scheduler/runtime):
+        // Need to coordinate graceful shutdown (let's assume k8s as the scheduler/runtime):
         // - deployment is configured with a terminationGracePeriod of 30s (default timeout before SIGKILL)
         // - k8s flow of information is eventually consistent.
-        //   it takes time for knowledge of SIGTERM on the worker node to propagate to e.g. networking layers
-        //   (k8s Service -> Endspoints rotation. It takes time to be taken out of Endpoint rotation)
+        //   it takes time for knowledge of SIGTERM on the worker node to propagate to e.g. networking layers
+        //   (k8s Service -> Endpoints rotation. It takes time to be taken out of Endpoint rotation)
         // - we want to gracefully drain ASP.NET core for requests, leaving some time for active requests to complete
         // This leaves us with the following sequence of events
         // - container receives SIGTERM
         // - `AppHostLifetime` intercepts SIGTERM and delays for `shutdownDelay`
         // - `AppHostLifetime` calls `IHostApplicationLifetime.StopApplication`, to start ASP.NET Core shutdown process
         // - ASP.NET Core will spend a maximum of `shutdownTimeout` trying to drain active requests
         //   (cancelable requests can combine cancellation tokens with `IHostApplicationLifetime.ApplicationStopping`)
         // - If ASP.NET Core completes shutdown within `shutdownTimeout`, everything is fine
         // - If ASP.NET Core is stuck or in some way can't terminate, kubelet will eventually SIGKILL
-        var shutdownDelay = TimeSpan.FromSeconds(5);
-        var shutdownTimeout = TimeSpan.FromSeconds(20);
+        var shutdownDelay = TimeSpan.FromSeconds(
+            services.BuildServiceProvider().GetRequiredService<IConfiguration>()
+                .GetValue("GracefulShutdown:DelaySeconds", 5)
+        );
+        var shutdownTimeout = TimeSpan.FromSeconds(
+            services.BuildServiceProvider().GetRequiredService<IConfiguration>()
+                .GetValue("GracefulShutdown:TimeoutSeconds", 20)
+        );
 
-        services.AddSingleton<IHostLifetime>(serviceProvider =>
-        {
-            var logger = serviceProvider.GetRequiredService<ILogger<AppHostLifetime>>();
-            var env = serviceProvider.GetRequiredService<IHostEnvironment>();
-            var lifetime = serviceProvider.GetRequiredService<IHostApplicationLifetime>();
-            return new AppHostLifetime(logger, env, lifetime, shutdownDelay);
-        });
+        // Only wire up in staging++ (tt02) and Production to avoid replacing ConsoleLifetime in Development/test-like envs
+        if (IsStagingPlus(env))
+        {
+            services.AddSingleton<IHostLifetime>(serviceProvider =>
+            {
+                var logger = serviceProvider.GetRequiredService<ILogger<AppHostLifetime>>();
+                var lifetime = serviceProvider.GetRequiredService<IHostApplicationLifetime>();
+                return new AppHostLifetime(logger, env, lifetime, shutdownDelay);
+            });
+        }
 
         services.Configure<HostOptions>(options => options.ShutdownTimeout = shutdownTimeout);
     }
+
+    private static bool IsStagingPlus(IHostEnvironment env) =>
+        env.IsProduction() || string.Equals(env.EnvironmentName, "tt02", StringComparison.OrdinalIgnoreCase);

Committable suggestion skipped: line range outside the PR's diff.

@sonarqubecloud
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
48.1% Coverage on New Code (required ≥ 65%)
50.0% Condition Coverage on New Code (required ≥ 65%)

See analysis details on SonarQube Cloud

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-ignore This PR is a new feature and should not be cherry-picked onto release branches other A PR that should be in release notes, but as a chore

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants