Files
Deal/src/telegram-service/Deal.Telegram/TelegramServiceHost.cs
T
Rustam Khalimov b053d58335 Почистить комментарии от упоминаний процесса
Удалены <remarks>, <summary> сжаты до короткой фразы, вырезаны
ссылки на Task/Ruling/этап/python/прототип; //-комментарии со ссылками
на процесс удалены; то же в .proto. Правила обновлены в
docs/spec/Код-стайл-Дейл.md. Строк комментариев 27210 -> ~19100.
2026-09-11 13:39:39 +03:00

80 lines
4.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Deal.Grpc.Hosting.Interceptors;
using Deal.Grpc.Hosting.Models;
using Deal.Grpc.Hosting.Options;
using Deal.Grpc.Hosting.Services;
using Deal.Telegram.Core;
using Deal.Telegram.Dialogs;
using Deal.Telegram.Discovery;
using Deal.Telegram.Hosting;
using Deal.Telegram.Sessions;
using Deal.Telegram.Telegram;
namespace Deal.Telegram;
/// <summary>
/// Собирает WebApplication gRPC-хоста telegram-service.
/// </summary>
public static class TelegramServiceHost
{
/// <summary>
/// Создаёт (не запускает) хост
/// </summary>
/// <param name="grpcPort">TCP-порт Kestrel.</param>
/// <param name="args">Аргументы командной строки (Program.cs); в тестах не нужны.</param>
/// <param name="configureServices">Опциональный хук DI для тестов (подмена зависимостей фейками, напр. ITelegramClientFactory).</param>
/// <param name="configureBuilder">Опциональный хук конфигурации билдера для production-точки входа (Program.cs): Serilog. Тесты хост поднимают БЕЗ этого хука — логирование файлов/консоли тестам не нужно.</param>
/// <returns>Собранный хост; запуск — StartAsync/RunAsync у вызывающего.</returns>
public static WebApplication Create(
int grpcPort,
string[]? args = null,
Action<IServiceCollection>? configureServices = null,
Action<WebApplicationBuilder>? configureBuilder = null)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args ?? []);
// Общая серверная обвязка (Deal.Grpc.Hosting, C31): mTLS env DEAL_MTLS_* — загрузка
// сертификатов сразу с fail-fast (compose-prod монтирует deploy/certs, scripts/mtls-certs.sh);
// Один экземпляр mtlsCertificates используют и Kestrel ниже, и исходящий канал в ядро
// (CoreIngressClient).
MtlsCertificates? mtlsCertificates = GrpcServer.LoadMtlsCertificates(builder);
GrpcServer.ConfigureKestrelHttp2Endpoint(builder, grpcPort, mtlsCertificates);
builder.Services.AddDealGrpcServer();
builder.Services.AddReadyHealthCheck("хост telegram-service готов");
// файлов data/sessions/<tenant>.session (AES-GCM, ключ из env), пул 1 аккаунт/тенант и
// фоновый цикл auto_resume/heartbeat (30 с). DEAL_TELEGRAM_SESSION_KEY обязателен —
// иначе хост не стартует (сессии не могут храниться в открытом виде).
TgOptions sessionOptions = TgOptions.FromConfiguration(builder.Configuration, builder.Environment);
builder.Services.AddSingleton(sessionOptions);
builder.Services.AddSingleton<SessionFileCipher>();
builder.Services.AddSingleton<SessionStore>();
builder.Services.AddSingleton<ITelegramClientFactory, ClientFactory>();
builder.Services.AddSingleton<SessionFarm>();
builder.Services.AddHostedService<SessionHeartbeatService>();
CoreIngressOptions ingressOptions = CoreIngressOptions.FromConfiguration(builder.Configuration);
builder.Services.AddSingleton(ingressOptions);
builder.Services.AddSingleton<ICoreIngressClient>(provider => new CoreIngressClient(
ingressOptions,
provider.GetRequiredService<ILogger<CoreIngressClient>>(),
mtlsCertificates));
builder.Services.AddSingleton<DialogCatalog>();
builder.Services.AddSingleton<IBackfillPacer, RandomBackfillPacer>();
builder.Services.AddSingleton<BackfillService>();
builder.Services.AddSingleton<DiscoveryOps>();
builder.Services.AddSingleton<RealtimeSweep>();
builder.Services.AddHostedService<RealtimeSweepService>();
builder.Services.AddHostedService<RealtimeMonitorService>();
configureServices?.Invoke(builder.Services);
configureBuilder?.Invoke(builder);
WebApplication app = builder.Build();
app.MapGrpcService<TelegramServiceImpl>();
app.MapGrpcHealthChecksService();
return app;
}
}