Código

Basado en el Reloj de Cobranza que diseñé en Totalplay

Motor de enrutamiento de cobranza

Un millón de cuentas por ciclo, en paralelo y escalado horizontalmente.

C# 96%MSBuild 4%14 archivos710 líneas de código 12/12 pruebas
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using CollectionRouter.Domain;

namespace CollectionRouter.Infrastructure;

/// <summary>
/// Escribe decisiones en Elasticsearch con la API <c>_bulk</c> usando solo HttpClient.
///
/// Idempotencia: el <c>_id</c> de cada documento es la clave de idempotencia,
/// así que reprocesar un lote sobrescribe el mismo documento en lugar de duplicarlo.
///
/// Seguridad: la URL y la API key se leen de variables de entorno; nunca van en el código
/// ni en archivos de configuración versionados.
/// </summary>
public sealed class ElasticsearchBulkSink : IDecisionSink
{
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
    private readonly HttpClient _http;
    private readonly string _index;

    public ElasticsearchBulkSink(HttpClient http, string index)
    {
        _http = http;
        _index = index;
    }

    /// <summary>Crea el sink desde <c>ELASTIC_URL</c> y <c>ELASTIC_API_KEY</c>.</summary>
    public static ElasticsearchBulkSink FromEnvironment(string index = "collection-routing")
    {
        var url = Environment.GetEnvironmentVariable("ELASTIC_URL")
                  ?? throw new InvalidOperationException("Falta la variable de entorno ELASTIC_URL.");
        var apiKey = Environment.GetEnvironmentVariable("ELASTIC_API_KEY")
                     ?? throw new InvalidOperationException("Falta la variable de entorno ELASTIC_API_KEY.");

        var http = new HttpClient { BaseAddress = new Uri(url), Timeout = TimeSpan.FromSeconds(30) };
        http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("ApiKey", apiKey);
        return new ElasticsearchBulkSink(http, index);
    }

    public async Task WriteBatchAsync(IReadOnlyList<RoutingDecision> batch, CancellationToken cancellationToken)
    {
        if (batch.Count == 0) return;

        var body = BuildBulkBody(_index, batch);
        using var content = new StringContent(body, Encoding.UTF8);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-ndjson");

        using var response = await _http.PostAsync("_bulk", content, cancellationToken);
        response.EnsureSuccessStatusCode();

        // _bulk responde 200 aunque fallen documentos individuales: hay que revisar "errors".
        await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
        using var result = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
        if (result.RootElement.TryGetProperty("errors", out var errors) && errors.GetBoolean())
            throw new InvalidOperationException($"Elasticsearch rechazó documentos del lote ({batch.Count} decisiones).");
    }

    /// <summary>Formato NDJSON: una línea de acción y una de documento por decisión.</summary>
    public static string BuildBulkBody(string index, IReadOnlyList<RoutingDecision> batch)
    {
        var sb = new StringBuilder(batch.Count * 256);
        foreach (var d in batch)
        {
            sb.Append(JsonSerializer.Serialize(new { index = new { _index = index, _id = d.IdempotencyKey } }, Json)).Append('\n');
            sb.Append(JsonSerializer.Serialize(new
            {
                accountId = d.AccountId,
                cycleId = d.CycleId,
                stage = d.Stage.ToString(),
                channel = d.Channel.ToString(),
                priority = d.Priority,
                reason = d.Reason,
                routedAt = DateTimeOffset.UtcNow,
            }, Json)).Append('\n');
        }
        return sb.ToString();
    }
}