Compare commits
22 Commits
993d9cfea0
...
8ff8a9e58b
| Author | SHA1 | Date | |
|---|---|---|---|
| 8ff8a9e58b | |||
| 8bbf6e1e3d | |||
| 376a22580b | |||
| 14cf8e8821 | |||
| 5944823155 | |||
| 084ddc4b56 | |||
| 8e397d8119 | |||
| 51732fa9fc | |||
| 9bd100c0c5 | |||
| 31932d6c3b | |||
| efdd5805d3 | |||
| 11ba3cdac4 | |||
| afc1a434db | |||
| 5ba650356a | |||
| 292b6e9f36 | |||
| 2fdc8982aa | |||
| be881ea7c9 | |||
| 76fc005b02 | |||
| 26c78d32ae | |||
| 57ba948fe6 | |||
| 8450806916 | |||
| acf40684f8 |
@@ -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);
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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);
|
||||
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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" />
|
||||
|
||||
@@ -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>
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 =>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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."));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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>();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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
|
||||
· <a href="/health-ui">Aktualisieren</a>
|
||||
· <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>
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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>
|
||||
@@ -0,0 +1,3 @@
|
||||
@using DigitalData.MessagingService.API.Pages
|
||||
@namespace DigitalData.MessagingService.API.Pages
|
||||
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
|
||||
@@ -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 ↗](/serilog-ui)
|
||||
- [Health Status ↗](/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();
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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>();
|
||||
|
||||
Reference in New Issue
Block a user