SMS služba: prostředník nad SMS-Služba.cz (API XML 3.0)

- JSON API /v1: odeslání SMS, doručenka, události, potvrzení událostí, kredit
- vlastní API klíč pro každou aplikaci (X-Api-Key, API_KEYS)
- po chybě přihlášení k bráně se volání zastaví, aby se účet nezablokoval
- heslo maskované v logu, odeslání se nikdy neopakuje automaticky
- /health, /docs a OpenAPI s prefixem z ROOT_PATH
- .NET 10, šablona .NET 8 nahrazena projektem v src/, testy v tests/
- dokumentace: návrh, stav a návod pro napojení aplikací
This commit is contained in:
JiriUhlir
2026-10-20 10:21:03 +02:00
parent 908d6c9954
commit 63547942af
57 changed files with 3233 additions and 40 deletions
@@ -0,0 +1,25 @@
using SmsSluzba.Api.Contracts;
using SmsSluzba.Api.Gateway;
namespace SmsSluzba.Api.Endpoints;
internal static class AccountEndpoints
{
public static RouteGroupBuilder MapAccountEndpoints(this RouteGroupBuilder group)
{
group.MapGet("/account/credit", GetCreditAsync)
.WithName("GetCredit")
.WithTags("Účet")
.WithSummary("Kredit a ceny SMS (Kč bez DPH)")
.Produces<CreditResponse>()
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status502BadGateway)
.ProducesProblem(StatusCodes.Status503ServiceUnavailable)
.ProducesProblem(StatusCodes.Status504GatewayTimeout);
return group;
}
private static Task<IResult> GetCreditAsync(SmsGatewayClient gateway, CancellationToken ct) =>
GatewayProblems.RunAsync(async () => Results.Ok(await gateway.GetCreditAsync(ct)));
}
@@ -0,0 +1,101 @@
using SmsSluzba.Api.Contracts;
using SmsSluzba.Api.Gateway;
using SmsSluzba.Api.Problems;
namespace SmsSluzba.Api.Endpoints;
internal static class EventEndpoints
{
private const string Tag = "Události";
// The gateway returns at most 30 messages per call; confirmations use the same batch size.
private const int MaxBatchSize = 30;
public static RouteGroupBuilder MapEventEndpoints(this RouteGroupBuilder group)
{
group.MapGet("/events", GetEventsAsync)
.WithName("GetEvents")
.WithTags(Tag)
.WithSummary("Příchozí SMS, odpovědi a doručenky")
.WithDescription("Brána vrací stejnou událost znovu, dokud ji nepotvrdíte přes POST /v1/events/confirm. Fronta je jedna pro celý účet, události má stahovat jen jedna aplikace.")
.Produces<EventsResponse>()
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status502BadGateway)
.ProducesProblem(StatusCodes.Status503ServiceUnavailable)
.ProducesProblem(StatusCodes.Status504GatewayTimeout);
group.MapPost("/events/confirm", ConfirmAsync)
.WithName("ConfirmEvents")
.WithTags(Tag)
.WithSummary("Potvrdí převzetí událostí")
.Produces<ConfirmEventsResponse>()
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status401Unauthorized);
return group;
}
private static async Task<IResult> GetEventsAsync(string? types, int? count, SmsGatewayClient gateway, CancellationToken ct)
{
var query = GatewayEventQuery.Parse(types);
if (query is null)
{
return ApiProblems.Validation(
$"Neplatný parametr 'types'. Povolené hodnoty: {EventTypes.Incoming}, {EventTypes.DeliveryReport}, {EventTypes.Outgoing}.");
}
var size = count ?? MaxBatchSize;
if (size is < 1 or > MaxBatchSize)
{
return ApiProblems.Validation($"Parametr 'count' musí být 1 až {MaxBatchSize}.");
}
return await GatewayProblems.RunAsync(async () =>
Results.Ok(new EventsResponse(await gateway.GetEventsAsync(query, size, ct))));
}
private static async Task<IResult> ConfirmAsync(ConfirmEventsRequest request, SmsGatewayClient gateway, CancellationToken ct)
{
if (request.Events is not { Count: > 0 } events)
{
return ApiProblems.Validation("Seznam 'events' je prázdný.");
}
if (events.Count > MaxBatchSize)
{
return ApiProblems.Validation($"Najednou lze potvrdit nejvýš {MaxBatchSize} událostí.");
}
var items = new List<(string Type, string Id, string GatewayType)>(events.Count);
foreach (var item in events)
{
if (item.Type is null
|| GatewayEventQuery.ConfirmTypeFor(item.Type) is not { } gatewayType
|| string.IsNullOrWhiteSpace(item.Id))
{
return ApiProblems.Validation($"Neplatná položka: type '{item.Type}', id '{item.Id}'.");
}
items.Add((item.Type, item.Id.Trim(), gatewayType));
}
var confirmed = new List<ConfirmedEvent>();
var failed = new List<FailedEvent>();
foreach (var (type, id, gatewayType) in items)
{
try
{
await gateway.ConfirmAsync(gatewayType, id, ct);
confirmed.Add(new ConfirmedEvent(type, id));
}
catch (GatewayException ex)
{
// Already logged by SmsGatewayClient; the caller retries the failed items later.
failed.Add(new FailedEvent(type, id, GatewayProblems.ErrorFor(ex.Kind).Code));
}
}
return Results.Ok(new ConfirmEventsResponse(confirmed, failed));
}
}
@@ -0,0 +1,41 @@
using SmsSluzba.Api.Gateway;
using SmsSluzba.Api.Problems;
namespace SmsSluzba.Api.Endpoints;
internal static class GatewayProblems
{
private const string UnknownStateDetail = "Stav není známý, brána mohla požadavek přijmout. Odeslání SMS neopakujte automaticky.";
public static ApiError ErrorFor(GatewayErrorKind kind) => kind switch
{
GatewayErrorKind.InvalidRecipient => ApiErrors.InvalidRecipient,
GatewayErrorKind.MissingText => ApiErrors.MissingText,
GatewayErrorKind.Rejected => ApiErrors.ProviderRejected,
GatewayErrorKind.AuthFailed or GatewayErrorKind.AuthBlocked => ApiErrors.ProviderAuthBlocked,
GatewayErrorKind.InsufficientCredit => ApiErrors.InsufficientCredit,
GatewayErrorKind.Timeout => ApiErrors.ProviderTimeout,
_ => ApiErrors.ProviderUnavailable,
};
public static IResult ToResult(GatewayException ex)
{
var error = ErrorFor(ex.Kind);
var detail = ex.ProviderMessage ?? (error.Status is 502 or 504 ? UnknownStateDetail : null);
return ApiProblems.Result(error, detail, ex.ProviderCode);
}
/// <summary>Runs a gateway call and turns a gateway failure into a problem response.</summary>
public static async Task<IResult> RunAsync(Func<Task<IResult>> call)
{
try
{
return await call();
}
catch (GatewayException ex)
{
// Already logged by SmsGatewayClient.
return ToResult(ex);
}
}
}
@@ -0,0 +1,98 @@
using SmsSluzba.Api.Auth;
using SmsSluzba.Api.Contracts;
using SmsSluzba.Api.Gateway;
using SmsSluzba.Api.Logging;
using SmsSluzba.Api.Messages;
using SmsSluzba.Api.Problems;
namespace SmsSluzba.Api.Endpoints;
internal static class MessageEndpoints
{
private const string Tag = "Zprávy";
private const string LoggerCategory = "SmsSluzba.Api.Messages";
public static RouteGroupBuilder MapMessageEndpoints(this RouteGroupBuilder group)
{
group.MapPost("/messages", SendAsync)
.WithName("SendMessage")
.WithTags(Tag)
.WithSummary("Odešle SMS")
.WithDescription("Každé úspěšné volání odešle a zaplatí jednu SMS. Po chybě 502 nebo 504 je stav neznámý, odeslání neopakujte automaticky.")
.Produces<SendMessageResponse>()
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status402PaymentRequired)
.ProducesProblem(StatusCodes.Status502BadGateway)
.ProducesProblem(StatusCodes.Status503ServiceUnavailable)
.ProducesProblem(StatusCodes.Status504GatewayTimeout);
group.MapGet("/messages/{id}/delivery-report", GetDeliveryReportAsync)
.WithName("GetDeliveryReport")
.WithTags(Tag)
.WithSummary("Doručenka k odeslané zprávě")
.Produces<DeliveryReportResponse>()
.ProducesProblem(StatusCodes.Status401Unauthorized)
.ProducesProblem(StatusCodes.Status404NotFound)
.ProducesProblem(StatusCodes.Status502BadGateway)
.ProducesProblem(StatusCodes.Status503ServiceUnavailable)
.ProducesProblem(StatusCodes.Status504GatewayTimeout);
return group;
}
private static async Task<IResult> SendAsync(
SendMessageRequest request,
SmsGatewayClient gateway,
HttpContext httpContext,
ILoggerFactory loggerFactory,
CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(request.To))
{
return ApiProblems.Validation("Pole 'to' je povinné.");
}
if (string.IsNullOrWhiteSpace(request.Text))
{
return ApiProblems.Result(ApiErrors.MissingText, "Pole 'text' je povinné.");
}
var length = SmsText.CountLength(request.Text);
if (length > SmsText.MaxLength)
{
return ApiProblems.Result(ApiErrors.TextTooLong, $"Text má {length} znaků, maximum je {SmsText.MaxLength}.");
}
var recipient = request.To.Trim();
var client = ApiClientRegistry.GetCurrent(httpContext);
var logger = loggerFactory.CreateLogger(LoggerCategory);
return await GatewayProblems.RunAsync(async () =>
{
var result = await gateway.SendAsync(recipient, request.Text, request.DeliveryReport, request.SendAt, ct);
logger.LogInformation(
"SMS {MessageId} for {Recipient} accepted by gateway, client {Client}, parts {Parts}, price {Price}",
result.Id,
LogMask.Phone(recipient),
client,
result.Parts,
result.Price);
return Results.Ok(result);
});
}
private static async Task<IResult> GetDeliveryReportAsync(string id, SmsGatewayClient gateway, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(id))
{
return ApiProblems.Validation("Chybí id zprávy.");
}
return await GatewayProblems.RunAsync(async () =>
{
var report = await gateway.GetDeliveryReportAsync(id.Trim(), ct);
return report is null ? ApiProblems.Result(ApiErrors.DeliveryReportNotFound) : Results.Ok(report);
});
}
}
@@ -0,0 +1,32 @@
using SmsSluzba.Api.Contracts;
using SmsSluzba.Api.Gateway;
namespace SmsSluzba.Api.Endpoints;
internal static class SystemEndpoints
{
private const string GatewayOk = "ok";
private const string GatewayBlocked = "blocked";
public static IEndpointRouteBuilder MapSystemEndpoints(this IEndpointRouteBuilder app)
{
app.MapGet("/", () => Results.Json(new
{
name = "SMS Služba",
service = "sms-sluzba",
status = "ok",
}))
.ExcludeFromDescription();
// Stays 200 even when the gateway login is blocked: a failing health check would make AppFactory
// restart the container, and every restart would try the wrong password again.
app.MapGet("/health", (GatewayAuthGuard authGuard) =>
Results.Ok(new HealthResponse("ok", authGuard.IsBlocked ? GatewayBlocked : GatewayOk)))
.WithName("Health")
.WithTags("Služba")
.WithSummary("Stav služby, nevolá SMS bránu")
.Produces<HealthResponse>();
return app;
}
}