shoc-backend/Api.SeaHavenIndustries/HostedServices/UpliftLifecycleHostedService.cs
Alexandre Brandizzi 6ceb274bfb
Some checks failed
Validate and deploy / Validate deployable source bundle (push) Has been cancelled
Validate and deploy / Deploy shoc-backend-dev through Terraform (push) Has been cancelled
Validate and deploy / Deploy shoc-backend-staging to Elastic Beanstalk (push) Has been cancelled
feat: add API Sentry tracing (SH-298) (#105)
* feat: add API Sentry tracing

* feat: activate Sentry deployment environments

* fix: allow Sentry-free design-time tooling

* fix: trace background jobs in Sentry

* feat(observability): identify and scrub Sentry transactions

* fix(observability): finish abandoned transactions
2026-09-04 14:11:32 -03:00

68 lines
2.5 KiB
C#

using Api.SeaHavenIndustries.Observability;
using Microsoft.Extensions.Options;
using SeaHaven.Services.Configuration;
using SeaHaven.Services.Interfaces;
using Sentry;
namespace Api.SeaHavenIndustries.HostedServices
{
public class UpliftLifecycleHostedService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<UpliftLifecycleHostedService> _logger;
private readonly ApprovalsOptions _options;
private readonly IHub _sentryHub;
public UpliftLifecycleHostedService(
IServiceScopeFactory scopeFactory,
IOptions<ApprovalsOptions> options,
ILogger<UpliftLifecycleHostedService> logger,
IHub sentryHub)
{
_scopeFactory = scopeFactory;
_logger = logger;
_options = options.Value;
_sentryHub = sentryHub;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
{
using var transaction = SentryObservability.BeginBackgroundTransaction(
_sentryHub,
"uplifts.lifecycle-sweep",
$"{nameof(UpliftLifecycleHostedService)}.{nameof(SweepAsync)}");
try
{
await SweepAsync(stoppingToken);
transaction.FinishOk();
}
catch (OperationCanceledException)
{
transaction.FinishCancelled();
throw;
}
catch (Exception ex)
{
_logger.LogError(ex, "Uplift lifecycle sweep failed; will retry on next interval");
transaction.FinishError(ex);
}
}
await Task.Delay(_options.EffectiveSweepInterval, stoppingToken);
}
}
private async Task SweepAsync(CancellationToken cancellationToken)
{
using var scope = _scopeFactory.CreateScope();
var lifecycle = scope.ServiceProvider.GetRequiredService<IUpliftLifecycleService>();
await lifecycle.ExpireDueAsync(cancellationToken);
await lifecycle.SendDueInitialNotificationsAsync(cancellationToken);
await lifecycle.EscalateDueAsync(cancellationToken);
}
}
}