Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 27f3603d8f | |||
| a44b98292f | |||
| b088640e9b | |||
| 26847f1e9f | |||
| 50033a5bd4 | |||
| 01c622038d | |||
| 1ceb71b9a2 | |||
| bb0de0f2c1 | |||
| d5a2e538f0 | |||
| 9d6b0717e6 | |||
| 2757869176 | |||
| b8435ac07b | |||
| cc3857a409 | |||
| 94f0d45aaf | |||
| 07f536938f | |||
| e7d3953747 | |||
| 3381fcc2f8 | |||
| 3bd952ef9e | |||
| 285cc6abb7 | |||
| 9589095760 | |||
| 25fb48ccf0 | |||
| ab042c7617 | |||
| 0861e18cec | |||
| dfa097eb43 | |||
| c18f0b7fb1 | |||
| 50828d23ec | |||
| f3966705ad | |||
| b4d8497ea7 | |||
| 7b77062aa7 | |||
| 9490718c04 | |||
| 0d1aa4f6be | |||
| 637af06a9c | |||
| 334bf2a567 | |||
| 9c2edd4712 | |||
| 5c7b5f7b10 | |||
| b07cd06477 | |||
| 9a0aaf629b | |||
| 859ae0b50d | |||
| 09c3985fad | |||
| 8dab3c0dc0 | |||
| a6f9a0a530 | |||
| c303514414 | |||
| 18f7981ccc |
+10
-9
@@ -1,9 +1,10 @@
|
|||||||
**/.git
|
**/.git
|
||||||
**/.vs
|
**/.vs
|
||||||
**/.idea
|
**/.idea
|
||||||
**/bin
|
**/bin
|
||||||
**/obj
|
**/obj
|
||||||
**/*.user
|
**/*.user
|
||||||
**/*.suo
|
**/*.suo
|
||||||
**/TestResults
|
**/TestResults
|
||||||
NuGet.Config
|
NuGet.Config
|
||||||
|
docker/kubernetes/
|
||||||
|
|||||||
@@ -480,3 +480,6 @@ $RECYCLE.BIN/
|
|||||||
|
|
||||||
# Vim temporary swap files
|
# Vim temporary swap files
|
||||||
*.swp
|
*.swp
|
||||||
|
|
||||||
|
# Local Docker Compose secrets and ports
|
||||||
|
docker/environments/.env.local
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# HrynCo Notification Service Agent Rules
|
||||||
|
|
||||||
|
## Git workflow
|
||||||
|
|
||||||
|
- Treat `main` as the only default and integration branch for this repository.
|
||||||
|
- Start every task branch from the latest `origin/main`.
|
||||||
|
- Before creating a task branch, fetch the remote, switch to `main`, and fast-forward it from `origin/main`.
|
||||||
|
- Create the task branch only after confirming that local `main` matches `origin/main`.
|
||||||
|
- Open pull requests from the task branch into `main`.
|
||||||
|
- Do not use `development` as the base or pull-request target for new work in this repository.
|
||||||
|
- Do not commit, push, publish, deploy, or merge unless the repository owner explicitly requests that step.
|
||||||
|
|
||||||
|
Recommended branch preparation:
|
||||||
|
|
||||||
|
```text
|
||||||
|
git fetch origin
|
||||||
|
git switch main
|
||||||
|
git pull --ff-only origin main
|
||||||
|
git switch -c <task-branch>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Delivery
|
||||||
|
|
||||||
|
- Keep changes focused and preserve backward compatibility where practical.
|
||||||
|
- Update the matching repository documentation when behavior, contracts, configuration, routing, or workflows change.
|
||||||
|
- Run the solution build and relevant tests before handoff.
|
||||||
|
- Use Conventional Commit messages with a lowercase subject and finish the commit body with `Ref: <issue-id>` when an issue exists.
|
||||||
@@ -4,10 +4,12 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<!-- Entity Framework Core -->
|
<!-- Entity Framework Core -->
|
||||||
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="9.0.5" />
|
<PackageVersion Include="HrynCo.DAL.Abstract" Version="1.0.11" />
|
||||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.5" />
|
<PackageVersion Include="HrynCo.DAL.EF" Version="1.0.11" />
|
||||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="9.0.5" />
|
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="10.0.7" />
|
||||||
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
|
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.7" />
|
||||||
|
<PackageVersion Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.7" />
|
||||||
|
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.1" />
|
||||||
<!-- MediatR -->
|
<!-- MediatR -->
|
||||||
<PackageVersion Include="MediatR" Version="12.4.1" />
|
<PackageVersion Include="MediatR" Version="12.4.1" />
|
||||||
<PackageVersion Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
|
<PackageVersion Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
|
||||||
@@ -28,9 +30,7 @@
|
|||||||
<PackageVersion Include="Serilog.Sinks.Seq" Version="9.0.0" />
|
<PackageVersion Include="Serilog.Sinks.Seq" Version="9.0.0" />
|
||||||
<!-- HrynCo shared packages -->
|
<!-- HrynCo shared packages -->
|
||||||
<PackageVersion Include="HrynCo.Common" Version="1.0.11" />
|
<PackageVersion Include="HrynCo.Common" Version="1.0.11" />
|
||||||
<PackageVersion Include="HrynCo.RabbitMq" Version="1.0.15" />
|
<PackageVersion Include="HrynCo.RabbitMq" Version="1.0.17" />
|
||||||
<PackageVersion Include="HrynCo.DAL.Abstract" Version="1.0.1" />
|
|
||||||
<PackageVersion Include="HrynCo.DAL.EF" Version="1.0.1" />
|
|
||||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||||
<PackageVersion Include="coverlet.collector" Version="6.0.4" />
|
<PackageVersion Include="coverlet.collector" Version="6.0.4" />
|
||||||
<PackageVersion Include="xunit" Version="2.9.3" />
|
<PackageVersion Include="xunit" Version="2.9.3" />
|
||||||
@@ -39,4 +39,4 @@
|
|||||||
<PackageVersion Include="Testcontainers.PostgreSql" Version="4.6.0" />
|
<PackageVersion Include="Testcontainers.PostgreSql" Version="4.6.0" />
|
||||||
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.5" />
|
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.5" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
<Description>RabbitMQ message contracts for HrynCo.NotificationService.</Description>
|
<Description>RabbitMQ message contracts for HrynCo.NotificationService.</Description>
|
||||||
<PackageTags>hrynco notification email rabbitmq contracts</PackageTags>
|
<PackageTags>hrynco notification email rabbitmq contracts</PackageTags>
|
||||||
<RepositoryType>git</RepositoryType>
|
<RepositoryType>git</RepositoryType>
|
||||||
<RepositoryUrl>https://gitea.grynco.com.ua/hrynco/hrynco-notification-service.git</RepositoryUrl>
|
<RepositoryUrl>https://gitea.hrynco.com/hrynco/hrynco-notification-service.git</RepositoryUrl>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
+4
-4
@@ -1,13 +1,13 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="HrynCo.DAL.Abstract" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="HrynCo.DAL.Abstract" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -12,4 +12,4 @@ public class EmailChannel : Entity
|
|||||||
public int? MonthlyLimit { get; set; }
|
public int? MonthlyLimit { get; set; }
|
||||||
public int WarnThresholdPercent { get; set; } = 90;
|
public int WarnThresholdPercent { get; set; } = 90;
|
||||||
public bool IsActive { get; set; } = true;
|
public bool IsActive { get; set; } = true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
using HrynCo.DAL.Abstract.Entities;
|
|
||||||
|
|
||||||
namespace HrynCo.NotificationService.DAL.Abstract.Providers;
|
namespace HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Tracks email send counts per EmailChannel per calendar day.
|
/// Tracks email send counts per EmailChannel per calendar day.
|
||||||
/// Monthly counts are derived by summing daily records within a month.
|
/// Monthly counts are derived by summing daily records within a month.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class EmailChannelUsage : Entity
|
public class EmailChannelUsage
|
||||||
{
|
{
|
||||||
|
public Guid Id { get; set; }
|
||||||
|
public DateTimeOffset Created { get; set; }
|
||||||
|
public DateTimeOffset? Updated { get; set; }
|
||||||
public Guid ProviderId { get; set; }
|
public Guid ProviderId { get; set; }
|
||||||
public DateOnly Date { get; set; }
|
public DateOnly Date { get; set; }
|
||||||
public int SentCount { get; set; }
|
public int SentCount { get; set; }
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ namespace HrynCo.NotificationService.DAL.Abstract.Repositories;
|
|||||||
|
|
||||||
public interface IEmailTemplateRepository
|
public interface IEmailTemplateRepository
|
||||||
{
|
{
|
||||||
Task<IReadOnlyList<EmailTemplate>> GetAllAsync(CancellationToken ct = default);
|
Task<IReadOnlyList<EmailTemplate>> GetAllAsync(string? serviceName = null, string? key = null, CancellationToken ct = default);
|
||||||
Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default);
|
Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default);
|
||||||
Task<EmailTemplate?> GetAsync(string serviceName, string key, string languageCode, CancellationToken ct = default);
|
Task<EmailTemplate?> GetAsync(string serviceName, string key, string languageCode, CancellationToken ct = default);
|
||||||
Task AddAsync(EmailTemplate template, CancellationToken ct = default);
|
Task AddAsync(EmailTemplate template, CancellationToken ct = default);
|
||||||
Task UpdateAsync(EmailTemplate template, CancellationToken ct = default);
|
Task UpdateAsync(EmailTemplate template, CancellationToken ct = default);
|
||||||
Task DeleteAsync(EmailTemplate template, CancellationToken ct = default);
|
Task DeleteAsync(EmailTemplate template, CancellationToken ct = default);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
namespace HrynCo.NotificationService.DAL.EF.Core;
|
||||||
|
|
||||||
|
using HrynCo.DAL.Abstract.Entities;
|
||||||
|
using HrynCo.DAL.EF.Core;
|
||||||
|
|
||||||
|
public abstract class NotificationBaseRepository<TEntity>
|
||||||
|
: BaseRepository<NotificationEfRepository<TEntity>, NotificationDbContext, TEntity, Guid> where TEntity : Entity
|
||||||
|
{
|
||||||
|
protected NotificationBaseRepository(NotificationDbContext dbContext)
|
||||||
|
{
|
||||||
|
DbContext = dbContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
private NotificationDbContext DbContext { get; set; }
|
||||||
|
|
||||||
|
protected override NotificationEfRepository<TEntity> CreateEfRepository()
|
||||||
|
{
|
||||||
|
return new NotificationEfRepository<TEntity>(DbContext);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
namespace HrynCo.NotificationService.DAL.EF.Core;
|
||||||
|
|
||||||
|
using HrynCo.DAL.Abstract.Entities;
|
||||||
|
using HrynCo.DAL.EF.Core;
|
||||||
|
|
||||||
|
public class NotificationEfRepository<TEntity> : BaseEfRepository<NotificationDbContext, TEntity, Guid>
|
||||||
|
where TEntity : class, IEntity<Guid>
|
||||||
|
{
|
||||||
|
public NotificationEfRepository(NotificationDbContext dbContext) :
|
||||||
|
base(dbContext)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
using HrynCo.DAL.EF.Core;
|
|
||||||
|
|
||||||
namespace HrynCo.NotificationService.DAL.EF.Core;
|
|
||||||
|
|
||||||
internal sealed class UnitOfWork : EfUnitOfWork<NotificationDbContext>
|
|
||||||
{
|
|
||||||
public UnitOfWork(NotificationDbContext context) : base(context)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,7 +6,6 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="HrynCo.DAL.EF" />
|
<PackageReference Include="HrynCo.DAL.EF" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" />
|
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace HrynCo.NotificationService.DAL.EF;
|
||||||
|
|
||||||
|
using HrynCo.DAL.EF.Core;
|
||||||
|
|
||||||
|
public class NotificationUnitOfWork : EfUnitOfWork<NotificationDbContext>
|
||||||
|
{
|
||||||
|
public NotificationUnitOfWork(NotificationDbContext context) : base(context)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,13 @@
|
|||||||
|
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||||
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.DAL.EF.Core;
|
using HrynCo.NotificationService.DAL.EF.Core;
|
||||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
internal sealed class EmailChannelRepository : NotificationBaseRepository<EmailChannelEntity>, IEmailChannelRepository
|
||||||
|
|
||||||
internal sealed class EmailChannelRepository : EfRepository<NotificationDbContext, EmailChannelEntity>, IEmailChannelRepository
|
|
||||||
{
|
{
|
||||||
public EmailChannelRepository(NotificationDbContext dbContext) : base(dbContext)
|
public EmailChannelRepository(NotificationDbContext dbContext) : base(dbContext)
|
||||||
{
|
{
|
||||||
@@ -15,20 +15,14 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
|||||||
|
|
||||||
public async Task<IReadOnlyList<EmailChannel>> GetAllAsync(CancellationToken ct = default)
|
public async Task<IReadOnlyList<EmailChannel>> GetAllAsync(CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var entities = await DbSet
|
var entities = await EfRepository.Get().ToListAsync(ct);
|
||||||
.AsNoTracking()
|
|
||||||
.OrderBy(x => x.ServiceName)
|
|
||||||
.ThenBy(x => x.Priority)
|
|
||||||
.ToListAsync(ct);
|
|
||||||
|
|
||||||
return entities.Select(MapToDomain).ToList();
|
return entities.Select(MapToDomain).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IReadOnlyList<EmailChannel>> GetByServiceAsync(string serviceName, CancellationToken ct = default)
|
public async Task<IReadOnlyList<EmailChannel>> GetByServiceAsync(string serviceName, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var entities = await DbSet
|
var entities = await EfRepository.Get(x => x.ServiceName == serviceName)
|
||||||
.AsNoTracking()
|
|
||||||
.Where(x => x.ServiceName == serviceName)
|
|
||||||
.OrderBy(x => x.Priority)
|
.OrderBy(x => x.Priority)
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
@@ -38,8 +32,7 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
|||||||
public async Task<IReadOnlyList<ChannelWithUsage>> GetAllWithUsageSummaryAsync(
|
public async Task<IReadOnlyList<ChannelWithUsage>> GetAllWithUsageSummaryAsync(
|
||||||
DateOnly today, CancellationToken ct = default)
|
DateOnly today, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var rows = await DbSet
|
var rows = await EfRepository.Get()
|
||||||
.AsNoTracking()
|
|
||||||
.OrderBy(c => c.ServiceName)
|
.OrderBy(c => c.ServiceName)
|
||||||
.ThenBy(c => c.Priority)
|
.ThenBy(c => c.Priority)
|
||||||
.Select(c => new
|
.Select(c => new
|
||||||
@@ -61,30 +54,24 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
|||||||
|
|
||||||
public async Task<EmailChannel?> GetByIdAsync(Guid id, CancellationToken ct = default)
|
public async Task<EmailChannel?> GetByIdAsync(Guid id, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
EmailChannelEntity? entity = await DbSet.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct);
|
EmailChannelEntity? entity = await EfRepository.GetByIdAsync(id);
|
||||||
return entity is null ? null : MapToDomain(entity);
|
return entity is null ? null : MapToDomain(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task AddAsync(EmailChannel channel, CancellationToken ct = default)
|
public Task AddAsync(EmailChannel channel, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
return base.AddAsync(MapToEntity(channel), ct);
|
return EfRepository.AddAsync(MapToEntity(channel));
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task UpdateAsync(EmailChannel channel, CancellationToken ct = default)
|
public async Task UpdateAsync(EmailChannel channel, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
EmailChannelEntity entity = MapToEntity(channel);
|
EmailChannelEntity entity = MapToEntity(channel);
|
||||||
entity.Updated = DateTimeOffset.UtcNow;
|
await EfRepository.UpdateAsync(entity);
|
||||||
Update(entity);
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task DeleteAsync(EmailChannel channel, CancellationToken ct = default)
|
public async Task DeleteAsync(EmailChannel channel, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
EmailChannelEntity? entity = await DbSet.FindAsync([channel.Id], ct);
|
await EfRepository.DeleteAsync(channel.Id);
|
||||||
if (entity is not null)
|
|
||||||
{
|
|
||||||
Delete(entity);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static EmailChannel MapToDomain(EmailChannelEntity e)
|
private static EmailChannel MapToDomain(EmailChannelEntity e)
|
||||||
@@ -128,8 +115,8 @@ internal sealed class EmailChannelRepository : EfRepository<NotificationDbContex
|
|||||||
return type switch
|
return type switch
|
||||||
{
|
{
|
||||||
EmailChannelType.Smtp => JsonSerializer.Deserialize<SmtpChannelSettings>(json)
|
EmailChannelType.Smtp => JsonSerializer.Deserialize<SmtpChannelSettings>(json)
|
||||||
?? throw new InvalidOperationException(
|
?? throw new InvalidOperationException(
|
||||||
"Failed to deserialize SMTP EmailChannel settings."),
|
"Failed to deserialize SMTP EmailChannel settings."),
|
||||||
_ => throw new InvalidOperationException($"Unknown or undefined email channel type: {type}")
|
_ => throw new InvalidOperationException($"Unknown or undefined email channel type: {type}")
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.DAL.EF.Core;
|
using HrynCo.NotificationService.DAL.EF.Core;
|
||||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||||
|
|
||||||
internal sealed class EmailChannelUsageRepository : EfRepository<NotificationDbContext, EmailChannelUsageEntity>, IEmailChannelUsageRepository
|
internal sealed class EmailChannelUsageRepository : NotificationBaseRepository<EmailChannelUsageEntity>, IEmailChannelUsageRepository
|
||||||
{
|
{
|
||||||
public EmailChannelUsageRepository(NotificationDbContext dbContext) : base(dbContext)
|
public EmailChannelUsageRepository(NotificationDbContext dbContext) : base(dbContext)
|
||||||
{
|
{
|
||||||
@@ -13,7 +13,8 @@ internal sealed class EmailChannelUsageRepository : EfRepository<NotificationDbC
|
|||||||
|
|
||||||
public async Task<int> GetDailyCountAsync(Guid providerId, DateOnly date, CancellationToken ct = default)
|
public async Task<int> GetDailyCountAsync(Guid providerId, DateOnly date, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
EmailChannelUsageEntity? entity = await DbSet
|
EmailChannelUsageEntity? entity = await EfRepository.Get()
|
||||||
|
.AsNoTracking()
|
||||||
.FirstOrDefaultAsync(x => x.ProviderId == providerId && x.Date == date, ct);
|
.FirstOrDefaultAsync(x => x.ProviderId == providerId && x.Date == date, ct);
|
||||||
|
|
||||||
return entity?.SentCount ?? 0;
|
return entity?.SentCount ?? 0;
|
||||||
@@ -21,7 +22,7 @@ internal sealed class EmailChannelUsageRepository : EfRepository<NotificationDbC
|
|||||||
|
|
||||||
public async Task<int> GetMonthlyCountAsync(Guid providerId, int year, int month, CancellationToken ct = default)
|
public async Task<int> GetMonthlyCountAsync(Guid providerId, int year, int month, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
return await DbSet
|
return await EfRepository.Get()
|
||||||
.Where(x => x.ProviderId == providerId
|
.Where(x => x.ProviderId == providerId
|
||||||
&& x.Date.Year == year
|
&& x.Date.Year == year
|
||||||
&& x.Date.Month == month)
|
&& x.Date.Month == month)
|
||||||
@@ -30,15 +31,16 @@ internal sealed class EmailChannelUsageRepository : EfRepository<NotificationDbC
|
|||||||
|
|
||||||
public async Task IncrementUsageAsync(Guid providerId, DateOnly date, CancellationToken ct = default)
|
public async Task IncrementUsageAsync(Guid providerId, DateOnly date, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
EmailChannelUsageEntity? entity = await DbSet
|
EmailChannelUsageEntity? entity = await EfRepository.Get()
|
||||||
|
.AsNoTracking()
|
||||||
.FirstOrDefaultAsync(x => x.ProviderId == providerId && x.Date == date, ct);
|
.FirstOrDefaultAsync(x => x.ProviderId == providerId && x.Date == date, ct);
|
||||||
|
|
||||||
if (entity is null)
|
if (entity is null)
|
||||||
await AddAsync(new EmailChannelUsageEntity { ProviderId = providerId, Date = date, SentCount = 1 }, ct);
|
await EfRepository.AddAsync(new EmailChannelUsageEntity { ProviderId = providerId, Date = date, SentCount = 1 });
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
entity.SentCount++;
|
entity.SentCount++;
|
||||||
Update(entity);
|
await EfRepository.UpdateAsync(entity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,26 +1,43 @@
|
|||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
using HrynCo.DAL.EF.Core;
|
using HrynCo.NotificationService.DAL.EF.Core;
|
||||||
using HrynCo.NotificationService.DAL.EF.Entities;
|
using HrynCo.NotificationService.DAL.EF.Entities;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
namespace HrynCo.NotificationService.DAL.EF.Repositories;
|
||||||
|
|
||||||
internal sealed class EmailTemplateRepository : EfRepository<NotificationDbContext, EmailTemplateEntity>, IEmailTemplateRepository
|
internal sealed class EmailTemplateRepository
|
||||||
|
: NotificationBaseRepository<EmailTemplateEntity>, IEmailTemplateRepository
|
||||||
{
|
{
|
||||||
public EmailTemplateRepository(NotificationDbContext dbContext) : base(dbContext)
|
public EmailTemplateRepository(NotificationDbContext dbContext) : base(dbContext)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IReadOnlyList<EmailTemplate>> GetAllAsync(CancellationToken ct = default)
|
public async Task<IReadOnlyList<EmailTemplate>> GetAllAsync(string? serviceName = null, string? key = null, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
List<EmailTemplateEntity> entities = await DbSet.ToListAsync(ct);
|
IQueryable<EmailTemplateEntity> query = EfRepository.Get();
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(serviceName))
|
||||||
|
{
|
||||||
|
query = query.Where(x => x.ServiceName == serviceName);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(key))
|
||||||
|
{
|
||||||
|
query = query.Where(x => x.Key == key);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<EmailTemplateEntity> entities = await query
|
||||||
|
.OrderBy(x => x.ServiceName).ThenBy(x => x.Key)
|
||||||
|
.AsNoTracking()
|
||||||
|
.ToListAsync(ct);
|
||||||
return entities.Select(MapToDomain).ToList();
|
return entities.Select(MapToDomain).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default)
|
public async Task<IReadOnlyList<EmailTemplate>> GetByServiceAsync(string serviceName, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
List<EmailTemplateEntity> entities = await DbSet
|
List<EmailTemplateEntity> entities = await EfRepository.Get()
|
||||||
|
.AsNoTracking()
|
||||||
.Where(x => x.ServiceName == serviceName)
|
.Where(x => x.ServiceName == serviceName)
|
||||||
.ToListAsync(ct);
|
.ToListAsync(ct);
|
||||||
|
|
||||||
@@ -29,28 +46,48 @@ internal sealed class EmailTemplateRepository : EfRepository<NotificationDbConte
|
|||||||
|
|
||||||
public async Task<EmailTemplate?> GetAsync(string serviceName, string key, string languageCode, CancellationToken ct = default)
|
public async Task<EmailTemplate?> GetAsync(string serviceName, string key, string languageCode, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
EmailTemplateEntity? entity = await DbSet.FirstOrDefaultAsync(
|
EmailTemplateEntity? entity = await EfRepository.Get()
|
||||||
x => x.ServiceName == serviceName && x.Key == key && x.LanguageCode == languageCode, ct);
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(
|
||||||
|
x => x.ServiceName == serviceName && x.Key == key && x.LanguageCode == languageCode, ct);
|
||||||
|
|
||||||
return entity is null ? null : MapToDomain(entity);
|
return entity is null ? null : MapToDomain(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task AddAsync(EmailTemplate EmailTemplate, CancellationToken ct = default) =>
|
public Task AddAsync(EmailTemplate EmailTemplate, CancellationToken ct = default)
|
||||||
base.AddAsync(MapToEntity(EmailTemplate), ct);
|
|
||||||
|
|
||||||
public Task UpdateAsync(EmailTemplate EmailTemplate, CancellationToken ct = default)
|
|
||||||
{
|
{
|
||||||
EmailTemplateEntity entity = MapToEntity(EmailTemplate);
|
return EfRepository.AddAsync(MapToEntity(EmailTemplate));
|
||||||
entity.Updated = DateTimeOffset.UtcNow;
|
}
|
||||||
Update(entity);
|
|
||||||
return Task.CompletedTask;
|
public async Task UpdateAsync(EmailTemplate EmailTemplate, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
EmailTemplateEntity? entity = await EfRepository.Get()
|
||||||
|
.FirstOrDefaultAsync(x => x.Id == EmailTemplate.Id, ct);
|
||||||
|
|
||||||
|
if (entity is null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
entity.ServiceName = EmailTemplate.ServiceName;
|
||||||
|
entity.Key = EmailTemplate.Key;
|
||||||
|
entity.LanguageCode = EmailTemplate.LanguageCode;
|
||||||
|
entity.Subject = EmailTemplate.Subject;
|
||||||
|
entity.HtmlBody = EmailTemplate.HtmlBody;
|
||||||
|
entity.TextBody = EmailTemplate.TextBody;
|
||||||
|
entity.Variables = EmailTemplate.Variables
|
||||||
|
.Select(v => new EmailTemplateVariableData { Name = v.Name, Required = v.Required })
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
await EfRepository.SaveChangesAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task DeleteAsync(EmailTemplate EmailTemplate, CancellationToken ct = default)
|
public async Task DeleteAsync(EmailTemplate EmailTemplate, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
EmailTemplateEntity? entity = await DbSet.FindAsync([EmailTemplate.Id], ct);
|
EmailTemplateEntity? entity = await EfRepository.Get()
|
||||||
|
.FirstOrDefaultAsync(x => x.Id == EmailTemplate.Id, ct);
|
||||||
if (entity is not null)
|
if (entity is not null)
|
||||||
Delete(entity);
|
await EfRepository.DeleteAsync(entity);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static EmailTemplate MapToDomain(EmailTemplateEntity e) => new()
|
private static EmailTemplate MapToDomain(EmailTemplateEntity e) => new()
|
||||||
@@ -80,4 +117,4 @@ internal sealed class EmailTemplateRepository : EfRepository<NotificationDbConte
|
|||||||
Created = t.Created,
|
Created = t.Created,
|
||||||
Updated = t.Updated
|
Updated = t.Updated
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,10 +16,10 @@ public static class ServiceCollectionExtensions
|
|||||||
services.AddDbContext<NotificationDbContext>(options =>
|
services.AddDbContext<NotificationDbContext>(options =>
|
||||||
options.UseNpgsql(connectionString));
|
options.UseNpgsql(connectionString));
|
||||||
|
|
||||||
services.AddScoped<IUnitOfWork, UnitOfWork>();
|
|
||||||
services.AddScoped<IEmailTemplateRepository, EmailTemplateRepository>();
|
services.AddScoped<IEmailTemplateRepository, EmailTemplateRepository>();
|
||||||
services.AddScoped<IEmailChannelRepository, EmailChannelRepository>();
|
services.AddScoped<IEmailChannelRepository, EmailChannelRepository>();
|
||||||
services.AddScoped<IEmailChannelUsageRepository, EmailChannelUsageRepository>();
|
services.AddScoped<IEmailChannelUsageRepository, EmailChannelUsageRepository>();
|
||||||
|
services.AddScoped<IUnitOfWork, NotificationUnitOfWork>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
namespace HrynCo.NotificationService.Migrator;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
internal sealed class DevelopmentDataSeeder
|
||||||
|
{
|
||||||
|
internal const string DefaultServiceName = "TestService";
|
||||||
|
internal const string DefaultLanguageCode = "en";
|
||||||
|
|
||||||
|
private readonly IEmailChannelRepository _channels;
|
||||||
|
private readonly IEmailTemplateRepository _templates;
|
||||||
|
private readonly ILogger<DevelopmentDataSeeder> _logger;
|
||||||
|
|
||||||
|
public DevelopmentDataSeeder(
|
||||||
|
IEmailChannelRepository channels,
|
||||||
|
IEmailTemplateRepository templates,
|
||||||
|
ILogger<DevelopmentDataSeeder> logger)
|
||||||
|
{
|
||||||
|
_channels = channels;
|
||||||
|
_templates = templates;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SeedAsync(string serviceName, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(serviceName))
|
||||||
|
throw new InvalidOperationException("Development seed service name is not configured.");
|
||||||
|
|
||||||
|
await SeedMailpitChannelAsync(serviceName, cancellationToken);
|
||||||
|
|
||||||
|
foreach (EmailTemplate template in CreateTemplates(serviceName))
|
||||||
|
{
|
||||||
|
EmailTemplate? existing = await _templates.GetAsync(
|
||||||
|
template.ServiceName, template.Key, template.LanguageCode, cancellationToken);
|
||||||
|
|
||||||
|
if (existing is not null)
|
||||||
|
{
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Development email template already exists; leaving it unchanged [ServiceName={ServiceName}, Key={TemplateKey}, LanguageCode={LanguageCode}]",
|
||||||
|
template.ServiceName, template.Key, template.LanguageCode);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _templates.AddAsync(template, cancellationToken);
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Created development email template [ServiceName={ServiceName}, Key={TemplateKey}, LanguageCode={LanguageCode}]",
|
||||||
|
template.ServiceName, template.Key, template.LanguageCode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SeedMailpitChannelAsync(string serviceName, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
IReadOnlyList<EmailChannel> existingChannels = await _channels.GetByServiceAsync(
|
||||||
|
serviceName, cancellationToken);
|
||||||
|
|
||||||
|
if (existingChannels.Count > 0)
|
||||||
|
{
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Development email channel already exists; leaving all channels unchanged [ServiceName={ServiceName}]",
|
||||||
|
serviceName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var channel = new EmailChannel
|
||||||
|
{
|
||||||
|
ServiceName = serviceName,
|
||||||
|
Priority = 1,
|
||||||
|
EmailChannelType = EmailChannelType.Smtp,
|
||||||
|
Settings = new SmtpChannelSettings
|
||||||
|
{
|
||||||
|
Host = "mailpit",
|
||||||
|
Port = 1025,
|
||||||
|
Username = string.Empty,
|
||||||
|
Password = string.Empty,
|
||||||
|
UseSsl = false,
|
||||||
|
FromEmail = "no-reply@local.hrynco.test",
|
||||||
|
FromName = "HrynCo Development"
|
||||||
|
},
|
||||||
|
WarnThresholdPercent = 90,
|
||||||
|
IsActive = true,
|
||||||
|
Created = DateTimeOffset.UtcNow
|
||||||
|
};
|
||||||
|
|
||||||
|
await _channels.AddAsync(channel, cancellationToken);
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Created Mailpit development email channel [ServiceName={ServiceName}]",
|
||||||
|
serviceName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<EmailTemplate> CreateTemplates(string serviceName)
|
||||||
|
{
|
||||||
|
DateTimeOffset created = DateTimeOffset.UtcNow;
|
||||||
|
|
||||||
|
return
|
||||||
|
[
|
||||||
|
new EmailTemplate
|
||||||
|
{
|
||||||
|
ServiceName = serviceName,
|
||||||
|
Key = "TestEmail",
|
||||||
|
LanguageCode = DefaultLanguageCode,
|
||||||
|
Subject = "Test notification",
|
||||||
|
HtmlBody = "<p>Hello {{RecipientName}},</p><p>{{Message}}</p>",
|
||||||
|
TextBody = "Hello {{RecipientName}}, {{Message}}",
|
||||||
|
Variables =
|
||||||
|
[
|
||||||
|
new EmailTemplateVariable { Name = "RecipientName", Required = true },
|
||||||
|
new EmailTemplateVariable { Name = "Message", Required = true }
|
||||||
|
],
|
||||||
|
Created = created
|
||||||
|
}
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
using HrynCo.NotificationService.DAL.EF;
|
using HrynCo.NotificationService.DAL.EF;
|
||||||
|
using HrynCo.NotificationService.Migrator;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
@@ -21,8 +23,8 @@ try
|
|||||||
var connectionString = ctx.Configuration["App:ConnectionString"]
|
var connectionString = ctx.Configuration["App:ConnectionString"]
|
||||||
?? throw new InvalidOperationException("App:ConnectionString is not configured.");
|
?? throw new InvalidOperationException("App:ConnectionString is not configured.");
|
||||||
|
|
||||||
services.AddDbContext<NotificationDbContext>(options =>
|
services.AddNotificationDataAccess(connectionString);
|
||||||
options.UseNpgsql(connectionString));
|
services.AddScoped<DevelopmentDataSeeder>();
|
||||||
})
|
})
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
@@ -32,6 +34,18 @@ try
|
|||||||
Log.Information("Applying migrations...");
|
Log.Information("Applying migrations...");
|
||||||
await db.Database.MigrateAsync();
|
await db.Database.MigrateAsync();
|
||||||
Log.Information("Migrations applied successfully.");
|
Log.Information("Migrations applied successfully.");
|
||||||
|
|
||||||
|
var environment = scope.ServiceProvider.GetRequiredService<IHostEnvironment>();
|
||||||
|
if (environment.IsDevelopment())
|
||||||
|
{
|
||||||
|
string serviceName = host.Services.GetRequiredService<IConfiguration>()["DevelopmentSeed:ServiceName"]
|
||||||
|
?? DevelopmentDataSeeder.DefaultServiceName;
|
||||||
|
|
||||||
|
Log.Information("Seeding development email configuration...");
|
||||||
|
var seeder = scope.ServiceProvider.GetRequiredService<DevelopmentDataSeeder>();
|
||||||
|
await seeder.SeedAsync(serviceName);
|
||||||
|
Log.Information("Development email configuration is ready.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
[assembly: InternalsVisibleTo("HrynCo.NotificationService.Services.Tests")]
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
namespace HrynCo.NotificationService.Services.Tests;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
|
using HrynCo.NotificationService.Migrator;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using NSubstitute;
|
||||||
|
|
||||||
|
public sealed class DevelopmentDataSeederTests
|
||||||
|
{
|
||||||
|
private readonly IEmailChannelRepository _channels = Substitute.For<IEmailChannelRepository>();
|
||||||
|
private readonly IEmailTemplateRepository _templates = Substitute.For<IEmailTemplateRepository>();
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SeedAsync_WhenConfigurationIsMissing_CreatesMailpitChannelAndTestTemplate()
|
||||||
|
{
|
||||||
|
_channels.GetByServiceAsync("TestService", Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Array.Empty<EmailChannel>());
|
||||||
|
_templates.GetAsync("TestService", "TestEmail", "en", Arg.Any<CancellationToken>())
|
||||||
|
.Returns((EmailTemplate?)null);
|
||||||
|
|
||||||
|
DevelopmentDataSeeder seeder = CreateSeeder();
|
||||||
|
|
||||||
|
await seeder.SeedAsync("TestService", CancellationToken.None);
|
||||||
|
|
||||||
|
await _channels.Received(1).AddAsync(
|
||||||
|
Arg.Is<EmailChannel>(channel => IsMailpitChannel(channel)),
|
||||||
|
Arg.Any<CancellationToken>());
|
||||||
|
await _templates.Received(1).AddAsync(
|
||||||
|
Arg.Is<EmailTemplate>(template =>
|
||||||
|
template.ServiceName == "TestService" &&
|
||||||
|
template.Key == "TestEmail" &&
|
||||||
|
template.Variables.Any(variable => variable.Name == "Message" && variable.Required)),
|
||||||
|
Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SeedAsync_WhenConfigurationExists_DoesNotDuplicateOrOverwriteIt()
|
||||||
|
{
|
||||||
|
_channels.GetByServiceAsync("TestService", Arg.Any<CancellationToken>())
|
||||||
|
.Returns([new EmailChannel
|
||||||
|
{
|
||||||
|
ServiceName = "TestService",
|
||||||
|
EmailChannelType = EmailChannelType.Smtp,
|
||||||
|
Settings = new SmtpChannelSettings()
|
||||||
|
}]);
|
||||||
|
_templates.GetAsync("TestService", "TestEmail", "en", Arg.Any<CancellationToken>())
|
||||||
|
.Returns(new EmailTemplate
|
||||||
|
{
|
||||||
|
ServiceName = "TestService",
|
||||||
|
Key = "TestEmail",
|
||||||
|
LanguageCode = "en",
|
||||||
|
Subject = "Existing",
|
||||||
|
HtmlBody = "Existing",
|
||||||
|
TextBody = "Existing"
|
||||||
|
});
|
||||||
|
|
||||||
|
DevelopmentDataSeeder seeder = CreateSeeder();
|
||||||
|
|
||||||
|
await seeder.SeedAsync("TestService", CancellationToken.None);
|
||||||
|
|
||||||
|
await _channels.DidNotReceive().AddAsync(Arg.Any<EmailChannel>(), Arg.Any<CancellationToken>());
|
||||||
|
await _templates.DidNotReceive().AddAsync(Arg.Any<EmailTemplate>(), Arg.Any<CancellationToken>());
|
||||||
|
await _channels.DidNotReceive().UpdateAsync(Arg.Any<EmailChannel>(), Arg.Any<CancellationToken>());
|
||||||
|
await _templates.DidNotReceive().UpdateAsync(Arg.Any<EmailTemplate>(), Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
private DevelopmentDataSeeder CreateSeeder() => new(
|
||||||
|
_channels,
|
||||||
|
_templates,
|
||||||
|
NullLogger<DevelopmentDataSeeder>.Instance);
|
||||||
|
|
||||||
|
private static bool IsMailpitChannel(EmailChannel channel)
|
||||||
|
{
|
||||||
|
return channel.ServiceName == "TestService" &&
|
||||||
|
channel.IsActive &&
|
||||||
|
channel.Settings is SmtpChannelSettings smtp &&
|
||||||
|
smtp.Host == "mailpit" &&
|
||||||
|
smtp.Port == 1025 &&
|
||||||
|
!smtp.UseSsl;
|
||||||
|
}
|
||||||
|
}
|
||||||
+88
@@ -0,0 +1,88 @@
|
|||||||
|
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
public sealed class EmailTemplateRenderingServiceTests
|
||||||
|
{
|
||||||
|
private readonly EmailTemplateRenderingService _service = new();
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Render_InterpolatesItemTrackerVariables()
|
||||||
|
{
|
||||||
|
EmailTemplate template = CreateTemplate();
|
||||||
|
SendEmailMessageData data = CreateData(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["AppName"] = "StoreMate",
|
||||||
|
["VerificationUrl"] = "https://example.invalid/verify"
|
||||||
|
});
|
||||||
|
|
||||||
|
RenderedEmail result = _service.Render(template, data);
|
||||||
|
|
||||||
|
Assert.Equal("Verify StoreMate", result.Subject);
|
||||||
|
Assert.Equal("<a href=\"https://example.invalid/verify\">Verify</a>", result.HtmlBody);
|
||||||
|
Assert.Equal("Verify at https://example.invalid/verify", result.TextBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Render_WhenRequiredVariableIsMissing_ThrowsObservableFailure()
|
||||||
|
{
|
||||||
|
EmailTemplate template = CreateTemplate();
|
||||||
|
SendEmailMessageData data = CreateData(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["AppName"] = "StoreMate"
|
||||||
|
});
|
||||||
|
|
||||||
|
InvalidDataException exception = Assert.Throws<InvalidDataException>(
|
||||||
|
() => _service.Render(template, data));
|
||||||
|
|
||||||
|
Assert.Equal("Required template variables are missing: VerificationUrl.", exception.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Render_HtmlEncodesVariablesWithoutChangingSubjectOrTextBody()
|
||||||
|
{
|
||||||
|
EmailTemplate template = CreateTemplate();
|
||||||
|
SendEmailMessageData data = CreateData(new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["AppName"] = "Invemory <script>alert('xss')</script>",
|
||||||
|
["VerificationUrl"] = "https://example.invalid/verify?next=\" onclick=\"alert('xss')"
|
||||||
|
});
|
||||||
|
|
||||||
|
RenderedEmail result = _service.Render(template, data);
|
||||||
|
|
||||||
|
Assert.Equal("Verify Invemory <script>alert('xss')</script>", result.Subject);
|
||||||
|
Assert.Equal(
|
||||||
|
"<a href=\"https://example.invalid/verify?next=" onclick="alert('xss')\">Verify</a>",
|
||||||
|
result.HtmlBody);
|
||||||
|
Assert.Equal(
|
||||||
|
"Verify at https://example.invalid/verify?next=\" onclick=\"alert('xss')",
|
||||||
|
result.TextBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static EmailTemplate CreateTemplate() => new()
|
||||||
|
{
|
||||||
|
ServiceName = "StoreMate-Prod",
|
||||||
|
Key = "EmailVerification",
|
||||||
|
LanguageCode = "uk",
|
||||||
|
Subject = "Verify {{AppName}}",
|
||||||
|
HtmlBody = "<a href=\"{{VerificationUrl}}\">Verify</a>",
|
||||||
|
TextBody = "Verify at {{VerificationUrl}}",
|
||||||
|
Variables =
|
||||||
|
[
|
||||||
|
new EmailTemplateVariable { Name = "AppName", Required = true },
|
||||||
|
new EmailTemplateVariable { Name = "VerificationUrl", Required = true }
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
private static SendEmailMessageData CreateData(IReadOnlyDictionary<string, string> variables) => new()
|
||||||
|
{
|
||||||
|
ServiceName = "StoreMate-Prod",
|
||||||
|
TemplateKey = "EmailVerification",
|
||||||
|
RecipientEmail = "owner@example.com",
|
||||||
|
RecipientName = "Owner",
|
||||||
|
LanguageCode = "uk",
|
||||||
|
Variables = variables
|
||||||
|
};
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
using NSubstitute;
|
||||||
|
|
||||||
|
public sealed class EmailTemplateServiceTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task GetAsync_WhenRequestedLanguageDoesNotExist_DoesNotSilentlyFallback()
|
||||||
|
{
|
||||||
|
IEmailTemplateRepository repository = Substitute.For<IEmailTemplateRepository>();
|
||||||
|
var service = new EmailTemplateService(repository);
|
||||||
|
|
||||||
|
InvalidOperationException exception = await Assert.ThrowsAsync<InvalidOperationException>(
|
||||||
|
() => service.GetAsync("StoreMate-Prod", "EmailVerification", "UK", CancellationToken.None));
|
||||||
|
|
||||||
|
Assert.Contains("language='uk'", exception.Message);
|
||||||
|
await repository.Received(1).GetAsync(
|
||||||
|
"StoreMate-Prod",
|
||||||
|
"EmailVerification",
|
||||||
|
"uk",
|
||||||
|
CancellationToken.None);
|
||||||
|
await repository.DidNotReceive().GetAsync(
|
||||||
|
"StoreMate-Prod",
|
||||||
|
"EmailVerification",
|
||||||
|
"en",
|
||||||
|
Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
}
|
||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
using System.Net.Mail;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
|
||||||
|
public sealed class NotificationDeliveryErrorFormatterTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Format_UsesInnermostMessageAndRemovesLineBreaks()
|
||||||
|
{
|
||||||
|
var exception = new InvalidOperationException(
|
||||||
|
"outer",
|
||||||
|
new Exception("provider failed\r\nretry rejected"));
|
||||||
|
|
||||||
|
string result = NotificationDeliveryErrorFormatter.Format(exception);
|
||||||
|
|
||||||
|
Assert.Equal(
|
||||||
|
"Notification delivery failed after all retry attempts (provider failed retry rejected).",
|
||||||
|
result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Format_UnresolvedSmtpHost_AddsSafeChannelContext()
|
||||||
|
{
|
||||||
|
var socketException = new SocketException((int)SocketError.HostNotFound);
|
||||||
|
var exception = new SmtpException("Failure sending mail.", socketException);
|
||||||
|
|
||||||
|
string result = NotificationDeliveryErrorFormatter.Format(exception);
|
||||||
|
|
||||||
|
Assert.Equal(
|
||||||
|
$"SMTP delivery failed after all retry attempts: the configured SMTP server host could not be resolved ({socketException.Message}).",
|
||||||
|
result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Format_RefusedSmtpConnection_AddsSafeChannelContext()
|
||||||
|
{
|
||||||
|
var socketException = new SocketException((int)SocketError.ConnectionRefused);
|
||||||
|
var exception = new SmtpException("Failure sending mail.", socketException);
|
||||||
|
|
||||||
|
string result = NotificationDeliveryErrorFormatter.Format(exception);
|
||||||
|
|
||||||
|
Assert.Equal(
|
||||||
|
$"SMTP delivery failed after all retry attempts: the configured SMTP server refused the connection ({socketException.Message}).",
|
||||||
|
result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Format_LongError_IsBoundedToOutboxColumnLength()
|
||||||
|
{
|
||||||
|
var exception = new Exception(new string('x', 2100));
|
||||||
|
|
||||||
|
string result = NotificationDeliveryErrorFormatter.Format(exception);
|
||||||
|
|
||||||
|
Assert.Equal(2000, result.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
+107
@@ -0,0 +1,107 @@
|
|||||||
|
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
using Hrynco.RabbitMq;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using NSubstitute;
|
||||||
|
|
||||||
|
public sealed class NotificationResultPublisherTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task PublishAsync_TerminalFailure_PublishesNeutralFailureResultToReplyQueue()
|
||||||
|
{
|
||||||
|
IRabbitMqPublisher rabbitMqPublisher = Substitute.For<IRabbitMqPublisher>();
|
||||||
|
var publisher = new NotificationResultPublisher(
|
||||||
|
rabbitMqPublisher,
|
||||||
|
NullLogger<NotificationResultPublisher>.Instance);
|
||||||
|
SendEmailMessage message = CreateMessage();
|
||||||
|
NotificationResultMessage? publishedResult = null;
|
||||||
|
rabbitMqPublisher
|
||||||
|
.When(x => x.PublishAsync(
|
||||||
|
"item-tracker.notifications.result",
|
||||||
|
Arg.Any<NotificationResultMessage>(),
|
||||||
|
Arg.Any<CancellationToken>()))
|
||||||
|
.Do(call => publishedResult = call.ArgAt<NotificationResultMessage>(1));
|
||||||
|
|
||||||
|
await publisher.PublishAsync(
|
||||||
|
message,
|
||||||
|
"Email provider could not deliver the notification.",
|
||||||
|
CancellationToken.None);
|
||||||
|
|
||||||
|
await rabbitMqPublisher.Received(1).PublishAsync(
|
||||||
|
"item-tracker.notifications.result",
|
||||||
|
Arg.Any<NotificationResultMessage>(),
|
||||||
|
CancellationToken.None);
|
||||||
|
Assert.NotNull(publishedResult);
|
||||||
|
Assert.Equal(message.CorrelationContext.CorrelationId, publishedResult.CorrelationContext.CorrelationId);
|
||||||
|
Assert.Null(publishedResult.CorrelationContext.ReplyTo);
|
||||||
|
Assert.Equal(message.Data.ServiceName, publishedResult.Data.ServiceName);
|
||||||
|
Assert.Equal(message.Data.TemplateKey, publishedResult.Data.TemplateKey);
|
||||||
|
Assert.Equal(message.Data.RecipientEmail, publishedResult.Data.RecipientEmail);
|
||||||
|
Assert.Equal("Email provider could not deliver the notification.", publishedResult.Data.ErrorMessage);
|
||||||
|
Assert.False(publishedResult.Data.IsSuccess);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PublishAsync_NoReplyQueue_DoesNotPublish()
|
||||||
|
{
|
||||||
|
IRabbitMqPublisher rabbitMqPublisher = Substitute.For<IRabbitMqPublisher>();
|
||||||
|
var publisher = new NotificationResultPublisher(
|
||||||
|
rabbitMqPublisher,
|
||||||
|
NullLogger<NotificationResultPublisher>.Instance);
|
||||||
|
SendEmailMessage message = CreateMessage();
|
||||||
|
message.CorrelationContext = message.CorrelationContext with { ReplyTo = null };
|
||||||
|
|
||||||
|
await publisher.PublishAsync(message, "delivery failed", CancellationToken.None);
|
||||||
|
|
||||||
|
await rabbitMqPublisher.DidNotReceive()
|
||||||
|
.PublishAsync<NotificationResultData>(
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<NotificationResultMessage>(),
|
||||||
|
Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task PublishAsync_ResultBrokerFailure_IsBestEffort()
|
||||||
|
{
|
||||||
|
IRabbitMqPublisher rabbitMqPublisher = Substitute.For<IRabbitMqPublisher>();
|
||||||
|
rabbitMqPublisher
|
||||||
|
.PublishAsync(
|
||||||
|
Arg.Any<string>(),
|
||||||
|
Arg.Any<NotificationResultMessage>(),
|
||||||
|
Arg.Any<CancellationToken>())
|
||||||
|
.Returns<Task>(_ => throw new InvalidOperationException("reply broker unavailable"));
|
||||||
|
var publisher = new NotificationResultPublisher(
|
||||||
|
rabbitMqPublisher,
|
||||||
|
NullLogger<NotificationResultPublisher>.Instance);
|
||||||
|
|
||||||
|
Exception? exception = await Record.ExceptionAsync(() => publisher.PublishAsync(
|
||||||
|
CreateMessage(),
|
||||||
|
"delivery failed",
|
||||||
|
CancellationToken.None));
|
||||||
|
|
||||||
|
Assert.Null(exception);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SendEmailMessage CreateMessage()
|
||||||
|
{
|
||||||
|
return new SendEmailMessage
|
||||||
|
{
|
||||||
|
CorrelationContext = new CorrelationContext
|
||||||
|
{
|
||||||
|
CorrelationId = "correlation-id",
|
||||||
|
ReplyTo = "item-tracker.notifications.result"
|
||||||
|
},
|
||||||
|
Data = new SendEmailMessageData
|
||||||
|
{
|
||||||
|
ServiceName = "TestService",
|
||||||
|
TemplateKey = "TestEmail",
|
||||||
|
RecipientEmail = "test.user@itemtracker.local",
|
||||||
|
RecipientName = "Test User",
|
||||||
|
LanguageCode = "en",
|
||||||
|
Variables = new Dictionary<string, string>()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
public sealed class RecipientAddressRedactorTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("owner@example.com", "o***@e***.com")]
|
||||||
|
[InlineData("a@b.test", "a***@b***.test")]
|
||||||
|
[InlineData("invalid", "***")]
|
||||||
|
[InlineData(null, "<missing>")]
|
||||||
|
public void Redact_DoesNotExposeFullAddress(string? address, string expected)
|
||||||
|
{
|
||||||
|
Assert.Equal(expected, RecipientAddressRedactor.Redact(address));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
public sealed class SendEmailContractTests
|
||||||
|
{
|
||||||
|
private const string ItemTrackerPayload = """
|
||||||
|
{
|
||||||
|
"CorrelationContext": {
|
||||||
|
"CorrelationId": "3ec4ad3f-0a8a-49f3-b31d-cdad5d1b95cc",
|
||||||
|
"ReplyTo": "item-tracker.notifications.result"
|
||||||
|
},
|
||||||
|
"Data": {
|
||||||
|
"ServiceName": "StoreMate-Prod",
|
||||||
|
"TemplateKey": "EmailVerification",
|
||||||
|
"RecipientEmail": "owner@example.com",
|
||||||
|
"RecipientName": "StoreMate Owner",
|
||||||
|
"Variables": {
|
||||||
|
"AppName": "StoreMate",
|
||||||
|
"VerificationUrl": "https://example.invalid/sensitive-token"
|
||||||
|
},
|
||||||
|
"LanguageCode": "uk"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PascalCaseItemTrackerPayload_DeserializesWithoutLosingValues()
|
||||||
|
{
|
||||||
|
SendEmailMessage? message = JsonSerializer.Deserialize<SendEmailMessage>(ItemTrackerPayload);
|
||||||
|
|
||||||
|
Assert.NotNull(message);
|
||||||
|
SendEmailMessageValidator.Validate(message);
|
||||||
|
Assert.Equal("3ec4ad3f-0a8a-49f3-b31d-cdad5d1b95cc", message.CorrelationContext.CorrelationId);
|
||||||
|
Assert.Equal("item-tracker.notifications.result", message.CorrelationContext.ReplyTo);
|
||||||
|
Assert.Equal("StoreMate-Prod", message.Data.ServiceName);
|
||||||
|
Assert.Equal("EmailVerification", message.Data.TemplateKey);
|
||||||
|
Assert.Equal("owner@example.com", message.Data.RecipientEmail);
|
||||||
|
Assert.Equal("StoreMate Owner", message.Data.RecipientName);
|
||||||
|
Assert.Equal("uk", message.Data.LanguageCode);
|
||||||
|
Assert.Equal("StoreMate", message.Data.Variables["AppName"]);
|
||||||
|
Assert.Equal(
|
||||||
|
"https://example.invalid/sensitive-token",
|
||||||
|
message.Data.Variables["VerificationUrl"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingLanguageCode_IsRejected()
|
||||||
|
{
|
||||||
|
SendEmailMessage? message = JsonSerializer.Deserialize<SendEmailMessage>(
|
||||||
|
ItemTrackerPayload.Replace("\"uk\"", "null", StringComparison.Ordinal));
|
||||||
|
|
||||||
|
InvalidDataException exception = Assert.Throws<InvalidDataException>(
|
||||||
|
() => SendEmailMessageValidator.Validate(message!));
|
||||||
|
|
||||||
|
Assert.Equal("LanguageCode is required.", exception.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
+77
@@ -0,0 +1,77 @@
|
|||||||
|
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using HrynCo.NotificationService.Worker;
|
||||||
|
using Hrynco.RabbitMq;
|
||||||
|
|
||||||
|
public sealed class SendEmailDeliveryValidatorTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void ValidItemTrackerDelivery_IsAccepted()
|
||||||
|
{
|
||||||
|
string? error = SendEmailDeliveryValidator.GetValidationError(
|
||||||
|
CreateMessage(),
|
||||||
|
CreateContext(),
|
||||||
|
SendEmailConsumer.SupportedMessageType);
|
||||||
|
|
||||||
|
Assert.Null(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MissingMessageId_IsRejected()
|
||||||
|
{
|
||||||
|
RabbitMqMessageContext context = CreateContext() with { MessageId = null };
|
||||||
|
|
||||||
|
string? error = SendEmailDeliveryValidator.GetValidationError(
|
||||||
|
CreateMessage(),
|
||||||
|
context,
|
||||||
|
SendEmailConsumer.SupportedMessageType);
|
||||||
|
|
||||||
|
Assert.Equal("AMQP MessageId is required.", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void UnsupportedContractVersion_IsRejected()
|
||||||
|
{
|
||||||
|
RabbitMqMessageContext context = CreateContext() with
|
||||||
|
{
|
||||||
|
MessageType = "Notification.SendEmail.v2"
|
||||||
|
};
|
||||||
|
|
||||||
|
string? error = SendEmailDeliveryValidator.GetValidationError(
|
||||||
|
CreateMessage(),
|
||||||
|
context,
|
||||||
|
SendEmailConsumer.SupportedMessageType);
|
||||||
|
|
||||||
|
Assert.Equal("Unsupported AMQP message type 'Notification.SendEmail.v2'.", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RabbitMqMessageContext CreateContext() => new()
|
||||||
|
{
|
||||||
|
QueueName = SendEmailConsumer.IncomingQueue,
|
||||||
|
Exchange = string.Empty,
|
||||||
|
RoutingKey = SendEmailConsumer.IncomingQueue,
|
||||||
|
MessageId = Guid.NewGuid().ToString("D"),
|
||||||
|
MessageType = SendEmailConsumer.SupportedMessageType,
|
||||||
|
CorrelationId = "correlation-id",
|
||||||
|
ContentType = "application/json"
|
||||||
|
};
|
||||||
|
|
||||||
|
private static SendEmailMessage CreateMessage() => new()
|
||||||
|
{
|
||||||
|
CorrelationContext = new CorrelationContext
|
||||||
|
{
|
||||||
|
CorrelationId = "correlation-id",
|
||||||
|
ReplyTo = "item-tracker.notifications.result"
|
||||||
|
},
|
||||||
|
Data = new SendEmailMessageData
|
||||||
|
{
|
||||||
|
ServiceName = "StoreMate-Prod",
|
||||||
|
TemplateKey = "EmailVerification",
|
||||||
|
RecipientEmail = "owner@example.com",
|
||||||
|
RecipientName = "Owner",
|
||||||
|
LanguageCode = "uk",
|
||||||
|
Variables = new Dictionary<string, string> { ["AppName"] = "StoreMate" }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
namespace HrynCo.NotificationService.Services.Tests.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
using Hrynco.RabbitMq;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using NSubstitute;
|
||||||
|
|
||||||
|
public sealed class SendEmailServiceTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task ProcessAsync_ValidItemTrackerMessage_SendsOnceAndUpdatesUsage()
|
||||||
|
{
|
||||||
|
Guid channelId = Guid.NewGuid();
|
||||||
|
var settings = new SmtpChannelSettings
|
||||||
|
{
|
||||||
|
Host = "smtp.example.invalid",
|
||||||
|
Port = 587,
|
||||||
|
Username = "smtp-user",
|
||||||
|
Password = "not-a-real-secret",
|
||||||
|
UseSsl = true,
|
||||||
|
FromEmail = "notifications@example.com",
|
||||||
|
FromName = "StoreMate"
|
||||||
|
};
|
||||||
|
var channel = new EmailChannel
|
||||||
|
{
|
||||||
|
Id = channelId,
|
||||||
|
ServiceName = "StoreMate-Prod",
|
||||||
|
Priority = 1,
|
||||||
|
EmailChannelType = EmailChannelType.Smtp,
|
||||||
|
Settings = settings,
|
||||||
|
IsActive = true
|
||||||
|
};
|
||||||
|
var template = new EmailTemplate
|
||||||
|
{
|
||||||
|
ServiceName = "StoreMate-Prod",
|
||||||
|
Key = "EmailVerification",
|
||||||
|
LanguageCode = "uk",
|
||||||
|
Subject = "Verify {{AppName}}",
|
||||||
|
HtmlBody = "<p>{{AppName}}</p>",
|
||||||
|
TextBody = "{{AppName}}",
|
||||||
|
Variables = [new EmailTemplateVariable { Name = "AppName", Required = true }]
|
||||||
|
};
|
||||||
|
|
||||||
|
IEmailChannelRepository channels = Substitute.For<IEmailChannelRepository>();
|
||||||
|
channels.GetByServiceAsync("StoreMate-Prod", Arg.Any<CancellationToken>())
|
||||||
|
.Returns([channel]);
|
||||||
|
IEmailChannelUsageRepository usage = Substitute.For<IEmailChannelUsageRepository>();
|
||||||
|
IEmailTemplateService templates = Substitute.For<IEmailTemplateService>();
|
||||||
|
templates.GetAsync("StoreMate-Prod", "EmailVerification", "uk", Arg.Any<CancellationToken>())
|
||||||
|
.Returns(template);
|
||||||
|
var renderer = new EmailTemplateRenderingService();
|
||||||
|
var smtp = new RecordingSmtpEmailSender();
|
||||||
|
INotificationResultPublisher resultPublisher = Substitute.For<INotificationResultPublisher>();
|
||||||
|
var service = new SendEmailService(
|
||||||
|
channels,
|
||||||
|
usage,
|
||||||
|
templates,
|
||||||
|
renderer,
|
||||||
|
smtp,
|
||||||
|
resultPublisher,
|
||||||
|
NullLogger<SendEmailService>.Instance);
|
||||||
|
var message = new SendEmailMessage
|
||||||
|
{
|
||||||
|
CorrelationContext = new CorrelationContext
|
||||||
|
{
|
||||||
|
CorrelationId = Guid.NewGuid().ToString("D")
|
||||||
|
},
|
||||||
|
Data = new SendEmailMessageData
|
||||||
|
{
|
||||||
|
ServiceName = "StoreMate-Prod",
|
||||||
|
TemplateKey = "EmailVerification",
|
||||||
|
RecipientEmail = "owner@example.com",
|
||||||
|
RecipientName = "Owner",
|
||||||
|
LanguageCode = "uk",
|
||||||
|
Variables = new Dictionary<string, string> { ["AppName"] = "StoreMate" }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
await service.ProcessAsync(message, CancellationToken.None);
|
||||||
|
|
||||||
|
Assert.Equal(1, smtp.SendCount);
|
||||||
|
Assert.Same(settings, smtp.Settings);
|
||||||
|
Assert.Equal("Verify StoreMate", smtp.Email?.Subject);
|
||||||
|
Assert.Equal("owner@example.com", smtp.RecipientEmail);
|
||||||
|
Assert.Equal("Owner", smtp.RecipientName);
|
||||||
|
await usage.Received(1).IncrementUsageAsync(
|
||||||
|
channelId,
|
||||||
|
Arg.Any<DateOnly>(),
|
||||||
|
CancellationToken.None);
|
||||||
|
await resultPublisher.Received(1).PublishAsync(
|
||||||
|
message,
|
||||||
|
null,
|
||||||
|
CancellationToken.None);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class RecordingSmtpEmailSender : ISmtpEmailSender
|
||||||
|
{
|
||||||
|
public int SendCount { get; private set; }
|
||||||
|
public SmtpChannelSettings? Settings { get; private set; }
|
||||||
|
public RenderedEmail? Email { get; private set; }
|
||||||
|
public string? RecipientEmail { get; private set; }
|
||||||
|
public string? RecipientName { get; private set; }
|
||||||
|
|
||||||
|
public Task SendAsync(
|
||||||
|
SmtpChannelSettings settings,
|
||||||
|
RenderedEmail email,
|
||||||
|
string recipientEmail,
|
||||||
|
string recipientName,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
SendCount++;
|
||||||
|
Settings = settings;
|
||||||
|
Email = email;
|
||||||
|
RecipientEmail = recipientEmail;
|
||||||
|
RecipientName = recipientName;
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-1
@@ -10,6 +10,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="coverlet.collector" />
|
<PackageReference Include="coverlet.collector" />
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||||
|
<PackageReference Include="NSubstitute" />
|
||||||
<PackageReference Include="xunit" />
|
<PackageReference Include="xunit" />
|
||||||
<PackageReference Include="xunit.runner.visualstudio" />
|
<PackageReference Include="xunit.runner.visualstudio" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
@@ -21,6 +22,10 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\HrynCo.NotificationService.Services\HrynCo.NotificationService.Services.csproj" />
|
<ProjectReference Include="..\HrynCo.NotificationService.Services\HrynCo.NotificationService.Services.csproj" />
|
||||||
<ProjectReference Include="..\HrynCo.NotificationService.DAL.Abstract\HrynCo.NotificationService.DAL.Abstract.csproj" />
|
<ProjectReference Include="..\HrynCo.NotificationService.DAL.Abstract\HrynCo.NotificationService.DAL.Abstract.csproj" />
|
||||||
|
<ProjectReference Include="..\HrynCo.NotificationService.Contracts\HrynCo.NotificationService.Contracts.csproj" />
|
||||||
|
<ProjectReference Include="..\HrynCo.NotificationService.Worker.Services\HrynCo.NotificationService.Worker.Services.csproj" />
|
||||||
|
<ProjectReference Include="..\HrynCo.NotificationService.Worker\HrynCo.NotificationService.Worker.csproj" />
|
||||||
|
<ProjectReference Include="..\HrynCo.NotificationService.Migrator\HrynCo.NotificationService.Migrator.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
namespace HrynCo.NotificationService.Services.Tests;
|
|
||||||
|
|
||||||
public class UnitTest1
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public void Test1()
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -18,11 +18,15 @@ public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TReque
|
|||||||
|
|
||||||
public Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken) =>
|
public Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken) =>
|
||||||
_profiler.MeasureExecutionAsync(
|
_profiler.MeasureExecutionAsync(
|
||||||
() => _unitOfWork.ExecuteInTransactionAsync(async () =>
|
async () =>
|
||||||
{
|
{
|
||||||
TResponse response = await next();
|
TResponse? response = default;
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
await _unitOfWork.ExecuteInTransactionAsync(async () =>
|
||||||
return response;
|
{
|
||||||
}),
|
response = await next();
|
||||||
|
});
|
||||||
|
|
||||||
|
return response!;
|
||||||
|
},
|
||||||
typeof(TRequest).Name);
|
typeof(TRequest).Name);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.Services.Logging;
|
using HrynCo.NotificationService.Services.Logging;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
@@ -8,14 +7,12 @@ namespace HrynCo.NotificationService.Services.Core;
|
|||||||
public abstract class RequestHandler<TRequest, TResponse> : IRequestHandler<TRequest, TResponse>
|
public abstract class RequestHandler<TRequest, TResponse> : IRequestHandler<TRequest, TResponse>
|
||||||
where TRequest : IRequest<TResponse>
|
where TRequest : IRequest<TResponse>
|
||||||
{
|
{
|
||||||
protected RequestHandler(IContextualSerilogLogger<TRequest> logger, IUnitOfWork unitOfWork)
|
protected RequestHandler(IContextualSerilogLogger<TRequest> logger)
|
||||||
{
|
{
|
||||||
Logger = logger.Logger;
|
Logger = logger.Logger;
|
||||||
UnitOfWork = unitOfWork;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected ILogger Logger { get; }
|
protected ILogger Logger { get; }
|
||||||
protected IUnitOfWork UnitOfWork { get; }
|
|
||||||
|
|
||||||
public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken)
|
public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
@@ -23,4 +20,4 @@ public abstract class RequestHandler<TRequest, TResponse> : IRequestHandler<TReq
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected abstract Task<TResponse> DoOnHandle(TRequest request, CancellationToken cancellationToken);
|
protected abstract Task<TResponse> DoOnHandle(TRequest request, CancellationToken cancellationToken);
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-2
@@ -14,9 +14,8 @@ internal sealed class CreateEmailChannelHandler
|
|||||||
|
|
||||||
public CreateEmailChannelHandler(
|
public CreateEmailChannelHandler(
|
||||||
IContextualSerilogLogger<CreateEmailChannelCommand> logger,
|
IContextualSerilogLogger<CreateEmailChannelCommand> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailChannelRepository channels)
|
IEmailChannelRepository channels)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_channels = channels;
|
_channels = channels;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-2
@@ -13,9 +13,8 @@ internal sealed class DeleteEmailChannelHandler
|
|||||||
|
|
||||||
public DeleteEmailChannelHandler(
|
public DeleteEmailChannelHandler(
|
||||||
IContextualSerilogLogger<DeleteEmailChannelCommand> logger,
|
IContextualSerilogLogger<DeleteEmailChannelCommand> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailChannelRepository channels)
|
IEmailChannelRepository channels)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_channels = channels;
|
_channels = channels;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
@@ -14,9 +13,8 @@ internal sealed class GetEmailChannelHandler
|
|||||||
|
|
||||||
public GetEmailChannelHandler(
|
public GetEmailChannelHandler(
|
||||||
IContextualSerilogLogger<GetEmailChannelQuery> logger,
|
IContextualSerilogLogger<GetEmailChannelQuery> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailChannelRepository channels)
|
IEmailChannelRepository channels)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_channels = channels;
|
_channels = channels;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-3
@@ -1,4 +1,3 @@
|
|||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
@@ -14,9 +13,8 @@ internal sealed class GetAllEmailChannelsHandler
|
|||||||
|
|
||||||
public GetAllEmailChannelsHandler(
|
public GetAllEmailChannelsHandler(
|
||||||
IContextualSerilogLogger<GetAllEmailChannelsQuery> logger,
|
IContextualSerilogLogger<GetAllEmailChannelsQuery> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailChannelRepository channels)
|
IEmailChannelRepository channels)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_channels = channels;
|
_channels = channels;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-3
@@ -1,4 +1,3 @@
|
|||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
@@ -14,9 +13,8 @@ internal sealed class GetEmailChannelsHandler
|
|||||||
|
|
||||||
public GetEmailChannelsHandler(
|
public GetEmailChannelsHandler(
|
||||||
IContextualSerilogLogger<GetEmailChannelsQuery> logger,
|
IContextualSerilogLogger<GetEmailChannelsQuery> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailChannelRepository channels)
|
IEmailChannelRepository channels)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_channels = channels;
|
_channels = channels;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-3
@@ -1,4 +1,3 @@
|
|||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
using HrynCo.NotificationService.Services.Logging;
|
using HrynCo.NotificationService.Services.Logging;
|
||||||
@@ -13,9 +12,8 @@ internal sealed class GetChannelUsageSummaryHandler
|
|||||||
|
|
||||||
public GetChannelUsageSummaryHandler(
|
public GetChannelUsageSummaryHandler(
|
||||||
IContextualSerilogLogger<GetChannelUsageSummaryQuery> logger,
|
IContextualSerilogLogger<GetChannelUsageSummaryQuery> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailChannelRepository channelsRepository)
|
IEmailChannelRepository channelsRepository)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_channelsRepository = channelsRepository;
|
_channelsRepository = channelsRepository;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.Mail;
|
using System.Net.Mail;
|
||||||
using HrynCo.DAL.Abstract;
|
using System.Text;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
@@ -17,10 +17,9 @@ internal sealed class SendEmailHandler
|
|||||||
|
|
||||||
public SendEmailHandler(
|
public SendEmailHandler(
|
||||||
IContextualSerilogLogger<SendEmailCommand> logger,
|
IContextualSerilogLogger<SendEmailCommand> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailChannelRepository channels,
|
IEmailChannelRepository channels,
|
||||||
IEmailChannelUsageRepository usage)
|
IEmailChannelUsageRepository usage)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_channels = channels;
|
_channels = channels;
|
||||||
_usage = usage;
|
_usage = usage;
|
||||||
@@ -50,14 +49,16 @@ internal sealed class SendEmailHandler
|
|||||||
{
|
{
|
||||||
From = new MailAddress(smtp.FromEmail, smtp.FromName),
|
From = new MailAddress(smtp.FromEmail, smtp.FromName),
|
||||||
Subject = request.Subject,
|
Subject = request.Subject,
|
||||||
Body = request.HtmlBody,
|
Body = request.TextBody ?? string.Empty,
|
||||||
IsBodyHtml = true
|
IsBodyHtml = false,
|
||||||
|
BodyEncoding = Encoding.UTF8,
|
||||||
|
SubjectEncoding = Encoding.UTF8
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(request.TextBody))
|
if (!string.IsNullOrWhiteSpace(request.HtmlBody))
|
||||||
{
|
{
|
||||||
var plain = AlternateView.CreateAlternateViewFromString(request.TextBody, null, "text/plain");
|
var html = AlternateView.CreateAlternateViewFromString(request.HtmlBody, Encoding.UTF8, "text/html");
|
||||||
mail.AlternateViews.Add(plain);
|
mail.AlternateViews.Add(html);
|
||||||
}
|
}
|
||||||
|
|
||||||
mail.To.Add(new MailAddress(request.RecipientEmail, request.RecipientName));
|
mail.To.Add(new MailAddress(request.RecipientEmail, request.RecipientName));
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.Mail;
|
using System.Net.Mail;
|
||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
using HrynCo.NotificationService.Services.Logging;
|
using HrynCo.NotificationService.Services.Logging;
|
||||||
using static HrynCo.NotificationService.Services.Core.ServiceResultHelper;
|
using static HrynCo.NotificationService.Services.Core.ServiceResultHelper;
|
||||||
@@ -11,9 +10,8 @@ internal sealed class TestSmtpHandler
|
|||||||
: RequestHandler<TestSmtpCommand, ServiceResult<Unit>>
|
: RequestHandler<TestSmtpCommand, ServiceResult<Unit>>
|
||||||
{
|
{
|
||||||
public TestSmtpHandler(
|
public TestSmtpHandler(
|
||||||
IContextualSerilogLogger<TestSmtpCommand> logger,
|
IContextualSerilogLogger<TestSmtpCommand> logger)
|
||||||
IUnitOfWork unitOfWork)
|
: base(logger)
|
||||||
: base(logger, unitOfWork)
|
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-2
@@ -13,9 +13,8 @@ internal sealed class UpdateEmailChannelHandler
|
|||||||
|
|
||||||
public UpdateEmailChannelHandler(
|
public UpdateEmailChannelHandler(
|
||||||
IContextualSerilogLogger<UpdateEmailChannelCommand> logger,
|
IContextualSerilogLogger<UpdateEmailChannelCommand> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailChannelRepository channels)
|
IEmailChannelRepository channels)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_channels = channels;
|
_channels = channels;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-3
@@ -1,4 +1,3 @@
|
|||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
@@ -14,9 +13,8 @@ internal sealed class CreateEmailTemplateHandler
|
|||||||
|
|
||||||
public CreateEmailTemplateHandler(
|
public CreateEmailTemplateHandler(
|
||||||
IContextualSerilogLogger<CreateEmailTemplateCommand> logger,
|
IContextualSerilogLogger<CreateEmailTemplateCommand> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailTemplateRepository templates)
|
IEmailTemplateRepository templates)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_templates = templates;
|
_templates = templates;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-2
@@ -13,9 +13,8 @@ internal sealed class DeleteEmailTemplateHandler
|
|||||||
|
|
||||||
public DeleteEmailTemplateHandler(
|
public DeleteEmailTemplateHandler(
|
||||||
IContextualSerilogLogger<DeleteEmailTemplateCommand> logger,
|
IContextualSerilogLogger<DeleteEmailTemplateCommand> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailTemplateRepository templates)
|
IEmailTemplateRepository templates)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_templates = templates;
|
_templates = templates;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
@@ -14,9 +13,8 @@ internal sealed class GetEmailTemplateHandler
|
|||||||
|
|
||||||
public GetEmailTemplateHandler(
|
public GetEmailTemplateHandler(
|
||||||
IContextualSerilogLogger<GetEmailTemplateQuery> logger,
|
IContextualSerilogLogger<GetEmailTemplateQuery> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailTemplateRepository templates)
|
IEmailTemplateRepository templates)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_templates = templates;
|
_templates = templates;
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-4
@@ -1,4 +1,3 @@
|
|||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
@@ -14,9 +13,8 @@ internal sealed class GetAllEmailTemplatesHandler
|
|||||||
|
|
||||||
public GetAllEmailTemplatesHandler(
|
public GetAllEmailTemplatesHandler(
|
||||||
IContextualSerilogLogger<GetAllEmailTemplatesQuery> logger,
|
IContextualSerilogLogger<GetAllEmailTemplatesQuery> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailTemplateRepository templates)
|
IEmailTemplateRepository templates)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_templates = templates;
|
_templates = templates;
|
||||||
}
|
}
|
||||||
@@ -24,7 +22,7 @@ internal sealed class GetAllEmailTemplatesHandler
|
|||||||
protected override async Task<ServiceResult<IReadOnlyList<EmailTemplate>>> DoOnHandle(
|
protected override async Task<ServiceResult<IReadOnlyList<EmailTemplate>>> DoOnHandle(
|
||||||
GetAllEmailTemplatesQuery request, CancellationToken cancellationToken)
|
GetAllEmailTemplatesQuery request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var templates = await _templates.GetAllAsync(cancellationToken);
|
var templates = await _templates.GetAllAsync(request.ServiceName, request.Key, cancellationToken);
|
||||||
return Success(templates);
|
return Success(templates);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -4,4 +4,5 @@ using HrynCo.NotificationService.Services.Core;
|
|||||||
|
|
||||||
namespace HrynCo.NotificationService.Services.EmailTemplates.GetAll;
|
namespace HrynCo.NotificationService.Services.EmailTemplates.GetAll;
|
||||||
|
|
||||||
public sealed record GetAllEmailTemplatesQuery : IRequest<ServiceResult<IReadOnlyList<EmailTemplate>>>;
|
public sealed record GetAllEmailTemplatesQuery(string? ServiceName = null, string? Key = null)
|
||||||
|
: IRequest<ServiceResult<IReadOnlyList<EmailTemplate>>>;
|
||||||
|
|||||||
+1
-3
@@ -1,4 +1,3 @@
|
|||||||
using HrynCo.DAL.Abstract;
|
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
using HrynCo.NotificationService.Services.Core;
|
using HrynCo.NotificationService.Services.Core;
|
||||||
@@ -14,9 +13,8 @@ internal sealed class GetEmailTemplatesHandler
|
|||||||
|
|
||||||
public GetEmailTemplatesHandler(
|
public GetEmailTemplatesHandler(
|
||||||
IContextualSerilogLogger<GetEmailTemplatesQuery> logger,
|
IContextualSerilogLogger<GetEmailTemplatesQuery> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailTemplateRepository templates)
|
IEmailTemplateRepository templates)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_templates = templates;
|
_templates = templates;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-2
@@ -13,9 +13,8 @@ internal sealed class UpdateEmailTemplateHandler
|
|||||||
|
|
||||||
public UpdateEmailTemplateHandler(
|
public UpdateEmailTemplateHandler(
|
||||||
IContextualSerilogLogger<UpdateEmailTemplateCommand> logger,
|
IContextualSerilogLogger<UpdateEmailTemplateCommand> logger,
|
||||||
IUnitOfWork unitOfWork,
|
|
||||||
IEmailTemplateRepository templates)
|
IEmailTemplateRepository templates)
|
||||||
: base(logger, unitOfWork)
|
: base(logger)
|
||||||
{
|
{
|
||||||
_templates = templates;
|
_templates = templates;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class AdminTemplatesIndexViewTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void CreateAndEditLinks_UseExplicitFilterQueryInterpolation()
|
||||||
|
{
|
||||||
|
string view = File.ReadAllText(FindIndexView());
|
||||||
|
|
||||||
|
Assert.Contains("/admin/templates/create@(filterQuery)", view);
|
||||||
|
Assert.Contains("@t.LanguageCode@(filterQuery)", view);
|
||||||
|
Assert.DoesNotContain("create@filterQuery", view);
|
||||||
|
Assert.DoesNotContain("LanguageCode@filterQuery", view);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FindIndexView()
|
||||||
|
{
|
||||||
|
DirectoryInfo? directory = new(AppContext.BaseDirectory);
|
||||||
|
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "HrynCo.NotificationService.slnx")))
|
||||||
|
{
|
||||||
|
directory = directory.Parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.NotNull(directory);
|
||||||
|
return Path.Combine(
|
||||||
|
directory.FullName,
|
||||||
|
"HrynCo.NotificationService.Web",
|
||||||
|
"Views",
|
||||||
|
"AdminTemplates",
|
||||||
|
"Index.cshtml");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
namespace HrynCo.NotificationService.Web.IntegrationTests;
|
|
||||||
|
|
||||||
public class UnitTest1
|
|
||||||
{
|
|
||||||
[Fact]
|
|
||||||
public void Test1()
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -23,9 +23,12 @@ public class AdminTemplatesController : Controller
|
|||||||
|
|
||||||
// GET /admin/templates
|
// GET /admin/templates
|
||||||
[HttpGet("")]
|
[HttpGet("")]
|
||||||
public async Task<IActionResult> Index(CancellationToken ct)
|
public async Task<IActionResult> Index([FromQuery] string? serviceName, [FromQuery] string? key, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var result = await _mediator.Send(new GetAllEmailTemplatesQuery(), ct);
|
ViewData["ServiceNameFilter"] = serviceName;
|
||||||
|
ViewData["KeyFilter"] = key;
|
||||||
|
|
||||||
|
var result = await _mediator.Send(new GetAllEmailTemplatesQuery(serviceName, key), ct);
|
||||||
if (!result.IsSuccess)
|
if (!result.IsSuccess)
|
||||||
{
|
{
|
||||||
ModelState.AddModelError("", result.Error?.Message ?? "Failed to load templates.");
|
ModelState.AddModelError("", result.Error?.Message ?? "Failed to load templates.");
|
||||||
@@ -37,14 +40,24 @@ public class AdminTemplatesController : Controller
|
|||||||
|
|
||||||
// GET /admin/templates/create
|
// GET /admin/templates/create
|
||||||
[HttpGet("create")]
|
[HttpGet("create")]
|
||||||
public IActionResult Create()
|
public IActionResult Create([FromQuery] string? serviceNameFilter, [FromQuery] string? keyFilter)
|
||||||
{
|
{
|
||||||
return View("Edit", new EmailTemplateEditViewModel());
|
return View("Edit", new EmailTemplateEditViewModel
|
||||||
|
{
|
||||||
|
ServiceNameFilter = serviceNameFilter,
|
||||||
|
KeyFilter = keyFilter
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// GET /admin/templates/{serviceName}/{key}/{languageCode}
|
// GET /admin/templates/{serviceName}/{key}/{languageCode}
|
||||||
[HttpGet("{serviceName}/{key}/{languageCode}")]
|
[HttpGet("{serviceName}/{key}/{languageCode}")]
|
||||||
public async Task<IActionResult> Edit(string serviceName, string key, string languageCode, CancellationToken ct)
|
public async Task<IActionResult> Edit(
|
||||||
|
string serviceName,
|
||||||
|
string key,
|
||||||
|
string languageCode,
|
||||||
|
[FromQuery] string? serviceNameFilter,
|
||||||
|
[FromQuery] string? keyFilter,
|
||||||
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
var result = await _mediator.Send(new GetEmailTemplateQuery(serviceName, key, languageCode), ct);
|
var result = await _mediator.Send(new GetEmailTemplateQuery(serviceName, key, languageCode), ct);
|
||||||
if (!result.IsSuccess || result.Result is null)
|
if (!result.IsSuccess || result.Result is null)
|
||||||
@@ -60,7 +73,9 @@ public class AdminTemplatesController : Controller
|
|||||||
Subject = template.Subject,
|
Subject = template.Subject,
|
||||||
HtmlBody = template.HtmlBody,
|
HtmlBody = template.HtmlBody,
|
||||||
TextBody = template.TextBody,
|
TextBody = template.TextBody,
|
||||||
VariablesJson = JsonSerializer.Serialize(template.Variables)
|
VariablesJson = JsonSerializer.Serialize(template.Variables),
|
||||||
|
ServiceNameFilter = serviceNameFilter,
|
||||||
|
KeyFilter = keyFilter
|
||||||
};
|
};
|
||||||
|
|
||||||
return View(vm);
|
return View(vm);
|
||||||
@@ -124,15 +139,21 @@ public class AdminTemplatesController : Controller
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return RedirectToAction(nameof(Index));
|
return RedirectToAction(nameof(Index), new { serviceName = model.ServiceNameFilter, key = model.KeyFilter });
|
||||||
}
|
}
|
||||||
|
|
||||||
// POST /admin/templates/{serviceName}/{key}/{languageCode}/delete
|
// POST /admin/templates/{serviceName}/{key}/{languageCode}/delete
|
||||||
[HttpPost("{serviceName}/{key}/{languageCode}/delete")]
|
[HttpPost("{serviceName}/{key}/{languageCode}/delete")]
|
||||||
[ValidateAntiForgeryToken]
|
[ValidateAntiForgeryToken]
|
||||||
public async Task<IActionResult> Delete(string serviceName, string key, string languageCode, CancellationToken ct)
|
public async Task<IActionResult> Delete(
|
||||||
|
string serviceName,
|
||||||
|
string key,
|
||||||
|
string languageCode,
|
||||||
|
[FromForm] string? serviceNameFilter,
|
||||||
|
[FromForm] string? keyFilter,
|
||||||
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
await _mediator.Send(new DeleteEmailTemplateCommand(serviceName, key, languageCode), ct);
|
await _mediator.Send(new DeleteEmailTemplateCommand(serviceName, key, languageCode), ct);
|
||||||
return RedirectToAction(nameof(Index));
|
return RedirectToAction(nameof(Index), new { serviceName = serviceNameFilter, key = keyFilter });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
@@ -25,6 +25,8 @@ public class EmailTemplateEditViewModel
|
|||||||
|
|
||||||
// JSON array: [{"name":"UserName","required":true}, ...]
|
// JSON array: [{"name":"UserName","required":true}, ...]
|
||||||
public string VariablesJson { get; set; } = "[]";
|
public string VariablesJson { get; set; } = "[]";
|
||||||
|
public string? ServiceNameFilter { get; set; }
|
||||||
|
public string? KeyFilter { get; set; }
|
||||||
|
|
||||||
public bool IsNew => Id == null;
|
public bool IsNew => Id == null;
|
||||||
public string PageTitle => IsNew ? "Create Email Template" : "Edit Email Template";
|
public string PageTitle => IsNew ? "Create Email Template" : "Edit Email Template";
|
||||||
|
|||||||
+3
-2
@@ -1,6 +1,7 @@
|
|||||||
using HrynCo.NotificationService.Web.Infrastructure;
|
using HrynCo.NotificationService.Web.Infrastructure;
|
||||||
using HrynCo.NotificationService.Services.EmailTemplates.Create;
|
using HrynCo.NotificationService.Services.EmailTemplates.Create;
|
||||||
using HrynCo.NotificationService.Services.EmailTemplates.Delete;
|
using HrynCo.NotificationService.Services.EmailTemplates.Delete;
|
||||||
|
using HrynCo.NotificationService.Services.EmailTemplates.GetAll;
|
||||||
using HrynCo.NotificationService.Services.EmailTemplates.Get;
|
using HrynCo.NotificationService.Services.EmailTemplates.Get;
|
||||||
using HrynCo.NotificationService.Services.EmailTemplates.GetByService;
|
using HrynCo.NotificationService.Services.EmailTemplates.GetByService;
|
||||||
using HrynCo.NotificationService.Services.EmailTemplates.Update;
|
using HrynCo.NotificationService.Services.EmailTemplates.Update;
|
||||||
@@ -15,9 +16,9 @@ public sealed class EmailTemplatesController : ApiControllerBase
|
|||||||
public EmailTemplatesController(IMediator mediator) : base(mediator) { }
|
public EmailTemplatesController(IMediator mediator) : base(mediator) { }
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
public async Task<IActionResult> GetAll([FromQuery] string serviceName, CancellationToken cancellationToken)
|
public async Task<IActionResult> GetAll([FromQuery] string? serviceName, [FromQuery] string? key, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var result = await Mediator.Send(new GetEmailTemplatesQuery(serviceName), cancellationToken);
|
var result = await Mediator.Send(new GetAllEmailTemplatesQuery(serviceName, key), cancellationToken);
|
||||||
return FromServiceResult(result);
|
return FromServiceResult(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,47 @@
|
|||||||
@HrynCo.NotificationService.Api_HostAddress = http://localhost:5188
|
@host = http://localhost:5188
|
||||||
|
|
||||||
GET {{HrynCo.NotificationService.Api_HostAddress}}/weatherforecast/
|
### Create a new email template
|
||||||
Accept: application/json
|
POST {{host}}/api/v1/email-templates
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
###
|
{
|
||||||
|
"ServiceName": "StoreMate-Prod",
|
||||||
|
"Key": "ShareInvite",
|
||||||
|
"LanguageCode": "uk",
|
||||||
|
"Subject": "Вас запрошено",
|
||||||
|
"HtmlBody": "<html><body><div style=\"font-family: Arial, sans-serif; color: #1f2937;\"><p>Вітаємо, \u007b\u007bRecipientName\u007d\u007d.</p><h1>Вас запрошено</h1><p>\u007b\u007bInviterName\u007d\u007d запросив вас приєднатися до \u007b\u007bAppName\u007d\u007d, щоб ви могли безпечно співпрацювати.</p><p><a href=\"\u007b\u007bInviteLink\u007d\u007d\">Відкрити запрошення</a></p><p>Запрошення дійсне до <strong>\u007b\u007bValidUntil\u007d\u007d</strong>.</p></div></body></html>",
|
||||||
|
"TextBody": "Вітаємо, \u007b\u007bRecipientName\u007d\u007d.\n\n\u007b\u007bInviterName\u007d\u007d запросив вас приєднатися до \u007b\u007bAppName\u007d\u007d, щоб ви могли безпечно співпрацювати.\n\nВідкрийте запрошення: \u007b\u007bInviteLink\u007d\u007d\nДійсне до: \u007b\u007bValidUntil\u007d\u007d",
|
||||||
|
"Variables": [
|
||||||
|
{ "Name": "RecipientName", "Required": false },
|
||||||
|
{ "Name": "InviterName", "Required": false },
|
||||||
|
{ "Name": "AppName", "Required": false },
|
||||||
|
{ "Name": "InviteLink", "Required": false },
|
||||||
|
{ "Name": "ValidUntil", "Required": false }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
### Get the created template
|
||||||
|
GET {{host}}/api/v1/email-templates/StoreMate-Prod/ShareInvite/uk
|
||||||
|
|
||||||
|
### List all templates for the service
|
||||||
|
GET {{host}}/api/v1/email-templates?serviceName=StoreMate-Prod
|
||||||
|
|
||||||
|
### Update the template
|
||||||
|
PUT {{host}}/api/v1/email-templates/StoreMate-Prod/ShareInvite/uk
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"Subject": "Вас запрошено",
|
||||||
|
"HtmlBody": "<html><body><p>Вітаємо, \u007b\u007bRecipientName\u007d\u007d.</p><p>\u007b\u007bInviterName\u007d\u007d запросив вас приєднатися до \u007b\u007bAppName\u007d\u007d.</p><p><a href=\"\u007b\u007bInviteLink\u007d\u007d\">Відкрити запрошення</a></p><p>Дійсне до <strong>\u007b\u007bValidUntil\u007d\u007d</strong>.</p></body></html>",
|
||||||
|
"TextBody": "Вітаємо, \u007b\u007bRecipientName\u007d\u007d.\n\n\u007b\u007bInviterName\u007d\u007d запросив вас приєднатися до \u007b\u007bAppName\u007d\u007d.\n\nВідкрийте запрошення: \u007b\u007bInviteLink\u007d\u007d\nДійсне до: \u007b\u007bValidUntil\u007d\u007d",
|
||||||
|
"Variables": [
|
||||||
|
{ "Name": "RecipientName", "Required": false },
|
||||||
|
{ "Name": "InviterName", "Required": false },
|
||||||
|
{ "Name": "AppName", "Required": false },
|
||||||
|
{ "Name": "InviteLink", "Required": false },
|
||||||
|
{ "Name": "ValidUntil", "Required": false }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
### Delete the template
|
||||||
|
DELETE {{host}}/api/v1/email-templates/StoreMate-Prod/ShareInvite/uk
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ using HrynCo.NotificationService.DAL.EF;
|
|||||||
using HrynCo.NotificationService.Services;
|
using HrynCo.NotificationService.Services;
|
||||||
using Scalar.AspNetCore;
|
using Scalar.AspNetCore;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
builder.AddSerilog();
|
builder.AddSerilog();
|
||||||
|
|
||||||
var appSettings = builder.Configuration
|
AppSettings appSettings = builder.Configuration
|
||||||
.GetSection(AppSettings.SectionName)
|
.GetSection(AppSettings.SectionName)
|
||||||
.Get<AppSettings>() ?? throw new InvalidOperationException("App settings are not configured.");
|
.Get<AppSettings>() ?? throw new InvalidOperationException("App settings are not configured.");
|
||||||
|
|
||||||
@@ -18,17 +18,14 @@ builder.Services.AddControllersWithViews()
|
|||||||
builder.Services.AddNotificationDataAccess(appSettings.ConnectionString);
|
builder.Services.AddNotificationDataAccess(appSettings.ConnectionString);
|
||||||
builder.Services.AddNotificationServices();
|
builder.Services.AddNotificationServices();
|
||||||
|
|
||||||
var app = builder.Build();
|
WebApplication app = builder.Build();
|
||||||
|
|
||||||
if (app.Environment.IsDevelopment())
|
app.MapOpenApi();
|
||||||
|
app.MapScalarApiReference(options =>
|
||||||
{
|
{
|
||||||
app.MapOpenApi();
|
options.Title = "HrynCo Notification Service";
|
||||||
app.MapScalarApiReference(options =>
|
options.Theme = ScalarTheme.DeepSpace;
|
||||||
{
|
});
|
||||||
options.Title = "HrynCo Notification Service";
|
|
||||||
options.Theme = ScalarTheme.DeepSpace;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
app.UseStaticFiles();
|
app.UseStaticFiles();
|
||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
|
|||||||
@@ -10,6 +10,8 @@
|
|||||||
@Html.AntiForgeryToken()
|
@Html.AntiForgeryToken()
|
||||||
<input asp-for="Id" type="hidden" />
|
<input asp-for="Id" type="hidden" />
|
||||||
<input type="hidden" name="IsNew" value="@Model.IsNew" />
|
<input type="hidden" name="IsNew" value="@Model.IsNew" />
|
||||||
|
<input asp-for="ServiceNameFilter" type="hidden" />
|
||||||
|
<input asp-for="KeyFilter" type="hidden" />
|
||||||
|
|
||||||
@if (!ViewData.ModelState.IsValid)
|
@if (!ViewData.ModelState.IsValid)
|
||||||
{
|
{
|
||||||
@@ -21,55 +23,278 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
<div class="row g-3 mb-3">
|
<ul class="nav nav-tabs template-editor-tabs mb-3" id="templateEditorTabs" role="tablist">
|
||||||
<div class="col-md-5">
|
<li class="nav-item" role="presentation">
|
||||||
<label asp-for="ServiceName" class="form-label fw-semibold">Service Name</label>
|
<button class="nav-link active" id="edit-tab" data-bs-toggle="tab" data-bs-target="#edit-pane" type="button" role="tab" aria-controls="edit-pane" aria-selected="true">
|
||||||
<input asp-for="ServiceName" class="form-control" readonly="@(!Model.IsNew)" />
|
Edit
|
||||||
<span asp-validation-for="ServiceName" class="text-danger small"></span>
|
</button>
|
||||||
|
</li>
|
||||||
|
<li class="nav-item" role="presentation">
|
||||||
|
<button class="nav-link" id="preview-tab" data-bs-toggle="tab" data-bs-target="#preview-pane" type="button" role="tab" aria-controls="preview-pane" aria-selected="false">
|
||||||
|
Preview
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<div class="tab-content">
|
||||||
|
<div class="tab-pane fade show active" id="edit-pane" role="tabpanel" aria-labelledby="edit-tab" tabindex="0">
|
||||||
|
<div class="row g-3 mb-3">
|
||||||
|
<div class="col-md-5">
|
||||||
|
<label asp-for="ServiceName" class="form-label fw-semibold">Service Name</label>
|
||||||
|
<input asp-for="ServiceName" class="form-control" readonly="@(!Model.IsNew)" />
|
||||||
|
<span asp-validation-for="ServiceName" class="text-danger small"></span>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-5">
|
||||||
|
<label asp-for="Key" class="form-label fw-semibold">Key</label>
|
||||||
|
<input asp-for="Key" class="form-control" readonly="@(!Model.IsNew)" />
|
||||||
|
<span asp-validation-for="Key" class="text-danger small"></span>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<label asp-for="LanguageCode" class="form-label fw-semibold">Language</label>
|
||||||
|
<input asp-for="LanguageCode" class="form-control" readonly="@(!Model.IsNew)" />
|
||||||
|
<span asp-validation-for="LanguageCode" class="text-danger small"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label asp-for="Subject" class="form-label fw-semibold">Subject</label>
|
||||||
|
<input asp-for="Subject" class="form-control" />
|
||||||
|
<span asp-validation-for="Subject" class="text-danger small"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label asp-for="HtmlBody" class="form-label fw-semibold">HTML Body</label>
|
||||||
|
<textarea asp-for="HtmlBody" class="form-control font-monospace" rows="10"></textarea>
|
||||||
|
<span asp-validation-for="HtmlBody" class="text-danger small"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label asp-for="TextBody" class="form-label fw-semibold">Text Body</label>
|
||||||
|
<textarea asp-for="TextBody" class="form-control font-monospace" rows="5"></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mb-3">
|
||||||
|
<label asp-for="VariablesJson" class="form-label fw-semibold">Variables (JSON)</label>
|
||||||
|
<textarea asp-for="VariablesJson" class="form-control font-monospace" rows="4"
|
||||||
|
placeholder='[{"name":"UserName","required":true}]'></textarea>
|
||||||
|
<span asp-validation-for="VariablesJson" class="text-danger small"></span>
|
||||||
|
<div class="form-text">JSON array of <code>{"name":"...", "required":true|false}</code></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-5">
|
|
||||||
<label asp-for="Key" class="form-label fw-semibold">Key</label>
|
<div class="tab-pane fade" id="preview-pane" role="tabpanel" aria-labelledby="preview-tab" tabindex="0">
|
||||||
<input asp-for="Key" class="form-control" readonly="@(!Model.IsNew)" />
|
<div class="template-preview-panel mb-3">
|
||||||
<span asp-validation-for="Key" class="text-danger small"></span>
|
<div class="template-preview-panel-header">
|
||||||
|
<div>
|
||||||
|
<div class="template-preview-title">Preview</div>
|
||||||
|
<div class="template-preview-subtitle">Rendered with sample values from the variable list.</div>
|
||||||
|
</div>
|
||||||
|
<span id="previewStatus" class="badge text-bg-secondary">Ready</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="template-preview-body">
|
||||||
|
<div class="template-preview-source template-preview-section-block">
|
||||||
|
<div class="template-preview-section-title">Sample values</div>
|
||||||
|
<div id="previewVariables" class="template-preview-variables"></div>
|
||||||
|
<div class="form-text mt-2">Change these values to see the rendered output update immediately.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="template-preview-output">
|
||||||
|
<div class="template-preview-section-title">Rendered subject</div>
|
||||||
|
<div id="previewSubject" class="template-preview-subject"></div>
|
||||||
|
|
||||||
|
<div class="template-preview-section-title mt-3">Rendered HTML</div>
|
||||||
|
<iframe id="previewHtmlFrame" class="template-preview-frame" title="Email HTML preview"></iframe>
|
||||||
|
|
||||||
|
<div class="template-preview-section-title mt-3">Rendered text</div>
|
||||||
|
<pre id="previewText" class="template-preview-text mb-0"></pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-2">
|
|
||||||
<label asp-for="LanguageCode" class="form-label fw-semibold">Language</label>
|
|
||||||
<input asp-for="LanguageCode" class="form-control" readonly="@(!Model.IsNew)" />
|
|
||||||
<span asp-validation-for="LanguageCode" class="text-danger small"></span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mb-3">
|
|
||||||
<label asp-for="Subject" class="form-label fw-semibold">Subject</label>
|
|
||||||
<input asp-for="Subject" class="form-control" />
|
|
||||||
<span asp-validation-for="Subject" class="text-danger small"></span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mb-3">
|
|
||||||
<label asp-for="HtmlBody" class="form-label fw-semibold">HTML Body</label>
|
|
||||||
<textarea asp-for="HtmlBody" class="form-control font-monospace" rows="10"></textarea>
|
|
||||||
<span asp-validation-for="HtmlBody" class="text-danger small"></span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mb-3">
|
|
||||||
<label asp-for="TextBody" class="form-label fw-semibold">Text Body</label>
|
|
||||||
<textarea asp-for="TextBody" class="form-control font-monospace" rows="5"></textarea>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="mb-3">
|
|
||||||
<label asp-for="VariablesJson" class="form-label fw-semibold">Variables (JSON)</label>
|
|
||||||
<textarea asp-for="VariablesJson" class="form-control font-monospace" rows="4"
|
|
||||||
placeholder='[{"name":"UserName","required":true}]'></textarea>
|
|
||||||
<span asp-validation-for="VariablesJson" class="text-danger small"></span>
|
|
||||||
<div class="form-text">JSON array of <code>{"name":"...", "required":true|false}</code></div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@section FormActions {
|
@section FormActions {
|
||||||
<button type="submit" form="templateForm" class="btn btn-primary">
|
<button type="submit" form="templateForm" class="btn btn-primary">
|
||||||
<i class="bi bi-floppy me-1"></i> Save
|
<i class="bi bi-floppy me-1"></i> Save
|
||||||
</button>
|
</button>
|
||||||
<a href="/admin/templates" class="btn btn-secondary">
|
<a href="/admin/templates@(string.IsNullOrWhiteSpace(Model.ServiceNameFilter) && string.IsNullOrWhiteSpace(Model.KeyFilter) ? string.Empty : $"?serviceName={Uri.EscapeDataString(Model.ServiceNameFilter ?? string.Empty)}&key={Uri.EscapeDataString(Model.KeyFilter ?? string.Empty)}")" class="btn btn-secondary">
|
||||||
<i class="bi bi-x-lg me-1"></i> Cancel
|
<i class="bi bi-x-lg me-1"></i> Cancel
|
||||||
</a>
|
</a>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@section Scripts {
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
const subjectField = document.getElementById('Subject');
|
||||||
|
const htmlField = document.getElementById('HtmlBody');
|
||||||
|
const textField = document.getElementById('TextBody');
|
||||||
|
const variablesField = document.getElementById('VariablesJson');
|
||||||
|
const previewVariablesHost = document.getElementById('previewVariables');
|
||||||
|
const previewSubject = document.getElementById('previewSubject');
|
||||||
|
const previewText = document.getElementById('previewText');
|
||||||
|
const previewFrame = document.getElementById('previewHtmlFrame');
|
||||||
|
const previewStatus = document.getElementById('previewStatus');
|
||||||
|
const previewTab = document.getElementById('preview-tab');
|
||||||
|
|
||||||
|
if (!subjectField || !htmlField || !textField || !variablesField || !previewVariablesHost || !previewSubject || !previewText || !previewFrame || !previewStatus) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(value) {
|
||||||
|
return String(value)
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseVariables() {
|
||||||
|
const raw = variablesField.value?.trim() || '[]';
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
|
||||||
|
if (!Array.isArray(parsed)) {
|
||||||
|
throw new Error('Variables JSON must be an array.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed
|
||||||
|
.filter(item => item && typeof item.Name === 'string' && item.Name.trim().length > 0)
|
||||||
|
.map(item => ({
|
||||||
|
name: item.Name.trim(),
|
||||||
|
required: !!item.Required
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildSampleValue(name) {
|
||||||
|
return `Sample ${name}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderVariableInputs() {
|
||||||
|
let variables = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
variables = parseVariables();
|
||||||
|
previewStatus.className = 'badge text-bg-secondary';
|
||||||
|
previewStatus.textContent = 'Ready';
|
||||||
|
} catch (error) {
|
||||||
|
previewVariablesHost.innerHTML = `<div class="alert alert-warning mb-0">${escapeHtml(error.message || 'Invalid variables JSON')}</div>`;
|
||||||
|
previewStatus.className = 'badge text-bg-danger';
|
||||||
|
previewStatus.textContent = 'Invalid JSON';
|
||||||
|
updatePreview();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (variables.length === 0) {
|
||||||
|
previewVariablesHost.innerHTML = '<div class="text-muted small">No variables defined.</div>';
|
||||||
|
updatePreview();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentValues = readVariableValues();
|
||||||
|
previewVariablesHost.innerHTML = variables.map(variable => {
|
||||||
|
const value = Object.prototype.hasOwnProperty.call(currentValues, variable.name)
|
||||||
|
? currentValues[variable.name]
|
||||||
|
: buildSampleValue(variable.name);
|
||||||
|
return `
|
||||||
|
<div class="mb-2">
|
||||||
|
<label class="form-label small fw-semibold mb-1">${escapeHtml(variable.name)}${variable.required ? ' *' : ''}</label>
|
||||||
|
<input type="text" class="form-control form-control-sm preview-variable-input" data-variable-name="${escapeHtml(variable.name)}" value="${escapeHtml(value)}" />
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}).join('');
|
||||||
|
|
||||||
|
previewVariablesHost.querySelectorAll('.preview-variable-input').forEach(input => {
|
||||||
|
input.addEventListener('input', updatePreview);
|
||||||
|
});
|
||||||
|
|
||||||
|
updatePreview();
|
||||||
|
}
|
||||||
|
|
||||||
|
function readVariableValues() {
|
||||||
|
const values = {};
|
||||||
|
previewVariablesHost.querySelectorAll('.preview-variable-input').forEach(input => {
|
||||||
|
values[input.dataset.variableName] = input.value;
|
||||||
|
});
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
function interpolate(text, values) {
|
||||||
|
let result = text || '';
|
||||||
|
|
||||||
|
Object.keys(values).forEach(key => {
|
||||||
|
const token = new RegExp(`\\{\\{${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\}\\}`, 'g');
|
||||||
|
result = result.replace(token, values[key] ?? '');
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updatePreview() {
|
||||||
|
let values = {};
|
||||||
|
|
||||||
|
try {
|
||||||
|
values = readVariableValues();
|
||||||
|
} catch (error) {
|
||||||
|
values = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const renderedSubject = interpolate(subjectField.value, values);
|
||||||
|
const renderedHtml = interpolate(htmlField.value, values);
|
||||||
|
const renderedText = interpolate(textField.value, values);
|
||||||
|
|
||||||
|
previewSubject.textContent = renderedSubject || '(empty subject)';
|
||||||
|
previewText.textContent = renderedText || '(empty text body)';
|
||||||
|
previewFrame.srcdoc = `
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 24px;
|
||||||
|
background: #eef2f7;
|
||||||
|
color: #1f2937;
|
||||||
|
font-family: Arial, Helvetica, sans-serif;
|
||||||
|
}
|
||||||
|
.email-shell {
|
||||||
|
max-width: 640px;
|
||||||
|
margin: 0 auto;
|
||||||
|
background: #ffffff;
|
||||||
|
border: 1px solid #dbe3ee;
|
||||||
|
border-radius: 20px;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: 0 12px 30px rgba(15, 23, 42, .08);
|
||||||
|
}
|
||||||
|
.email-body {
|
||||||
|
padding: 28px 36px;
|
||||||
|
}
|
||||||
|
img { max-width: 100%; height: auto; }
|
||||||
|
a { color: #2563eb; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="email-shell">
|
||||||
|
<div class="email-body">
|
||||||
|
${renderedHtml || '<div style="color:#6b7280">No HTML body provided.</div>'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
variablesField.addEventListener('input', renderVariableInputs);
|
||||||
|
subjectField.addEventListener('input', updatePreview);
|
||||||
|
htmlField.addEventListener('input', updatePreview);
|
||||||
|
textField.addEventListener('input', updatePreview);
|
||||||
|
if (previewTab) {
|
||||||
|
previewTab.addEventListener('shown.bs.tab', updatePreview);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderVariableInputs();
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
}
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -2,15 +2,50 @@
|
|||||||
@model IReadOnlyList<EmailTemplate>
|
@model IReadOnlyList<EmailTemplate>
|
||||||
@{
|
@{
|
||||||
ViewData["Title"] = "Email Templates";
|
ViewData["Title"] = "Email Templates";
|
||||||
|
var serviceNameFilter = ViewData["ServiceNameFilter"] as string ?? string.Empty;
|
||||||
|
var keyFilter = ViewData["KeyFilter"] as string ?? string.Empty;
|
||||||
|
var filterQuery = string.IsNullOrWhiteSpace(serviceNameFilter) && string.IsNullOrWhiteSpace(keyFilter)
|
||||||
|
? string.Empty
|
||||||
|
: $"?serviceNameFilter={Uri.EscapeDataString(serviceNameFilter)}&keyFilter={Uri.EscapeDataString(keyFilter)}";
|
||||||
|
var listQuery = string.IsNullOrWhiteSpace(serviceNameFilter) && string.IsNullOrWhiteSpace(keyFilter)
|
||||||
|
? string.Empty
|
||||||
|
: $"?serviceName={Uri.EscapeDataString(serviceNameFilter)}&key={Uri.EscapeDataString(keyFilter)}";
|
||||||
}
|
}
|
||||||
|
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<h2><i class="bi bi-envelope-paper"></i> Email Templates</h2>
|
<h2><i class="bi bi-envelope-paper"></i> Email Templates</h2>
|
||||||
<a href="/admin/templates/create" class="btn btn-primary btn-sm">
|
<a href="/admin/templates/create@(filterQuery)" class="btn btn-primary btn-sm">
|
||||||
<i class="bi bi-plus-lg me-1"></i> Create New Template
|
<i class="bi bi-plus-lg me-1"></i> Create New Template
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="card shadow-sm mb-3">
|
||||||
|
<div class="card-body">
|
||||||
|
<form id="templateFiltersForm" method="get" action="/admin/templates" class="row g-2 align-items-end">
|
||||||
|
<div class="col-12 col-md-5">
|
||||||
|
<label class="form-label fw-semibold" for="serviceName">Service Name</label>
|
||||||
|
<input id="serviceName"
|
||||||
|
name="serviceName"
|
||||||
|
value="@serviceNameFilter"
|
||||||
|
class="form-control"
|
||||||
|
placeholder="Filter by service name" />
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-md-5">
|
||||||
|
<label class="form-label fw-semibold" for="key">Key</label>
|
||||||
|
<input id="key"
|
||||||
|
name="key"
|
||||||
|
value="@keyFilter"
|
||||||
|
class="form-control"
|
||||||
|
placeholder="Filter by key" />
|
||||||
|
</div>
|
||||||
|
<div class="col-12 col-md-2 d-flex gap-2">
|
||||||
|
<button type="submit" class="btn btn-primary w-100">Filter</button>
|
||||||
|
<a id="clearTemplateFilters" href="/admin/templates" class="btn btn-outline-secondary w-100">Clear</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
@if (!ViewData.ModelState.IsValid)
|
@if (!ViewData.ModelState.IsValid)
|
||||||
{
|
{
|
||||||
<div class="alert alert-danger">
|
<div class="alert alert-danger">
|
||||||
@@ -21,6 +56,61 @@
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(() => {
|
||||||
|
const storageKey = 'hrynco.notificationService.adminTemplates.filters';
|
||||||
|
const form = document.getElementById('templateFiltersForm');
|
||||||
|
const serviceNameInput = document.getElementById('serviceName');
|
||||||
|
const keyInput = document.getElementById('key');
|
||||||
|
const clearLink = document.getElementById('clearTemplateFilters');
|
||||||
|
|
||||||
|
if (!form || !serviceNameInput || !keyInput || !clearLink) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const saveState = () => {
|
||||||
|
const state = {
|
||||||
|
serviceName: serviceNameInput.value ?? '',
|
||||||
|
key: keyInput.value ?? ''
|
||||||
|
};
|
||||||
|
|
||||||
|
localStorage.setItem(storageKey, JSON.stringify(state));
|
||||||
|
};
|
||||||
|
|
||||||
|
const restoreState = () => {
|
||||||
|
const raw = localStorage.getItem(storageKey);
|
||||||
|
if (!raw) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const state = JSON.parse(raw);
|
||||||
|
const serviceName = typeof state.serviceName === 'string' ? state.serviceName : '';
|
||||||
|
const key = typeof state.key === 'string' ? state.key : '';
|
||||||
|
|
||||||
|
serviceNameInput.value = serviceName;
|
||||||
|
keyInput.value = key;
|
||||||
|
|
||||||
|
return serviceName.length > 0 || key.length > 0;
|
||||||
|
} catch {
|
||||||
|
localStorage.removeItem(storageKey);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
form.addEventListener('submit', saveState);
|
||||||
|
clearLink.addEventListener('click', () => localStorage.removeItem(storageKey));
|
||||||
|
|
||||||
|
const hasQueryParams = new URLSearchParams(window.location.search).toString().length > 0;
|
||||||
|
if (!hasQueryParams && restoreState()) {
|
||||||
|
form.requestSubmit();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
saveState();
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
|
||||||
@if (Model is null || Model.Count == 0)
|
@if (Model is null || Model.Count == 0)
|
||||||
{
|
{
|
||||||
<div class="card shadow-sm table-card">
|
<div class="card shadow-sm table-card">
|
||||||
@@ -56,13 +146,15 @@ else
|
|||||||
<td>@t.LanguageCode</td>
|
<td>@t.LanguageCode</td>
|
||||||
<td>@t.Subject</td>
|
<td>@t.Subject</td>
|
||||||
<td class="text-end">
|
<td class="text-end">
|
||||||
<a href="/admin/templates/@t.ServiceName/@t.Key/@t.LanguageCode"
|
<a href="/admin/templates/@t.ServiceName/@t.Key/@t.LanguageCode@(filterQuery)"
|
||||||
class="btn btn-sm btn-outline-primary me-1">
|
class="btn btn-sm btn-outline-primary me-1">
|
||||||
<i class="bi bi-pencil"></i> Edit
|
<i class="bi bi-pencil"></i> Edit
|
||||||
</a>
|
</a>
|
||||||
<form method="post"
|
<form method="post"
|
||||||
action="/admin/templates/@t.ServiceName/@t.Key/@t.LanguageCode/delete"
|
action="/admin/templates/@t.ServiceName/@t.Key/@t.LanguageCode/delete"
|
||||||
class="d-inline">
|
class="d-inline">
|
||||||
|
<input type="hidden" name="serviceNameFilter" value="@serviceNameFilter" />
|
||||||
|
<input type="hidden" name="keyFilter" value="@keyFilter" />
|
||||||
@Html.AntiForgeryToken()
|
@Html.AntiForgeryToken()
|
||||||
<button type="submit"
|
<button type="submit"
|
||||||
class="btn btn-sm btn-outline-danger"
|
class="btn btn-sm btn-outline-danger"
|
||||||
|
|||||||
@@ -14,3 +14,4 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@RenderSection("Scripts", required: false)
|
||||||
|
|||||||
@@ -118,9 +118,10 @@ body {
|
|||||||
.empty-state .bi { font-size: 2.5rem; opacity: .35; display: block; margin-bottom: .75rem; }
|
.empty-state .bi { font-size: 2.5rem; opacity: .35; display: block; margin-bottom: .75rem; }
|
||||||
.empty-state p { font-size: .9rem; margin-bottom: 0; }
|
.empty-state p { font-size: .9rem; margin-bottom: 0; }
|
||||||
|
|
||||||
/* ── Editor wrapper — constrains width ───────────────── */
|
/* ── Editor wrapper ──────────────────────────────────── */
|
||||||
.editor-wrapper {
|
.editor-wrapper {
|
||||||
max-width: 860px;
|
width: 100%;
|
||||||
|
max-width: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Editor card ──────────────────────────────────────── */
|
/* ── Editor card ──────────────────────────────────────── */
|
||||||
@@ -154,6 +155,149 @@ body {
|
|||||||
border-radius: 0 0 .5rem .5rem !important;
|
border-radius: 0 0 .5rem .5rem !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── Editor tabs ─────────────────────────────────────── */
|
||||||
|
.template-editor-tabs {
|
||||||
|
border-bottom-color: #dce3eb;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-editor-tabs .nav-link {
|
||||||
|
color: #526072;
|
||||||
|
font-weight: 600;
|
||||||
|
border-radius: .5rem .5rem 0 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-editor-tabs .nav-link.active {
|
||||||
|
color: #0d6efd;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Tab content ──────────────────────────────────────── */
|
||||||
|
.tab-content {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Email template preview ───────────────────────────── */
|
||||||
|
.template-preview-panel {
|
||||||
|
border: 1px solid #dce3eb;
|
||||||
|
border-radius: .75rem;
|
||||||
|
background: #fff;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: 0 10px 24px rgba(15, 23, 42, .06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-panel-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 1rem;
|
||||||
|
padding: 1rem 1.25rem;
|
||||||
|
background: linear-gradient(180deg, #f9fbff 0%, #f3f6fb 100%);
|
||||||
|
border-bottom: 1px solid #e1e7ef;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-title {
|
||||||
|
font-size: .9rem;
|
||||||
|
font-weight: 700;
|
||||||
|
color: #1f2937;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-subtitle {
|
||||||
|
font-size: .82rem;
|
||||||
|
color: #6b7280;
|
||||||
|
margin-top: .15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-body {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
gap: 1rem;
|
||||||
|
padding: 1rem 1.25rem 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-source,
|
||||||
|
.template-preview-output {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-section-block {
|
||||||
|
padding: 1rem;
|
||||||
|
border: 1px solid #e5ebf2;
|
||||||
|
border-radius: .65rem;
|
||||||
|
background: #fafcff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-section-title {
|
||||||
|
font-size: .7rem;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: .08em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: #6b7280;
|
||||||
|
margin-bottom: .5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-variables {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||||
|
gap: .75rem 1rem;
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-variables > div {
|
||||||
|
margin-bottom: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-variables .form-label {
|
||||||
|
font-size: .72rem;
|
||||||
|
margin-bottom: .2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-variables .form-control-sm {
|
||||||
|
background: #fff;
|
||||||
|
min-height: calc(1.5em + .45rem + 2px);
|
||||||
|
padding: .2rem .45rem;
|
||||||
|
font-size: .82rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-subject {
|
||||||
|
padding: .75rem 1rem;
|
||||||
|
border: 1px dashed #cfd8e3;
|
||||||
|
border-radius: .5rem;
|
||||||
|
background: #f8fafc;
|
||||||
|
min-height: 3rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: #111827;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-frame {
|
||||||
|
width: 100%;
|
||||||
|
height: 420px;
|
||||||
|
border: 1px solid #cfd8e3;
|
||||||
|
border-radius: .5rem;
|
||||||
|
background: #eef2f7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-text {
|
||||||
|
padding: .75rem 1rem;
|
||||||
|
border: 1px solid #cfd8e3;
|
||||||
|
border-radius: .5rem;
|
||||||
|
background: #0f172a;
|
||||||
|
color: #e2e8f0;
|
||||||
|
min-height: 120px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 992px) {
|
||||||
|
.template-preview-body {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
|
.template-preview-frame {
|
||||||
|
height: 360px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Form-section divider ─────────────────────────────── */
|
/* ── Form-section divider ─────────────────────────────── */
|
||||||
.form-section-title {
|
.form-section-title {
|
||||||
font-size: .68rem;
|
font-size: .68rem;
|
||||||
|
|||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
using System.Net;
|
||||||
|
using System.Text;
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
|
|
||||||
|
internal sealed class EmailTemplateRenderingService : IEmailTemplateRenderingService
|
||||||
|
{
|
||||||
|
public RenderedEmail Render(EmailTemplate template, SendEmailMessageData data)
|
||||||
|
{
|
||||||
|
string[] missingVariables = template.Variables
|
||||||
|
.Where(variable => variable.Required)
|
||||||
|
.Select(variable => variable.Name)
|
||||||
|
.Where(name => !data.Variables.TryGetValue(name, out string? value) || string.IsNullOrWhiteSpace(value))
|
||||||
|
.ToArray();
|
||||||
|
|
||||||
|
if (missingVariables.Length > 0)
|
||||||
|
{
|
||||||
|
throw new InvalidDataException(
|
||||||
|
$"Required template variables are missing: {string.Join(", ", missingVariables)}.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return new RenderedEmail(
|
||||||
|
Interpolate(template.Subject, data.Variables),
|
||||||
|
InterpolateHtml(template.HtmlBody, data.Variables),
|
||||||
|
Interpolate(template.TextBody, data.Variables));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string InterpolateHtml(string text, IReadOnlyDictionary<string, string> variables)
|
||||||
|
{
|
||||||
|
return Interpolate(text, variables, WebUtility.HtmlEncode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Interpolate(string text, IReadOnlyDictionary<string, string> variables)
|
||||||
|
{
|
||||||
|
return Interpolate(text, variables, static value => value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Interpolate(
|
||||||
|
string text,
|
||||||
|
IReadOnlyDictionary<string, string> variables,
|
||||||
|
Func<string, string> encodeValue)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder(text);
|
||||||
|
foreach (var (key, value) in variables)
|
||||||
|
sb.Replace($"{{{{{key}}}}}", encodeValue(value));
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
|
|
||||||
|
internal sealed class EmailTemplateService : IEmailTemplateService
|
||||||
|
{
|
||||||
|
private readonly IEmailTemplateRepository _templateRepository;
|
||||||
|
|
||||||
|
public EmailTemplateService(IEmailTemplateRepository templateRepository)
|
||||||
|
{
|
||||||
|
_templateRepository = templateRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<EmailTemplate> GetAsync(
|
||||||
|
string serviceName,
|
||||||
|
string templateKey,
|
||||||
|
string? languageCode,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(languageCode))
|
||||||
|
throw new InvalidDataException("LanguageCode is required.");
|
||||||
|
|
||||||
|
string lang = languageCode.Trim().ToLowerInvariant();
|
||||||
|
EmailTemplate? template = await _templateRepository.GetAsync(
|
||||||
|
serviceName,
|
||||||
|
templateKey,
|
||||||
|
lang,
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
return template
|
||||||
|
?? throw new InvalidOperationException(
|
||||||
|
$"Template not found: service='{serviceName}' key='{templateKey}' language='{lang}'.");
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
|
|
||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
public interface IEmailTemplateRenderingService
|
||||||
|
{
|
||||||
|
RenderedEmail Render(EmailTemplate template, SendEmailMessageData data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
|
|
||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
public interface IEmailTemplateService
|
||||||
|
{
|
||||||
|
Task<EmailTemplate> GetAsync(
|
||||||
|
string serviceName,
|
||||||
|
string templateKey,
|
||||||
|
string? languageCode,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
|
||||||
|
public interface INotificationResultPublisher
|
||||||
|
{
|
||||||
|
Task PublishAsync(
|
||||||
|
SendEmailMessage message,
|
||||||
|
string? deliveryError,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
|
||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
public interface ISendEmailService
|
||||||
|
{
|
||||||
|
Task ProcessAsync(SendEmailMessage message, CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
|
|
||||||
|
internal interface ISmtpEmailSender
|
||||||
|
{
|
||||||
|
Task SendAsync(
|
||||||
|
SmtpChannelSettings settings,
|
||||||
|
RenderedEmail email,
|
||||||
|
string recipientEmail,
|
||||||
|
string recipientName,
|
||||||
|
CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
+80
@@ -0,0 +1,80 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
using System.Net.Mail;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
|
||||||
|
public static class NotificationDeliveryErrorFormatter
|
||||||
|
{
|
||||||
|
private const int MaximumErrorLength = 2000;
|
||||||
|
private const string FallbackError = "Notification delivery failed after all retry attempts.";
|
||||||
|
|
||||||
|
public static string Format(Exception exception)
|
||||||
|
{
|
||||||
|
string technicalMessage = Normalize(exception.GetBaseException().Message);
|
||||||
|
if (string.IsNullOrWhiteSpace(technicalMessage))
|
||||||
|
{
|
||||||
|
return FallbackError;
|
||||||
|
}
|
||||||
|
|
||||||
|
string contextualMessage = CreateContextualMessage(exception, technicalMessage);
|
||||||
|
return contextualMessage.Length <= MaximumErrorLength
|
||||||
|
? contextualMessage
|
||||||
|
: contextualMessage[..MaximumErrorLength];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string CreateContextualMessage(Exception exception, string technicalMessage)
|
||||||
|
{
|
||||||
|
if (FindException<SmtpFailedRecipientException>(exception) is not null)
|
||||||
|
{
|
||||||
|
return "SMTP delivery failed after all retry attempts: " +
|
||||||
|
"the SMTP server rejected the recipient address.";
|
||||||
|
}
|
||||||
|
|
||||||
|
SocketException? socketException = FindException<SocketException>(exception);
|
||||||
|
if (socketException is not null)
|
||||||
|
{
|
||||||
|
string reason = socketException.SocketErrorCode switch
|
||||||
|
{
|
||||||
|
SocketError.HostNotFound or SocketError.NoData =>
|
||||||
|
"the configured SMTP server host could not be resolved",
|
||||||
|
SocketError.ConnectionRefused =>
|
||||||
|
"the configured SMTP server refused the connection",
|
||||||
|
SocketError.TimedOut =>
|
||||||
|
"the connection to the configured SMTP server timed out",
|
||||||
|
_ when technicalMessage.Contains(
|
||||||
|
"Name or service not known",
|
||||||
|
StringComparison.OrdinalIgnoreCase) =>
|
||||||
|
"the configured SMTP server host could not be resolved",
|
||||||
|
_ => "the configured SMTP server could not be reached"
|
||||||
|
};
|
||||||
|
|
||||||
|
return $"SMTP delivery failed after all retry attempts: {reason} ({technicalMessage}).";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (FindException<SmtpException>(exception) is not null)
|
||||||
|
{
|
||||||
|
return $"SMTP delivery failed after all retry attempts ({technicalMessage}).";
|
||||||
|
}
|
||||||
|
|
||||||
|
return $"Notification delivery failed after all retry attempts ({technicalMessage}).";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TException? FindException<TException>(Exception exception)
|
||||||
|
where TException : Exception
|
||||||
|
{
|
||||||
|
for (Exception? current = exception; current is not null; current = current.InnerException)
|
||||||
|
{
|
||||||
|
if (current is TException typedException)
|
||||||
|
{
|
||||||
|
return typedException;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Normalize(string message)
|
||||||
|
{
|
||||||
|
return message.ReplaceLineEndings(" ").Trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
+63
@@ -0,0 +1,63 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using Hrynco.RabbitMq;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
internal sealed class NotificationResultPublisher : INotificationResultPublisher
|
||||||
|
{
|
||||||
|
private readonly ILogger<NotificationResultPublisher> _logger;
|
||||||
|
private readonly IRabbitMqPublisher _publisher;
|
||||||
|
|
||||||
|
public NotificationResultPublisher(
|
||||||
|
IRabbitMqPublisher publisher,
|
||||||
|
ILogger<NotificationResultPublisher> logger)
|
||||||
|
{
|
||||||
|
_publisher = publisher;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task PublishAsync(
|
||||||
|
SendEmailMessage message,
|
||||||
|
string? deliveryError,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
CorrelationContext correlationContext = message.CorrelationContext;
|
||||||
|
string? replyTo = correlationContext.ReplyTo;
|
||||||
|
if (string.IsNullOrWhiteSpace(replyTo))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = new NotificationResultMessage
|
||||||
|
{
|
||||||
|
CorrelationContext = correlationContext with { ReplyTo = null },
|
||||||
|
Data = new NotificationResultData
|
||||||
|
{
|
||||||
|
ServiceName = message.Data.ServiceName,
|
||||||
|
RecipientEmail = message.Data.RecipientEmail,
|
||||||
|
TemplateKey = message.Data.TemplateKey,
|
||||||
|
Timestamp = DateTimeOffset.UtcNow,
|
||||||
|
ErrorMessage = deliveryError
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
await _publisher.PublishAsync(replyTo, result, cancellationToken);
|
||||||
|
|
||||||
|
_logger.LogDebug(
|
||||||
|
"Notification result published to reply queue {Queue} [CorrelationId={CorrelationId}]",
|
||||||
|
replyTo,
|
||||||
|
correlationContext.CorrelationId);
|
||||||
|
}
|
||||||
|
catch (Exception exception)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(
|
||||||
|
exception,
|
||||||
|
"Failed to publish notification result to reply queue {Queue} [CorrelationId={CorrelationId}]",
|
||||||
|
replyTo,
|
||||||
|
correlationContext.CorrelationId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
public static class RecipientAddressRedactor
|
||||||
|
{
|
||||||
|
public static string Redact(string? address)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(address))
|
||||||
|
return "<missing>";
|
||||||
|
|
||||||
|
int separator = address.LastIndexOf('@');
|
||||||
|
if (separator <= 0 || separator == address.Length - 1)
|
||||||
|
return "***";
|
||||||
|
|
||||||
|
string local = address[..separator];
|
||||||
|
string domain = address[(separator + 1)..];
|
||||||
|
int dot = domain.LastIndexOf('.');
|
||||||
|
string domainName = dot > 0 ? domain[..dot] : domain;
|
||||||
|
string suffix = dot > 0 ? domain[dot..] : string.Empty;
|
||||||
|
|
||||||
|
return $"{local[0]}***@{domainName[0]}***{suffix}";
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
namespace HrynCo.NotificationService.Worker;
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
public record RenderedEmail(string Subject, string HtmlBody, string TextBody);
|
public record RenderedEmail(string Subject, string HtmlBody, string TextBody);
|
||||||
+36
@@ -0,0 +1,36 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
using System.Net.Mail;
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
|
||||||
|
public static class SendEmailMessageValidator
|
||||||
|
{
|
||||||
|
public static void Validate(SendEmailMessage message)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(message);
|
||||||
|
|
||||||
|
if (message.CorrelationContext is null)
|
||||||
|
throw new InvalidDataException("CorrelationContext is required.");
|
||||||
|
if (string.IsNullOrWhiteSpace(message.CorrelationContext.CorrelationId))
|
||||||
|
throw new InvalidDataException("CorrelationContext.CorrelationId is required.");
|
||||||
|
if (message.Data is null)
|
||||||
|
throw new InvalidDataException("Data is required.");
|
||||||
|
|
||||||
|
Require(message.Data.ServiceName, nameof(message.Data.ServiceName));
|
||||||
|
Require(message.Data.TemplateKey, nameof(message.Data.TemplateKey));
|
||||||
|
Require(message.Data.RecipientEmail, nameof(message.Data.RecipientEmail));
|
||||||
|
Require(message.Data.RecipientName, nameof(message.Data.RecipientName));
|
||||||
|
Require(message.Data.LanguageCode, nameof(message.Data.LanguageCode));
|
||||||
|
|
||||||
|
if (!MailAddress.TryCreate(message.Data.RecipientEmail, out _))
|
||||||
|
throw new InvalidDataException("RecipientEmail is not a valid email address.");
|
||||||
|
if (message.Data.Variables is null)
|
||||||
|
throw new InvalidDataException("Variables is required.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Require(string? value, string fieldName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(value))
|
||||||
|
throw new InvalidDataException($"{fieldName} is required.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
internal sealed class SendEmailService : ISendEmailService
|
||||||
|
{
|
||||||
|
private readonly IEmailChannelRepository _channelRepository;
|
||||||
|
private readonly IEmailChannelUsageRepository _usageRepository;
|
||||||
|
private readonly IEmailTemplateService _templateService;
|
||||||
|
private readonly IEmailTemplateRenderingService _templateRenderingService;
|
||||||
|
private readonly ISmtpEmailSender _smtpEmailSender;
|
||||||
|
private readonly INotificationResultPublisher _resultPublisher;
|
||||||
|
private readonly ILogger<SendEmailService> _logger;
|
||||||
|
|
||||||
|
public SendEmailService(
|
||||||
|
IEmailChannelRepository channelRepository,
|
||||||
|
IEmailChannelUsageRepository usageRepository,
|
||||||
|
IEmailTemplateService templateService,
|
||||||
|
IEmailTemplateRenderingService templateRenderingService,
|
||||||
|
ISmtpEmailSender smtpEmailSender,
|
||||||
|
INotificationResultPublisher resultPublisher,
|
||||||
|
ILogger<SendEmailService> logger)
|
||||||
|
{
|
||||||
|
_channelRepository = channelRepository;
|
||||||
|
_usageRepository = usageRepository;
|
||||||
|
_templateService = templateService;
|
||||||
|
_templateRenderingService = templateRenderingService;
|
||||||
|
_smtpEmailSender = smtpEmailSender;
|
||||||
|
_resultPublisher = resultPublisher;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task ProcessAsync(SendEmailMessage message, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
SendEmailMessageValidator.Validate(message);
|
||||||
|
SendEmailMessageData data = message.Data;
|
||||||
|
string redactedRecipient = RecipientAddressRedactor.Redact(data.RecipientEmail);
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Processing SendEmail for service={Service} template={Template} recipient={Recipient} [CorrelationId={CorrelationId}]",
|
||||||
|
data.ServiceName, data.TemplateKey, redactedRecipient, message.CorrelationContext?.CorrelationId);
|
||||||
|
|
||||||
|
EmailChannel channel = await ResolveChannelAsync(data.ServiceName, cancellationToken);
|
||||||
|
EmailTemplate template = await GetTemplateAsync(data, cancellationToken);
|
||||||
|
|
||||||
|
await EnforceLimitsAsync(channel, cancellationToken);
|
||||||
|
|
||||||
|
RenderedEmail rendered = _templateRenderingService.Render(template, data);
|
||||||
|
|
||||||
|
SmtpChannelSettings smtpChannel = channel.Settings as SmtpChannelSettings
|
||||||
|
?? throw new InvalidOperationException(
|
||||||
|
$"Channel type '{channel.EmailChannelType}' is not supported for sending.");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _smtpEmailSender.SendAsync(
|
||||||
|
smtpChannel,
|
||||||
|
rendered,
|
||||||
|
data.RecipientEmail,
|
||||||
|
data.RecipientName,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "SMTP send failed for channel {ChannelId}", channel.Id);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _usageRepository.IncrementUsageAsync(
|
||||||
|
channel.Id,
|
||||||
|
DateOnly.FromDateTime(DateTime.UtcNow),
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
_logger.LogInformation(
|
||||||
|
"Email sent successfully service={Service} template={Template} recipient={Recipient}",
|
||||||
|
data.ServiceName, data.TemplateKey, redactedRecipient);
|
||||||
|
|
||||||
|
await _resultPublisher.PublishAsync(message, null, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<EmailTemplate> GetTemplateAsync(SendEmailMessageData data, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
return await _templateService.GetAsync(
|
||||||
|
data.ServiceName,
|
||||||
|
data.TemplateKey,
|
||||||
|
data.LanguageCode,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<EmailChannel> ResolveChannelAsync(string serviceName, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var channels = await _channelRepository.GetByServiceAsync(serviceName, ct);
|
||||||
|
|
||||||
|
return channels
|
||||||
|
.Where(c => c.IsActive)
|
||||||
|
.OrderBy(c => c.Priority)
|
||||||
|
.FirstOrDefault()
|
||||||
|
?? throw new InvalidOperationException(
|
||||||
|
$"No active email channel found for service '{serviceName}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task EnforceLimitsAsync(EmailChannel channel, CancellationToken ct)
|
||||||
|
{
|
||||||
|
DateOnly today = DateOnly.FromDateTime(DateTime.UtcNow);
|
||||||
|
|
||||||
|
if (channel.DailyLimit.HasValue)
|
||||||
|
{
|
||||||
|
int daily = await _usageRepository.GetDailyCountAsync(channel.Id, today, ct);
|
||||||
|
|
||||||
|
if (daily >= channel.DailyLimit.Value)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"Channel '{channel.Id}' daily limit of {channel.DailyLimit.Value} reached ({daily} sent today).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (channel.MonthlyLimit.HasValue)
|
||||||
|
{
|
||||||
|
int monthly = await _usageRepository.GetMonthlyCountAsync(channel.Id, today.Year, today.Month, ct);
|
||||||
|
|
||||||
|
if (monthly >= channel.MonthlyLimit.Value)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException(
|
||||||
|
$"Channel '{channel.Id}' monthly limit of {channel.MonthlyLimit.Value} reached ({monthly} sent this month).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Mail;
|
||||||
|
using System.Text;
|
||||||
|
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
||||||
|
|
||||||
|
internal sealed class SmtpEmailSender : ISmtpEmailSender
|
||||||
|
{
|
||||||
|
public async Task SendAsync(
|
||||||
|
SmtpChannelSettings settings,
|
||||||
|
RenderedEmail email,
|
||||||
|
string recipientEmail,
|
||||||
|
string recipientName,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using var client = new SmtpClient(settings.Host, settings.Port)
|
||||||
|
{
|
||||||
|
EnableSsl = settings.UseSsl,
|
||||||
|
Credentials = string.IsNullOrWhiteSpace(settings.Username)
|
||||||
|
? null
|
||||||
|
: new NetworkCredential(settings.Username, settings.Password)
|
||||||
|
};
|
||||||
|
|
||||||
|
using var mail = new MailMessage
|
||||||
|
{
|
||||||
|
From = new MailAddress(settings.FromEmail, settings.FromName),
|
||||||
|
Subject = email.Subject,
|
||||||
|
Body = email.TextBody,
|
||||||
|
IsBodyHtml = false,
|
||||||
|
BodyEncoding = Encoding.UTF8,
|
||||||
|
SubjectEncoding = Encoding.UTF8
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(email.HtmlBody))
|
||||||
|
{
|
||||||
|
AlternateView html = AlternateView.CreateAlternateViewFromString(
|
||||||
|
email.HtmlBody,
|
||||||
|
Encoding.UTF8,
|
||||||
|
"text/html");
|
||||||
|
mail.AlternateViews.Add(html);
|
||||||
|
}
|
||||||
|
|
||||||
|
mail.To.Add(new MailAddress(recipientEmail, recipientName));
|
||||||
|
await client.SendMailAsync(mail, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>HrynCo.NotificationService.Worker.Services</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="HrynCo.RabbitMq" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HrynCo.NotificationService.Contracts\HrynCo.NotificationService.Contracts.csproj" />
|
||||||
|
<ProjectReference Include="..\HrynCo.NotificationService.DAL.Abstract\HrynCo.NotificationService.DAL.Abstract.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
[assembly: InternalsVisibleTo("HrynCo.NotificationService.Services.Tests")]
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
using Hrynco.RabbitMq;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
|
||||||
|
namespace HrynCo.NotificationService.Worker.Services;
|
||||||
|
|
||||||
|
public static class ServiceCollectionExtensions
|
||||||
|
{
|
||||||
|
public static IServiceCollection AddNotificationWorkerServices(this IServiceCollection services)
|
||||||
|
{
|
||||||
|
services.AddSingleton<IRabbitMqPublisher, RabbitMqPublisher>();
|
||||||
|
services.AddScoped<IEmailTemplateService, EmailTemplateService>();
|
||||||
|
services.AddScoped<IEmailTemplateRenderingService, EmailTemplateRenderingService>();
|
||||||
|
services.AddScoped<ISmtpEmailSender, SmtpEmailSender>();
|
||||||
|
services.AddScoped<INotificationResultPublisher, NotificationResultPublisher>();
|
||||||
|
services.AddScoped<ISendEmailService, SendEmailService>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,4 +8,4 @@ public sealed class AppSettings
|
|||||||
|
|
||||||
public string ConnectionString { get; init; } = string.Empty;
|
public string ConnectionString { get; init; } = string.Empty;
|
||||||
public RabbitMqSettings RabbitMq { get; init; } = null!;
|
public RabbitMqSettings RabbitMq { get; init; } = null!;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ COPY ["Directory.Build.props", "."]
|
|||||||
COPY ["Directory.Packages.props", "."]
|
COPY ["Directory.Packages.props", "."]
|
||||||
COPY ["HrynCo.NotificationService.DAL.Abstract/HrynCo.NotificationService.DAL.Abstract.csproj", "HrynCo.NotificationService.DAL.Abstract/"]
|
COPY ["HrynCo.NotificationService.DAL.Abstract/HrynCo.NotificationService.DAL.Abstract.csproj", "HrynCo.NotificationService.DAL.Abstract/"]
|
||||||
COPY ["HrynCo.NotificationService.DAL.EF/HrynCo.NotificationService.DAL.EF.csproj", "HrynCo.NotificationService.DAL.EF/"]
|
COPY ["HrynCo.NotificationService.DAL.EF/HrynCo.NotificationService.DAL.EF.csproj", "HrynCo.NotificationService.DAL.EF/"]
|
||||||
COPY ["HrynCo.NotificationService.Services/HrynCo.NotificationService.Services.csproj", "HrynCo.NotificationService.Services/"]
|
COPY ["HrynCo.NotificationService.Worker.Services/HrynCo.NotificationService.Worker.Services.csproj", "HrynCo.NotificationService.Worker.Services/"]
|
||||||
COPY ["HrynCo.NotificationService.Worker/HrynCo.NotificationService.Worker.csproj", "HrynCo.NotificationService.Worker/"]
|
COPY ["HrynCo.NotificationService.Worker/HrynCo.NotificationService.Worker.csproj", "HrynCo.NotificationService.Worker/"]
|
||||||
|
|
||||||
RUN dotnet restore "HrynCo.NotificationService.Worker/HrynCo.NotificationService.Worker.csproj"
|
RUN dotnet restore "HrynCo.NotificationService.Worker/HrynCo.NotificationService.Worker.csproj"
|
||||||
@@ -28,4 +28,4 @@ RUN dotnet publish "./HrynCo.NotificationService.Worker.csproj" -c $BUILD_CONFIG
|
|||||||
FROM base AS final
|
FROM base AS final
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=publish /app/publish .
|
COPY --from=publish /app/publish .
|
||||||
ENTRYPOINT ["dotnet", "HrynCo.NotificationService.Worker.dll"]
|
ENTRYPOINT ["dotnet", "HrynCo.NotificationService.Worker.dll"]
|
||||||
|
|||||||
@@ -10,7 +10,6 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Extensions.Hosting" />
|
<PackageReference Include="Microsoft.Extensions.Hosting" />
|
||||||
<PackageReference Include="HrynCo.RabbitMq" />
|
<PackageReference Include="HrynCo.RabbitMq" />
|
||||||
<PackageReference Include="MediatR" />
|
|
||||||
<PackageReference Include="Serilog.Extensions.Hosting" />
|
<PackageReference Include="Serilog.Extensions.Hosting" />
|
||||||
<PackageReference Include="Serilog.Settings.Configuration" />
|
<PackageReference Include="Serilog.Settings.Configuration" />
|
||||||
<PackageReference Include="Serilog.Sinks.Console" />
|
<PackageReference Include="Serilog.Sinks.Console" />
|
||||||
@@ -19,7 +18,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\HrynCo.NotificationService.Contracts\HrynCo.NotificationService.Contracts.csproj" />
|
<ProjectReference Include="..\HrynCo.NotificationService.Contracts\HrynCo.NotificationService.Contracts.csproj" />
|
||||||
<ProjectReference Include="..\HrynCo.NotificationService.Services\HrynCo.NotificationService.Services.csproj" />
|
|
||||||
<ProjectReference Include="..\HrynCo.NotificationService.DAL.EF\HrynCo.NotificationService.DAL.EF.csproj" />
|
<ProjectReference Include="..\HrynCo.NotificationService.DAL.EF\HrynCo.NotificationService.DAL.EF.csproj" />
|
||||||
|
<ProjectReference Include="..\HrynCo.NotificationService.Worker.Services\HrynCo.NotificationService.Worker.Services.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
using HrynCo.NotificationService.DAL.EF;
|
using HrynCo.NotificationService.DAL.EF;
|
||||||
using HrynCo.NotificationService.Services;
|
|
||||||
using HrynCo.NotificationService.Worker;
|
using HrynCo.NotificationService.Worker;
|
||||||
|
using HrynCo.NotificationService.Worker.Services;
|
||||||
using Hrynco.RabbitMq;
|
using Hrynco.RabbitMq;
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
|
|
||||||
var builder = Host.CreateApplicationBuilder(args);
|
var builder = Host.CreateApplicationBuilder(args);
|
||||||
|
|
||||||
@@ -14,7 +13,7 @@ var appSettings = builder.Configuration
|
|||||||
|
|
||||||
builder.Services.AddSingleton(appSettings);
|
builder.Services.AddSingleton(appSettings);
|
||||||
builder.Services.AddNotificationDataAccess(appSettings.ConnectionString);
|
builder.Services.AddNotificationDataAccess(appSettings.ConnectionString);
|
||||||
builder.Services.AddNotificationServices();
|
builder.Services.AddNotificationWorkerServices();
|
||||||
|
|
||||||
builder.Services.Configure<RabbitMqSettings>(
|
builder.Services.Configure<RabbitMqSettings>(
|
||||||
builder.Configuration.GetSection($"{AppSettings.SectionName}:RabbitMq"));
|
builder.Configuration.GetSection($"{AppSettings.SectionName}:RabbitMq"));
|
||||||
@@ -22,4 +21,4 @@ builder.Services.Configure<RabbitMqSettings>(
|
|||||||
builder.Services.AddHostedService<SendEmailConsumer>();
|
builder.Services.AddHostedService<SendEmailConsumer>();
|
||||||
|
|
||||||
var host = builder.Build();
|
var host = builder.Build();
|
||||||
host.Run();
|
host.Run();
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
|
[assembly: InternalsVisibleTo("HrynCo.NotificationService.Services.Tests")]
|
||||||
@@ -1,174 +1,70 @@
|
|||||||
namespace HrynCo.NotificationService.Worker;
|
namespace HrynCo.NotificationService.Worker;
|
||||||
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HrynCo.NotificationService.Contracts.Messages;
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Providers;
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Repositories;
|
|
||||||
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
|
||||||
using HrynCo.NotificationService.Services.EmailChannels.Send;
|
|
||||||
using Hrynco.RabbitMq;
|
using Hrynco.RabbitMq;
|
||||||
using MediatR;
|
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using RabbitMQ.Client;
|
|
||||||
|
|
||||||
public sealed class SendEmailConsumer(
|
public sealed class SendEmailConsumer : RabbitMqConsumerBase<SendEmailMessage, SendEmailMessageData>
|
||||||
IOptionsMonitor<RabbitMqSettings> options,
|
|
||||||
IEmailChannelRepository channelRepository,
|
|
||||||
IEmailTemplateRepository templateRepository,
|
|
||||||
IEmailChannelUsageRepository usageRepository,
|
|
||||||
IMediator mediator,
|
|
||||||
AppSettings appSettings,
|
|
||||||
ILogger<SendEmailConsumer> logger)
|
|
||||||
: RabbitMqConsumerBase<SendEmailMessage, SendEmailMessageData>(options, logger)
|
|
||||||
{
|
{
|
||||||
private const string IncomingQueue = "notification.send-email";
|
internal const string IncomingQueue = "notification.send-email";
|
||||||
|
internal const string SupportedMessageType = "Notification.SendEmail.v1";
|
||||||
|
|
||||||
|
private readonly IServiceScopeFactory _scopeFactory;
|
||||||
|
private readonly ILogger<SendEmailConsumer> _logger;
|
||||||
|
|
||||||
|
public SendEmailConsumer(
|
||||||
|
IOptionsMonitor<RabbitMqSettings> options,
|
||||||
|
IServiceScopeFactory scopeFactory,
|
||||||
|
ILogger<SendEmailConsumer> logger)
|
||||||
|
: base(options, logger)
|
||||||
|
{
|
||||||
|
_scopeFactory = scopeFactory;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
protected override string QueueName => IncomingQueue;
|
protected override string QueueName => IncomingQueue;
|
||||||
|
|
||||||
protected override async Task HandleMessageAsync(SendEmailMessage message, CancellationToken cancellationToken)
|
protected override bool TryValidateMessage(
|
||||||
|
SendEmailMessage message,
|
||||||
|
RabbitMqMessageContext context,
|
||||||
|
out string? validationError)
|
||||||
{
|
{
|
||||||
var data = message.Data;
|
validationError = SendEmailDeliveryValidator.GetValidationError(
|
||||||
|
message,
|
||||||
logger.LogInformation(
|
context,
|
||||||
"Processing SendEmail for service={Service} template={Template} recipient={Recipient} [CorrelationId={CorrelationId}]",
|
SupportedMessageType);
|
||||||
data.ServiceName, data.TemplateKey, data.RecipientEmail, message.CorrelationContext?.CorrelationId);
|
return validationError is null;
|
||||||
|
|
||||||
var channel = await ResolveChannelAsync(data.ServiceName, cancellationToken);
|
|
||||||
var template = await ResolveTemplateAsync(data.ServiceName, data.TemplateKey, data.LanguageCode, cancellationToken);
|
|
||||||
|
|
||||||
await EnforceLimitsAsync(channel, cancellationToken);
|
|
||||||
|
|
||||||
var rendered = RenderTemplate(template, data);
|
|
||||||
|
|
||||||
var sendResult = await mediator.Send(
|
|
||||||
new SendEmailCommand(channel.Id, data.RecipientEmail, data.RecipientName,
|
|
||||||
rendered.Subject, rendered.HtmlBody, rendered.TextBody),
|
|
||||||
cancellationToken);
|
|
||||||
|
|
||||||
if (!sendResult.IsSuccess)
|
|
||||||
throw new InvalidOperationException(sendResult.Error?.Message ?? "Send failed.");
|
|
||||||
|
|
||||||
logger.LogInformation(
|
|
||||||
"Email sent successfully service={Service} template={Template} recipient={Recipient}",
|
|
||||||
data.ServiceName, data.TemplateKey, data.RecipientEmail);
|
|
||||||
|
|
||||||
await PublishResultAsync(message.CorrelationContext, data, errorMessage: null, cancellationToken);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<EmailChannel> ResolveChannelAsync(string serviceName, CancellationToken ct)
|
protected override async Task HandleMessageAsync(
|
||||||
|
SendEmailMessage message,
|
||||||
|
RabbitMqMessageContext context,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var channels = await channelRepository.GetByServiceAsync(serviceName, ct);
|
string payloadCorrelationId = message.CorrelationContext.CorrelationId;
|
||||||
|
if (!string.IsNullOrWhiteSpace(context.CorrelationId) &&
|
||||||
return channels
|
!string.Equals(context.CorrelationId, payloadCorrelationId, StringComparison.Ordinal))
|
||||||
.Where(c => c.IsActive)
|
|
||||||
.OrderBy(c => c.Priority)
|
|
||||||
.FirstOrDefault()
|
|
||||||
?? throw new InvalidOperationException(
|
|
||||||
$"No active email channel found for service '{serviceName}'.");
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<EmailTemplate> ResolveTemplateAsync(
|
|
||||||
string serviceName, string templateKey, string? languageCode, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var lang = string.IsNullOrWhiteSpace(languageCode) ? "en" : languageCode;
|
|
||||||
var template = await templateRepository.GetAsync(serviceName, templateKey, lang, ct);
|
|
||||||
|
|
||||||
if (template is null && lang != "en")
|
|
||||||
template = await templateRepository.GetAsync(serviceName, templateKey, "en", ct);
|
|
||||||
|
|
||||||
return template
|
|
||||||
?? throw new InvalidOperationException(
|
|
||||||
$"Template not found: service='{serviceName}' key='{templateKey}' language='{lang}'.");
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task EnforceLimitsAsync(EmailChannel channel, CancellationToken ct)
|
|
||||||
{
|
|
||||||
var today = DateOnly.FromDateTime(DateTime.UtcNow);
|
|
||||||
|
|
||||||
if (channel.DailyLimit.HasValue)
|
|
||||||
{
|
{
|
||||||
var daily = await usageRepository.GetDailyCountAsync(channel.Id, today, ct);
|
_logger.LogWarning(
|
||||||
if (daily >= channel.DailyLimit.Value)
|
"Broker and payload correlation IDs differ; payload correlation ID will be used");
|
||||||
throw new InvalidOperationException(
|
|
||||||
$"Channel '{channel.Id}' daily limit of {channel.DailyLimit.Value} reached ({daily} sent today).");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (channel.MonthlyLimit.HasValue)
|
await using AsyncServiceScope scope = _scopeFactory.CreateAsyncScope();
|
||||||
{
|
ISendEmailService service = scope.ServiceProvider.GetRequiredService<ISendEmailService>();
|
||||||
var monthly = await usageRepository.GetMonthlyCountAsync(channel.Id, today.Year, today.Month, ct);
|
await service.ProcessAsync(message, cancellationToken);
|
||||||
if (monthly >= channel.MonthlyLimit.Value)
|
|
||||||
throw new InvalidOperationException(
|
|
||||||
$"Channel '{channel.Id}' monthly limit of {channel.MonthlyLimit.Value} reached ({monthly} sent this month).");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static RenderedEmail RenderTemplate(EmailTemplate template, SendEmailMessageData data)
|
protected override async Task HandleMessageRetriesExhaustedAsync(
|
||||||
|
SendEmailMessage message,
|
||||||
|
RabbitMqMessageContext context,
|
||||||
|
Exception exception,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
return new RenderedEmail(
|
string deliveryError = NotificationDeliveryErrorFormatter.Format(exception);
|
||||||
Interpolate(template.Subject, data.Variables),
|
await using AsyncServiceScope scope = _scopeFactory.CreateAsyncScope();
|
||||||
Interpolate(template.HtmlBody, data.Variables),
|
INotificationResultPublisher resultPublisher =
|
||||||
Interpolate(template.TextBody, data.Variables));
|
scope.ServiceProvider.GetRequiredService<INotificationResultPublisher>();
|
||||||
}
|
await resultPublisher.PublishAsync(message, deliveryError, cancellationToken);
|
||||||
|
|
||||||
private static string Interpolate(string text, IReadOnlyDictionary<string, string> variables)
|
|
||||||
{
|
|
||||||
var sb = new StringBuilder(text);
|
|
||||||
foreach (var (key, value) in variables)
|
|
||||||
sb.Replace($"{{{{{key}}}}}", value);
|
|
||||||
return sb.ToString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task PublishResultAsync(
|
|
||||||
CorrelationContext? correlationContext,
|
|
||||||
SendEmailMessageData data,
|
|
||||||
string? errorMessage,
|
|
||||||
CancellationToken ct)
|
|
||||||
{
|
|
||||||
var replyTo = correlationContext?.ReplyTo;
|
|
||||||
if (string.IsNullOrWhiteSpace(replyTo))
|
|
||||||
return;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var result = new NotificationResultMessage
|
|
||||||
{
|
|
||||||
CorrelationContext = (correlationContext ?? new CorrelationContext { CorrelationId = Guid.NewGuid().ToString() }) with { ReplyTo = null },
|
|
||||||
Data = new NotificationResultData
|
|
||||||
{
|
|
||||||
ServiceName = data.ServiceName,
|
|
||||||
RecipientEmail = data.RecipientEmail,
|
|
||||||
TemplateKey = data.TemplateKey,
|
|
||||||
Timestamp = DateTimeOffset.UtcNow,
|
|
||||||
ErrorMessage = errorMessage
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
byte[] body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(result));
|
|
||||||
|
|
||||||
var factory = new ConnectionFactory
|
|
||||||
{
|
|
||||||
HostName = appSettings.RabbitMq.Host,
|
|
||||||
Port = appSettings.RabbitMq.Port,
|
|
||||||
UserName = appSettings.RabbitMq.User,
|
|
||||||
Password = appSettings.RabbitMq.Password,
|
|
||||||
VirtualHost = appSettings.RabbitMq.VirtualHost
|
|
||||||
};
|
|
||||||
|
|
||||||
await using var conn = await factory.CreateConnectionAsync(ct);
|
|
||||||
await using var ch = await conn.CreateChannelAsync(cancellationToken: ct);
|
|
||||||
|
|
||||||
await ch.QueueDeclareAsync(replyTo, durable: true, exclusive: false, autoDelete: false,
|
|
||||||
cancellationToken: ct);
|
|
||||||
await ch.BasicPublishAsync(exchange: string.Empty, routingKey: replyTo, body: body,
|
|
||||||
cancellationToken: ct);
|
|
||||||
|
|
||||||
logger.LogDebug("Result published to reply queue '{Queue}' [CorrelationId={CorrelationId}]",
|
|
||||||
replyTo, correlationContext?.CorrelationId);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogWarning(ex, "Failed to publish notification result to reply queue '{Queue}'", replyTo);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
namespace HrynCo.NotificationService.Worker;
|
||||||
|
|
||||||
|
using HrynCo.NotificationService.Contracts.Messages;
|
||||||
|
using HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
||||||
|
using Hrynco.RabbitMq;
|
||||||
|
|
||||||
|
internal static class SendEmailDeliveryValidator
|
||||||
|
{
|
||||||
|
public static string? GetValidationError(
|
||||||
|
SendEmailMessage message,
|
||||||
|
RabbitMqMessageContext context,
|
||||||
|
string supportedMessageType)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(context.MessageId))
|
||||||
|
return "AMQP MessageId is required.";
|
||||||
|
|
||||||
|
if (!string.Equals(context.MessageType, supportedMessageType, StringComparison.Ordinal))
|
||||||
|
return $"Unsupported AMQP message type '{context.MessageType ?? "<missing>"}'.";
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SendEmailMessageValidator.Validate(message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (InvalidDataException exception)
|
||||||
|
{
|
||||||
|
return exception.Message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,14 @@
|
|||||||
{
|
{
|
||||||
|
"App": {
|
||||||
|
"ConnectionString": "Host=192.168.2.121;Port=55435;Database=hrynco_ns_prod;Username=ns_user;Password=HAwS0c4A1QmH",
|
||||||
|
"RabbitMq": {
|
||||||
|
"Host": "192.168.2.121",
|
||||||
|
"Port": 5675,
|
||||||
|
"User": "ns_user",
|
||||||
|
"Password": "LN22mEWYdfCy",
|
||||||
|
"VirtualHost": "/"
|
||||||
|
}
|
||||||
|
},
|
||||||
"Serilog": {
|
"Serilog": {
|
||||||
"MinimumLevel": {
|
"MinimumLevel": {
|
||||||
"Default": "Debug",
|
"Default": "Debug",
|
||||||
@@ -7,6 +17,20 @@
|
|||||||
"Microsoft.EntityFrameworkCore": "Information",
|
"Microsoft.EntityFrameworkCore": "Information",
|
||||||
"Microsoft.AspNetCore": "Information"
|
"Microsoft.AspNetCore": "Information"
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"WriteTo": [
|
||||||
|
{ "Name": "Console" },
|
||||||
|
{
|
||||||
|
"Name": "Seq",
|
||||||
|
"Args": {
|
||||||
|
"serverUrl": "http://192.168.2.121:5341"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"Enrich": [ "FromLogContext" ],
|
||||||
|
"Properties": {
|
||||||
|
"Application": "hrynco-notification-service-worker",
|
||||||
|
"Environment": "Development"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,5 +20,6 @@
|
|||||||
<Project Path="HrynCo.NotificationService.DAL.EF/HrynCo.NotificationService.DAL.EF.csproj" />
|
<Project Path="HrynCo.NotificationService.DAL.EF/HrynCo.NotificationService.DAL.EF.csproj" />
|
||||||
<Project Path="HrynCo.NotificationService.Services.Tests/HrynCo.NotificationService.Services.Tests.csproj" />
|
<Project Path="HrynCo.NotificationService.Services.Tests/HrynCo.NotificationService.Services.Tests.csproj" />
|
||||||
<Project Path="HrynCo.NotificationService.Services/HrynCo.NotificationService.Services.csproj" />
|
<Project Path="HrynCo.NotificationService.Services/HrynCo.NotificationService.Services.csproj" />
|
||||||
|
<Project Path="HrynCo.NotificationService.Worker.Services/HrynCo.NotificationService.Worker.Services.csproj" />
|
||||||
<Project Path="HrynCo.NotificationService.Worker/HrynCo.NotificationService.Worker.csproj" />
|
<Project Path="HrynCo.NotificationService.Worker/HrynCo.NotificationService.Worker.csproj" />
|
||||||
</Solution>
|
</Solution>
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<configuration>
|
<configuration>
|
||||||
<config>
|
|
||||||
<add key="globalPackagesFolder" value="%USERPROFILE%\.nuget\packages" />
|
|
||||||
</config>
|
|
||||||
<packageSources>
|
<packageSources>
|
||||||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
||||||
</packageSources>
|
</packageSources>
|
||||||
|
|||||||
@@ -1 +1,121 @@
|
|||||||
# hrynco-notification-service
|
# hrynco-notification-service
|
||||||
|
|
||||||
|
Production image references now use `registry.hrynco.com`, preserving the existing image-tag variables. Contracts package repository metadata uses `gitea.hrynco.com`. These are source configuration changes; production containers and live CI configuration were not restarted or updated by this migration.
|
||||||
|
|
||||||
|
## Documentation
|
||||||
|
|
||||||
|
- [ItemTracker outbox email consumer](docs/itemtracker-outbox-email-consumer.md)
|
||||||
|
- [Shared Notification Service Kubernetes package](docker/kubernetes/shared-notification/README.md)
|
||||||
|
|
||||||
|
## Development environment
|
||||||
|
|
||||||
|
The development Docker Compose stack runs PostgreSQL, RabbitMQ, database migrations,
|
||||||
|
the Notification Service Web and Worker applications, Seq, and Mailpit.
|
||||||
|
|
||||||
|
Prerequisite: install and start Docker Desktop. Then run the installation script from
|
||||||
|
the repository root:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\docker\environments\install-development.cmd
|
||||||
|
```
|
||||||
|
|
||||||
|
The script validates Docker and the Compose configuration, builds the application
|
||||||
|
images, starts the complete stack in the background, and prints container status and
|
||||||
|
the main development URLs. It can also be launched directly from File Explorer or
|
||||||
|
from another working directory.
|
||||||
|
|
||||||
|
To validate the setup without building images or creating containers, run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\docker\environments\install-development.cmd --validate-only
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, the script uses the tracked `docker/environments/.env.Development` file:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
DB_NAME=notification_service
|
||||||
|
DB_USER=postgres
|
||||||
|
DB_PASS=postgres
|
||||||
|
VOLUME_PREFIX=ns-dev
|
||||||
|
RABBITMQ_USER=guest
|
||||||
|
RABBITMQ_PASSWORD=guest
|
||||||
|
RABBITMQ_AMQP_PORT=5672
|
||||||
|
RABBITMQ_MANAGEMENT_PORT=15672
|
||||||
|
WEB_PORT=5200
|
||||||
|
DEVELOPMENT_EMAIL_SERVICE_NAME=TestService
|
||||||
|
```
|
||||||
|
|
||||||
|
To use personal values, copy it to the Git-ignored
|
||||||
|
`docker/environments/.env.local`, adjust the values, and run Docker Compose manually:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker compose --env-file docker/environments/.env.local `
|
||||||
|
-f docker/environments/docker-compose.yml `
|
||||||
|
-f docker/environments/docker-compose.Development.yml `
|
||||||
|
up --build -d
|
||||||
|
```
|
||||||
|
|
||||||
|
After startup, the main development endpoints are:
|
||||||
|
|
||||||
|
- Notification Service admin: `http://localhost:5200/admin/channels`
|
||||||
|
- Notification templates: `http://localhost:5200/admin/templates`
|
||||||
|
- RabbitMQ management: `http://localhost:15672` (`guest` / `guest`)
|
||||||
|
- Mailpit inbox: `http://localhost:8025`
|
||||||
|
- Seq logs: `http://localhost:5342`
|
||||||
|
- PostgreSQL: `localhost:5433`
|
||||||
|
|
||||||
|
During development migrations, the stack idempotently creates an active Mailpit SMTP
|
||||||
|
channel and a neutral English `TestEmail` template for
|
||||||
|
`DEVELOPMENT_EMAIL_SERVICE_NAME`. Existing channels and templates are never
|
||||||
|
overwritten. Change that environment value when the publisher uses another service
|
||||||
|
name.
|
||||||
|
|
||||||
|
Check container status and follow Worker logs:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker compose --env-file docker/environments/.env.local `
|
||||||
|
-f docker/environments/docker-compose.yml `
|
||||||
|
-f docker/environments/docker-compose.Development.yml `
|
||||||
|
ps
|
||||||
|
|
||||||
|
docker compose --env-file docker/environments/.env.local `
|
||||||
|
-f docker/environments/docker-compose.yml `
|
||||||
|
-f docker/environments/docker-compose.Development.yml `
|
||||||
|
logs -f worker
|
||||||
|
```
|
||||||
|
|
||||||
|
Stop the environment without deleting its database and RabbitMQ volumes:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
docker compose --env-file docker/environments/.env.local `
|
||||||
|
-f docker/environments/docker-compose.yml `
|
||||||
|
-f docker/environments/docker-compose.Development.yml `
|
||||||
|
down
|
||||||
|
```
|
||||||
|
|
||||||
|
See the [ItemTracker consumer guide](docs/itemtracker-outbox-email-consumer.md#local-end-to-end-setup)
|
||||||
|
for the complete end-to-end setup.
|
||||||
|
|
||||||
|
## Notification worker flow
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A[Worker host starts] --> B[Load config and register services]
|
||||||
|
B --> C[Start SendEmailConsumer]
|
||||||
|
C --> D[Receive message from notification.send-email]
|
||||||
|
D --> E[Validate Notification.SendEmail.v1 metadata and payload]
|
||||||
|
E --> F[Resolve SendEmailService]
|
||||||
|
F --> G[Pick channel and exact-language template]
|
||||||
|
G --> H[Validate variables and render email content]
|
||||||
|
H --> I[Send via SMTP]
|
||||||
|
I --> J[Update usage counters]
|
||||||
|
J --> K[Optionally publish result to reply queue]
|
||||||
|
K --> L[Acknowledge RabbitMQ delivery]
|
||||||
|
I -. failure .-> M[Log and retry]
|
||||||
|
M -->|retries exhausted| N[Publish terminal failure result]
|
||||||
|
N --> O[Nack original delivery without requeue]
|
||||||
|
```
|
||||||
|
|
||||||
|
Template variables are treated as plain text. The worker HTML-encodes every variable while
|
||||||
|
rendering `HtmlBody`; subject and plain-text body interpolation preserve the original value.
|
||||||
|
Templates must express markup in `body.html` instead of supplying HTML through variables.
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
DB_NAME=notification_service
|
||||||
|
DB_USER=postgres
|
||||||
|
DB_PASS=postgres
|
||||||
|
VOLUME_PREFIX=ns-dev
|
||||||
|
RABBITMQ_USER=guest
|
||||||
|
RABBITMQ_PASSWORD=guest
|
||||||
|
RABBITMQ_AMQP_PORT=5672
|
||||||
|
RABBITMQ_MANAGEMENT_PORT=15672
|
||||||
|
WEB_PORT=5200
|
||||||
|
DEVELOPMENT_EMAIL_SERVICE_NAME=TestService
|
||||||
@@ -3,7 +3,9 @@ name: hrynco-notification-service
|
|||||||
services:
|
services:
|
||||||
migrator:
|
migrator:
|
||||||
environment:
|
environment:
|
||||||
|
- DOTNET_ENVIRONMENT=Development
|
||||||
- App__ConnectionString=Host=db;Port=5432;Database=notification_service;Username=postgres;Password=postgres
|
- App__ConnectionString=Host=db;Port=5432;Database=notification_service;Username=postgres;Password=postgres
|
||||||
|
- DevelopmentSeed__ServiceName=${DEVELOPMENT_EMAIL_SERVICE_NAME:-TestService}
|
||||||
|
|
||||||
web:
|
web:
|
||||||
environment:
|
environment:
|
||||||
@@ -29,9 +31,6 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
RABBITMQ_DEFAULT_USER: guest
|
RABBITMQ_DEFAULT_USER: guest
|
||||||
RABBITMQ_DEFAULT_PASS: guest
|
RABBITMQ_DEFAULT_PASS: guest
|
||||||
ports:
|
|
||||||
- "5672:5672"
|
|
||||||
- "15672:15672"
|
|
||||||
networks:
|
networks:
|
||||||
- internal
|
- internal
|
||||||
|
|
||||||
@@ -55,10 +54,17 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- internal
|
- internal
|
||||||
|
|
||||||
|
mailpit:
|
||||||
|
image: axllent/mailpit:v1.30.0
|
||||||
|
ports:
|
||||||
|
- "8025:8025"
|
||||||
|
networks:
|
||||||
|
- internal
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pgdata:
|
pgdata:
|
||||||
name: ns-dev-pgdata
|
name: ns-dev-pgdata
|
||||||
rabbitmq_data:
|
rabbitmq_data:
|
||||||
name: ns-dev-rabbitmq-data
|
name: ns-dev-rabbitmq-data
|
||||||
seq_data:
|
seq_data:
|
||||||
name: ns-dev-seq
|
name: ns-dev-seq
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
services:
|
services:
|
||||||
migrator:
|
migrator:
|
||||||
build: {}
|
build: {}
|
||||||
image: registry.grynco.com.ua/hrynco.notification-service.migrator:${MIGRATOR_IMAGE_TAG:?MIGRATOR_IMAGE_TAG is required}
|
image: registry.hrynco.com/hrynco.notification-service.migrator:${MIGRATOR_IMAGE_TAG:?MIGRATOR_IMAGE_TAG is required}
|
||||||
|
|
||||||
web:
|
web:
|
||||||
build: {}
|
build: {}
|
||||||
image: registry.grynco.com.ua/hrynco.notification-service.web:${WEB_IMAGE_TAG:?WEB_IMAGE_TAG is required}
|
image: registry.hrynco.com/hrynco.notification-service.web:${WEB_IMAGE_TAG:?WEB_IMAGE_TAG is required}
|
||||||
ports:
|
ports:
|
||||||
- "${WEB_PORT:?WEB_PORT is required}:8080"
|
- "${WEB_PORT:?WEB_PORT is required}:8080"
|
||||||
environment:
|
environment:
|
||||||
@@ -14,7 +14,7 @@ services:
|
|||||||
|
|
||||||
worker:
|
worker:
|
||||||
build: {}
|
build: {}
|
||||||
image: registry.grynco.com.ua/hrynco.notification-service.worker:${WORKER_IMAGE_TAG:?WORKER_IMAGE_TAG is required}
|
image: registry.hrynco.com/hrynco.notification-service.worker:${WORKER_IMAGE_TAG:?WORKER_IMAGE_TAG is required}
|
||||||
environment:
|
environment:
|
||||||
- Serilog__WriteTo__1__Args__serverUrl=${SEQ_URL:-}
|
- Serilog__WriteTo__1__Args__serverUrl=${SEQ_URL:-}
|
||||||
restart: always
|
restart: always
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ services:
|
|||||||
- App__RabbitMq__Port=5672
|
- App__RabbitMq__Port=5672
|
||||||
- App__RabbitMq__User=${RABBITMQ_USER:?RABBITMQ_USER is required}
|
- App__RabbitMq__User=${RABBITMQ_USER:?RABBITMQ_USER is required}
|
||||||
- App__RabbitMq__Password=${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required}
|
- App__RabbitMq__Password=${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required}
|
||||||
|
- App__RabbitMq__VirtualHost=${RABBITMQ_VIRTUAL_HOST:-/}
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -92,4 +93,4 @@ volumes:
|
|||||||
|
|
||||||
networks:
|
networks:
|
||||||
internal:
|
internal:
|
||||||
driver: bridge
|
driver: bridge
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
set "SCRIPT_DIR=%~dp0"
|
||||||
|
for %%I in ("%SCRIPT_DIR%..\..") do set "REPOSITORY_ROOT=%%~fI"
|
||||||
|
set "ENV_FILE=%SCRIPT_DIR%.env.Development"
|
||||||
|
set "BASE_COMPOSE=%SCRIPT_DIR%docker-compose.yml"
|
||||||
|
set "DEVELOPMENT_COMPOSE=%SCRIPT_DIR%docker-compose.Development.yml"
|
||||||
|
|
||||||
|
where docker >nul 2>&1
|
||||||
|
if errorlevel 1 goto docker_missing
|
||||||
|
|
||||||
|
docker info >nul 2>&1
|
||||||
|
if errorlevel 1 goto docker_unavailable
|
||||||
|
|
||||||
|
if not exist "%ENV_FILE%" goto environment_missing
|
||||||
|
|
||||||
|
pushd "%REPOSITORY_ROOT%"
|
||||||
|
if errorlevel 1 goto repository_unavailable
|
||||||
|
|
||||||
|
echo Validating the development Docker Compose configuration...
|
||||||
|
docker compose --env-file "%ENV_FILE%" -f "%BASE_COMPOSE%" -f "%DEVELOPMENT_COMPOSE%" config --quiet
|
||||||
|
if errorlevel 1 goto compose_invalid
|
||||||
|
if /i "%~1"=="--validate-only" goto validation_complete
|
||||||
|
|
||||||
|
echo Building and starting the Notification Service development environment...
|
||||||
|
docker compose --env-file "%ENV_FILE%" -f "%BASE_COMPOSE%" -f "%DEVELOPMENT_COMPOSE%" up --build -d
|
||||||
|
if errorlevel 1 goto installation_failed
|
||||||
|
|
||||||
|
echo.
|
||||||
|
docker compose --env-file "%ENV_FILE%" -f "%BASE_COMPOSE%" -f "%DEVELOPMENT_COMPOSE%" ps
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Notification Service development environment is running.
|
||||||
|
echo Admin: http://localhost:5200/admin/channels
|
||||||
|
echo RabbitMQ: http://localhost:15672
|
||||||
|
echo Mailpit: http://localhost:8025
|
||||||
|
echo Seq: http://localhost:5342
|
||||||
|
echo.
|
||||||
|
popd
|
||||||
|
exit /b 0
|
||||||
|
|
||||||
|
:validation_complete
|
||||||
|
echo Development Docker Compose configuration is valid.
|
||||||
|
popd
|
||||||
|
exit /b 0
|
||||||
|
|
||||||
|
:compose_invalid
|
||||||
|
echo ERROR: The development Docker Compose configuration is invalid.
|
||||||
|
popd
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:installation_failed
|
||||||
|
echo ERROR: Failed to build or start the development environment.
|
||||||
|
popd
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:docker_missing
|
||||||
|
echo ERROR: Docker CLI was not found. Install and start Docker Desktop, then run this script again.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:docker_unavailable
|
||||||
|
echo ERROR: Docker is installed, but the Docker engine is not available. Start Docker Desktop and try again.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:environment_missing
|
||||||
|
echo ERROR: Development environment file was not found: "%ENV_FILE%"
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:repository_unavailable
|
||||||
|
echo ERROR: Repository root is not available: "%REPOSITORY_ROOT%"
|
||||||
|
exit /b 1
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
*.local.json
|
||||||
|
private/
|
||||||
|
rendered/
|
||||||
@@ -0,0 +1,331 @@
|
|||||||
|
# Shared Notification Service on MicroK8s
|
||||||
|
|
||||||
|
This package deploys one shared Web/Worker, PostgreSQL 17, RabbitMQ 4 and a temporary
|
||||||
|
Mailpit sandbox in `shared-notification`, on `mini-pc-2`. It does not expose public
|
||||||
|
Ingress, NodePort or unauthenticated administration. Application administration,
|
||||||
|
RabbitMQ management and the sandbox inbox are available through explicit local
|
||||||
|
`kubectl port-forward` sessions over SSH.
|
||||||
|
|
||||||
|
The initial channel is `Invemory.Staging.Sandbox`, template `TestEmail`, exact language
|
||||||
|
`en`. SMTP egress permits only Mailpit:1025. Mailpit has no relay configuration.
|
||||||
|
Only its temporary inbox is ephemeral. Channels, templates, SMTP settings and usage
|
||||||
|
counters are persisted in PostgreSQL; durable broker queues, messages, users and
|
||||||
|
permissions are retained on the RabbitMQ volume. Never put real SMTP credentials
|
||||||
|
into this sandbox package.
|
||||||
|
|
||||||
|
Mailpit runs as UID/GID `1000:1000` with dropped capabilities and writes its temporary
|
||||||
|
SQLite inbox under `/tmp` on the writable container filesystem. Exact manifest flags
|
||||||
|
and `/livez` were verified with the pinned image in an isolated local container.
|
||||||
|
Adding `readOnlyRootFilesystem` requires a separate writable `/tmp` mount; the image
|
||||||
|
exits immediately without it. The current manifest keeps that filesystem writable.
|
||||||
|
|
||||||
|
## Verified code contract
|
||||||
|
|
||||||
|
The current Worker consumes the fixed durable queue `notification.send-email` using
|
||||||
|
the default exchange. `ServiceName` selects channels and exact-language templates;
|
||||||
|
`CorrelationContext.ReplyTo` selects a result queue. These are logical routing
|
||||||
|
boundaries, not authorization of the message's `ServiceName`. Separate credentials
|
||||||
|
and queue permissions cannot restrict the JSON service name inside that shared queue.
|
||||||
|
There is one consumer and at-least-once processing; a redelivery can produce duplicates.
|
||||||
|
See [the consumer contract](../../../docs/itemtracker-outbox-email-consumer.md).
|
||||||
|
|
||||||
|
This initial vhost is `/notification`. Separate broker users are generated for
|
||||||
|
administration, the Notification Worker and the future staging publisher. Worker
|
||||||
|
read permission covers only `notification.send-email`; staging reads only its result
|
||||||
|
queue. Both require write access to RabbitMQ's authorization name `amq.default` for
|
||||||
|
default-exchange publication. Resource ACLs constrain exchange/queue names, not the
|
||||||
|
routing key of a publish operation: access to the default exchange permits routing
|
||||||
|
to other existing queues within the same vhost. This MVP shared-queue design therefore
|
||||||
|
does not provide security isolation between message ServiceNames or routing keys.
|
||||||
|
No production publisher or SMTP egress is configured.
|
||||||
|
Additional environments need separately reviewed routing, users, permissions, exact
|
||||||
|
templates, provider settings and egress before they can join the shared service.
|
||||||
|
|
||||||
|
Web/API administration has no built-in authentication in this source revision. Its
|
||||||
|
Service stays ClusterIP and default-deny ingress; access through SSH/port-forward is
|
||||||
|
restricted to operators. The worker exposes no health HTTP endpoint. Pod rollout is
|
||||||
|
a process-start check; the explicit consumer gate also verifies one broker consumer.
|
||||||
|
An actual owned smoke message and Seq event remain required after startup.
|
||||||
|
|
||||||
|
## Storage preparation
|
||||||
|
|
||||||
|
Owner decision on 2026-10-02: Notification PostgreSQL and RabbitMQ use the external
|
||||||
|
XFS disk. Invemory staging PostgreSQL remains on its existing internal disk.
|
||||||
|
|
||||||
|
| Service | Data directory | Owner | Mode | Retain capacity |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| PostgreSQL | `/mnt/shared/notification-service/postgres` (`pgdata` child) | `999:999` | `0700` | `10Gi` |
|
||||||
|
| RabbitMQ | `/mnt/shared/notification-service/rabbitmq` | `100:101` | `0700` | `5Gi` |
|
||||||
|
|
||||||
|
`/mnt/shared` is the bind mount of `/mnt/files/shared`; both reach the same original
|
||||||
|
data. They are not backups. The required filesystem UUID is
|
||||||
|
`c2c31640-a247-4988-bc7b-9ee9789464d1`. Static local PVs use `Retain`, fixed node
|
||||||
|
affinity and prebound PVCs. Capacity declarations are scheduling/accounting budgets;
|
||||||
|
local PVs do not enforce filesystem byte quotas.
|
||||||
|
|
||||||
|
Transfer the package to `/home/devops/notification-package`, then the owner runs
|
||||||
|
one command on mini-pc-2:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 /home/devops/notification-package/prepare-storage.py
|
||||||
|
```
|
||||||
|
|
||||||
|
The script verifies exact `/mnt/files` and `/mnt/shared` XFS mount targets and UUID
|
||||||
|
before creating anything. It accepts the already provisioned exact empty directories,
|
||||||
|
or creates missing directories under a root-owned `0755` parent. It writes root-owned
|
||||||
|
`0644` `.invemory-storage.json` markers with the UUID and roles
|
||||||
|
`shared-notification/postgres` / `shared-notification/rabbitmq`. Repeated execution
|
||||||
|
verifies markers without replacing them. It refuses symlinks, incorrect permissions,
|
||||||
|
unexpected parent contents and unmarked nonempty directories. It never deletes data.
|
||||||
|
|
||||||
|
The deployment host preflight runs `findmnt` for each PV directory and checks actual
|
||||||
|
UUID, filesystem and ownership. Each Pod has a nonroot startup guard that checks
|
||||||
|
XFS `statfs` and the exact role/UUID marker on its mounted PVC. The marker is an
|
||||||
|
owner-provisioned assertion of UUID, not a live block-device query; the host preflight
|
||||||
|
supplies that check. A missing external mount falls onto ext4 and fails the guard.
|
||||||
|
These checks and `Retain` do not protect against direct manual deletion.
|
||||||
|
|
||||||
|
Storage Pods deliberately omit `fsGroup` so kubelet does not recursively change
|
||||||
|
the owner-provisioned directory and marker permissions. PostgreSQL uses the pinned
|
||||||
|
image's writable `/var/run/postgresql` directory on its container filesystem;
|
||||||
|
RabbitMQ writes its cookie/state in its UID-owned retained data directory. Both run
|
||||||
|
with explicit nonroot UID/GID, dropped capabilities and restricted Pod security.
|
||||||
|
|
||||||
|
RabbitMQ diagnostics probes allow 15 seconds per call: a healthy call on the
|
||||||
|
resource-limited node took seven seconds. Startup keeps a three-minute failure
|
||||||
|
budget (nine attempts, every 20 seconds); readiness runs every 20 seconds and
|
||||||
|
liveness every 30 seconds. Startup must succeed before the other probes run.
|
||||||
|
|
||||||
|
Never remove files directly from these data directories. Storage path/UUID/node/
|
||||||
|
capacity changes and database/broker image changes are rejected by repeated deploys.
|
||||||
|
A future storage move requires a separate controlled procedure: stop publishers and
|
||||||
|
both service writers, verify database and broker backups, stop storage processes,
|
||||||
|
copy and verify offline data, provision target markers/ownership, bind new retained
|
||||||
|
claims, test restoration and perform rollback checks before retiring old storage.
|
||||||
|
This package does not perform that migration.
|
||||||
|
|
||||||
|
## Artifacts and private state
|
||||||
|
|
||||||
|
Copy `config.example.json` to `config.local.json` and verify actual Seq/publisher Pod
|
||||||
|
selectors. The example reply queue `invemory.staging.notification-results` is isolated
|
||||||
|
from the old client fallback. Its exact name must be agreed and configured in the
|
||||||
|
Invemory publisher/result consumer before that later cutover. The current publisher
|
||||||
|
remains `LogOnly`, and its result consumer remains disabled.
|
||||||
|
|
||||||
|
Build Web, Worker and Migrator from the same verified source archive, using each
|
||||||
|
existing Dockerfile. Record the checked commit and archive SHA256, including any
|
||||||
|
explicitly recorded uncommitted delta. Mirror PostgreSQL, RabbitMQ, Mailpit and a
|
||||||
|
Python 3 Linux image to `registry.hrynco.com`. Copy `artifacts.example.json` to
|
||||||
|
`artifacts.local.json` and record all seven immutable image digests, source hashes
|
||||||
|
and the two reviewed migration IDs. The script rejects placeholder/tag references,
|
||||||
|
other registries, mismatched application/migrator archives and unsupported DB/broker
|
||||||
|
major versions. The archive hash fields are an operator provenance record; independently
|
||||||
|
verify the build inputs and registry digests before live application.
|
||||||
|
|
||||||
|
Provision a **dedicated** Seq ingestion key for Notification Service, with its own
|
||||||
|
identity/permissions, in a private file. Do not reuse the staging application's stamped
|
||||||
|
key. Store registry authentication as a private Docker `config.json` with only
|
||||||
|
`registry.hrynco.com` in `auths`. Never print key values, full Secrets or credentials.
|
||||||
|
|
||||||
|
Run the dedicated helper as devops on mini-pc-2 after package review:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 /home/devops/notification-package/prepare-seq-key.py
|
||||||
|
```
|
||||||
|
|
||||||
|
It reads the existing private `/home/devops/seq-first/credentials.json` silently and
|
||||||
|
uses the checked session/CSRF API pattern at the trusted Seq LAN endpoint. It creates
|
||||||
|
only `HrynCo Notification Service`, granting only `Ingest` and stamping
|
||||||
|
`Environment=SharedNotification`, `Service=HrynCo.NotificationService`. `Application`
|
||||||
|
remains supplied by each application. It stores the token only in
|
||||||
|
`/home/devops/notification-private/seq-key.txt` (`0600`, parent `0700`) before the
|
||||||
|
create request, so an unknown POST outcome can be retried with the same token.
|
||||||
|
Repeats verify existing permissions/properties and preserve the token; mismatches,
|
||||||
|
duplicate keys or a missing local token for an existing key fail without rotation.
|
||||||
|
The installed Seq does not expose the original token after creation, and its
|
||||||
|
EventEntity has no `ApiKeyId`. The helper therefore adds the server-applied property
|
||||||
|
`NotificationIngestKeyId=<dedicated key ID>` through a guarded PUT of **only** the
|
||||||
|
dedicated key (`apikey-79` at the initial checkpoint). It preserves its token,
|
||||||
|
permissions, all other input settings and entity fields. It verifies that no other
|
||||||
|
key has the same identity marker before and after updating using explicit
|
||||||
|
`api/apikeys?shared=true` lists (including shared keys), and verifies exact
|
||||||
|
readback. Repeats with the correct marker perform no PUT. An unknown PUT outcome is
|
||||||
|
recovered by reading the existing marker on the next run, without token rotation or
|
||||||
|
another key. A marker mismatch/collision stops without changing another key.
|
||||||
|
The [official Seq API update contract](https://github.com/datalust/seq-api/blob/dev/src/Seq.Api/ResourceGroups/ApiKeysResourceGroup.cs)
|
||||||
|
states that updating settings cannot change the API key token.
|
||||||
|
HTTP redirects are denied before forwarding credentials; environment proxies are
|
||||||
|
disabled for this fixed LAN operation. Each run verifies token ingestion using one
|
||||||
|
technical canary event without user payload or credentials, then reads that exact
|
||||||
|
`ProvisioningCheckId` through the admin session with bounded polling. It verifies
|
||||||
|
the actual server-stamped `NotificationIngestKeyId`, Environment and Service. The
|
||||||
|
canary body omits all three stamps, so a valid staging/foreign token cannot supply
|
||||||
|
the dedicated identity marker. If `ApiKeyId` is exposed by a server version, it must
|
||||||
|
also agree. Missing or conflicting identity proof fails closed without rotation.
|
||||||
|
No event payload/token is printed. Back up the private file.
|
||||||
|
|
||||||
|
The key's stamped properties take precedence over application fields. Verify the first
|
||||||
|
Web/Worker event has `Environment=SharedNotification` before accepting delivery.
|
||||||
|
The helper never changes staging keys, signals, retention or Seq deployment.
|
||||||
|
The existing shared Seq retention/storage policy remains in force; changing retention
|
||||||
|
is a separate observability decision. Dedicated key and event verification remain
|
||||||
|
mandatory live gates if the helper has not yet been run.
|
||||||
|
|
||||||
|
`bootstrap` generates random passwords once in
|
||||||
|
`/home/devops/shared-notification-private/credentials.json` (`0600`, parent `0700`)
|
||||||
|
and reconciles Kubernetes Secrets. Keep and back up this private file outside Git.
|
||||||
|
Repeats reuse it, compare live Secret data and refuse implicit password/key/routing
|
||||||
|
rotation. If the file is missing while a live Secret exists, recover the original
|
||||||
|
file; generating new credentials would not change an existing PostgreSQL role.
|
||||||
|
Registry authentication can be refreshed independently. `.local.json`, rendered files
|
||||||
|
and `private/` are ignored in this package, but prefer keeping secrets outside the repo.
|
||||||
|
|
||||||
|
## Ordered installation and repeat deployment
|
||||||
|
|
||||||
|
All mutating commands run as devops on mini-pc-2. `prepare-storage.py` is the only
|
||||||
|
owner-run root operation. Scripts use Python's standard library, MicroK8s kubectl,
|
||||||
|
`/home/devops/.kube/cluster-admin.conf` and bounded timeouts. No command prints Secrets.
|
||||||
|
|
||||||
|
1. Review source changes, artifacts and manifests independently. Measure live node
|
||||||
|
requests/limits and usage; inspect namespace/node pressure. The namespace budget is
|
||||||
|
8 Pods, 5 Deployments, 3 Jobs, 2 PVCs, 15Gi storage, requests1600m/2Gi and limits4CPU/4Gi.
|
||||||
|
This is a separate budget; existing `invemory-staging` quotas are not expanded.
|
||||||
|
2. Run owner storage preparation and privately supply registry/Seq files.
|
||||||
|
3. Bootstrap the namespace and preserved Secrets:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 notification.py bootstrap --config config.local.json --artifacts artifacts.local.json --seq-key-file /home/devops/notification-private/seq-key.txt --registry-auth-file /home/devops/notification-private/registry-auth.json
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Render for review and run server-side dry-run. `check` also rejects resource
|
||||||
|
adoption, wrong mounted disk, Pod selector mismatches and storage/image changes:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 notification.py render --config config.local.json --artifacts artifacts.local.json --output /home/devops/notification-manifests.json
|
||||||
|
python3 notification.py check --config config.local.json --artifacts artifacts.local.json
|
||||||
|
```
|
||||||
|
|
||||||
|
5. First install applies storage/isolated foundation and runs migrations with Web and
|
||||||
|
Worker stopped. The migration target is exactly `InitialCreate` + `PendingChanges`.
|
||||||
|
After migration success, the script verifies history, grants a separate
|
||||||
|
`notification_runtime` role only DML on the three application tables, and idempotently
|
||||||
|
seeds the Mailpit channel and neutral English `TestEmail`. Existing matching-service
|
||||||
|
channels/templates are left unchanged. It resumes Web after these gates; Worker
|
||||||
|
remains stopped for inspection:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 notification.py deploy --config config.local.json --artifacts artifacts.local.json --migrate
|
||||||
|
```
|
||||||
|
|
||||||
|
6. Inspect channel/template, queue backlog/permissions, DB role and Seq identity.
|
||||||
|
Start the Worker only after those checks. The script verifies the sandbox SMTP
|
||||||
|
settings, required template, empty incoming queue and exactly one consumer:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 notification.py deploy --config config.local.json --artifacts artifacts.local.json --enable-worker --sandbox-verified
|
||||||
|
```
|
||||||
|
|
||||||
|
7. Send one owned neutral test message to Mailpit; inspect its matching result,
|
||||||
|
usage counter, ACK and redacted technical logs. Test malformed metadata and
|
||||||
|
missing template/variable failure with owned safe fixtures. Remove only owned
|
||||||
|
test data through application/broker APIs. No arbitrary live email or client backlog
|
||||||
|
is authorized by this smoke test.
|
||||||
|
|
||||||
|
Ordinary repeat `deploy` verifies target schema and preserves the current Worker
|
||||||
|
replica count. It reapplies canonical manifests with the same persistent claims and
|
||||||
|
Secret references. When Worker remains enabled, it waits for its rollout and verifies
|
||||||
|
exactly one broker consumer before reporting completion. Both explicit enable and
|
||||||
|
ordinary redeploy allow up to 60 seconds after rollout for a zero consumer count to
|
||||||
|
become one, polling with a two-second pause and bounded broker commands. Extra or
|
||||||
|
unreadable consumer counts fail immediately. Rollout failure, verification failure
|
||||||
|
or timeout scales Worker to zero and stops the deployment without reporting success.
|
||||||
|
It does not recreate Secrets
|
||||||
|
or reseed provider settings. A later
|
||||||
|
`--migrate` stops Web/Worker, takes a verified local PostgreSQL custom-format dump,
|
||||||
|
runs the Migrator and history/grant/seed gates, then resumes Web. Worker stays stopped
|
||||||
|
unless `--enable-worker --sandbox-verified` is supplied and all gates pass. Once
|
||||||
|
writers have been stopped, backup, migration, history or grants failure leaves them
|
||||||
|
stopped. An initial history mismatch on an already ready database is rejected before
|
||||||
|
scaling writers, without changing their state. Failed Jobs remain for
|
||||||
|
private inspection; the next run replaces only its own named Job. Migration locking
|
||||||
|
uses a private host file and is local to this deployment host.
|
||||||
|
|
||||||
|
An interrupted first install can leave the PostgreSQL Deployment present with no
|
||||||
|
ready Pod (for example, before owner storage markers exist). A retry with `--migrate`
|
||||||
|
first verifies ownership/storage/images, stops both writers and reconciles only the
|
||||||
|
foundation/storage workloads. It waits for PostgreSQL, RabbitMQ and Mailpit readiness
|
||||||
|
before querying actual migration history. Every migration cycle backs up the actual
|
||||||
|
initialized database, including an empty first database: Deployment absence/existence
|
||||||
|
never establishes that the retained volume has no data. Backup/history/storage
|
||||||
|
failure keeps writers stopped and prevents migration. An ordinary deploy against an
|
||||||
|
unready database requires this explicit recovery path and performs no mutation.
|
||||||
|
Stopping an already empty Deployment is supported: collection reads require a JSON
|
||||||
|
PodList, and an empty `items` list needs no Pod-termination wait. Named resource
|
||||||
|
lookups alone use `--ignore-not-found`.
|
||||||
|
|
||||||
|
Backups are retained under the private directory with a SHA256/byte-count/history
|
||||||
|
manifest. `pg_restore --list` validates dump structure; a full restore test and offsite
|
||||||
|
copy are separate gates. This backup covers the Notification database only. It is not
|
||||||
|
a snapshot of RabbitMQ's queue files. Migration does not upgrade/recreate the broker
|
||||||
|
volume; durable queues remain on that retained volume. Broker disk backup/recovery
|
||||||
|
must be verified before a broker upgrade or storage migration.
|
||||||
|
|
||||||
|
## Access and networking
|
||||||
|
|
||||||
|
Use SSH to the deployment host, then forward one local port when needed:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
/snap/microk8s/current/kubectl --kubeconfig=/home/devops/.kube/cluster-admin.conf -n shared-notification port-forward service/web 5200:8080 --address=127.0.0.1
|
||||||
|
```
|
||||||
|
|
||||||
|
Apply equivalent explicit forwards for `service/rabbitmq`15672 and `service/mailpit`8025.
|
||||||
|
Keep them bound to loopback. ClusterIP services expose no LAN/public ports.
|
||||||
|
|
||||||
|
Default-deny policies allow namespace-scoped DB5432, shared Worker/bounded staging
|
||||||
|
publisher AMQP5672, sandbox SMTP1025, cluster DNS53 and Web/Worker Seq8080 only.
|
||||||
|
The package adds its own `notification-seq-ingress` policy in `observability` and
|
||||||
|
`notification-broker-egress` in `invemory-staging`; existing policies stay owned by
|
||||||
|
their original packages. Verify these exact selectors in the rendered diff.
|
||||||
|
No SMTP internet egress or broad namespace allowance is included.
|
||||||
|
|
||||||
|
The Invemory publisher/result-consumer cutover remains a separate operation after
|
||||||
|
Notification acceptance, exact staged settings and backlog inspection. The package
|
||||||
|
does not change Invemory configuration, production routes or CI deployment.
|
||||||
|
|
||||||
|
## Local validation
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -m unittest discover -s docker/kubernetes/shared-notification/tests -v
|
||||||
|
dotnet build HrynCo.NotificationService.slnx --no-restore
|
||||||
|
dotnet test HrynCo.NotificationService.slnx --no-build --no-restore
|
||||||
|
```
|
||||||
|
|
||||||
|
Unit tests cover immutable artifacts, Secret preservation structure, isolated network
|
||||||
|
and storage contracts, failure ordering and no automatic Worker activation. Passing
|
||||||
|
local tests does not establish live storage, image startup, Seq access, mail delivery,
|
||||||
|
backups/restoration or repeat-deploy acceptance; record these after actual testing.
|
||||||
|
|
||||||
|
## Verified mini-pc-2 sandbox checkpoint (2026-10-02)
|
||||||
|
|
||||||
|
The initial installation from source commit `a44b98292f9001f28fed425be131a2c993a85847`
|
||||||
|
completed on mini-pc-2. The external XFS storage guards passed; PostgreSQL, RabbitMQ,
|
||||||
|
Mailpit, Web and one Worker are Ready with zero restarts. The namespace has no Ingress
|
||||||
|
or NodePort. `InitialCreate` and `PendingChanges`, runtime grants and sandbox seed
|
||||||
|
completed. Two private local PostgreSQL backups were created and validated by the
|
||||||
|
deployment script before the initial and repeated migration runs. Neither backup is
|
||||||
|
an offsite copy or a RabbitMQ backup; full restoration was not tested.
|
||||||
|
|
||||||
|
The dedicated Seq key was verified on live ingestion and Web/Worker events carry
|
||||||
|
`Environment=SharedNotification`. A single owned `TestEmail` message reached only
|
||||||
|
Mailpit, was ACKed, produced a matching successful result and incremented the usage
|
||||||
|
counter to one. An unsupported message type was rejected without an email; a missing
|
||||||
|
template produced a matching negative result without an email. The owned messages and
|
||||||
|
results were removed afterward. Both queues are empty and the incoming queue has one
|
||||||
|
consumer. Ordinary repeat deploy with the Worker running and a repeated no-op
|
||||||
|
migration passed; the Worker was enabled again afterward. The external volume data
|
||||||
|
measured about 47MiB for PostgreSQL and 292KiB for RabbitMQ at this checkpoint.
|
||||||
|
|
||||||
|
Invemory staging still publishes Outbox entries in `LogOnly` mode and does not
|
||||||
|
consume results. Connecting its publisher/result consumer and proving a real staging
|
||||||
|
application flow remain separate gated work. Other environments and production SMTP
|
||||||
|
are not part of this sandbox checkpoint.
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"sourceCommit": "REPLACE_WITH_CHECKED_SOURCE_COMMIT",
|
||||||
|
"sourceArchiveSha256": "REPLACE_WITH_VERIFIED_SOURCE_ARCHIVE_SHA256",
|
||||||
|
"migrations": ["20260501214629_InitialCreate", "20260502154249_PendingChanges"],
|
||||||
|
"images": {
|
||||||
|
"web": {"image": "registry.hrynco.com/hrynco.notificationservice.web@sha256:REPLACE", "sourceArchiveSha256": "REPLACE_WITH_VERIFIED_SOURCE_ARCHIVE_SHA256"},
|
||||||
|
"worker": {"image": "registry.hrynco.com/hrynco.notificationservice.worker@sha256:REPLACE", "sourceArchiveSha256": "REPLACE_WITH_VERIFIED_SOURCE_ARCHIVE_SHA256"},
|
||||||
|
"migrator": {"image": "registry.hrynco.com/hrynco.notificationservice.migrator@sha256:REPLACE", "sourceArchiveSha256": "REPLACE_WITH_VERIFIED_SOURCE_ARCHIVE_SHA256"},
|
||||||
|
"postgres": {"image": "registry.hrynco.com/mirror/postgres@sha256:REPLACE", "version": "17"},
|
||||||
|
"rabbitmq": {"image": "registry.hrynco.com/mirror/rabbitmq@sha256:REPLACE", "version": "4"},
|
||||||
|
"mailpit": {"image": "registry.hrynco.com/mirror/mailpit@sha256:REPLACE"},
|
||||||
|
"guard": {"image": "registry.hrynco.com/mirror/python@sha256:REPLACE"}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"namespace": "shared-notification",
|
||||||
|
"node": "mini-pc-2",
|
||||||
|
"storage": {
|
||||||
|
"basePath": "/mnt/shared/notification-service",
|
||||||
|
"filesystem": "xfs",
|
||||||
|
"uuid": "c2c31640-a247-4988-bc7b-9ee9789464d1",
|
||||||
|
"postgresSize": "10Gi",
|
||||||
|
"rabbitmqSize": "5Gi"
|
||||||
|
},
|
||||||
|
"sandboxServiceName": "Invemory.Staging.Sandbox",
|
||||||
|
"rabbitVirtualHost": "/notification",
|
||||||
|
"replyQueue": "invemory.staging.notification-results",
|
||||||
|
"publisherNamespace": "invemory-staging",
|
||||||
|
"publisherPodLabels": {"app.kubernetes.io/component": "worker"},
|
||||||
|
"seqNamespace": "observability",
|
||||||
|
"seqPodLabels": {"app.kubernetes.io/name": "seq"},
|
||||||
|
"seqUrl": "http://seq.observability.svc.cluster.local:8080"
|
||||||
|
}
|
||||||
@@ -0,0 +1,695 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Bounded shared Notification Service deployment. Python standard library only."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import contextlib
|
||||||
|
import datetime
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path, PurePosixPath
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
NAMESPACE = "shared-notification"
|
||||||
|
MANAGED = "hrynco-shared-notification"
|
||||||
|
MIGRATIONS = ["20260501214629_InitialCreate", "20260502154249_PendingChanges"]
|
||||||
|
IMAGE = re.compile(r"registry\.hrynco\.com/[a-z0-9._/-]+@sha256:[a-f0-9]{64}$")
|
||||||
|
SHA = re.compile(r"[a-f0-9]{64}$")
|
||||||
|
|
||||||
|
# Marker must be provisioned only after findmnt proves the backing filesystem UUID.
|
||||||
|
# XFS/ext4 statfs plus exact marker prevents a missing-mount fallback onto another FS.
|
||||||
|
# Marker alone is not a live query of the block-device UUID: verify findmnt at preflight.
|
||||||
|
GUARD = r'''
|
||||||
|
import ctypes, json, os
|
||||||
|
buf = ctypes.create_string_buffer(512)
|
||||||
|
libc = ctypes.CDLL(None, use_errno=True)
|
||||||
|
if libc.statfs(b'/data', ctypes.byref(buf)) != 0:
|
||||||
|
raise RuntimeError('storage statfs failed')
|
||||||
|
magic = ctypes.cast(buf, ctypes.POINTER(ctypes.c_long))[0]
|
||||||
|
expected = {'ext4': 0xEF53, 'xfs': 0x58465342}[os.environ['EXPECTED_FS']]
|
||||||
|
if magic != expected:
|
||||||
|
raise RuntimeError('unexpected storage filesystem')
|
||||||
|
with open('/data/.invemory-storage.json', encoding='utf-8') as stream:
|
||||||
|
marker = json.load(stream)
|
||||||
|
if marker != {'uuid': os.environ['EXPECTED_UUID'], 'role': os.environ['EXPECTED_ROLE']}:
|
||||||
|
raise RuntimeError('unexpected storage UUID/role marker')
|
||||||
|
print('storage guard passed')
|
||||||
|
'''
|
||||||
|
|
||||||
|
# Variables are quoted by PostgreSQL format, never interpolated into SQL by the shell.
|
||||||
|
GRANTS = r'''
|
||||||
|
\getenv runtime_password RUNTIME_PASSWORD
|
||||||
|
SELECT format('CREATE ROLE notification_runtime LOGIN PASSWORD %L NOSUPERUSER NOCREATEDB NOCREATEROLE', :'runtime_password')
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'notification_runtime') \gexec
|
||||||
|
SELECT format('ALTER ROLE notification_runtime PASSWORD %L', :'runtime_password') \gexec
|
||||||
|
REVOKE ALL ON DATABASE notification_service FROM PUBLIC;
|
||||||
|
GRANT CONNECT ON DATABASE notification_service TO notification_runtime;
|
||||||
|
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
|
||||||
|
GRANT USAGE ON SCHEMA public TO notification_runtime;
|
||||||
|
GRANT SELECT, INSERT, UPDATE, DELETE ON email_channels, email_templates, email_channel_usage TO notification_runtime;
|
||||||
|
'''
|
||||||
|
|
||||||
|
SANDBOX = r'''
|
||||||
|
BEGIN;
|
||||||
|
INSERT INTO email_channels (id, service_name, priority, provider_type, settings, warn_threshold_percent, is_active, created)
|
||||||
|
SELECT gen_random_uuid(), 'Invemory.Staging.Sandbox', 1, 1,
|
||||||
|
'{"EmailChannelType":1,"Host":"mailpit","Port":1025,"Username":"","Password":"","UseSsl":false,"FromEmail":"no-reply@local.hrynco.test","FromName":"Invemory Sandbox"}'::jsonb, 90, true, now()
|
||||||
|
WHERE NOT EXISTS (SELECT 1 FROM email_channels WHERE service_name = 'Invemory.Staging.Sandbox');
|
||||||
|
INSERT INTO email_templates (id, service_name, key, language_code, subject, html_body, text_body, variables, created)
|
||||||
|
VALUES (gen_random_uuid(), 'Invemory.Staging.Sandbox', 'TestEmail', 'en', 'Test notification',
|
||||||
|
'<p>Hello {{RecipientName}},</p><p>{{Message}}</p>', 'Hello {{RecipientName}}, {{Message}}',
|
||||||
|
'[{"name":"RecipientName","required":true},{"name":"Message","required":true}]'::jsonb, now())
|
||||||
|
ON CONFLICT (service_name, key, language_code) DO NOTHING;
|
||||||
|
COMMIT;
|
||||||
|
'''
|
||||||
|
|
||||||
|
SANDBOX_CHECK = """SELECT
|
||||||
|
(SELECT count(*) = 1 AND bool_and(provider_type = 1 AND is_active AND
|
||||||
|
settings->>'Host' = 'mailpit' AND settings->>'Port' = '1025' AND
|
||||||
|
settings->>'UseSsl' = 'false' AND settings->>'Username' = '' AND settings->>'Password' = '')
|
||||||
|
FROM email_channels WHERE service_name = 'Invemory.Staging.Sandbox') AND
|
||||||
|
EXISTS (SELECT 1 FROM email_templates WHERE service_name = 'Invemory.Staging.Sandbox'
|
||||||
|
AND key = 'TestEmail' AND language_code = 'en'
|
||||||
|
AND variables @> '[{"name":"RecipientName","required":true},{"name":"Message","required":true}]'::jsonb)"""
|
||||||
|
|
||||||
|
|
||||||
|
def read_json(path):
|
||||||
|
return json.loads(Path(path).read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def write_private(path, value):
|
||||||
|
path = Path(path)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
|
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
||||||
|
json.dump(value, stream, indent=2)
|
||||||
|
stream.write("\n")
|
||||||
|
|
||||||
|
|
||||||
|
def validate(config, artifacts):
|
||||||
|
if config.get("namespace") != NAMESPACE:
|
||||||
|
raise ValueError("this package manages only shared-notification")
|
||||||
|
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]*", config["node"]):
|
||||||
|
raise ValueError("invalid node name")
|
||||||
|
storage = config["storage"]
|
||||||
|
path = PurePosixPath(storage["basePath"])
|
||||||
|
if not path.is_absolute() or ".." in path.parts or str(path) != storage["basePath"]:
|
||||||
|
raise ValueError("storage must be an absolute normalized path")
|
||||||
|
if str(path) not in ("/home/devops/shared-notification", "/mnt/shared/notification-service"):
|
||||||
|
raise ValueError("unexpected storage path; a new location requires package review")
|
||||||
|
if storage["filesystem"] not in ("ext4", "xfs"):
|
||||||
|
raise ValueError("unsupported filesystem")
|
||||||
|
if not re.fullmatch(r"[a-f0-9-]{36}", storage["uuid"]):
|
||||||
|
raise ValueError("invalid storage UUID")
|
||||||
|
for name in ("postgresSize", "rabbitmqSize"):
|
||||||
|
if not re.fullmatch(r"[1-9][0-9]*Gi", storage[name]):
|
||||||
|
raise ValueError("invalid storage capacity")
|
||||||
|
for key in ("sandboxServiceName", "replyQueue", "rabbitVirtualHost"):
|
||||||
|
if not re.fullmatch(r"[A-Za-z0-9._/-]{1,100}", config[key]):
|
||||||
|
raise ValueError("invalid routing value")
|
||||||
|
if config["sandboxServiceName"] != "Invemory.Staging.Sandbox":
|
||||||
|
raise ValueError("initial package is restricted to the reviewed sandbox identity")
|
||||||
|
if config["seqNamespace"] != "observability" or config["publisherNamespace"] != "invemory-staging":
|
||||||
|
raise ValueError("unexpected dependent namespace")
|
||||||
|
if config["seqUrl"] != "http://seq.observability.svc.cluster.local:8080":
|
||||||
|
raise ValueError("unexpected Seq endpoint")
|
||||||
|
for key in ("seqPodLabels", "publisherPodLabels"):
|
||||||
|
if not isinstance(config[key], dict) or not config[key]:
|
||||||
|
raise ValueError("exact dependent pod selector required")
|
||||||
|
if not re.fullmatch(r"[a-f0-9]{40}", artifacts.get("sourceCommit", "")):
|
||||||
|
raise ValueError("checked source commit required")
|
||||||
|
if not SHA.fullmatch(artifacts.get("sourceArchiveSha256", "")):
|
||||||
|
raise ValueError("verified source archive hash required")
|
||||||
|
if artifacts.get("migrations") != MIGRATIONS:
|
||||||
|
raise ValueError("migration list differs from reviewed source")
|
||||||
|
expected = {"web", "worker", "migrator", "postgres", "rabbitmq", "mailpit", "guard"}
|
||||||
|
if set(artifacts["images"]) != expected:
|
||||||
|
raise ValueError("complete image set required")
|
||||||
|
for name, artifact in artifacts["images"].items():
|
||||||
|
if not IMAGE.fullmatch(artifact["image"]) or artifact["image"].endswith("0" * 64):
|
||||||
|
raise ValueError("registry.hrynco.com immutable image required: " + name)
|
||||||
|
if name in ("web", "worker", "migrator") and artifact.get("sourceArchiveSha256") != artifacts["sourceArchiveSha256"]:
|
||||||
|
raise ValueError("application and migrator source archives differ")
|
||||||
|
if artifacts["images"]["postgres"].get("version") != "17" or artifacts["images"]["rabbitmq"].get("version") != "4":
|
||||||
|
raise ValueError("database/broker major upgrade requires separate reviewed procedure")
|
||||||
|
|
||||||
|
|
||||||
|
def labels(component=None):
|
||||||
|
result = {"app.kubernetes.io/name": MANAGED, "app.kubernetes.io/managed-by": MANAGED}
|
||||||
|
if component:
|
||||||
|
result["app.kubernetes.io/component"] = component
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def obj(kind, name, spec=None, namespace=NAMESPACE, api="v1", **extra):
|
||||||
|
value = {"apiVersion": api, "kind": kind, "metadata": {"name": name, "labels": labels()}}
|
||||||
|
if namespace:
|
||||||
|
value["metadata"]["namespace"] = namespace
|
||||||
|
if spec is not None:
|
||||||
|
value["spec"] = spec
|
||||||
|
value.update(extra)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def env(name, value=None, secret=None, key=None):
|
||||||
|
if secret:
|
||||||
|
return {"name": name, "valueFrom": {"secretKeyRef": {"name": secret, "key": key}}}
|
||||||
|
return {"name": name, "value": str(value)}
|
||||||
|
|
||||||
|
|
||||||
|
def secure(uid=1000, gid=1000):
|
||||||
|
return {"runAsNonRoot": True, "runAsUser": uid, "runAsGroup": gid,
|
||||||
|
"allowPrivilegeEscalation": False, "capabilities": {"drop": ["ALL"]},
|
||||||
|
"seccompProfile": {"type": "RuntimeDefault"}}
|
||||||
|
|
||||||
|
|
||||||
|
def manifest(config, artifacts):
|
||||||
|
validate(config, artifacts)
|
||||||
|
images = {key: value["image"] for key, value in artifacts["images"].items()}
|
||||||
|
storage = config["storage"]
|
||||||
|
output = [obj("Namespace", NAMESPACE, namespace=None)]
|
||||||
|
output[0]["metadata"]["labels"].update({"pod-security.kubernetes.io/enforce": "restricted"})
|
||||||
|
output.append(obj("ResourceQuota", "notification-budget", {"hard": {
|
||||||
|
"pods": "8", "count/deployments.apps": "5", "count/jobs.batch": "3",
|
||||||
|
"persistentvolumeclaims": "2", "requests.storage": str(int(storage["postgresSize"][:-2]) + int(storage["rabbitmqSize"][:-2])) + "Gi",
|
||||||
|
"requests.cpu": "1600m", "requests.memory": "2Gi", "limits.cpu": "4", "limits.memory": "4Gi"}}))
|
||||||
|
output.append(obj("LimitRange", "container-budget", {"limits": [{"type": "Container",
|
||||||
|
"defaultRequest": {"cpu": "50m", "memory": "64Mi"}, "default": {"cpu": "250m", "memory": "256Mi"}}]}))
|
||||||
|
for component, size, uid, gid in (("postgres", storage["postgresSize"], 999, 999), ("rabbitmq", storage["rabbitmqSize"], 100, 101)):
|
||||||
|
pv = obj("PersistentVolume", "shared-notification-" + component, {
|
||||||
|
"capacity": {"storage": size}, "accessModes": ["ReadWriteOnce"], "volumeMode": "Filesystem",
|
||||||
|
"persistentVolumeReclaimPolicy": "Retain", "storageClassName": "",
|
||||||
|
"claimRef": {"namespace": NAMESPACE, "name": component + "-data"},
|
||||||
|
"local": {"path": storage["basePath"] + "/" + component},
|
||||||
|
"nodeAffinity": {"required": {"nodeSelectorTerms": [{"matchExpressions": [{
|
||||||
|
"key": "kubernetes.io/hostname", "operator": "In", "values": [config["node"]]}]}]}}}, namespace=None)
|
||||||
|
pv["metadata"]["annotations"] = {"hrynco.com/storage-uuid": storage["uuid"], "hrynco.com/filesystem": storage["filesystem"]}
|
||||||
|
output += [pv, obj("PersistentVolumeClaim", component + "-data", {
|
||||||
|
"accessModes": ["ReadWriteOnce"], "volumeMode": "Filesystem", "storageClassName": "",
|
||||||
|
"volumeName": pv["metadata"]["name"], "resources": {"requests": {"storage": size}}})]
|
||||||
|
output.append(obj("ConfigMap", "rabbit-config", data={"rabbitmq.conf":
|
||||||
|
"listeners.tcp.default = 5672\nmanagement.tcp.port = 15672\nmanagement.load_definitions = /etc/rabbitmq/definitions/definitions.json\n"}))
|
||||||
|
output.append(obj("ConfigMap", "runtime-grants", data={"grants.sql": GRANTS}))
|
||||||
|
output.append(obj("ConfigMap", "sandbox-seed", data={"sandbox.sql": SANDBOX}))
|
||||||
|
output.append(obj("ConfigMap", "notification-config", data={
|
||||||
|
"ASPNETCORE_ENVIRONMENT": "Production", "DOTNET_ENVIRONMENT": "Production",
|
||||||
|
"ASPNETCORE_HTTP_PORTS": "8080", "App__RabbitMq__Host": "rabbitmq",
|
||||||
|
"App__RabbitMq__Port": "5672", "App__RabbitMq__VirtualHost": config["rabbitVirtualHost"],
|
||||||
|
"Serilog__WriteTo__1__Name": "Seq", "Serilog__WriteTo__1__Args__serverUrl": config["seqUrl"],
|
||||||
|
"Serilog__Properties__Environment": "Shared", "Serilog__Properties__Service": "HrynCo.NotificationService"}))
|
||||||
|
|
||||||
|
def workload(component, image, resources, environment=None, ports=None, volumes=None, mounts=None, replicas=1, uid=1000, gid=1000, **extra):
|
||||||
|
container = {"name": component, "image": image, "imagePullPolicy": "IfNotPresent",
|
||||||
|
"resources": resources, "securityContext": secure(uid, gid)}
|
||||||
|
if environment:
|
||||||
|
container["env"] = environment
|
||||||
|
if ports:
|
||||||
|
container["ports"] = [{"name": name, "containerPort": port} for name, port in ports]
|
||||||
|
if mounts:
|
||||||
|
container["volumeMounts"] = mounts
|
||||||
|
container.update(extra)
|
||||||
|
pod = {"automountServiceAccountToken": False, "nodeSelector": {"kubernetes.io/hostname": config["node"]},
|
||||||
|
"imagePullSecrets": [{"name": "registry-pull"}], "containers": [container],
|
||||||
|
"terminationGracePeriodSeconds": 60}
|
||||||
|
if volumes:
|
||||||
|
pod["volumes"] = volumes
|
||||||
|
if component in ("postgres", "rabbitmq"):
|
||||||
|
pod["initContainers"] = [{"name": "storage-guard", "image": images["guard"],
|
||||||
|
"command": ["python3", "-c", GUARD], "securityContext": secure(uid, gid),
|
||||||
|
"resources": {"requests": {"cpu": "10m", "memory": "32Mi"}, "limits": {"cpu": "100m", "memory": "64Mi"}},
|
||||||
|
"env": [env("EXPECTED_UUID", storage["uuid"]), env("EXPECTED_ROLE", NAMESPACE + "/" + component), env("EXPECTED_FS", storage["filesystem"])],
|
||||||
|
"volumeMounts": [{"name": "data", "mountPath": "/data", "readOnly": True}]}]
|
||||||
|
value = obj("Deployment", component, {"replicas": replicas, "strategy": {"type": "Recreate"},
|
||||||
|
"selector": {"matchLabels": labels(component)}, "template": {"metadata": {"labels": labels(component),
|
||||||
|
"annotations": {"hrynco.com/source-archive-sha256": artifacts["sourceArchiveSha256"]}}, "spec": pod}}, api="apps/v1")
|
||||||
|
output.append(value)
|
||||||
|
if ports:
|
||||||
|
output.append(obj("Service", component, {"selector": labels(component), "ports": [
|
||||||
|
{"name": name, "port": port, "targetPort": name} for name, port in ports]}))
|
||||||
|
|
||||||
|
def res(cpu, memory, limit_cpu, limit_memory):
|
||||||
|
return {"requests": {"cpu": cpu, "memory": memory}, "limits": {"cpu": limit_cpu, "memory": limit_memory}}
|
||||||
|
|
||||||
|
workload("postgres", images["postgres"], res("100m", "256Mi", "500m", "512Mi"),
|
||||||
|
[env("POSTGRES_DB", "notification_service"), env("POSTGRES_USER", "notification_owner"),
|
||||||
|
env("POSTGRES_PASSWORD", secret="notification-private", key="postgresPassword"), env("PGDATA", "/data/pgdata")],
|
||||||
|
[("postgres", 5432)], [{"name": "data", "persistentVolumeClaim": {"claimName": "postgres-data"}}],
|
||||||
|
[{"name": "data", "mountPath": "/data"}], uid=999, gid=999,
|
||||||
|
readinessProbe={"exec": {"command": ["pg_isready", "-U", "notification_owner", "-d", "notification_service"]}, "periodSeconds": 5},
|
||||||
|
livenessProbe={"exec": {"command": ["pg_isready", "-U", "notification_owner", "-d", "notification_service"]}, "initialDelaySeconds": 30, "periodSeconds": 10})
|
||||||
|
workload("rabbitmq", images["rabbitmq"], res("100m", "256Mi", "500m", "512Mi"),
|
||||||
|
[env("RABBITMQ_NODENAME", "rabbit@rabbitmq"), env("RABBITMQ_DEFAULT_USER", "notification_admin"),
|
||||||
|
env("RABBITMQ_DEFAULT_PASS", secret="notification-private", key="rabbitAdminPassword")],
|
||||||
|
[("amqp", 5672), ("management", 15672)],
|
||||||
|
[{"name": "data", "persistentVolumeClaim": {"claimName": "rabbitmq-data"}},
|
||||||
|
{"name": "config", "configMap": {"name": "rabbit-config"}}, {"name": "definitions", "secret": {"secretName": "rabbit-definitions"}}],
|
||||||
|
[{"name": "data", "mountPath": "/var/lib/rabbitmq"}, {"name": "config", "mountPath": "/etc/rabbitmq/rabbitmq.conf", "subPath": "rabbitmq.conf", "readOnly": True},
|
||||||
|
{"name": "definitions", "mountPath": "/etc/rabbitmq/definitions", "readOnly": True}], uid=100, gid=101,
|
||||||
|
startupProbe={"exec": {"command": ["rabbitmq-diagnostics", "-q", "ping"]}, "timeoutSeconds": 15, "periodSeconds": 20, "failureThreshold": 9},
|
||||||
|
readinessProbe={"exec": {"command": ["rabbitmq-diagnostics", "-q", "check_running"]}, "timeoutSeconds": 15, "periodSeconds": 20},
|
||||||
|
livenessProbe={"exec": {"command": ["rabbitmq-diagnostics", "-q", "ping"]}, "timeoutSeconds": 15, "periodSeconds": 30})
|
||||||
|
output[-2]["spec"]["template"]["spec"]["hostname"] = "rabbitmq"
|
||||||
|
workload("mailpit", images["mailpit"], res("25m", "32Mi", "100m", "128Mi"),
|
||||||
|
[env("MP_SMTP_BIND_ADDR", "0.0.0.0:1025"), env("MP_UI_BIND_ADDR", "0.0.0.0:8025"), env("MP_MAX_MESSAGES", "100")],
|
||||||
|
[("smtp", 1025), ("http", 8025)], readinessProbe={"httpGet": {"path": "/livez", "port": "http"}, "periodSeconds": 10})
|
||||||
|
for component in ("web", "worker"):
|
||||||
|
environment = [env("App__ConnectionString", secret="notification-private", key="runtimeConnectionString"),
|
||||||
|
env("Serilog__WriteTo__1__Args__apiKey", secret="notification-private", key="seqApiKey")]
|
||||||
|
if component == "worker":
|
||||||
|
environment += [env("App__RabbitMq__User", "notification_worker"), env("App__RabbitMq__Password", secret="notification-private", key="rabbitWorkerPassword")]
|
||||||
|
workload(component, images[component], res("50m", "128Mi", "250m", "256Mi"), environment,
|
||||||
|
[("http", 8080)] if component == "web" else None, replicas=0,
|
||||||
|
**({"readinessProbe": {"httpGet": {"path": "/api/v1/email-channels?serviceName=" + config["sandboxServiceName"], "port": "http"}, "periodSeconds": 10}} if component == "web" else {}))
|
||||||
|
deployment = output[-2] if component == "web" else output[-1]
|
||||||
|
deployment["spec"]["template"]["spec"]["containers"][0]["envFrom"] = [{"configMapRef": {"name": "notification-config"}}]
|
||||||
|
output += network_policies(config)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def peer(component=None, namespace=NAMESPACE, selector=None):
|
||||||
|
return {"namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": namespace}},
|
||||||
|
"podSelector": {"matchLabels": selector if selector is not None else labels(component)}}
|
||||||
|
|
||||||
|
|
||||||
|
def network_policies(config):
|
||||||
|
def policy(name, selector, ingress=None, egress=None, namespace=NAMESPACE):
|
||||||
|
spec = {"podSelector": {"matchLabels": selector}, "policyTypes": []}
|
||||||
|
if ingress is not None:
|
||||||
|
spec.update(ingress=ingress)
|
||||||
|
spec["policyTypes"].append("Ingress")
|
||||||
|
if egress is not None:
|
||||||
|
spec.update(egress=egress)
|
||||||
|
spec["policyTypes"].append("Egress")
|
||||||
|
return obj("NetworkPolicy", name, spec, namespace, "networking.k8s.io/v1")
|
||||||
|
|
||||||
|
def port(number, protocol="TCP"):
|
||||||
|
return {"protocol": protocol, "port": number}
|
||||||
|
|
||||||
|
output = [policy("default-deny", {}, [], [])]
|
||||||
|
output.append(policy("dns", labels(), egress=[{"to": [peer(namespace="kube-system", selector={"k8s-app": "kube-dns"})], "ports": [port(53, "UDP"), port(53)]}]))
|
||||||
|
output.append(policy("postgres-ingress", labels("postgres"), ingress=[{"from": [peer(x) for x in ("web", "worker", "migrator", "grants", "sandbox")], "ports": [port(5432)]}]))
|
||||||
|
output.append(policy("rabbitmq-ingress", labels("rabbitmq"), ingress=[{"from": [peer("worker"), peer(namespace=config["publisherNamespace"], selector=config["publisherPodLabels"])], "ports": [port(5672)]}]))
|
||||||
|
output.append(policy("mailpit-ingress", labels("mailpit"), ingress=[{"from": [peer("worker"), peer("web")], "ports": [port(1025)]}]))
|
||||||
|
for component in ("web", "worker", "migrator", "grants", "sandbox"):
|
||||||
|
rules = [{"to": [peer("postgres")], "ports": [port(5432)]}]
|
||||||
|
if component in ("web", "worker"):
|
||||||
|
rules.append({"to": [peer(namespace=config["seqNamespace"], selector=config["seqPodLabels"])], "ports": [port(8080)]})
|
||||||
|
if component == "worker":
|
||||||
|
rules += [{"to": [peer("rabbitmq")], "ports": [port(5672)]}, {"to": [peer("mailpit")], "ports": [port(1025)]}]
|
||||||
|
if component == "web":
|
||||||
|
rules.append({"to": [peer("mailpit")], "ports": [port(1025)]})
|
||||||
|
output.append(policy(component + "-egress", labels(component), egress=rules))
|
||||||
|
# Additive allowances, separately owned; existing deny policies remain effective.
|
||||||
|
output.append(policy("notification-seq-ingress", config["seqPodLabels"], ingress=[{
|
||||||
|
"from": [peer("web"), peer("worker")], "ports": [port(8080)]}], namespace=config["seqNamespace"]))
|
||||||
|
# Publisher remains LogOnly until its separate, explicitly controlled cutover.
|
||||||
|
output.append(policy("notification-broker-egress", config["publisherPodLabels"], egress=[{
|
||||||
|
"to": [peer("rabbitmq")], "ports": [port(5672)]}], namespace=config["publisherNamespace"]))
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def rabbit_definitions(config, credentials):
|
||||||
|
def hashed(password, salt):
|
||||||
|
return base64.b64encode(salt + hashlib.sha256(salt + password.encode()).digest()).decode()
|
||||||
|
|
||||||
|
users = []
|
||||||
|
for name, key, tag in (("notification_admin", "rabbitAdminPassword", "administrator"), ("notification_worker", "rabbitWorkerPassword", ""), ("invemory_staging", "rabbitPublisherPassword", "")):
|
||||||
|
salt = base64.b64decode(credentials[key + "Salt"])
|
||||||
|
users.append({"name": name, "password_hash": hashed(credentials[key], salt), "hashing_algorithm": "rabbit_password_hashing_sha256", "tags": tag})
|
||||||
|
incoming = re.escape("notification.send-email")
|
||||||
|
reply = re.escape(config["replyQueue"])
|
||||||
|
vhost = config["rabbitVirtualHost"]
|
||||||
|
return {"users": users, "vhosts": [{"name": vhost}], "permissions": [
|
||||||
|
{"user": "notification_admin", "vhost": vhost, "configure": ".*", "write": ".*", "read": ".*"},
|
||||||
|
{"user": "notification_worker", "vhost": vhost, "configure": "^(" + incoming + "|" + reply + ")$", "write": "^(amq\\.default|" + reply + ")$", "read": "^" + incoming + "$"},
|
||||||
|
{"user": "invemory_staging", "vhost": vhost, "configure": "^(" + incoming + "|" + reply + ")$", "write": "^(amq\\.default|" + incoming + ")$", "read": "^" + reply + "$"}],
|
||||||
|
"queues": [{"name": name, "vhost": vhost, "durable": True, "auto_delete": False, "arguments": {}} for name in ("notification.send-email", config["replyQueue"])], "exchanges": [], "bindings": []}
|
||||||
|
|
||||||
|
|
||||||
|
def secret_manifests(config, credentials, registry):
|
||||||
|
def secret(name, data, kind="Opaque"):
|
||||||
|
return obj("Secret", name, type=kind, data={key: base64.b64encode(value.encode()).decode() for key, value in data.items()})
|
||||||
|
|
||||||
|
data = {key: credentials[key] for key in ("postgresPassword", "runtimePassword", "rabbitAdminPassword", "rabbitWorkerPassword", "rabbitPublisherPassword", "seqApiKey")}
|
||||||
|
data["ownerConnectionString"] = "Host=postgres;Database=notification_service;Username=notification_owner;Password=" + credentials["postgresPassword"]
|
||||||
|
data["runtimeConnectionString"] = "Host=postgres;Database=notification_service;Username=notification_runtime;Password=" + credentials["runtimePassword"]
|
||||||
|
return [secret("notification-private", data), secret("rabbit-definitions", {"definitions.json": json.dumps(rabbit_definitions(config, credentials))}),
|
||||||
|
secret("registry-pull", {".dockerconfigjson": json.dumps(registry)}, "kubernetes.io/dockerconfigjson")]
|
||||||
|
|
||||||
|
|
||||||
|
class Cluster:
|
||||||
|
def __init__(self, args):
|
||||||
|
self.command = [args.kubectl, "--kubeconfig=" + args.kubeconfig, "--request-timeout=20s"]
|
||||||
|
|
||||||
|
def run(self, *args, data=None, timeout=120, sensitive=False):
|
||||||
|
result = subprocess.run(self.command + list(args), input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
|
||||||
|
if result.returncode:
|
||||||
|
# Error output can contain submitted secret resources or provider details.
|
||||||
|
detail = "" if sensitive else result.stderr.decode(errors="replace")[:1000]
|
||||||
|
raise RuntimeError("kubectl operation failed: " + " ".join(args[:3]) + ("\n" + detail if detail else ""))
|
||||||
|
return result.stdout
|
||||||
|
|
||||||
|
def get(self, kind, name=None, namespace=NAMESPACE):
|
||||||
|
args = ["get", kind]
|
||||||
|
if name:
|
||||||
|
args.append(name)
|
||||||
|
if namespace:
|
||||||
|
args += ["-n", namespace]
|
||||||
|
args += ["-o", "json"]
|
||||||
|
if name:
|
||||||
|
args.append("--ignore-not-found")
|
||||||
|
data = self.run(*args)
|
||||||
|
if not data.strip():
|
||||||
|
if name:
|
||||||
|
return None
|
||||||
|
raise RuntimeError("kubectl returned no JSON for resource listing: " + kind)
|
||||||
|
value = json.loads(data)
|
||||||
|
if not name and (not isinstance(value, dict) or not isinstance(value.get("items"), list)):
|
||||||
|
raise RuntimeError("kubectl returned an unexpected resource list: " + kind)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def apply(self, values, dry_run=False, sensitive=False):
|
||||||
|
args = ["apply", "-f", "-"]
|
||||||
|
if dry_run:
|
||||||
|
args += ["--dry-run=server"]
|
||||||
|
self.run(*args, data=json.dumps({"apiVersion": "v1", "kind": "List", "items": values}).encode(), sensitive=sensitive)
|
||||||
|
|
||||||
|
def scale(self, component, replicas):
|
||||||
|
if self.get("deployment", component):
|
||||||
|
self.run("scale", "deployment/" + component, "-n", NAMESPACE, "--replicas=" + str(replicas))
|
||||||
|
if replicas == 0 and any(p["metadata"].get("labels", {}).get("app.kubernetes.io/component") == component for p in self.get("pods")["items"]):
|
||||||
|
self.run("wait", "--for=delete", "pod", "-n", NAMESPACE, "-l", "app.kubernetes.io/component=" + component, "--timeout=120s", timeout=140)
|
||||||
|
|
||||||
|
def rollout(self, component):
|
||||||
|
self.run("rollout", "status", "deployment/" + component, "-n", NAMESPACE, "--timeout=240s", timeout=260)
|
||||||
|
|
||||||
|
def history(self):
|
||||||
|
table = self.run("exec", "deployment/postgres", "-n", NAMESPACE, "--", "psql", "-U", "notification_owner", "-d", "notification_service", "-At", "-c", "SELECT to_regclass('public.\"__EFMigrationsHistory\"')").decode().strip()
|
||||||
|
if not table:
|
||||||
|
return []
|
||||||
|
return self.run("exec", "deployment/postgres", "-n", NAMESPACE, "--", "psql", "-U", "notification_owner", "-d", "notification_service", "-At", "-c", 'SELECT "MigrationId" FROM "__EFMigrationsHistory" ORDER BY "MigrationId"').decode().splitlines()
|
||||||
|
|
||||||
|
|
||||||
|
@contextlib.contextmanager
|
||||||
|
def lock(directory):
|
||||||
|
directory = Path(directory)
|
||||||
|
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
|
path = directory / "deployment.lock"
|
||||||
|
try:
|
||||||
|
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
||||||
|
except FileExistsError:
|
||||||
|
raise RuntimeError("deployment lock exists; verify no active deployment before manually removing a stale lock")
|
||||||
|
try:
|
||||||
|
os.write(fd, str(os.getpid()).encode())
|
||||||
|
os.close(fd)
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
path.unlink()
|
||||||
|
|
||||||
|
|
||||||
|
def preflight(cluster, config, resources):
|
||||||
|
node = cluster.get("node", config["node"], namespace=None)
|
||||||
|
if not node or not any(x["type"] == "Ready" and x["status"] == "True" for x in node["status"]["conditions"]):
|
||||||
|
raise RuntimeError("target storage node is not Ready")
|
||||||
|
if any(x["type"] in ("DiskPressure", "MemoryPressure", "PIDPressure") and x["status"] == "True" for x in node["status"]["conditions"]):
|
||||||
|
raise RuntimeError("target node has resource pressure")
|
||||||
|
seq_pods = cluster.get("pods", namespace=config["seqNamespace"])["items"]
|
||||||
|
if not any(all(p["metadata"].get("labels", {}).get(k) == v for k, v in config["seqPodLabels"].items()) for p in seq_pods):
|
||||||
|
raise RuntimeError("Seq selector matches no existing pod; verify dependency labels")
|
||||||
|
for item in resources:
|
||||||
|
kind, name = item["kind"], item["metadata"]["name"]
|
||||||
|
current = cluster.get(kind, name, item["metadata"].get("namespace"))
|
||||||
|
if not current:
|
||||||
|
continue
|
||||||
|
if current["metadata"].get("labels", {}).get("app.kubernetes.io/managed-by") != MANAGED:
|
||||||
|
raise RuntimeError("existing resource is not owned by this package: " + kind + "/" + name)
|
||||||
|
if kind == "PersistentVolume":
|
||||||
|
old = current["spec"]
|
||||||
|
for key in ("local", "nodeAffinity", "capacity", "persistentVolumeReclaimPolicy"):
|
||||||
|
if old.get(key) != item["spec"][key]:
|
||||||
|
raise RuntimeError("storage changes require a separate migration procedure")
|
||||||
|
if current["metadata"].get("annotations", {}).get("hrynco.com/storage-uuid") != config["storage"]["uuid"]:
|
||||||
|
raise RuntimeError("storage UUID change requires a separate migration procedure")
|
||||||
|
if kind == "Deployment" and name in ("postgres", "rabbitmq"):
|
||||||
|
if current["spec"]["template"]["spec"]["containers"][0]["image"] != item["spec"]["template"]["spec"]["containers"][0]["image"]:
|
||||||
|
raise RuntimeError("database/broker image change requires separate backup/upgrade procedure")
|
||||||
|
|
||||||
|
|
||||||
|
def host_storage_check(config):
|
||||||
|
"""Run on the storage node, not on the developer workstation."""
|
||||||
|
if sys.platform != "linux":
|
||||||
|
raise RuntimeError("host storage preflight and deployment must run on the Linux storage node")
|
||||||
|
for component, uid, gid in (("postgres", 999, 999), ("rabbitmq", 100, 101)):
|
||||||
|
path = config["storage"]["basePath"] + "/" + component
|
||||||
|
result = subprocess.run(["findmnt", "--json", "--target", path, "--output", "FSTYPE,UUID"], capture_output=True, check=True, timeout=20)
|
||||||
|
filesystems = json.loads(result.stdout)["filesystems"]
|
||||||
|
if len(filesystems) != 1 or filesystems[0]["fstype"] != config["storage"]["filesystem"] or filesystems[0]["uuid"] != config["storage"]["uuid"]:
|
||||||
|
raise RuntimeError("host storage filesystem/UUID does not match reviewed configuration")
|
||||||
|
info = os.stat(path)
|
||||||
|
if info.st_uid != uid or info.st_gid != gid or info.st_mode & 0o007:
|
||||||
|
raise RuntimeError("storage ownership or world permissions differ from provisioned contract")
|
||||||
|
|
||||||
|
|
||||||
|
def job(component, image, command=None, environment=None, volumes=None, mounts=None):
|
||||||
|
container = {"name": component, "image": image, "securityContext": secure(),
|
||||||
|
"resources": {"requests": {"cpu": "100m", "memory": "128Mi"}, "limits": {"cpu": "500m", "memory": "512Mi"}}, "env": environment or []}
|
||||||
|
if command:
|
||||||
|
container["command"] = command
|
||||||
|
if mounts:
|
||||||
|
container["volumeMounts"] = mounts
|
||||||
|
pod = {"restartPolicy": "Never", "automountServiceAccountToken": False,
|
||||||
|
"imagePullSecrets": [{"name": "registry-pull"}], "containers": [container]}
|
||||||
|
if volumes:
|
||||||
|
pod["volumes"] = volumes
|
||||||
|
return obj("Job", "notification-" + component, {"backoffLimit": 0, "activeDeadlineSeconds": 300,
|
||||||
|
"template": {"metadata": {"labels": labels(component)}, "spec": pod}}, api="batch/v1")
|
||||||
|
|
||||||
|
|
||||||
|
def run_job(cluster, value):
|
||||||
|
name = value["metadata"]["name"]
|
||||||
|
cluster.run("delete", "job", name, "-n", NAMESPACE, "--ignore-not-found", "--wait=true", "--timeout=60s")
|
||||||
|
cluster.apply([value])
|
||||||
|
cluster.run("wait", "--for=condition=complete", "job/" + name, "-n", NAMESPACE, "--timeout=300s", timeout=320)
|
||||||
|
|
||||||
|
|
||||||
|
def backup(cluster, private_dir):
|
||||||
|
folder = Path(private_dir) / ("backup-" + datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%S%fZ"))
|
||||||
|
folder.mkdir(mode=0o700)
|
||||||
|
dump = cluster.run("exec", "deployment/postgres", "-n", NAMESPACE, "--", "pg_dump", "-U", "notification_owner", "-d", "notification_service", "-Fc", timeout=300, sensitive=True)
|
||||||
|
if not dump.startswith(b"PGDMP"):
|
||||||
|
raise RuntimeError("invalid PostgreSQL backup")
|
||||||
|
fd = os.open(folder / "database.dump", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, "wb") as stream:
|
||||||
|
stream.write(dump)
|
||||||
|
cluster.run("exec", "-i", "deployment/postgres", "-n", NAMESPACE, "--", "pg_restore", "--list", data=dump, sensitive=True)
|
||||||
|
write_private(folder / "manifest.json", {"sha256": hashlib.sha256(dump).hexdigest(), "bytes": len(dump), "history": cluster.history(), "scope": "notification_service database only; broker PV retained, no offsite proof"})
|
||||||
|
return folder.name
|
||||||
|
|
||||||
|
|
||||||
|
def database_ready(deployment):
|
||||||
|
if not deployment or deployment.get("spec", {}).get("replicas") != 1:
|
||||||
|
return False
|
||||||
|
status = deployment.get("status", {})
|
||||||
|
return (status.get("readyReplicas", 0) == 1 and status.get("updatedReplicas", 0) == 1 and
|
||||||
|
status.get("observedGeneration", 0) >= deployment.get("metadata", {}).get("generation", 1))
|
||||||
|
|
||||||
|
|
||||||
|
def recovery_foundation(resources):
|
||||||
|
# Ownership/storage/image preflight has already passed. Do not apply Web/Worker
|
||||||
|
# targets or start their writers before history and a verified database backup.
|
||||||
|
return [value for value in resources if not (
|
||||||
|
value["kind"] in ("Deployment", "Service") and value["metadata"]["name"] in ("web", "worker"))]
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for_worker_consumer(cluster, config, timeout=60):
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
while True:
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise RuntimeError("expected exactly one notification.send-email consumer before timeout")
|
||||||
|
try:
|
||||||
|
output = cluster.run("exec", "deployment/rabbitmq", "-n", NAMESPACE, "--", "rabbitmqctl", "-q",
|
||||||
|
"list_queues", "-p", config["rabbitVirtualHost"], "name", "consumers",
|
||||||
|
timeout=min(20, remaining), sensitive=True).decode()
|
||||||
|
except (RuntimeError, subprocess.TimeoutExpired):
|
||||||
|
raise RuntimeError("could not verify notification.send-email consumer count") from None
|
||||||
|
rows = [line.split() for line in output.splitlines() if line.split()[:1] == ["notification.send-email"]]
|
||||||
|
if len(rows) != 1 or len(rows[0]) != 2 or rows[0][1] not in ("0", "1"):
|
||||||
|
raise RuntimeError("expected exactly one notification.send-email consumer; unexpected broker count")
|
||||||
|
remaining = deadline - time.monotonic()
|
||||||
|
if remaining <= 0:
|
||||||
|
raise RuntimeError("expected exactly one notification.send-email consumer before timeout")
|
||||||
|
if rows[0][1] == "1":
|
||||||
|
return
|
||||||
|
# Process rollout can complete before the RabbitMQ subscription attaches.
|
||||||
|
# Only zero consumers is a transient state; extra/unknown counts fail closed.
|
||||||
|
time.sleep(min(2, remaining))
|
||||||
|
|
||||||
|
|
||||||
|
def deploy(cluster, config, artifacts, args):
|
||||||
|
resources = manifest(config, artifacts)
|
||||||
|
preflight(cluster, config, resources)
|
||||||
|
host_storage_check(config)
|
||||||
|
exists = cluster.get("namespace", NAMESPACE, namespace=None) is not None
|
||||||
|
if not exists:
|
||||||
|
raise RuntimeError("run bootstrap first, then inspect node capacity and server dry-run before deploy")
|
||||||
|
if not cluster.get("secret", "notification-private") or not cluster.get("secret", "registry-pull"):
|
||||||
|
raise RuntimeError("private credentials and registry pull Secret required")
|
||||||
|
with lock(args.private_dir):
|
||||||
|
# Never let an ordinary redeploy bypass migrations/schema validation.
|
||||||
|
database = cluster.get("deployment", "postgres")
|
||||||
|
current_worker = cluster.get("deployment", "worker")
|
||||||
|
worker_replicas = current_worker["spec"].get("replicas", 0) if current_worker else 0
|
||||||
|
if args.enable_worker and not args.sandbox_verified:
|
||||||
|
raise RuntimeError("inspect sandbox channel/template and broker backlog before enabling the Worker")
|
||||||
|
if not database_ready(database):
|
||||||
|
if not args.migrate:
|
||||||
|
raise RuntimeError("PostgreSQL is not ready; interrupted install/recovery requires --migrate")
|
||||||
|
cluster.scale("worker", 0)
|
||||||
|
cluster.scale("web", 0)
|
||||||
|
cluster.apply(recovery_foundation(resources))
|
||||||
|
for component in ("postgres", "rabbitmq", "mailpit"):
|
||||||
|
cluster.rollout(component)
|
||||||
|
# Deployment existence does not establish a running database or empty disk.
|
||||||
|
# After recovery, query the actual retained DB rather than assume [] history.
|
||||||
|
before = cluster.history()
|
||||||
|
if before != MIGRATIONS and not args.migrate:
|
||||||
|
raise RuntimeError("schema is not the reviewed target; --migrate required")
|
||||||
|
if before != MIGRATIONS[:len(before)]:
|
||||||
|
raise RuntimeError("database has unknown or non-prefix migration history")
|
||||||
|
if args.migrate:
|
||||||
|
cluster.scale("worker", 0)
|
||||||
|
cluster.scale("web", 0)
|
||||||
|
# Always back up the actual DB, including an empty initialized first DB.
|
||||||
|
# A removed Deployment or interrupted first install may retain real data.
|
||||||
|
backup(cluster, args.private_dir)
|
||||||
|
# Preserve runtime replicas during normal reconciliation. First install stays stopped.
|
||||||
|
for value in resources:
|
||||||
|
if value["kind"] == "Deployment" and value["metadata"]["name"] in ("web", "worker"):
|
||||||
|
value["spec"]["replicas"] = 0 if args.migrate else (1 if value["metadata"]["name"] == "web" else worker_replicas)
|
||||||
|
cluster.apply(resources)
|
||||||
|
for component in ("postgres", "rabbitmq", "mailpit"):
|
||||||
|
cluster.rollout(component)
|
||||||
|
if args.migrate:
|
||||||
|
run_job(cluster, job("migrator", artifacts["images"]["migrator"]["image"], environment=[
|
||||||
|
env("DOTNET_ENVIRONMENT", "Production"), env("App__ConnectionString", secret="notification-private", key="ownerConnectionString")]))
|
||||||
|
if cluster.history() != MIGRATIONS:
|
||||||
|
raise RuntimeError("migrator completed but schema history is not the reviewed target")
|
||||||
|
run_job(cluster, job("grants", artifacts["images"]["postgres"]["image"],
|
||||||
|
["psql", "-h", "postgres", "-U", "notification_owner", "-d", "notification_service", "-v", "ON_ERROR_STOP=1", "-q", "-f", "/sql/grants.sql"],
|
||||||
|
[env("PGPASSWORD", secret="notification-private", key="postgresPassword"), env("RUNTIME_PASSWORD", secret="notification-private", key="runtimePassword")],
|
||||||
|
[{"name": "sql", "configMap": {"name": "runtime-grants"}}], [{"name": "sql", "mountPath": "/sql", "readOnly": True}]))
|
||||||
|
run_job(cluster, job("sandbox", artifacts["images"]["postgres"]["image"],
|
||||||
|
["psql", "-h", "postgres", "-U", "notification_owner", "-d", "notification_service", "-v", "ON_ERROR_STOP=1", "-q", "-f", "/sql/sandbox.sql"],
|
||||||
|
[env("PGPASSWORD", secret="notification-private", key="postgresPassword")],
|
||||||
|
[{"name": "sql", "configMap": {"name": "sandbox-seed"}}], [{"name": "sql", "mountPath": "/sql", "readOnly": True}]))
|
||||||
|
cluster.scale("web", 1)
|
||||||
|
cluster.rollout("web")
|
||||||
|
# Worker startup is separate: inspect/seed sandbox config before consuming anything.
|
||||||
|
if args.enable_worker:
|
||||||
|
safe = cluster.run("exec", "deployment/postgres", "-n", NAMESPACE, "--", "psql", "-U", "notification_owner", "-d", "notification_service", "-At", "-c", SANDBOX_CHECK).decode().strip()
|
||||||
|
if safe != "t":
|
||||||
|
raise RuntimeError("sandbox channel/template configuration does not match the safe seed")
|
||||||
|
queues = cluster.run("exec", "deployment/rabbitmq", "-n", NAMESPACE, "--", "rabbitmqctl", "-q", "list_queues", "-p", config["rabbitVirtualHost"], "name", "messages_ready", "messages_unacknowledged").decode()
|
||||||
|
if not any(line.split() == ["notification.send-email", "0", "0"] for line in queues.splitlines()):
|
||||||
|
raise RuntimeError("incoming queue is not empty; inspect backlog before enabling the Worker")
|
||||||
|
cluster.scale("worker", 1)
|
||||||
|
# A preserved running Worker is also a required gate during ordinary deploy.
|
||||||
|
if args.enable_worker or (not args.migrate and worker_replicas > 0):
|
||||||
|
try:
|
||||||
|
cluster.rollout("worker")
|
||||||
|
wait_for_worker_consumer(cluster, config)
|
||||||
|
except Exception:
|
||||||
|
cluster.scale("worker", 0)
|
||||||
|
raise
|
||||||
|
print("deployment complete; SMTP is sandbox-only, Invemory publisher cutover is separate")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("command", choices=("render", "check", "bootstrap", "deploy", "backup"))
|
||||||
|
parser.add_argument("--config", required=True)
|
||||||
|
parser.add_argument("--artifacts", required=True)
|
||||||
|
parser.add_argument("--kubectl", default="/snap/microk8s/current/kubectl")
|
||||||
|
parser.add_argument("--kubeconfig", default="/home/devops/.kube/cluster-admin.conf")
|
||||||
|
parser.add_argument("--private-dir", default="/home/devops/shared-notification-private")
|
||||||
|
parser.add_argument("--output")
|
||||||
|
parser.add_argument("--seq-key-file")
|
||||||
|
parser.add_argument("--registry-auth-file")
|
||||||
|
parser.add_argument("--migrate", action="store_true")
|
||||||
|
parser.add_argument("--enable-worker", action="store_true")
|
||||||
|
parser.add_argument("--sandbox-verified", action="store_true")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
config, artifacts = read_json(args.config), read_json(args.artifacts)
|
||||||
|
resources = manifest(config, artifacts)
|
||||||
|
if args.command == "render":
|
||||||
|
if not args.output:
|
||||||
|
raise ValueError("render requires --output")
|
||||||
|
Path(args.output).write_text(json.dumps({"apiVersion": "v1", "kind": "List", "items": resources}, indent=2) + "\n", encoding="utf-8")
|
||||||
|
print("rendered reviewed resource package")
|
||||||
|
return
|
||||||
|
cluster = Cluster(args)
|
||||||
|
if args.command == "bootstrap":
|
||||||
|
if sys.platform != "linux":
|
||||||
|
raise RuntimeError("private secret bootstrap must run on the Linux deployment host")
|
||||||
|
if not args.seq_key_file or not args.registry_auth_file:
|
||||||
|
raise ValueError("bootstrap requires private dedicated Seq ingest key and registry auth files")
|
||||||
|
path = Path(args.private_dir) / "credentials.json"
|
||||||
|
current_secret = cluster.get("secret", "notification-private")
|
||||||
|
if path.exists():
|
||||||
|
credentials = read_json(path)
|
||||||
|
else:
|
||||||
|
if current_secret:
|
||||||
|
raise RuntimeError("private credential file missing while live Secret exists; recover original private file; do not regenerate passwords")
|
||||||
|
credentials = {key: secrets.token_hex(32) for key in ("postgresPassword", "runtimePassword", "rabbitAdminPassword", "rabbitWorkerPassword", "rabbitPublisherPassword")}
|
||||||
|
for key in ("rabbitAdminPassword", "rabbitWorkerPassword", "rabbitPublisherPassword"):
|
||||||
|
credentials[key + "Salt"] = base64.b64encode(secrets.token_bytes(4)).decode()
|
||||||
|
credentials["seqApiKey"] = Path(args.seq_key_file).read_text(encoding="utf-8").strip()
|
||||||
|
if not credentials["seqApiKey"]:
|
||||||
|
raise ValueError("dedicated Seq key is empty")
|
||||||
|
write_private(path, credentials)
|
||||||
|
if credentials["seqApiKey"] != Path(args.seq_key_file).read_text(encoding="utf-8").strip():
|
||||||
|
raise RuntimeError("dedicated Seq key differs from preserved credentials; explicit rotation procedure required")
|
||||||
|
registry = read_json(args.registry_auth_file)
|
||||||
|
if set(registry.get("auths", {})) != {"registry.hrynco.com"}:
|
||||||
|
raise ValueError("registry auth must contain registry.hrynco.com only")
|
||||||
|
namespace = cluster.get("namespace", NAMESPACE, namespace=None)
|
||||||
|
if namespace and namespace["metadata"].get("labels", {}).get("app.kubernetes.io/managed-by") != MANAGED:
|
||||||
|
raise RuntimeError("refusing to adopt existing namespace")
|
||||||
|
cluster.apply([resources[0]])
|
||||||
|
values = secret_manifests(config, credentials, registry)
|
||||||
|
for value in values:
|
||||||
|
current = cluster.get("secret", value["metadata"]["name"])
|
||||||
|
if current and current["metadata"].get("labels", {}).get("app.kubernetes.io/managed-by") != MANAGED:
|
||||||
|
raise RuntimeError("refusing to adopt existing Secret")
|
||||||
|
if current and value["metadata"]["name"] != "registry-pull" and current.get("data") != value["data"]:
|
||||||
|
raise RuntimeError("preserved credentials or broker definitions differ from live Secret; explicit rotation/routing procedure required")
|
||||||
|
cluster.apply(values, sensitive=True)
|
||||||
|
print("private credentials preserved and Secrets reconciled; values not printed")
|
||||||
|
elif args.command == "check":
|
||||||
|
preflight(cluster, config, resources)
|
||||||
|
host_storage_check(config)
|
||||||
|
if not cluster.get("namespace", NAMESPACE, namespace=None):
|
||||||
|
raise RuntimeError("bootstrap namespace/Secrets before server-side dry-run")
|
||||||
|
cluster.apply(resources, dry_run=True)
|
||||||
|
print("ownership, host storage UUID, pinned artifacts and server-side dry-run passed; measured node capacity remains mandatory")
|
||||||
|
elif args.command == "backup":
|
||||||
|
with lock(args.private_dir):
|
||||||
|
if any((cluster.get("deployment", x) or {}).get("spec", {}).get("replicas", 0) for x in ("web", "worker")):
|
||||||
|
raise RuntimeError("stop Web/Worker writers before backup")
|
||||||
|
print("verified local backup: " + backup(cluster, args.private_dir))
|
||||||
|
else:
|
||||||
|
deploy(cluster, config, artifacts, args)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except (ValueError, RuntimeError, KeyError, OSError, subprocess.TimeoutExpired, subprocess.CalledProcessError) as error:
|
||||||
|
print("STOP: " + str(error), file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Provision only the dedicated Notification ingest key; never print credentials."""
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import copy
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import http.cookiejar
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import stat
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
BASE = "http://192.168.2.44:30534/"
|
||||||
|
CREDENTIALS = Path("/home/devops/seq-first/credentials.json")
|
||||||
|
TOKEN_FILE = Path("/home/devops/notification-private/seq-key.txt")
|
||||||
|
TITLE = "HrynCo Notification Service"
|
||||||
|
PROPERTIES = [{"Name": "Environment", "Value": "SharedNotification"},
|
||||||
|
{"Name": "Service", "Value": "HrynCo.NotificationService"}]
|
||||||
|
MARKER = "NotificationIngestKeyId"
|
||||||
|
KEY_LIST = "api/apikeys?shared=true"
|
||||||
|
|
||||||
|
|
||||||
|
def allowed_path(method, path):
|
||||||
|
methods = {"api/users/login": "POST", KEY_LIST: "GET", "api/apikeys/template": "GET",
|
||||||
|
"api/apikeys/": "POST", "api/events/raw": "POST"}
|
||||||
|
return methods.get(path) == method or (method == "GET" and re.fullmatch(
|
||||||
|
r"api/events\?count=2&filter=ProvisioningCheckId%20%3D%20%27[a-f0-9]{32}%27", path)) or (
|
||||||
|
method == "PUT" and re.fullmatch(r"api/apikeys/apikey-[a-z0-9-]+", path))
|
||||||
|
|
||||||
|
|
||||||
|
def require(condition, message):
|
||||||
|
if not condition:
|
||||||
|
raise RuntimeError(message)
|
||||||
|
|
||||||
|
|
||||||
|
class NoRedirects(urllib.request.HTTPRedirectHandler):
|
||||||
|
def redirect_request(self, request, fp, code, message, headers, new_url):
|
||||||
|
raise RuntimeError("unexpected Seq redirect denied")
|
||||||
|
|
||||||
|
|
||||||
|
class Client:
|
||||||
|
def __init__(self):
|
||||||
|
self.session = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirects(),
|
||||||
|
urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
|
||||||
|
self.csrf = None
|
||||||
|
|
||||||
|
def request(self, method, path, body=None, key=None):
|
||||||
|
require(allowed_path(method, path), "unexpected Seq API path")
|
||||||
|
if method == "PUT":
|
||||||
|
verify_key(body)
|
||||||
|
require(path == "api/apikeys/" + body["Id"], "dedicated Seq update path mismatch")
|
||||||
|
headers = {}
|
||||||
|
if isinstance(body, dict):
|
||||||
|
body = json.dumps(body).encode()
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
if key:
|
||||||
|
require(path == "api/events/raw", "ingestion token used outside ingestion")
|
||||||
|
headers["X-Seq-ApiKey"] = key
|
||||||
|
headers["Content-Type"] = "application/vnd.serilog.clef"
|
||||||
|
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirects())
|
||||||
|
else:
|
||||||
|
opener = self.session
|
||||||
|
if self.csrf and method != "GET":
|
||||||
|
headers["X-Seq-CsrfToken"] = self.csrf
|
||||||
|
request = urllib.request.Request(BASE + path, data=body, headers=headers, method=method)
|
||||||
|
try:
|
||||||
|
with opener.open(request, timeout=15) as response:
|
||||||
|
require(response.geturl() == BASE + path, "unexpected Seq response endpoint")
|
||||||
|
raw = response.read(1024 * 1024 + 1)
|
||||||
|
require(len(raw) <= 1024 * 1024, "unexpected Seq response size")
|
||||||
|
require(response.status in (200, 201, 202, 204), "Seq request failed")
|
||||||
|
return json.loads(raw) if raw and "json" in response.headers.get("Content-Type", "") else None
|
||||||
|
except urllib.error.HTTPError as error:
|
||||||
|
code = error.code
|
||||||
|
error.close()
|
||||||
|
raise RuntimeError("Seq request denied (HTTP " + str(code) + ")") from None
|
||||||
|
except (urllib.error.URLError, TimeoutError):
|
||||||
|
raise RuntimeError("trusted Seq endpoint unavailable") from None
|
||||||
|
|
||||||
|
def login(self, credentials):
|
||||||
|
response = self.request("POST", "api/users/login", {
|
||||||
|
"Username": credentials["adminUsername"], "Password": credentials["adminPassword"]})
|
||||||
|
require(response["Username"] == credentials["adminUsername"] and
|
||||||
|
isinstance(response.get("CsrfToken"), str) and response["CsrfToken"], "Seq login identity/CSRF mismatch")
|
||||||
|
self.csrf = response["CsrfToken"]
|
||||||
|
|
||||||
|
|
||||||
|
def private_directory(path):
|
||||||
|
require(not path.is_symlink(), "private directory must not be a symlink")
|
||||||
|
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||||
|
require(path.is_dir(), "private directory is not a directory")
|
||||||
|
if os.name == "posix":
|
||||||
|
info = path.stat()
|
||||||
|
require(info.st_uid == os.getuid() and stat.S_IMODE(info.st_mode) == 0o700,
|
||||||
|
"private directory ownership/mode must match devops/0700")
|
||||||
|
|
||||||
|
|
||||||
|
def private_file(path):
|
||||||
|
require(not path.is_symlink() and path.is_file(), "private file missing or unexpected type")
|
||||||
|
if os.name == "posix":
|
||||||
|
info = path.stat()
|
||||||
|
require(info.st_uid == os.getuid() and stat.S_IMODE(info.st_mode) == 0o600,
|
||||||
|
"private file ownership/mode must match devops/0600")
|
||||||
|
|
||||||
|
|
||||||
|
@contextlib.contextmanager
|
||||||
|
def key_lock(directory):
|
||||||
|
path = directory / ".seq-key.lock"
|
||||||
|
try:
|
||||||
|
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
except FileExistsError:
|
||||||
|
raise RuntimeError("Seq key lock exists; inspect active run before removing stale lock") from None
|
||||||
|
try:
|
||||||
|
os.close(fd)
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
path.unlink()
|
||||||
|
|
||||||
|
|
||||||
|
def verify_key(value, allow_unmarked=False):
|
||||||
|
require(isinstance(value, dict), "unexpected dedicated Seq key response")
|
||||||
|
require(value.get("Title") == TITLE and isinstance(value.get("Id"), str) and
|
||||||
|
re.fullmatch(r"apikey-[a-z0-9-]+", value["Id"]), "dedicated Seq key identity mismatch")
|
||||||
|
require(value.get("AssignedPermissions") == ["Ingest"], "dedicated Seq key must grant only Ingest")
|
||||||
|
properties = value.get("InputSettings", {}).get("AppliedProperties")
|
||||||
|
expected = PROPERTIES + [{"Name": MARKER, "Value": value["Id"]}]
|
||||||
|
unmarked = allow_unmarked and isinstance(properties, list) and len(properties) == len(PROPERTIES) and (
|
||||||
|
sorted(properties, key=lambda x: x["Name"]) == sorted(PROPERTIES, key=lambda x: x["Name"]))
|
||||||
|
require(isinstance(properties, list) and (unmarked or (
|
||||||
|
len(properties) == len(expected) and sorted(properties, key=lambda x: x["Name"]) == sorted(expected, key=lambda x: x["Name"]))),
|
||||||
|
"dedicated Seq key stamped properties mismatch")
|
||||||
|
|
||||||
|
|
||||||
|
def dedicated_keys(client):
|
||||||
|
values = client.request("GET", KEY_LIST)
|
||||||
|
require(isinstance(values, list), "unexpected Seq key list")
|
||||||
|
matches = [value for value in values if value.get("Title") == TITLE]
|
||||||
|
require(len(matches) <= 1, "ambiguous dedicated Seq keys; no key changed")
|
||||||
|
return matches
|
||||||
|
|
||||||
|
|
||||||
|
def marker_unique(values, key_id):
|
||||||
|
for value in values:
|
||||||
|
if value.get("Id") == key_id:
|
||||||
|
continue
|
||||||
|
properties = value.get("InputSettings", {}).get("AppliedProperties") or []
|
||||||
|
require(isinstance(properties, list) and all(isinstance(p, dict) for p in properties), "unexpected Seq marker property schema")
|
||||||
|
require(not any(p.get("Name") == MARKER and p.get("Value") == key_id for p in properties),
|
||||||
|
"dedicated Seq identity marker collision; no foreign key changed")
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_identity_marker(client, key_id):
|
||||||
|
values = client.request("GET", KEY_LIST)
|
||||||
|
require(isinstance(values, list), "unexpected Seq key list")
|
||||||
|
targets = [v for v in values if v.get("Id") == key_id and v.get("Title") == TITLE]
|
||||||
|
require(len(targets) == 1, "dedicated Seq key changed before guarded update")
|
||||||
|
target = targets[0]
|
||||||
|
verify_key(target, allow_unmarked=True)
|
||||||
|
marker_unique(values, key_id)
|
||||||
|
expected_settings = copy.deepcopy(target["InputSettings"])
|
||||||
|
if not any(p["Name"] == MARKER for p in expected_settings["AppliedProperties"]):
|
||||||
|
expected_settings["AppliedProperties"].append({"Name": MARKER, "Value": key_id})
|
||||||
|
updated = copy.deepcopy(target)
|
||||||
|
updated["InputSettings"] = expected_settings
|
||||||
|
# Seq's documented UpdateAsync cannot change the token. Preserve every
|
||||||
|
# existing entity field; only this dedicated key's one stamp is added.
|
||||||
|
client.request("PUT", "api/apikeys/" + key_id, updated)
|
||||||
|
readback = client.request("GET", KEY_LIST)
|
||||||
|
require(isinstance(readback, list), "unexpected Seq key readback")
|
||||||
|
marker_unique(readback, key_id)
|
||||||
|
targets = [v for v in readback if v.get("Id") == key_id and v.get("Title") == TITLE]
|
||||||
|
require(len(targets) == 1, "dedicated Seq key readback missing")
|
||||||
|
result = targets[0]
|
||||||
|
verify_key(result)
|
||||||
|
require(result.get("InputSettings") == expected_settings and
|
||||||
|
all(result.get(field) == target.get(field) for field in ("AssignedPermissions", "OwnerId", "IsDefault", "Token", "TokenPrefix")),
|
||||||
|
"dedicated Seq update changed settings beyond identity marker")
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def verify_canary(client, check_id, expected_key):
|
||||||
|
query = "api/events?count=2&filter=" + urllib.parse.quote("ProvisioningCheckId = '" + check_id + "'")
|
||||||
|
events = []
|
||||||
|
for attempt in range(20):
|
||||||
|
events = client.request("GET", query)
|
||||||
|
require(isinstance(events, list), "unexpected Seq canary readback")
|
||||||
|
if events:
|
||||||
|
break
|
||||||
|
if attempt < 19:
|
||||||
|
time.sleep(1)
|
||||||
|
require(len(events) == 1 and isinstance(events[0], dict), "Seq canary readback must contain exactly one event")
|
||||||
|
event = events[0]
|
||||||
|
# Seq's official EventEntity exposes Properties as EventPropertyPart{Name,Value}.
|
||||||
|
parts = event.get("Properties")
|
||||||
|
require(isinstance(parts, list) and all(isinstance(p, dict) and "Name" in p and "Value" in p for p in parts),
|
||||||
|
"unexpected Seq canary property schema")
|
||||||
|
properties = {p["Name"]: p["Value"] for p in parts}
|
||||||
|
require(len(properties) == len(parts), "ambiguous Seq canary properties")
|
||||||
|
require(properties.get("ProvisioningCheckId") == check_id, "Seq canary correlation mismatch")
|
||||||
|
# The canary payload omits this server-stamped, globally unique key marker.
|
||||||
|
# Installed Seq exposes neither the original token nor ApiKeyId on EventEntity.
|
||||||
|
require(properties.get(MARKER) == expected_key["Id"], "Seq canary token belongs to a different or unverified key")
|
||||||
|
actual_key = event.get("ApiKeyId", properties.get("ApiKeyId"))
|
||||||
|
if actual_key is not None:
|
||||||
|
require(actual_key == expected_key["Id"], "Seq canary provenance conflicts with identity marker")
|
||||||
|
require(properties.get("Environment") == "SharedNotification" and
|
||||||
|
properties.get("Service") == "HrynCo.NotificationService", "Seq canary stamped identity mismatch")
|
||||||
|
|
||||||
|
|
||||||
|
def provision(client, token_file=TOKEN_FILE):
|
||||||
|
private_directory(token_file.parent)
|
||||||
|
with key_lock(token_file.parent):
|
||||||
|
existing = dedicated_keys(client)
|
||||||
|
if existing:
|
||||||
|
verify_key(existing[0], allow_unmarked=True)
|
||||||
|
require(token_file.exists(), "dedicated remote key exists but local token is missing; recover original file; no rotation performed")
|
||||||
|
if token_file.exists():
|
||||||
|
private_file(token_file)
|
||||||
|
token = token_file.read_text(encoding="utf-8").strip()
|
||||||
|
require(re.fullmatch(r"[a-f0-9]{64}", token), "private token format mismatch; no rotation performed")
|
||||||
|
else:
|
||||||
|
token = secrets.token_hex(32)
|
||||||
|
# Persist BEFORE POST: a timed-out create can be recovered without rotation.
|
||||||
|
fd = os.open(token_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as stream:
|
||||||
|
stream.write(token + "\n")
|
||||||
|
stream.flush()
|
||||||
|
os.fsync(stream.fileno())
|
||||||
|
if not existing:
|
||||||
|
template = client.request("GET", "api/apikeys/template")
|
||||||
|
require(isinstance(template, dict) and isinstance(template.get("InputSettings"), dict), "unexpected Seq key template")
|
||||||
|
template.update({"Title": TITLE, "Token": token, "AssignedPermissions": ["Ingest"]})
|
||||||
|
template["InputSettings"]["AppliedProperties"] = PROPERTIES
|
||||||
|
created = client.request("POST", "api/apikeys/", template)
|
||||||
|
verify_key(created, allow_unmarked=True)
|
||||||
|
readback = dedicated_keys(client)
|
||||||
|
require(len(readback) == 1, "dedicated Seq key readback missing")
|
||||||
|
dedicated = ensure_identity_marker(client, readback[0]["Id"])
|
||||||
|
# A valid foreign token must not pass. The marker is applied by Seq only,
|
||||||
|
# never supplied by this canary's body, and is unique across all keys.
|
||||||
|
canary = {"@t": datetime.now(timezone.utc).isoformat(),
|
||||||
|
"@mt": "HrynCo Notification Service ingest key verification",
|
||||||
|
"Application": "hrynco-notification-service-provisioning",
|
||||||
|
"ProvisioningCheckId": secrets.token_hex(16)}
|
||||||
|
client.request("POST", "api/events/raw", json.dumps(canary).encode() + b"\n", key=token)
|
||||||
|
verify_canary(client, canary["ProvisioningCheckId"], dedicated)
|
||||||
|
return dedicated["Id"]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
require(sys.platform == "linux" and os.getuid() != 0, "run as devops on mini-pc-2")
|
||||||
|
import pwd
|
||||||
|
require(pwd.getpwuid(os.getuid()).pw_name == "devops", "run as devops on mini-pc-2")
|
||||||
|
private_file(CREDENTIALS)
|
||||||
|
credentials = json.loads(CREDENTIALS.read_text(encoding="utf-8"))
|
||||||
|
client = Client()
|
||||||
|
client.login(credentials)
|
||||||
|
provision(client)
|
||||||
|
print("Dedicated Notification Seq key/marker verified; private token preserved; other keys and retention unchanged.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except (RuntimeError, OSError, ValueError, KeyError, TypeError) as error:
|
||||||
|
# RuntimeError messages are fixed gates; never API responses or file contents.
|
||||||
|
message = str(error) if isinstance(error, RuntimeError) else type(error).__name__
|
||||||
|
print("STOP: " + message, file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user