Adds 2 units and docs for unit 3. nfr-requirements plan

This commit is contained in:
2026-06-29 22:18:37 +02:00
parent 0e01ca1e1c
commit c156107cb1
126 changed files with 15204 additions and 80199 deletions
@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.DataProtection;
namespace SlpModularCms.Modules.Master.Services;
public class ApiKeyProtector(IDataProtectionProvider provider) : IApiKeyProtector
{
private readonly IDataProtector _protector = provider.CreateProtector("SlpModularCms.Master.ApiKey");
public string Protect(string plainApiKey) => _protector.Protect(plainApiKey);
public string Unprotect(string encryptedApiKey) => _protector.Unprotect(encryptedApiKey);
}
@@ -0,0 +1,175 @@
using Microsoft.Extensions.Logging;
using SlpModularCms.Modules.Master.Data.Entities;
using SlpModularCms.Modules.Master.Models;
namespace SlpModularCms.Modules.Master.Services;
public class CmsInstanceService(MasterServiceDependencies deps) : ICmsInstanceService
{
public async Task<IReadOnlyList<CmsInstanceDto>> GetAllAsync()
{
var instances = await deps.Repository.GetAllAsync();
return instances.Select(ToDto).ToList();
}
public async Task<CmsInstanceDto> AddAsync(CreateCmsInstanceRequest request)
{
if (string.IsNullOrWhiteSpace(request.Name))
throw new ArgumentException("Name is required.", nameof(request));
if (string.IsNullOrWhiteSpace(request.Url))
throw new ArgumentException("Url is required.", nameof(request));
if (string.IsNullOrWhiteSpace(request.ApiKey))
throw new ArgumentException("ApiKey is required.", nameof(request));
var encryptedKey = deps.ApiKeyProtector.Protect(request.ApiKey);
var instance = new CmsInstance
{
Id = Guid.NewGuid(),
Name = request.Name,
Url = request.Url,
ApiKey = encryptedKey,
Status = CmsInstanceStatus.Available
};
await deps.Repository.AddAsync(instance);
await deps.Repository.SaveChangesAsync();
var masterUrl = ResolveMasterUrl();
if (masterUrl is not null)
{
var registered = await deps.SlaveClient.RegisterMasterAsync(instance.Url, request.ApiKey, masterUrl);
if (registered)
{
instance.LastContactedAt = DateTimeOffset.UtcNow;
deps.Repository.Update(instance);
await deps.Repository.SaveChangesAsync();
}
else
{
deps.Logger.LogWarning("Master registration failed for slave {SlaveUrl}", instance.Url);
}
}
else
{
deps.Logger.LogWarning("MasterUrl could not be determined; skipping slave registration for {SlaveUrl}", instance.Url);
}
return ToDto(instance);
}
public async Task<UpdateStatusResult> UpdateStatusAsync(Guid id, UpdateStatusRequest request)
{
var instance = await deps.Repository.GetByIdAsync(id)
?? throw new KeyNotFoundException($"CMS instance {id} not found.");
if (request.Status == CmsInstanceStatus.NotAvailable && string.IsNullOrWhiteSpace(request.DisableMessage))
throw new ArgumentException("DisableMessage is required when setting status to NotAvailable.", nameof(request));
instance.Status = request.Status;
instance.DisableMessage = request.Status == CmsInstanceStatus.Available ? null : request.DisableMessage;
deps.Repository.Update(instance);
await deps.Repository.SaveChangesAsync();
if (request.Status == CmsInstanceStatus.Inactive)
return new UpdateStatusResult(Success: true, SlaveContactSuccess: true);
var plainKey = deps.ApiKeyProtector.Unprotect(instance.ApiKey);
var pushed = await deps.SlaveClient.PushStatusAsync(
instance.Url,
plainKey,
isAvailable: request.Status == CmsInstanceStatus.Available,
disableMessage: instance.DisableMessage);
if (pushed)
{
instance.LastStatusPushedAt = DateTimeOffset.UtcNow;
deps.Repository.Update(instance);
await deps.Repository.SaveChangesAsync();
}
else
{
deps.Logger.LogError("Status push failed for slave {SlaveUrl}", instance.Url);
}
return new UpdateStatusResult(Success: true, SlaveContactSuccess: pushed);
}
public async Task VerifyIntegrityAsync()
{
var masterUrl = ResolveMasterUrl();
if (masterUrl is null)
{
deps.Logger.LogWarning("MasterUrl not configured; skipping integrity check.");
return;
}
var activeInstances = await deps.Repository.GetActiveAsync();
foreach (var instance in activeInstances)
{
try
{
var plainKey = deps.ApiKeyProtector.Unprotect(instance.ApiKey);
var registeredUrl = await deps.SlaveClient.GetRegisteredMasterUrlAsync(instance.Url, plainKey);
if (registeredUrl is null)
{
deps.Logger.LogWarning("Slave {SlaveUrl} unreachable during integrity check.", instance.Url);
instance.LastIntegrityCheckFailedAt = DateTimeOffset.UtcNow;
deps.Repository.Update(instance);
await deps.Repository.SaveChangesAsync();
continue;
}
if (!string.Equals(registeredUrl, masterUrl, StringComparison.OrdinalIgnoreCase))
{
deps.Logger.LogWarning("Slave {SlaveUrl} has wrong master URL '{RegisteredUrl}'; re-registering.", instance.Url, registeredUrl);
var reRegistered = await deps.SlaveClient.RegisterMasterAsync(instance.Url, plainKey, masterUrl);
if (reRegistered)
{
instance.LastContactedAt = DateTimeOffset.UtcNow;
instance.LastIntegrityCheckFailedAt = null;
}
else
{
instance.LastIntegrityCheckFailedAt = DateTimeOffset.UtcNow;
}
}
else
{
instance.LastIntegrityCheckFailedAt = null;
}
deps.Repository.Update(instance);
await deps.Repository.SaveChangesAsync();
}
catch (Exception ex)
{
deps.Logger.LogError(ex, "Integrity check error for slave {SlaveUrl}", instance.Url);
}
}
}
private string? ResolveMasterUrl()
{
var httpContext = deps.HttpContextAccessor.HttpContext;
if (httpContext is not null)
{
var request = httpContext.Request;
return $"{request.Scheme}://{request.Host}";
}
return deps.Options.Value.MasterUrl;
}
private static CmsInstanceDto ToDto(CmsInstance instance) => new(
instance.Id,
instance.Name,
instance.Url,
instance.Status,
instance.DisableMessage,
instance.LastContactedAt,
instance.LastStatusPushedAt,
instance.LastIntegrityCheckFailedAt
);
}
@@ -0,0 +1,7 @@
namespace SlpModularCms.Modules.Master.Services;
public interface IApiKeyProtector
{
string Protect(string plainApiKey);
string Unprotect(string encryptedApiKey);
}
@@ -0,0 +1,11 @@
using SlpModularCms.Modules.Master.Models;
namespace SlpModularCms.Modules.Master.Services;
public interface ICmsInstanceService
{
Task<IReadOnlyList<CmsInstanceDto>> GetAllAsync();
Task<CmsInstanceDto> AddAsync(CreateCmsInstanceRequest request);
Task<UpdateStatusResult> UpdateStatusAsync(Guid id, UpdateStatusRequest request);
Task VerifyIntegrityAsync();
}
@@ -0,0 +1,8 @@
namespace SlpModularCms.Modules.Master.Services;
public interface ISlaveApiClient
{
Task<bool> RegisterMasterAsync(string slaveUrl, string plainApiKey, string masterUrl);
Task<bool> PushStatusAsync(string slaveUrl, string plainApiKey, bool isAvailable, string? disableMessage);
Task<string?> GetRegisteredMasterUrlAsync(string slaveUrl, string plainApiKey);
}
@@ -0,0 +1,18 @@
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Modules.Master.Config;
using SlpModularCms.Modules.Master.Repositories;
namespace SlpModularCms.Modules.Master.Services;
[ExcludeFromCodeCoverage]
public record MasterServiceDependencies(
ICmsInstanceRepository Repository,
ISlaveApiClient SlaveClient,
IApiKeyProtector ApiKeyProtector,
IOptions<MasterModuleOptions> Options,
IHttpContextAccessor HttpContextAccessor,
ILogger<CmsInstanceService> Logger
);
@@ -0,0 +1,65 @@
using System.Net.Http.Json;
using System.Text.Json;
namespace SlpModularCms.Modules.Master.Services;
public class SlaveApiClient(HttpClient httpClient) : ISlaveApiClient
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
public async Task<bool> RegisterMasterAsync(string slaveUrl, string plainApiKey, string masterUrl)
{
try
{
var request = new HttpRequestMessage(HttpMethod.Post, $"{slaveUrl.TrimEnd('/')}/api/v1/master/register");
request.Headers.Add("X-Master-Api-Key", plainApiKey);
request.Content = JsonContent.Create(new { MasterUrl = masterUrl }, options: JsonOptions);
var response = await httpClient.SendAsync(request);
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
public async Task<bool> PushStatusAsync(string slaveUrl, string plainApiKey, bool isAvailable, string? disableMessage)
{
try
{
var request = new HttpRequestMessage(HttpMethod.Post, $"{slaveUrl.TrimEnd('/')}/api/v1/master/status");
request.Headers.Add("X-Master-Api-Key", plainApiKey);
request.Content = JsonContent.Create(new { IsAvailable = isAvailable, DisableMessage = disableMessage }, options: JsonOptions);
var response = await httpClient.SendAsync(request);
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
public async Task<string?> GetRegisteredMasterUrlAsync(string slaveUrl, string plainApiKey)
{
try
{
var request = new HttpRequestMessage(HttpMethod.Get, $"{slaveUrl.TrimEnd('/')}/api/v1/master/registered-url");
request.Headers.Add("X-Master-Api-Key", plainApiKey);
var response = await httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
return null;
var result = await response.Content.ReadFromJsonAsync<RegisteredMasterUrlResponse>(JsonOptions);
return result?.MasterUrl;
}
catch
{
return null;
}
}
private record RegisteredMasterUrlResponse(string? MasterUrl);
}