Compare commits

...

22 Commits

Author SHA1 Message Date
8ff8a9e58b test: update SendingEmailPublisherTests to use new publisher builder API
Pass builder delegate to AddMessagingServicePublisher() calling
cfg.AddRabbitMqConnectionFactory(RabbitMqTestConfig.Apply).
2026-11-02 15:02:55 +01:00
8bbf6e1e3d chore(client): update EmailSender to use new publisher builder API
Pass builder delegate to AddMessagingServicePublisher() calling
cfg.AddRabbitMqConnectionFactory(configure) instead of passing
Action<RabbitMqConfiguration> directly.
2026-11-02 15:02:46 +01:00
376a22580b chore(api): update Program.cs to use new infrastructure builder API
- Update using directive to new DependencyInjection namespace
- Pass builder delegate to AddInfrastructure() calling
  cfg.AddRabbitMqConnectionFactory(builder.Configuration)
2026-11-02 15:02:36 +01:00
14cf8e8821 refactor(publisher): introduce MessagingServicePublisherConfiguration builder
Replace Action<RabbitMqConfiguration> parameter on AddMessagingServicePublisher()
with a builder to keep the publisher API consistent with the infrastructure layer.

- Add MessagingServicePublisherConfiguration exposing
  AddRabbitMqConnectionFactory() with IConfiguration and Action<T> overloads
- Callers that need RabbitMQ must now call cfg.AddRabbitMqConnectionFactory(...)
  inside the configure delegate instead of configuring RabbitMQ directly
2026-11-02 15:02:27 +01:00
5944823155 refactor(infrastructure): introduce MessagingServiceInfrastructureConfiguration builder
Replace the IConfiguration parameter on AddInfrastructure() with a builder
that makes RabbitMQ wiring explicit and validated.

- Add MessagingServiceInfrastructureConfiguration exposing
  AddRabbitMqConnectionFactory() with IConfiguration and Action<T> overloads
- EnsureRabbitMqConnectionFactoryAdded() throws at registration time if the
  caller omits the wiring step
- Remove the implicit services.AddRabbitMqConnectionFactory(configuration)
  call from AddInfrastructure(); callers must opt in via the builder
2026-11-02 15:02:17 +01:00
084ddc4b56 refactor(application): introduce MessagingServiceApplicationConfiguration builder
Replace the implicit IConfiguration-based DI registration with an explicit
builder that validates required steps at startup.

- Add MessagingServiceApplicationConfiguration with mandatory steps:
    SetLuckyPennySoftLicenseKey(), ConfigureEmailAccounts() / PublishOnly()
- EnsureConfigured() throws at registration time if either step is missing,
  surfacing misconfiguration before the app starts
- Keep the IConfiguration convenience overload as a thin wrapper over the
  builder for backward-compatible call sites
- Move DependencyInjection.cs into a DependencyInjection/ subfolder alongside
  the new configuration class
2026-11-02 15:02:07 +01:00
8e397d8119 fix(options): relax EmailAccountsOptions properties from init-only to set
init-only properties cannot be mutated by Options configure delegates.
Switching to set allows the builder pattern to bind values post-construction.
Also narrows Accounts type from IEnumerable to List for index access.
2026-11-02 15:01:56 +01:00
51732fa9fc feat(rabbitmq): add optional sectionName param to AddRabbitMqConnectionFactory
Allow callers to bind RabbitMQ config from a non-default section name.
Defaults to RabbitMqConfiguration.SectionName to keep existing callers working.
2026-11-02 15:01:46 +01:00
9bd100c0c5 Rename service registration method for clarity
Renamed the method in `DependencyInjection.cs` from `AddApplicationServices` to `AddMessagingServiceApplication` to better reflect its purpose related to the Messaging Service Application. Updated the corresponding method call in `Program.cs` to ensure consistency and correct service registration.
2026-11-02 10:52:37 +01:00
31932d6c3b chore: add Limilabs Mail.dll license file
Store the commercial Mail.dll license alongside the infrastructure project. The file is not referenced by the csproj, so it is not copied to build output automatically.
2026-11-02 10:11:35 +01:00
efdd5805d3 test(client): await async EmailSender.Send in integration tests
Record.Exception does not observe faults from an async method. Convert the affected tests to async Task and use Record.ExceptionAsync so publish failures are actually asserted.
2026-11-02 10:11:31 +01:00
11ba3cdac4 refactor(client)!: return Task from EmailSender.Send
Await ISendingEmailPublisher.EnqueueAsync so publish failures surface to the caller instead of being lost in a fire-and-forget call.

BREAKING CHANGE: EmailSender.Send now returns Task and must be awaited. Synchronous callers that relied on exceptions being thrown directly from Send will no longer observe them.
2026-11-02 10:11:27 +01:00
afc1a434db build(client): bundle referenced assemblies into the NuGet package
Make the client package self-contained:

- Set IsPackable and keep project references private
- Add direct Application and Domain references needed at compile time
- Add EmbedProjectReferences target so referenced assemblies ship inside the package
- Reference System.Text.Json for .NET Framework targets
- Reference Options.ConfigurationExtensions explicitly
- Bump package version to 1.0.5
2026-11-02 10:11:23 +01:00
5ba650356a chore(api): bump version to 2.1.0-beta
Version bump for the health check endpoint and dashboard release.
2026-11-02 10:11:19 +01:00
292b6e9f36 feat(api): expose /health endpoint and health dashboard
Wire the infrastructure health checks into ASP.NET Core:

- /health returns JSON via UIResponseWriter and maps Unhealthy to HTTP 503
- /health-ui renders a Razor Pages dashboard with per-check status, description, tags and duration
- Tag health checks (rabbitmq, workers, ready, live) for monitoring filters
- Link the dashboard from the Swagger description and the page layout
2026-11-02 10:11:14 +01:00
2fdc8982aa feat(infrastructure): publish worker status to health checks
ConsumerInitWorker marks ConsumerInitHealthCheck as unhealthy when the consumer pool fails to start, so callers receive HTTP 503 instead of a silently degraded service.

EmailSyncWorker now reports its startup interval and the result of every sync cycle. SyncAccountAsync returns whether the account failed, letting the worker count errors per cycle and expose them through EmailSyncWorkerHealthCheck.
2026-11-02 10:10:55 +01:00
be881ea7c9 feat(infrastructure): add health checks for RabbitMQ and email sync worker
Introduce singleton health checks that background workers update at runtime:

- ConsumerInitHealthCheck reports whether the RabbitMQ consumer pool started
- RabbitMqConnectionHealthCheck opens a channel to verify broker reachability
- EmailSyncWorkerHealthCheck detects stalled or erroring sync cycles

Register all three in the infrastructure DI container so the API layer can wire them into the health check pipeline.
2026-11-02 10:10:51 +01:00
76fc005b02 Replace AsyncInitWorker with ConsumerInitWorker
Replaced the `AsyncInitWorker` background service with the new `ConsumerInitWorker`, which introduces enhanced error handling, logging, and configurability for RabbitMQ consumer initialization.

Updated `MessagingServiceDbContext` to remove the `UseCollation` configuration for the `Username` property in the `EmailAccount` entity, ensuring compatibility with the InMemory database.

Added the `ContinueOnInitFailure` property to `RabbitMqConfiguration` to allow the application to continue running if RabbitMQ consumer initialization fails.

Cleaned up unused `using` directives in `DependencyInjection.cs` and removed the obsolete `AsyncInitWorker` class.
2026-08-18 16:38:25 +02:00
26c78d32ae Remove encryption service and related configurations
The `IEncryptionService` interface and its implementation,
`DataProtectionEncryptionService`, have been removed from the
codebase. These components previously provided encryption and
decryption functionality using the ASP.NET Core Data Protection API.

Additionally, the dependency injection setup for the encryption
service and the Data Protection API configuration (e.g., key
persistence and application name) have been removed from
`DependencyInjection.cs`.
2026-08-18 15:49:44 +02:00
57ba948fe6 Update base path for configuration loading
Replaced `Directory.GetCurrentDirectory()` with `AppContext.BaseDirectory` in `Program.cs` to set the base path for configuration loading. This ensures configuration files are loaded relative to the application's runtime location instead of the current working directory.
2026-08-18 15:49:30 +02:00
8450806916 Refactor email fetching and handling logic
Consolidated email fetching queries into a unified `ReadEmailQuery` to support multiple protocols (IMAP, IMAP OAuth2, POP3) dynamically. Removed redundant query handlers (`ReadEmailViaImapQuery`, `ReadEmailViaOAuth2Query`, `ReadEmailViaPop3Query`) and merged their functionality into `ReadEmailQueryHandler` with protocol-specific methods.

Updated `FetchEmailsQueryValidator` to validate the new query. Refactored `EmailController` to use the unified query, simplifying endpoints and consolidating functionality. Removed obsolete endpoints for POP3 and OAuth2 fetching.

Performed code cleanup, including removing redundant imports and consolidating attachment handling logic. Updated project version to `2.0.0-beta` to reflect these significant changes. Improved documentation to align with the new structure.
2026-08-18 15:26:21 +02:00
acf40684f8 refactor: rename ReadEmailQuery to ReadEmailViaImapQuery, rename PublishEmailCommand to PublishEmailViaSmtpCommand 2026-08-17 17:03:59 +02:00
39 changed files with 817 additions and 507 deletions

View File

@@ -1,10 +0,0 @@
namespace DigitalData.MessagingService.Application.Common.Interfaces;
/// <summary>
/// Encryption service interface for password encryption.
/// </summary>
public interface IEncryptionService
{
string Encrypt(string plainText);
string Decrypt(string cipherText);
}

View File

@@ -16,7 +16,7 @@ public class EmailMappingProfile : Profile
{
// PublishEmailCommand -> Email
// Sender is resolved via MediatR in the handler and set separately after mapping.
CreateMap<PublishEmailCommand, EmailContext>()
CreateMap<PublishEmailViaSmtpCommand, EmailContext>()
.ForMember(dest => dest.Sender, opt => opt.Ignore())
.ForMember(dest => dest.Attachments, opt => opt.MapFrom(src => src.Attachments));

View File

@@ -17,18 +17,18 @@ public class EmailAccountsOptions
/// <summary>
/// The list of configured email accounts.
/// </summary>
public required IEnumerable<EmailAccountModificationDto> Accounts { get; init; } = [];
public required List<EmailAccountModificationDto> Accounts { get; set; } = [];
/// <summary>
/// How often the IMAP sync worker polls for new emails, in seconds.
/// Defaults to 300 seconds (5 minutes).
/// </summary>
public int SyncIntervalSeconds { get; init; } = 300;
public int SyncIntervalSeconds { get; set; } = 300;
/// <summary>
/// The minimum interval, in seconds, between forced IMAP sync operations regardless of idle state.
/// Defaults to 30 seconds (0.5 minute).
/// </summary>
public int ForcedSyncIntervalSeconds { get; init; } = 30;
public int ForcedSyncIntervalSeconds { get; set; } = 30;
}
#endif

View File

@@ -1,46 +0,0 @@
#if NET
using DigitalData.MessagingService.Application.Common.Options;
using FluentValidation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
namespace DigitalData.MessagingService.Application;
/// <summary>
/// Dependency injection configuration for Application layer.
/// </summary>
public static class DependencyInjection
{
public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration configuration)
{
var assembly = Assembly.GetExecutingAssembly();
// Read LuckyPennySoft license key from appsettings.json
var licenseKey = configuration.GetValue<string>("LuckyPennySoftLicenseKey")
?? throw new InvalidOperationException("LuckyPennySoftLicenseKey not found in configuration");
// MediatR - Register all handlers
services.AddMediatR(config =>
{
config.LicenseKey = licenseKey;
config.RegisterServicesFromAssembly(assembly);
});
// AutoMapper - Use built-in DI extension (AutoMapper 16.2.0+)
services.AddAutoMapper(config =>
{
config.LicenseKey = licenseKey;
config.AddMaps(assembly);
});
// FluentValidation - Register all validators
services.AddValidatorsFromAssembly(assembly);
// Register EmailAccounts configuration (IOptions<EmailAccountsOptions>)
services.Configure<EmailAccountsOptions>(configuration.GetSection(EmailAccountsOptions.SectionName));
return services;
}
}
#endif

View File

@@ -0,0 +1,51 @@
#if NET
using FluentValidation;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
namespace DigitalData.MessagingService.Application.DependencyInjection;
/// <summary>
/// Dependency injection configuration for Application layer.
/// </summary>
public static class DependencyInjection
{
public static IServiceCollection AddMessagingServiceApplication(this IServiceCollection services, Action<MessagingServiceApplicationConfiguration> configure)
{
var assembly = Assembly.GetExecutingAssembly();
var configuration = new MessagingServiceApplicationConfiguration(services);
configure(configuration);
configuration.EnsureConfigured();
// MediatR - Register all handlers
services.AddMediatR(config =>
{
config.LicenseKey = configuration.LuckyPennySoftLicenseKey;
config.RegisterServicesFromAssembly(assembly);
});
// AutoMapper - Use built-in DI extension (AutoMapper 16.2.0+)
services.AddAutoMapper(config =>
{
config.LicenseKey = configuration.LuckyPennySoftLicenseKey;
config.AddMaps(assembly);
});
// FluentValidation - Register all validators
services.AddValidatorsFromAssembly(assembly);
return services;
}
public static IServiceCollection AddMessagingServiceApplication(this IServiceCollection services, IConfiguration configuration)
{
return services.AddMessagingServiceApplication(cfg =>
{
cfg.SetLuckyPennySoftLicenseKey(configuration);
cfg.ConfigureEmailAccounts(configuration);
});
}
}
#endif

View File

@@ -0,0 +1,78 @@
#if NET
using DigitalData.MessagingService.Application.Common.Options;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DigitalData.MessagingService.Application.DependencyInjection;
public partial class MessagingServiceApplicationConfiguration
{
private IServiceCollection Services { get; }
private (bool LuckyPennySoftLicenseKey, bool EmailAccounts) _configured = (LuckyPennySoftLicenseKey: false, EmailAccounts: false);
internal MessagingServiceApplicationConfiguration(IServiceCollection services)
{
Services = services;
}
internal void EnsureConfigured()
{
if (!_configured.LuckyPennySoftLicenseKey)
{
throw new InvalidOperationException("LuckyPennySoftLicenseKey is not configured. Please call SetLuckyPennySoftLicenseKey() or SetLuckyPennySoftLicenseKey(IConfiguration) in DI configuration.");
}
if (!_configured.EmailAccounts)
{
throw new InvalidOperationException("EmailAccountsOptions is not configured. Please call ConfigureEmailAccountsOptions() or ConfigureEmailAccounts(IConfiguration) in DI configuration.");
}
}
#region LuckyPennySoftLicenseKey
internal string? LuckyPennySoftLicenseKey { get; set; } = null;
public MessagingServiceApplicationConfiguration SetLuckyPennySoftLicenseKey(string licenseKey)
{
if (string.IsNullOrWhiteSpace(licenseKey))
throw new InvalidOperationException("LuckyPennySoftLicenseKey is not configured. Please call SetLuckyPennySoftLicenseKey() or SetLuckyPennySoftLicenseKey(IConfiguration) in DI configuration.");
LuckyPennySoftLicenseKey = licenseKey;
_configured.LuckyPennySoftLicenseKey = true;
return this;
}
public MessagingServiceApplicationConfiguration SetLuckyPennySoftLicenseKey(IConfiguration configuration, string key = "LuckyPennySoftLicenseKey")
{
return SetLuckyPennySoftLicenseKey(configuration.GetValue<string>(key) ?? string.Empty);
}
#endregion LuckyPennySoftLicenseKey
#region EmailAccountsOptions
/// <summary>
/// Ignores whether EmailAccountsOptions is configured or not. Use this method if you just want to publish messages to the messaging service; not to send
/// emails. If you want to consume the messaging service to send emails, you must configure EmailAccountsOptions using ConfigureEmailAccountsOptions() or
/// ConfigureEmailAccounts(IConfiguration).
/// </summary>
/// <returns></returns>
public MessagingServiceApplicationConfiguration PublishOnly()
{
_configured.EmailAccounts = true;
return this;
}
public MessagingServiceApplicationConfiguration ConfigureEmailAccountsOptions(Action<EmailAccountsOptions> configureOptions)
{
Services.Configure(configureOptions);
_configured.EmailAccounts = true;
return this;
}
public MessagingServiceApplicationConfiguration ConfigureEmailAccounts(IConfiguration configuration, string sectionName = EmailAccountsOptions.SectionName)
{
Services.Configure<EmailAccountsOptions>(configuration.GetSection(sectionName));
_configured.EmailAccounts = true;
return this;
}
#endregion EmailAccountsOptions
}
#endif

View File

@@ -6,6 +6,7 @@ using DigitalData.MessagingService.Application.Common.Interfaces;
using DigitalData.MessagingService.Application.Common.Interfaces.Repositories;
using DigitalData.MessagingService.Application.EmailAccounts.Queries;
using DigitalData.MessagingService.Domain.Entities;
using DigitalData.MessagingService.Domain.Enums;
using DigitalData.MessagingService.Domain.Exceptions;
using MediatR;
using Microsoft.Extensions.Logging;
@@ -13,7 +14,8 @@ using Microsoft.Extensions.Logging;
namespace DigitalData.MessagingService.Application.EmailReceiving.Queries;
/// <summary>
/// Query to fetch emails from an IMAP mailbox.
/// Query to fetch emails from an email account.
/// The protocol and authentication method are determined by <see cref="EmailAccount.IncomingProtocol"/>.
/// </summary>
public record ReadEmailQuery : IRequest<ReadEmailQueryResponse>
{
@@ -28,25 +30,90 @@ public record ReadEmailQuery : IRequest<ReadEmailQueryResponse>
public MailSearchFilter Mail { get; init; } = new();
}
public class ReadEmailQueryHandler(IMapper Mapper, ILogger<ReadEmailQueryHandler> Logger, IRepository<EmailAccount> EmailAccountRepo, IReceivedEmailRepository MailRepo, IImapEmailService imapEmailService) : IRequestHandler<ReadEmailQuery, ReadEmailQueryResponse>
public class ReadEmailQueryHandler(
IMapper Mapper,
ILogger<ReadEmailQueryHandler> Logger,
IRepository<EmailAccount> EmailAccountRepo,
IReceivedEmailRepository MailRepo,
IImapEmailService ImapEmailService,
IPop3EmailService Pop3EmailService) : IRequestHandler<ReadEmailQuery, ReadEmailQueryResponse>
{
public async Task<ReadEmailQueryResponse> Handle(ReadEmailQuery request, CancellationToken cancellationToken)
{
var accounts = await EmailAccountRepo.FindAsync(request.Account.Id is int id ? x => x.Id == id : x => x.Username == request.Account.Username, cancellationToken: cancellationToken);
var accounts = await EmailAccountRepo.FindAsync(
request.Account.Id is int id ? x => x.Id == id : x => x.Username == request.Account.Username,
cancellationToken: cancellationToken);
if (accounts.Count() > 1)
Logger.LogWarning("Multiple email accounts found for the given criteria ({Criteria}). Returning the first one.", request.Account.Id is not null ? $"Id: {request.Account.Id}" : $"Username: {request.Account.Username}");
Logger.LogWarning("Multiple email accounts found for the given criteria ({Criteria}). Returning the first one.",
request.Account.Id is not null ? $"Id: {request.Account.Id}" : $"Username: {request.Account.Username}");
var account = accounts.FirstOrDefault()
?? throw new NotFoundException($"No email account found for the given criteria (Id: {request.Account.Id}, Username: {request.Account.Username}).");
return account.IncomingProtocol switch
{
IncomingProtocol.Imap => await HandleImapAsync(account, request.Mail, cancellationToken),
IncomingProtocol.ImapOAuth2 => await HandleImapOAuth2Async(account, request.Mail, cancellationToken),
IncomingProtocol.Pop3 => await HandlePop3Async(account, request.Mail, cancellationToken),
IncomingProtocol.Pop3OAuth2 => throw new NotImplementedException(
$"POP3 OAuth2 is not yet supported. Account: '{account.Username}' (Id: {account.Id})."),
IncomingProtocol.None => throw new BadRequestException(
$"Account '{account.Username}' (Id: {account.Id}) has no incoming protocol configured (IncomingProtocol = None)."),
_ => throw new BadRequestException(
$"Unknown IncomingProtocol value '{account.IncomingProtocol}' for account '{account.Username}' (Id: {account.Id}).")
};
}
private async Task<ReadEmailQueryResponse> HandleImapAsync(EmailAccount account, MailSearchFilter filter, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(account.ImapServer))
throw new BadRequestException(
$"IMAP is not configured for account '{account.Username}' (Id: {account.Id}). Set ImapServer in EmailAccounts configuration.");
var mails = await MailRepo.FindAsync(filter, account, cancellationToken);
var lastSync = ImapEmailService.GetLastImapSyncDate(account.Id, filter.Folder);
return new ReadEmailQueryResponse
{
LastSync = lastSync,
Emails = Mapper.Map<IEnumerable<ReceivedEmailDto>>(mails)
};
}
private async Task<ReadEmailQueryResponse> HandleImapOAuth2Async(EmailAccount account, MailSearchFilter filter, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(account.OAuth2ClientId) || string.IsNullOrWhiteSpace(account.OAuth2ClientSecret))
throw new BadRequestException(
$"OAuth2 credentials (ClientId, ClientSecret) are not configured for account '{account.Username}' (Id: {account.Id}).");
if (string.IsNullOrWhiteSpace(account.ImapServer))
throw new BadRequestException(
$"IMAP is not configured for account '{account.Username}' (Id: {account.Id}). Set ImapServer in EmailAccounts configuration.");
var mails = await MailRepo.FindAsync(request.Mail, account, cancellationToken);
var mails = await MailRepo.FindAsync(filter, account, cancellationToken);
var lastSync = ImapEmailService.GetLastImapSyncDate(account.Id, filter.Folder);
var lastSync = imapEmailService.GetLastImapSyncDate(account.Id, request.Mail.Folder);
return new ReadEmailQueryResponse
{
LastSync = lastSync,
Emails = Mapper.Map<IEnumerable<ReceivedEmailDto>>(mails)
};
}
private async Task<ReadEmailQueryResponse> HandlePop3Async(EmailAccount account, MailSearchFilter filter, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(account.Pop3Server))
throw new BadRequestException(
$"POP3 is not configured for account '{account.Username}' (Id: {account.Id}). Set Pop3Server in EmailAccounts configuration.");
// Trigger on-demand POP3 sync before querying local storage
await Pop3EmailService.SyncEmailsAsync(account, cancellationToken);
// POP3 has no folder concept — always query INBOX
var pop3Filter = filter with { Folder = "INBOX" };
var mails = await MailRepo.FindAsync(pop3Filter, account, cancellationToken);
var lastSync = Pop3EmailService.GetLastPop3SyncDate(account.Id);
return new ReadEmailQueryResponse
{
@@ -55,4 +122,4 @@ public class ReadEmailQueryHandler(IMapper Mapper, ILogger<ReadEmailQueryHandler
};
}
}
#endif
#endif

View File

@@ -1,77 +0,0 @@
#if NET
using AutoMapper;
using DigitalData.MessagingService.Application.Common.Dto;
using DigitalData.MessagingService.Application.Common.Dto.MailSearch;
using DigitalData.MessagingService.Application.Common.Interfaces;
using DigitalData.MessagingService.Application.Common.Interfaces.Repositories;
using DigitalData.MessagingService.Application.EmailAccounts.Queries;
using DigitalData.MessagingService.Application.EmailReceiving.Queries;
using DigitalData.MessagingService.Domain.Entities;
using DigitalData.MessagingService.Domain.Exceptions;
using MediatR;
using Microsoft.Extensions.Logging;
namespace DigitalData.MessagingService.Application.EmailReceiving.Queries;
/// <summary>
/// Query to fetch emails from an IMAP mailbox using OAuth2 authentication.
/// The account must have <c>UseOAuth2 = true</c> and valid OAuth2 credentials configured.
/// </summary>
public record ReadEmailViaOAuth2Query : IRequest<ReadEmailQueryResponse>
{
/// <summary>
/// Identifies the email account to use.
/// </summary>
public required GetEmailAccountQuery Account { get; init; }
/// <summary>
/// Mail query used to filter and limit the emails retrieved.
/// </summary>
public MailSearchFilter Mail { get; init; } = new();
}
public class ReadEmailViaOAuth2QueryHandler(
IMapper Mapper,
ILogger<ReadEmailViaOAuth2QueryHandler> Logger,
IRepository<EmailAccount> EmailAccountRepo,
IReceivedEmailRepository MailRepo,
IImapEmailService imapEmailService) : IRequestHandler<ReadEmailViaOAuth2Query, ReadEmailQueryResponse>
{
public async Task<ReadEmailQueryResponse> Handle(ReadEmailViaOAuth2Query request, CancellationToken cancellationToken)
{
var accounts = await EmailAccountRepo.FindAsync(
request.Account.Id is int id ? x => x.Id == id : x => x.Username == request.Account.Username,
cancellationToken: cancellationToken);
if (accounts.Count() > 1)
Logger.LogWarning("Multiple email accounts found ({Criteria}). Using first.",
request.Account.Id is not null ? $"Id: {request.Account.Id}" : $"Username: {request.Account.Username}");
var account = accounts.FirstOrDefault()
?? throw new NotFoundException($"No email account found (Id: {request.Account.Id}, Username: {request.Account.Username}).");
if (!account.UseOAuth2)
throw new BadRequestException(
$"Account '{account.Username}' (Id: {account.Id}) is not configured for OAuth2. Set UseOAuth2 = true.");
if (string.IsNullOrWhiteSpace(account.OAuth2ClientId) ||
string.IsNullOrWhiteSpace(account.OAuth2ClientSecret))
throw new BadRequestException(
$"OAuth2 credentials (ClientId, ClientSecret) are not configured for account '{account.Username}'.");
if (string.IsNullOrWhiteSpace(account.ImapServer))
throw new BadRequestException(
$"IMAP is not configured for account '{account.Username}' (Id: {account.Id}). Set ImapServer in EmailAccounts configuration.");
var mails = await MailRepo.FindAsync(request.Mail, account, cancellationToken);
var lastSync = imapEmailService.GetLastImapSyncDate(account.Id, request.Mail.Folder);
return new ReadEmailQueryResponse
{
LastSync = lastSync,
Emails = Mapper.Map<IEnumerable<ReceivedEmailDto>>(mails)
};
}
}
#endif

View File

@@ -1,74 +0,0 @@
#if NET
using AutoMapper;
using DigitalData.MessagingService.Application.Common.Dto;
using DigitalData.MessagingService.Application.Common.Dto.MailSearch;
using DigitalData.MessagingService.Application.Common.Interfaces;
using DigitalData.MessagingService.Application.Common.Interfaces.Repositories;
using DigitalData.MessagingService.Application.EmailAccounts.Queries;
using DigitalData.MessagingService.Application.EmailReceiving.Queries;
using DigitalData.MessagingService.Domain.Entities;
using DigitalData.MessagingService.Domain.Exceptions;
using MediatR;
using Microsoft.Extensions.Logging;
namespace DigitalData.MessagingService.Application.EmailReceiving.Queries;
/// <summary>
/// Query to fetch emails from a POP3 mailbox.
/// Triggers an on-demand sync and returns stored results filtered by <see cref="Mail"/>.
/// </summary>
public record ReadEmailViaPop3Query : IRequest<ReadEmailQueryResponse>
{
/// <summary>
/// Identifies the email account to use.
/// </summary>
public required GetEmailAccountQuery Account { get; init; }
/// <summary>
/// Mail query used to filter and limit the emails retrieved from local storage.
/// Note: POP3 has no folder concept — all messages are stored under "INBOX".
/// </summary>
public MailSearchFilter Mail { get; init; } = new();
}
public class ReadEmailViaPop3QueryHandler(
IMapper Mapper,
ILogger<ReadEmailViaPop3QueryHandler> Logger,
IRepository<EmailAccount> EmailAccountRepo,
IReceivedEmailRepository MailRepo,
IPop3EmailService pop3EmailService) : IRequestHandler<ReadEmailViaPop3Query, ReadEmailQueryResponse>
{
public async Task<ReadEmailQueryResponse> Handle(ReadEmailViaPop3Query request, CancellationToken cancellationToken)
{
var accounts = await EmailAccountRepo.FindAsync(
request.Account.Id is int id ? x => x.Id == id : x => x.Username == request.Account.Username,
cancellationToken: cancellationToken);
if (accounts.Count() > 1)
Logger.LogWarning("Multiple email accounts found ({Criteria}). Using first.",
request.Account.Id is not null ? $"Id: {request.Account.Id}" : $"Username: {request.Account.Username}");
var account = accounts.FirstOrDefault()
?? throw new NotFoundException($"No email account found (Id: {request.Account.Id}, Username: {request.Account.Username}).");
if (string.IsNullOrWhiteSpace(account.Pop3Server))
throw new BadRequestException(
$"POP3 is not configured for account '{account.Username}' (Id: {account.Id}). Set Pop3Server in EmailAccounts configuration.");
// Trigger on-demand POP3 sync before querying local storage
await pop3EmailService.SyncEmailsAsync(account, cancellationToken);
// POP3 has no folder concept — always query INBOX
var filter = request.Mail with { Folder = "INBOX" };
var mails = await MailRepo.FindAsync(filter, account, cancellationToken);
var lastSync = pop3EmailService.GetLastPop3SyncDate(account.Id);
return new ReadEmailQueryResponse
{
LastSync = lastSync,
Emails = Mapper.Map<IEnumerable<ReceivedEmailDto>>(mails)
};
}
}
#endif

View File

@@ -15,7 +15,7 @@ namespace DigitalData.MessagingService.Application.EmailSending.Commands;
/// <summary>
/// Command to send an email (enqueue to RabbitMQ)
/// </summary>
public record PublishEmailCommand : IRequest<Guid>
public record PublishEmailViaSmtpCommand : IRequest<Guid>
{
public required GetEmailAccountQuery Sender { get; init; }
@@ -46,7 +46,7 @@ public record PublishEmailCommand : IRequest<Guid>
/// Returns a new command instance with the supplied attachments.
/// Called by the controller after resolving uploaded files.
/// </summary>
public PublishEmailCommand WithAttachments(IEnumerable<EmailAttachmentDto> attachments)
public PublishEmailViaSmtpCommand WithAttachments(IEnumerable<EmailAttachmentDto> attachments)
=> this with { Attachments = attachments };
}
@@ -54,9 +54,9 @@ public record PublishEmailCommand : IRequest<Guid>
/// Handler for PublishEmailCommand
/// Resolves the sender account via MediatR, maps to SendingEmailEvent and enqueues to RabbitMQ
/// </summary>
public class PublishEmailCommandHandler(IRepository<EmailAccount> Repo, ISendingEmailPublisher Publisher, IMapper Mapper, ILogger<PublishEmailCommandHandler> Logger) : IRequestHandler<PublishEmailCommand, Guid>
public class PublishEmailViaSmtpCommandHandler(IRepository<EmailAccount> Repo, ISendingEmailPublisher Publisher, IMapper Mapper, ILogger<PublishEmailViaSmtpCommandHandler> Logger) : IRequestHandler<PublishEmailViaSmtpCommand, Guid>
{
public async Task<Guid> Handle(PublishEmailCommand request, CancellationToken cancellationToken)
public async Task<Guid> Handle(PublishEmailViaSmtpCommand request, CancellationToken cancellationToken)
{
var senderAccounts = await Repo.FindAsync(request.Sender.Id is int id ? x => x.Id == id : x => x.Username == request.Sender.Username, cancellationToken: cancellationToken);

View File

@@ -7,7 +7,7 @@ namespace DigitalData.MessagingService.Application.EmailSending.Validators;
/// <summary>
/// Validator for PublishEmailCommand
/// </summary>
public class PublishEmailCommandValidator : AbstractValidator<PublishEmailCommand>
public class PublishEmailCommandValidator : AbstractValidator<PublishEmailViaSmtpCommand>
{
public PublishEmailCommandValidator()
{

View File

@@ -1,4 +1,3 @@
using AutoMapper;
using DigitalData.MessagingService.Application.Common.Interfaces;
using DigitalData.MessagingService.Application.Common.Interfaces.Repositories;
using DigitalData.MessagingService.Infrastructure.Mappings;
@@ -8,10 +7,7 @@ using DigitalData.MessagingService.Infrastructure.Repositories;
using DigitalData.MessagingService.Infrastructure.Services;
using DigitalData.MessagingService.Infrastructure.Services.Background;
using DigitalData.MessagingService.Publisher;
using DigitalData.MessagingService.RabbitMQ;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
@@ -25,10 +21,12 @@ public static class DependencyInjection
/// <summary>
/// Adds Infrastructure layer services to the DI container
/// </summary>
public static IServiceCollection AddInfrastructure(
this IServiceCollection services,
IConfiguration configuration)
public static IServiceCollection AddInfrastructure(this IServiceCollection services, Action<MessagingServiceInfrastructureConfiguration> configure)
{
var configuration = new MessagingServiceInfrastructureConfiguration(services);
configure.Invoke(configuration);
configuration.EnsureRabbitMqConnectionFactoryAdded();
// --- External Services ---
// OAuth2 token services — provider-specific implementations registered separately,
// dispatcher is the single IOAuth2TokenService consumed by all other services.
@@ -53,23 +51,19 @@ public static class DependencyInjection
// PDF Processing Service (using DevExpress.Pdf)
services.AddScoped<IPdfProcessingService, DevExpressPdfProcessingService>();
// Encryption Service (using Data Protection API - Singleton, thread-safe)
services.AddSingleton<IEncryptionService, DataProtectionEncryptionService>();
// --- Email Queue (RabbitMQ) ---
services.AddSingleton<SendingEmailConsumerPool>();
services.AddMessagingServicePublisher();
// --- RabbitMQ Configuration ---
services.AddRabbitMqConnectionFactory(configuration);
// --- Data Protection (for encryption) ---
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"C:\ProgramData\EmailService\Keys"))
.SetApplicationName("MessagingService");
// ConsumerInitHealthCheck, RabbitMqConnectionHealthCheck and EmailSyncWorkerHealthCheck are
// registered as singletons here so background workers can inject and update them.
// Health check pipeline is wired up in the API layer via AddHealthChecks().
services.AddSingleton<ConsumerInitHealthCheck>();
services.AddSingleton<RabbitMqConnectionHealthCheck>();
services.AddSingleton<EmailSyncWorkerHealthCheck>();
// Register Background Workers
services.AddHostedService<AsyncInitWorker>();
services.AddHostedService<ConsumerInitWorker>();
services.AddHostedService<EmailSyncWorker>();
services.AddSingleton<IEmailSyncService>(p =>
@@ -82,8 +76,7 @@ public static class DependencyInjection
services.AddMemoryCache();
// --- Database (InMemory) ---
services.AddDbContext<MessagingServiceDbContext>(options =>
options.UseInMemoryDatabase("MessagingServiceDb"));
services.AddDbContext<MessagingServiceDbContext>(options => options.UseInMemoryDatabase("MessagingServiceDb"));
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
@@ -94,5 +87,4 @@ public static class DependencyInjection
return services;
}
}
}

View File

@@ -22,6 +22,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="8.0.11" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.10" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.10" />

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<License>
<Id>4dc5ef40-f1a9-468b-994c-b7ed600ad878</Id>
<ProductName>Mail.dll</ProductName>
<SubscriptionUntil>2022-07-29</SubscriptionUntil>
<RegisteredTo>Digital Data GmbH</RegisteredTo>
<LicenseType>single developer</LicenseType>
<BuyerName>Digital Data GmbH</BuyerName>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>75MRtl4ipYelIZYlpT8O7QDX9Zc=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>Raxfkz6DfQVs/sMvH+F2nH0eHXD8FoUFSdP3t7AgBUdpABJQx86srlyuMSEhXPlc1THCqPouEVob4RsWnd9OXvTiPPSOUSK9zuNG6uz93KLAhpSD5PraAgBCF4jwZArlAp7aCNfZpHqQ3w6TRHS+CfravUU0AHHG3MZ1ZcRkGuo=</SignatureValue>
</Signature>
</License>

View File

@@ -0,0 +1,40 @@
using DigitalData.MessagingService.RabbitMQ;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DigitalData.MessagingService.Infrastructure;
public class MessagingServiceInfrastructureConfiguration
{
internal IServiceCollection Services { get; }
private bool _rabbitMqConnectionFactoryAdded = false;
internal MessagingServiceInfrastructureConfiguration(IServiceCollection services)
{
Services = services;
}
public void EnsureRabbitMqConnectionFactoryAdded()
{
if (!_rabbitMqConnectionFactoryAdded)
{
throw new InvalidOperationException("RabbitMQ connection factory has not been added. Please call AddRabbitMqConnectionFactory() before using this configuration.");
}
}
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConfiguration> configure)
{
Services.AddRabbitMqConnectionFactory(configure);
_rabbitMqConnectionFactoryAdded = true;
return this;
}
public MessagingServiceInfrastructureConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
{
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
_rabbitMqConnectionFactoryAdded = true;
return this;
}
}

View File

@@ -18,8 +18,9 @@ public class MessagingServiceDbContext(DbContextOptions<MessagingServiceDbContex
modelBuilder.Entity<EmailAccount>(entity =>
{
entity.Property(e => e.Username)
.UseCollation("SQL_Latin1_General_CP1_CI_AS");
// UseCollation is only supported by relational databases (e.g. SQL Server).
// Skipped here to remain compatible with the current InMemory database configuration.
// entity.Property(e => e.Username).UseCollation("SQL_Latin1_General_CP1_CI_AS");
});
modelBuilder.Entity<ReceivedEmail>(entity =>

View File

@@ -1,19 +0,0 @@
using DigitalData.MessagingService.Infrastructure.Queue;
using Microsoft.Extensions.Hosting;
namespace DigitalData.MessagingService.Infrastructure.Services.Background;
/// <summary>
/// A hosted background service responsible for initializing the competing email consumer pool.
/// Leverages a push-based, event-driven RabbitMQ consumer to eliminate polling overhead.
/// Email account configuration is resolved exclusively from application settings; no database access is performed.
/// </summary>
public class AsyncInitWorker(SendingEmailConsumerPool ConsumerPool) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await ConsumerPool.InitAsync();
await Task.Delay(Timeout.Infinite, stoppingToken).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
}
}

View File

@@ -0,0 +1,29 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace DigitalData.MessagingService.Infrastructure.Services.Background;
/// <summary>
/// Reports the initialization status of <see cref="ConsumerInitWorker"/>.
/// Marked as <see cref="HealthStatus.Unhealthy"/> if the RabbitMQ consumer pool
/// failed to start, causing the health endpoint to return HTTP 503.
/// </summary>
public class ConsumerInitHealthCheck : IHealthCheck
{
private volatile bool _isHealthy = true;
private string? _failureMessage;
internal void MarkUnhealthy(string message)
{
_isHealthy = false;
_failureMessage = message;
}
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
return Task.FromResult(_isHealthy
? HealthCheckResult.Healthy("RabbitMQ consumer pool is running.")
: HealthCheckResult.Unhealthy(_failureMessage ?? "RabbitMQ consumer pool failed to initialize."));
}
}

View File

@@ -0,0 +1,40 @@
using DigitalData.MessagingService.Infrastructure.Queue;
using DigitalData.MessagingService.RabbitMQ;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace DigitalData.MessagingService.Infrastructure.Services.Background;
/// <summary>
/// A hosted background service responsible for initializing the competing email consumer pool.
/// Leverages a push-based, event-driven RabbitMQ consumer to eliminate polling overhead.
/// Email account configuration is resolved exclusively from application settings; no database access is performed.
/// </summary>
public class ConsumerInitWorker(
SendingEmailConsumerPool ConsumerPool,
ILogger<ConsumerInitWorker> Logger,
IOptions<RabbitMqConfiguration> RabbitMqOptions,
ConsumerInitHealthCheck HealthCheck) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await ConsumerPool.InitAsync();
}
catch (Exception ex)
{
// Log and mark the health check as unhealthy — callers will receive HTTP 503.
// The API remains operational; only outgoing email delivery via the consumer pool is affected.
Logger.LogError(ex, "Failed to initialize SendingEmailConsumerPool. Outgoing email consumers are not running.");
HealthCheck.MarkUnhealthy(ex.Message);
if (!RabbitMqOptions.Value.ContinueOnInitFailure)
throw;
}
await Task.Delay(Timeout.Infinite, stoppingToken).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
}
}

View File

@@ -11,7 +11,7 @@ using Microsoft.Extensions.Options;
namespace DigitalData.MessagingService.Infrastructure.Services.Background;
public class EmailSyncWorker(IOptions<EmailAccountsOptions> Options, IServiceProvider Provider, ILogger<EmailSyncWorker> Logger, IMemoryCache Cache) : BackgroundService, IEmailSyncService
public class EmailSyncWorker(IOptions<EmailAccountsOptions> Options, IServiceProvider Provider, ILogger<EmailSyncWorker> Logger, IMemoryCache Cache, EmailSyncWorkerHealthCheck HealthCheck) : BackgroundService, IEmailSyncService
{
private static string ForcedSyncDateCacheKey => $"{nameof(EmailSyncWorker)}_TriggerSync";
@@ -44,6 +44,7 @@ public class EmailSyncWorker(IOptions<EmailAccountsOptions> Options, IServicePro
await UpsertSeedEmailAccount(stoppingToken);
var interval = TimeSpan.FromSeconds(Options.Value.SyncIntervalSeconds);
HealthCheck.OnWorkerStarted(interval);
while (!stoppingToken.IsCancellationRequested)
{
@@ -53,11 +54,15 @@ public class EmailSyncWorker(IOptions<EmailAccountsOptions> Options, IServicePro
var imapService = scope.ServiceProvider.GetRequiredService<IImapEmailService>();
var pop3Service = scope.ServiceProvider.GetRequiredService<IPop3EmailService>();
int cycleErrorCount = 0;
foreach (var account in await emailAccountRepo.GetAllAsync(stoppingToken))
{
await SyncAccountAsync(account, imapService, pop3Service, stoppingToken);
var hadError = await SyncAccountAsync(account, imapService, pop3Service, stoppingToken);
if (hadError) cycleErrorCount++;
}
HealthCheck.OnCycleCompleted(cycleErrorCount);
// Reset trigger before waiting so any TriggerSync() call during the delay is caught
_syncTrigger = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -70,14 +75,15 @@ public class EmailSyncWorker(IOptions<EmailAccountsOptions> Options, IServicePro
}
}
private async Task SyncAccountAsync(
/// <returns><c>true</c> if the sync failed for this account; otherwise <c>false</c>.</returns>
private async Task<bool> SyncAccountAsync(
EmailAccount account,
IImapEmailService imapService,
IPop3EmailService pop3Service,
CancellationToken stoppingToken)
{
if (account.IncomingProtocol == IncomingProtocol.None)
return;
return false;
Logger.LogDebug(
"Email sync started. Account={Username}, Protocol={Protocol}.",
@@ -100,12 +106,16 @@ public class EmailSyncWorker(IOptions<EmailAccountsOptions> Options, IServicePro
Logger.LogDebug(
"Email sync completed. Account={Username}, Protocol={Protocol}, Processed={Processed}, Failed={Failed}.",
account.Username, account.IncomingProtocol, result.ProcessedCount, result.FailedCount);
return false;
}
catch (Exception ex)
{
Logger.LogError(ex,
"Email sync failed. Account={Username}, Protocol={Protocol}.",
account.Username, account.IncomingProtocol);
return true;
}
}

View File

@@ -0,0 +1,53 @@
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace DigitalData.MessagingService.Infrastructure.Services.Background;
/// <summary>
/// Reports the operational status of <see cref="EmailSyncWorker"/>.
/// Becomes <see cref="HealthStatus.Unhealthy"/> if the sync loop has not completed
/// a cycle within twice the configured sync interval, indicating a stalled worker.
/// Becomes <see cref="HealthStatus.Degraded"/> if the last sync cycle had errors.
/// </summary>
public class EmailSyncWorkerHealthCheck : IHealthCheck
{
private DateTimeOffset? _lastCycleCompletedAt;
private int _consecutiveErrorCount;
private TimeSpan _syncInterval = TimeSpan.FromSeconds(300);
private bool _started;
internal void OnWorkerStarted(TimeSpan syncInterval)
{
_syncInterval = syncInterval;
_started = true;
_lastCycleCompletedAt = DateTimeOffset.UtcNow;
}
internal void OnCycleCompleted(int errorCount)
{
_lastCycleCompletedAt = DateTimeOffset.UtcNow;
_consecutiveErrorCount = errorCount;
}
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
if (!_started)
return Task.FromResult(HealthCheckResult.Degraded("EmailSyncWorker has not started yet."));
var deadline = _lastCycleCompletedAt!.Value + (_syncInterval * 2);
if (DateTimeOffset.UtcNow > deadline)
return Task.FromResult(HealthCheckResult.Unhealthy(
$"EmailSyncWorker has not completed a cycle since {_lastCycleCompletedAt:HH:mm:ss} UTC. " +
$"Expected within {_syncInterval.TotalSeconds * 2}s."));
if (_consecutiveErrorCount > 0)
return Task.FromResult(HealthCheckResult.Degraded(
$"EmailSyncWorker last cycle had {_consecutiveErrorCount} account error(s). " +
$"Last cycle: {_lastCycleCompletedAt:HH:mm:ss} UTC."));
return Task.FromResult(HealthCheckResult.Healthy(
$"EmailSyncWorker is running. Last cycle: {_lastCycleCompletedAt:HH:mm:ss} UTC."));
}
}

View File

@@ -0,0 +1,33 @@
using DigitalData.MessagingService.RabbitMQ;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace DigitalData.MessagingService.Infrastructure.Services.Background;
/// <summary>
/// Verifies the RabbitMQ connection is open and reachable by attempting to open a channel.
/// Returns <see cref="HealthStatus.Unhealthy"/> if the broker is unreachable or the connection is closed.
/// </summary>
public class RabbitMqConnectionHealthCheck(RabbitMqConnectionFactory ConnectionFactory) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
try
{
var connection = await ConnectionFactory.GetDefaultConnectionAsync();
if (!connection.IsOpen)
return HealthCheckResult.Unhealthy("RabbitMQ connection is closed.");
// Open and immediately close a lightweight channel to confirm broker is responsive
await using var channel = await connection.CreateChannelAsync(cancellationToken: cancellationToken);
return HealthCheckResult.Healthy("RabbitMQ connection is open.");
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy("RabbitMQ connection check failed.", ex);
}
}
}

View File

@@ -1,23 +0,0 @@
using DigitalData.MessagingService.Application.Common.Interfaces;
using Microsoft.AspNetCore.DataProtection;
namespace DigitalData.MessagingService.Infrastructure.Services;
/// <summary>
/// Encryption service using ASP.NET Core Data Protection API.
/// Passwords are encrypted at rest in the database.
/// </summary>
public class DataProtectionEncryptionService(IDataProtectionProvider Provider) : IEncryptionService
{
private readonly IDataProtector Protector = Provider.CreateProtector("MessagingService.Passwords");
public string Encrypt(string plainText)
{
return Protector.Protect(plainText);
}
public string Decrypt(string cipherText)
{
return Protector.Unprotect(cipherText);
}
}

View File

@@ -1,15 +1,17 @@
using DigitalData.MessagingService.Application.Common.Interfaces;
using DigitalData.MessagingService.RabbitMQ;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DigitalData.MessagingService.Publisher;
public static class DependencyInjection
{
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services, Action<RabbitMqConfiguration>? configure = null)
public static IServiceCollection AddMessagingServicePublisher(this IServiceCollection services, Action<MessagingServicePublisherConfiguration>? configure = null)
{
if(configure is not null)
services.AddRabbitMqConnectionFactory(configure);
var configuration = new MessagingServicePublisherConfiguration(services);
configure?.Invoke(configuration);
// --- Email Queue (RabbitMQ) ---
services.AddSingleton<ISendingEmailPublisher, SendingEmailPublisher>();

View File

@@ -0,0 +1,27 @@
using DigitalData.MessagingService.RabbitMQ;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DigitalData.MessagingService.Publisher;
public class MessagingServicePublisherConfiguration
{
internal IServiceCollection Services { get; }
internal MessagingServicePublisherConfiguration(IServiceCollection services)
{
Services = services;
}
public MessagingServicePublisherConfiguration AddRabbitMqConnectionFactory(Action<RabbitMqConfiguration> configure)
{
Services.AddRabbitMqConnectionFactory(configure);
return this;
}
public MessagingServicePublisherConfiguration AddRabbitMqConnectionFactory(IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
{
Services.AddRabbitMqConnectionFactory(configuration, sectionName);
return this;
}
}

View File

@@ -31,13 +31,12 @@ namespace DigitalData.MessagingService.RabbitMQ
/// <summary>
/// Adds Infrastructure layer services to the DI container
/// </summary>
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, IConfiguration configuration)
public static IServiceCollection AddRabbitMqConnectionFactory(this IServiceCollection services, IConfiguration configuration, string sectionName = RabbitMqConfiguration.SectionName)
{
services.AddDefaultServices();
// --- RabbitMQ Configuration ---
services.Configure<RabbitMqConfiguration>(
configuration.GetSection(RabbitMqConfiguration.SectionName));
services.Configure<RabbitMqConfiguration>(configuration.GetSection(sectionName));
return services;
}

View File

@@ -81,5 +81,7 @@ namespace DigitalData.MessagingService.RabbitMQ
/// Maps directly to RabbitMQ prefetchCount. Recommended: 3–5.
/// </summary>
public ushort ConsumerConcurrency { get; set; } = 5;
public bool ContinueOnInitFailure { get; set; } = false;
}
}

View File

@@ -1,49 +1,83 @@
using DigitalData.MessagingService.Application.EmailSending.Commands;
using DigitalData.MessagingService.Application.Common.Dto;
using DigitalData.MessagingService.Application.EmailReceiving.Queries;
using DigitalData.MessagingService.Application.EmailSending.Commands;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using DigitalData.MessagingService.Application.Common.Dto;
namespace DigitalData.MessagingService.API.Controllers;
/// <summary>
/// Email sending API controller.
/// Enqueues outgoing emails to RabbitMQ for async processing.
/// Email API controller.
/// Handles sending and receiving emails across all supported protocols and auth methods.
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class EmailController(IMediator mediator) : ControllerBase
{
/// <summary>
///
/// Controls which field(s) to return from a fetch-emails response.
/// </summary>
public enum OnlyFilter
{
/// <summary>
///
/// </summary>
/// <summary>Returns only the HTML body of the first matching email.</summary>
HtmlBody,
/// <summary>
///
/// </summary>
/// <summary>Returns only the UID list of matching emails.</summary>
Uid,
}
#region Send
#region Receive
/// <summary>
/// Send an email, optionally with file attachments.
/// Fetch emails from an email account.
/// The protocol (IMAP, POP3) and authentication method (basic, OAuth2) are determined
/// by the <c>IncomingProtocol</c> field configured on the account.
/// </summary>
/// <param name="query">Query parameters for filtering and fetching emails.</param>
/// <param name="only">Optional filter to return only specific fields.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>HTTP 200 with list of received emails.</returns>
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> FetchEmails(
[FromQuery] ReadEmailQuery query,
[FromQuery] OnlyFilter? only = null,
CancellationToken cancellationToken = default)
{
var res = await mediator.Send(query, cancellationToken);
if (!res.Emails.Any())
return NotFound("No emails found matching the specified criteria.");
if (only == OnlyFilter.HtmlBody)
{
if (res.Emails.FirstOrDefault()?.HtmlBody is string htmlBody)
return Content(htmlBody, "text/html");
else
return NotFound();
}
else if (only == OnlyFilter.Uid)
return Ok(res.Emails.Select(e => e.Uid).ToList());
else
return Ok(res);
}
#endregion Receive
#region SMTP Send
/// <summary>
/// Send an email via SMTP, optionally with file attachments.
/// Omit the <c>attachments</c> field for a plain send.
/// </summary>
/// <param name="command">Email fields as form values</param>
/// <param name="attachments">Optional uploaded files</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>HTTP 202 Accepted with the queued event ID</returns>
[HttpPost]
[HttpPost("smtp")]
[Consumes("multipart/form-data")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> SendEmail(
[FromForm] PublishEmailCommand command,
[FromForm] PublishEmailViaSmtpCommand command,
IFormFileCollection? attachments,
CancellationToken cancellationToken)
{
@@ -53,6 +87,59 @@ public class EmailController(IMediator mediator) : ControllerBase
var eventId = await mediator.Send(commandWithAttachments, cancellationToken);
return Accepted(new { Id = eventId });
}
#endregion SMTP Send
#region IMAP Send
/// <summary>
/// Send an email using IMAP account credentials (via RabbitMQ queue).
/// After the message is sent, it is appended to the IMAP Sent Items folder.
/// </summary>
/// <param name="command">Email fields as form values</param>
/// <param name="attachments">Optional uploaded files</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>HTTP 202 Accepted with the queued event ID</returns>
[HttpPost("imap")]
[Consumes("multipart/form-data")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> SendEmailViaImap(
[FromForm] PublishEmailViaImapCommand command,
IFormFileCollection? attachments,
CancellationToken cancellationToken)
{
var commandWithAttachments = command.WithAttachments(
await BuildAttachmentsAsync(attachments, cancellationToken));
var eventId = await mediator.Send(commandWithAttachments, cancellationToken);
return Accepted(new { Id = eventId });
}
#endregion IMAP Send
#region OAuth2 Send
/// <summary>
/// Send an email via SMTP using OAuth2 authentication (via RabbitMQ queue).
/// The account must have <c>UseOAuth2 = true</c> and valid OAuth2 credentials configured.
/// </summary>
/// <param name="command">Email fields as form values</param>
/// <param name="attachments">Optional uploaded files</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>HTTP 202 Accepted with the queued event ID</returns>
[HttpPost("oauth2")]
[Consumes("multipart/form-data")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> SendEmailViaOAuth2(
[FromForm] PublishEmailViaOAuth2Command command,
IFormFileCollection? attachments,
CancellationToken cancellationToken)
{
var commandWithAttachments = command.WithAttachments(
await BuildAttachmentsAsync(attachments, cancellationToken));
var eventId = await mediator.Send(commandWithAttachments, cancellationToken);
return Accepted(new { Id = eventId });
}
#endregion OAuth2 Send
private static async Task<IEnumerable<EmailAttachmentDto>> BuildAttachmentsAsync(
IFormFileCollection? files,
@@ -78,164 +165,4 @@ public class EmailController(IMediator mediator) : ControllerBase
return result;
}
#endregion Send
#region Receive
/// <summary>
/// Fetch emails from an IMAP mailbox.
/// </summary>
/// <param name="query">Query parameters for filtering and fetching emails from the IMAP mailbox.</param>
/// <param name="only"></param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>HTTP 200 with list of received emails.</returns>
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> FetchEmails([FromQuery] ReadEmailQuery query, [FromQuery] OnlyFilter? only = null, CancellationToken cancellationToken = default)
{
var res = await mediator.Send(query, cancellationToken);
if(!res.Emails.Any())
return NotFound("No emails found matching the specified criteria.");
if (only == OnlyFilter.HtmlBody)
{
if (res.Emails.FirstOrDefault()?.HtmlBody is string htmlBody)
return Content(htmlBody, "text/html");
else
return NotFound();
}
else if (only == OnlyFilter.Uid)
return Ok(res.Emails.Select(e => e.Uid).ToList());
else
return Ok(res);
}
#endregion Receive
#region IMAP Send
/// <summary>
/// Send an email using IMAP account credentials (via RabbitMQ queue).
/// After the message is sent, it is appended to the IMAP Sent Items folder.
/// </summary>
/// <param name="command">Email fields as form values</param>
/// <param name="attachments">Optional uploaded files</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>HTTP 202 Accepted with the queued event ID</returns>
[HttpPost("imap/send")]
[Consumes("multipart/form-data")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> SendEmailViaImap(
[FromForm] PublishEmailViaImapCommand command,
IFormFileCollection? attachments,
CancellationToken cancellationToken)
{
var commandWithAttachments = command.WithAttachments(
await BuildAttachmentsAsync(attachments, cancellationToken));
var eventId = await mediator.Send(commandWithAttachments, cancellationToken);
return Accepted(new { Id = eventId });
}
#endregion IMAP Send
#region POP3 Receive
/// <summary>
/// Fetch emails from a POP3 mailbox.
/// Triggers an on-demand POP3 sync before returning results.
/// </summary>
/// <param name="query">Query parameters for filtering and fetching emails from the POP3 mailbox.</param>
/// <param name="only">Optional filter to return only specific fields.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>HTTP 200 with list of received emails.</returns>
[HttpGet("pop3")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> FetchEmailsViaPop3(
[FromQuery] ReadEmailViaPop3Query query,
[FromQuery] OnlyFilter? only = null,
CancellationToken cancellationToken = default)
{
var res = await mediator.Send(query, cancellationToken);
if (!res.Emails.Any())
return NotFound("No emails found matching the specified criteria.");
if (only == OnlyFilter.HtmlBody)
{
if (res.Emails.FirstOrDefault()?.HtmlBody is string htmlBody)
return Content(htmlBody, "text/html");
else
return NotFound();
}
else if (only == OnlyFilter.Uid)
return Ok(res.Emails.Select(e => e.Uid).ToList());
else
return Ok(res);
}
#endregion POP3 Receive
#region OAuth2 Send
/// <summary>
/// Send an email via SMTP using OAuth2 authentication (via RabbitMQ queue).
/// The account must have <c>UseOAuth2 = true</c> and valid OAuth2 credentials configured.
/// </summary>
/// <param name="command">Email fields as form values</param>
/// <param name="attachments">Optional uploaded files</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>HTTP 202 Accepted with the queued event ID</returns>
[HttpPost("oauth2/send")]
[Consumes("multipart/form-data")]
[ProducesResponseType(StatusCodes.Status202Accepted)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> SendEmailViaOAuth2(
[FromForm] PublishEmailViaOAuth2Command command,
IFormFileCollection? attachments,
CancellationToken cancellationToken)
{
var commandWithAttachments = command.WithAttachments(
await BuildAttachmentsAsync(attachments, cancellationToken));
var eventId = await mediator.Send(commandWithAttachments, cancellationToken);
return Accepted(new { Id = eventId });
}
#endregion OAuth2 Send
#region OAuth2 Receive
/// <summary>
/// Fetch emails from an IMAP mailbox using OAuth2 authentication.
/// The account must have <c>UseOAuth2 = true</c> and valid OAuth2 credentials configured.
/// </summary>
/// <param name="query">Query parameters for filtering and fetching emails.</param>
/// <param name="only">Optional filter to return only specific fields.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>HTTP 200 with list of received emails.</returns>
[HttpGet("oauth2/imap")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> FetchEmailsViaOAuth2(
[FromQuery] ReadEmailViaOAuth2Query query,
[FromQuery] OnlyFilter? only = null,
CancellationToken cancellationToken = default)
{
var res = await mediator.Send(query, cancellationToken);
if (!res.Emails.Any())
return NotFound("No emails found matching the specified criteria.");
if (only == OnlyFilter.HtmlBody)
{
if (res.Emails.FirstOrDefault()?.HtmlBody is string htmlBody)
return Content(htmlBody, "text/html");
else
return NotFound();
}
else if (only == OnlyFilter.Uid)
return Ok(res.Emails.Select(e => e.Uid).ToList());
else
return Ok(res);
}
#endregion OAuth2 Receive
}

View File

@@ -10,9 +10,9 @@
<Authors>Digital Data GmbH</Authors>
<Company>Digital Data GmbH</Company>
<Product>DigitalData.MessagingService.API</Product>
<Version>1.0.0-beta</Version>
<FileVersion>1.0.0.0</FileVersion>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<Version>2.1.0-beta</Version>
<FileVersion>2.1.0.0</FileVersion>
<AssemblyVersion>2.1.0.0</AssemblyVersion>
<Copyright>Copyright © 2026 Digital Data GmbH. All rights reserved.</Copyright>
<DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
</PropertyGroup>
@@ -26,8 +26,9 @@
<PackageReference Include="Serilog.UI" Version="3.2.0" />
<PackageReference Include="Serilog.UI.SqliteProvider" Version="1.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.10" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.10" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.10" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.10" />
<PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="8.0.1" />
</ItemGroup>
<ItemGroup>

View File

@@ -0,0 +1,68 @@
@page "/health-ui"
@model DigitalData.MessagingService.API.Pages.HealthDashboardModel
@{
ViewData["Title"] = "Health Dashboard";
Layout = "_Layout";
}
<style>
h1 { font-size: 1.5rem; margin-bottom: 1.5rem; color: #e2e8f0; }
.overall { display: inline-flex; align-items: center; gap: .5rem; font-size: 1rem; font-weight: 600;
padding: .35rem .9rem; border-radius: 999px; margin-bottom: 2rem; }
.overall.Healthy { background: #14532d; color: #4ade80; }
.overall.Degraded { background: #713f12; color: #fbbf24; }
.overall.Unhealthy { background: #7f1d1d; color: #f87171; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1rem; }
.card { background: #1a1d2e; border: 1px solid #2d3148; border-radius: .75rem; padding: 1.25rem; }
.card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: .75rem; }
.card-name { font-weight: 600; font-size: .95rem; }
.badge { font-size: .75rem; font-weight: 700; padding: .2rem .6rem; border-radius: 999px; }
.badge-Healthy { background: #14532d; color: #4ade80; }
.badge-Degraded { background: #713f12; color: #fbbf24; }
.badge-Unhealthy { background: #7f1d1d; color: #f87171; }
.desc { font-size: .82rem; color: #94a3b8; }
.tags { margin-top: .6rem; display: flex; gap: .4rem; flex-wrap: wrap; }
.tag { font-size: .7rem; background: #2d3148; color: #94a3b8; padding: .15rem .5rem; border-radius: 4px; }
.duration { font-size: .75rem; color: #64748b; margin-top: .5rem; }
.refresh { font-size: .8rem; color: #64748b; margin-bottom: 1.5rem; }
.refresh a { color: #a78bfa; text-decoration: none; }
</style>
<h1>Health Dashboard</h1>
<div class="overall @Model.OverallStatus.ToString()">
<span>@(Model.OverallStatus == Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Healthy ? "?" : "?")</span>
<span>@Model.OverallStatus</span>
</div>
<p class="refresh">
Zuletzt geprüft: <strong>@Model.CheckedAt.ToString("yyyy-MM-dd HH:mm:ss")</strong> UTC
&nbsp;·&nbsp; <a href="/health-ui">Aktualisieren</a>
&nbsp;·&nbsp; <a href="/health" target="_blank">JSON</a>
</p>
<div class="grid">
@foreach (var entry in Model.Entries)
{
<div class="card">
<div class="card-header">
<span class="card-name">@entry.Name</span>
<span class="badge badge-@entry.Status.ToString()">@entry.Status</span>
</div>
@if (!string.IsNullOrWhiteSpace(entry.Description))
{
<div class="desc">@entry.Description</div>
}
@if (entry.Tags.Any())
{
<div class="tags">
@foreach (var tag in entry.Tags)
{
<span class="tag">@tag</span>
}
</div>
}
<div class="duration">Dauer: @entry.Duration.TotalMilliseconds.ToString("0")ms</div>
</div>
}
</div>

View File

@@ -0,0 +1,34 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace DigitalData.MessagingService.API.Pages;
public class HealthDashboardModel(HealthCheckService healthCheckService) : PageModel
{
public HealthStatus OverallStatus { get; private set; }
public DateTime CheckedAt { get; private set; }
public IReadOnlyList<HealthEntry> Entries { get; private set; } = [];
public async Task OnGetAsync()
{
var report = await healthCheckService.CheckHealthAsync();
CheckedAt = DateTime.UtcNow;
OverallStatus = report.Status;
Entries = report.Entries
.Select(e => new HealthEntry(
Name: e.Key,
Status: e.Value.Status,
Description: e.Value.Description,
Duration: e.Value.Duration,
Tags: e.Value.Tags))
.OrderBy(e => e.Status)
.ToList();
}
public record HealthEntry(
string Name,
HealthStatus Status,
string? Description,
TimeSpan Duration,
IEnumerable<string> Tags);
}

View File

@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] — DigitalData MessagingService</title>
<style>
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #0f1117; color: #e2e8f0; }
header { background: #1a1d2e; border-bottom: 1px solid #2d3148; padding: 0 2rem; display: flex; align-items: center; height: 56px; gap: 1.5rem; }
header a { color: #a78bfa; text-decoration: none; font-weight: 600; font-size: 1rem; }
header a:hover { color: #c4b5fd; }
header .brand { color: #e2e8f0; font-size: 1.1rem; font-weight: 700; margin-right: auto; }
main { padding: 2rem; max-width: 1100px; margin: 0 auto; }
</style>
</head>
<body>
<header>
<span class="brand">DigitalData MessagingService</span>
<a href="/health-ui">Health</a>
<a href="/serilog-ui">Logs</a>
<a href="/swagger">API</a>
</header>
<main>
@RenderBody()
</main>
</body>
</html>

View File

@@ -0,0 +1,3 @@
@using DigitalData.MessagingService.API.Pages
@namespace DigitalData.MessagingService.API.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@@ -1,6 +1,10 @@
using DigitalData.MessagingService.API.Middleware;
using DigitalData.MessagingService.Application;
using DigitalData.MessagingService.Application.DependencyInjection;
using DigitalData.MessagingService.Infrastructure;
using DigitalData.MessagingService.Infrastructure.Services.Background;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Serilog;
using Serilog.Ui.Core.Extensions;
using Serilog.Ui.SqliteDataProvider.Extensions;
@@ -8,10 +12,10 @@ using Serilog.Ui.Web.Extensions;
// Build temporary configuration to read log directory early
var tempConfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: false)
.Build();
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: false)
.Build();
var logDirectoryRaw = tempConfig.GetValue<string>("Application:LogDirectory") ?? "logs";
// Always resolve to an absolute path so sink and UI provider point to the same file
@@ -61,12 +65,19 @@ try
builder.Configuration.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: true);
// Register Application layer (MediatR, AutoMapper, FluentValidation)
builder.Services.AddApplicationServices(builder.Configuration);
builder.Services.AddMessagingServiceApplication(builder.Configuration);
// Register Infrastructure layer (RabbitMQ, Repositories, etc.)
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddInfrastructure(cfg => cfg.AddRabbitMqConnectionFactory(builder.Configuration));
// Health checks — each check corresponds to a singleton registered in the Infrastructure layer
builder.Services.AddHealthChecks()
.AddCheck<ConsumerInitHealthCheck>("rabbitmq-consumers", tags: ["rabbitmq", "ready"])
.AddCheck<RabbitMqConnectionHealthCheck>("rabbitmq-connection", tags: ["rabbitmq", "live"])
.AddCheck<EmailSyncWorkerHealthCheck>("email-sync-worker", tags: ["workers", "live"]);
builder.Services.AddControllers();
builder.Services.AddRazorPages();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
@@ -95,6 +106,7 @@ try
## Weiterführende Links
- [Serilog Log-Viewer &nearr;](/serilog-ui)
- [Health Status &nearr;](/health-ui)
"""
});
});
@@ -155,6 +167,22 @@ try
app.MapControllers();
// Health check endpoint — raw JSON, used by HealthChecks UI and monitoring tools
// Returns HTTP 503 if any check tagged 'ready' is Unhealthy
app.MapHealthChecks("/health", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
ResultStatusCodes =
{
[HealthStatus.Healthy] = StatusCodes.Status200OK,
[HealthStatus.Degraded] = StatusCodes.Status200OK,
[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable,
}
});
app.MapRazorPages();
Log.Information("MessagingService API started successfully");
app.Run();

View File

@@ -11,13 +11,14 @@
<PackageIcon>icon.png</PackageIcon>
<RepositoryUrl>http://git.dd:3000/AppStd/Rec.git</RepositoryUrl>
<PackageTags>digital data messaging service api client</PackageTags>
<Version>1.0.0</Version>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<FileVersion>1.0.0.0</FileVersion>
<Version>1.0.5</Version>
<AssemblyVersion>1.0.5.0</AssemblyVersion>
<FileVersion>1.0.5.0</FileVersion>
<Description></Description>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<IsPackable>true</IsPackable>
</PropertyGroup>
<ItemGroup>
@@ -25,6 +26,11 @@
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.10" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.10" />
<PackageReference Include="RabbitMQ.Client" Version="7.2.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.10" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<PackageReference Include="System.Text.Json" Version="10.0.10" />
</ItemGroup>
<ItemGroup>
@@ -34,13 +40,29 @@
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\infrastructure\DigitalData.MessagingService.Publisher\DigitalData.MessagingService.Publisher.csproj">
<PrivateAssets>all</PrivateAssets>
</ProjectReference>
<ProjectReference Include="..\..\infrastructure\DigitalData.MessagingService.RabbitMQ\DigitalData.MessagingService.RabbitMQ.csproj">
<PrivateAssets>all</PrivateAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\core\DigitalData.MessagingService.Application\DigitalData.MessagingService.Application.csproj">
<PrivateAssets>all</PrivateAssets>
</ProjectReference>
<ProjectReference Include="..\..\core\DigitalData.MessagingService.Domain\DigitalData.MessagingService.Domain.csproj">
<PrivateAssets>all</PrivateAssets>
</ProjectReference>
<ProjectReference Include="..\..\infrastructure\DigitalData.MessagingService.Publisher\DigitalData.MessagingService.Publisher.csproj">
<PrivateAssets>all</PrivateAssets>
</ProjectReference>
<ProjectReference Include="..\..\infrastructure\DigitalData.MessagingService.RabbitMQ\DigitalData.MessagingService.RabbitMQ.csproj">
<PrivateAssets>all</PrivateAssets>
</ProjectReference>
</ItemGroup>
<PropertyGroup>
<TargetsForTfmSpecificBuildOutput>$(TargetsForTfmSpecificBuildOutput);EmbedProjectReferences</TargetsForTfmSpecificBuildOutput>
</PropertyGroup>
<Target Name="EmbedProjectReferences" DependsOnTargets="ResolveReferences">
<ItemGroup>
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget','ProjectReference'))" />
</ItemGroup>
</Target>
</Project>

View File

@@ -69,7 +69,7 @@ public static class EmailSender
if(IsConnected && onReconnect == OnReconnect.ThrowException)
throw new InvalidOperationException("Messaging service is already connected.");
ConfigureServices += services => services.AddMessagingServicePublisher(configure);
ConfigureServices += services => services.AddMessagingServicePublisher(cfg => cfg.AddRabbitMqConnectionFactory(configure));
_ = LazyProvider.Value; // Force initialization
}
@@ -120,13 +120,13 @@ public static class EmailSender
/// Ensure that any unhandled exceptions from the async operation are handled
/// at the publisher level.
/// </remarks>
public static void Send(EmailContext email)
public static async Task Send(EmailContext email)
{
if(!IsConnected)
throw new InvalidOperationException("Messaging service is not connected. Call ConnectRabbitMq first.");
var publisher = LazyProvider.Value.GetRequiredService<ISendingEmailPublisher>();
publisher.EnqueueAsync(new SendingEmailEvent()
await publisher.EnqueueAsync(new SendingEmailEvent()
{
Id = Guid.NewGuid(),
Mail = email,

View File

@@ -74,7 +74,7 @@ public sealed class EmailSenderTests
}
[Fact]
public void Send_WithValidEmail_DoesNotThrow()
public async Task Send_WithValidEmail_DoesNotThrow()
{
var email = new EmailContext
{
@@ -85,13 +85,13 @@ public sealed class EmailSenderTests
IsHtml = true,
};
var exception = Record.Exception(() => EmailSender.Send(email));
var exception = await Record.ExceptionAsync(() => EmailSender.Send(email));
Assert.Null(exception);
}
[Fact]
public void Send_WithPlainTextBody_DoesNotThrow()
public async Task Send_WithPlainTextBody_DoesNotThrow()
{
var email = new EmailContext
{
@@ -102,7 +102,7 @@ public sealed class EmailSenderTests
IsHtml = false
};
var exception = Record.Exception(() => EmailSender.Send(email));
var exception = await Record.ExceptionAsync(() => EmailSender.Send(email));
Assert.Null(exception);
}

View File

@@ -54,7 +54,7 @@ public sealed class EmailSenderUrlOverloadTests
}
[Fact]
public void Send_AfterUrlOverloadConnection_DoesNotThrow()
public async Task Send_AfterUrlOverloadConnection_DoesNotThrow()
{
var email = new EmailContext
{
@@ -67,7 +67,7 @@ public sealed class EmailSenderUrlOverloadTests
// Connection was established via Action<> overload in the fixture;
// Send should work regardless of which overload was used to connect.
var exception = Record.Exception(() => EmailSender.Send(email));
var exception = await Record.ExceptionAsync(() => EmailSender.Send(email));
Assert.Null(exception);
}

View File

@@ -24,7 +24,7 @@ public sealed class SendingEmailPublisherTests : IAsyncDisposable
{
var services = new ServiceCollection();
services.AddLogging();
services.AddMessagingServicePublisher(RabbitMqTestConfig.Apply);
services.AddMessagingServicePublisher(cfg => cfg.AddRabbitMqConnectionFactory(RabbitMqTestConfig.Apply));
_serviceProvider = services.BuildServiceProvider();
_publisher = _serviceProvider.GetRequiredService<ISendingEmailPublisher>();