Path: redb-route/redb.Route.Telegram/TelegramProducer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Telegram/TelegramProducer.cs
----
using System.Diagnostics;
using System.Globalization;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using TgMessage = Telegram.Bot.Types.Message;
namespace redb.Route.Telegram;
///
/// Telegram Bot producer.
/// Supported modes: send, document, photo, answer, edit, delete, download.
///
/// ChatId is resolved (in priority order):
/// 1. Header telegram.chatId on the exchange
/// 2. Options.ChatId (from URI or DSL)
///
/// The answer and download modes need no chatId: the first is addressed by
/// callback query id, the second by file id.
///
/// On successful send/document/photo/edit the resulting Message.MessageId
/// is written back to the exchange as header ;
/// download writes the bytes to Out.Body.
///
public sealed class TelegramProducer : ConnectableProducer
{
private readonly TelegramEndpoint _endpoint;
private readonly TelegramEndpointOptions _options;
private ITelegramBotClient? _bot;
private ITelegramBotClient? _testClient;
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => $"telegram:{_endpoint.Mode}";
/// Creates a Telegram producer.
public TelegramProducer(TelegramEndpoint endpoint, TelegramEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
}
///
protected override Task ConnectAsync(CancellationToken ct)
{
// Test seam: a mock ITelegramBotClient injected via UseTestClient bypasses the component.
if (_testClient is not null)
{
_bot = _testClient;
return Task.CompletedTask;
}
// Client is owned and pooled by TelegramComponent (shared per resolved token).
// Producer/consumer for the same token get the same instance.
if (_endpoint.Component is not TelegramComponent component)
throw new InvalidOperationException(
"Telegram producer requires TelegramComponent as its owning component.");
_bot = component.GetOrCreateClient(_options.Token);
Logger?.LogInformation("Telegram producer connected (mode={Mode})", _endpoint.Mode);
return Task.CompletedTask;
}
/// Test seam: inject a mock used instead of the component client.
internal void UseTestClient(ITelegramBotClient bot) => _testClient = bot;
///
protected override Task DisconnectAsync(CancellationToken ct)
{
// Ownership of the client (and its HttpClient) stays with TelegramComponent.
// Releasing our reference is enough here.
_bot = null;
return Task.CompletedTask;
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
// Capture the client locally: DisconnectAsync nulls _bot on Stop(), and a concurrent Process
// must not dereference a null field (shutdown race).
var bot = _bot
?? throw new InvalidOperationException(
$"{ProducerName}: producer client is unavailable (stopped concurrently?).");
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"telegram.{_endpoint.Mode} publish", ActivityKind.Producer, "messaging.system", "telegram",
_endpoint.Uri.NormalizedKey, operation: "publish");
if (activity is { IsAllDataRequested: true })
activity.SetTag("messaging.telegram.mode", _endpoint.Mode);
// Per-request timeout linked to the caller ct. Uses the dedicated producer send timeout
// (SendTimeoutSeconds) — independent from the long-poll HTTP ceiling on the shared client, so a
// large upload over a slow link is not capped at the ~50s long-poll window.
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(_options.SendTimeoutSeconds));
var reqCt = cts.Token;
try
{
// answer is addressed by callbackQueryId, download by fileId — neither needs a chat.
if (_endpoint.Mode == "answer")
{
await AnswerCallbackQueryAsync(bot, exchange, activity, reqCt).ConfigureAwait(false);
}
else if (_endpoint.Mode == "download")
{
await DownloadFileAsync(bot, exchange, activity, reqCt).ConfigureAwait(false);
}
else
{
var chatId = ResolveChatId(exchange);
switch (_endpoint.Mode)
{
case "document":
await SendDocumentAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false);
break;
case "photo":
await SendPhotoAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false);
break;
case "edit":
await EditMessageAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false);
break;
case "delete":
await DeleteMessageAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false);
break;
default: // "send"
await SendMessageAsync(bot, exchange, chatId, reqCt).ConfigureAwait(false);
break;
}
}
// No RecordMessageOut: a routed .To() is counted by ToProcessor and a template send
// by the ProducerTemplate - self-recording here doubled both (ownership audit).
}
catch (ApiRequestException ex)
{
activity.RecordFailure(ex);
LogPublishDiagnostics(ex, exchange);
throw;
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Only our own token cancelling the send is a stop; the per-request timeout or any other failure marks the span.
activity.RecordFailure(ex);
throw;
}
}
// ── Rate-limit (429) retry ────────────────────────────────────────────────
///
/// Telegram enforces per-chat/global flood limits and answers with HTTP 429 plus a
/// retry_after hint. Bot API contract: wait that long and retry. Failing to wait (and
/// letting the route retry immediately) escalates to a temporary token ban, so this is the one
/// obligation a Telegram producer must implement. Retries are bounded and honour the request
/// cancellation token; retry_after is clamped to [1, 60]s to avoid an unbounded stall.
///
private async Task WithRateLimitRetryAsync(Func> action, CancellationToken ct)
{
const int maxRetries = 3;
for (var attempt = 0; ; attempt++)
{
try
{
return await action(ct).ConfigureAwait(false);
}
catch (ApiRequestException ex) when (ex.ErrorCode == 429 && attempt < maxRetries)
{
var retryAfter = Math.Clamp(ex.Parameters?.RetryAfter ?? 1, 1, 60);
Logger?.LogWarning(
"Telegram: rate-limited (429) on mode={Mode}; waiting {RetryAfter}s before retry {Attempt}/{Max}.",
_endpoint.Mode, retryAfter, attempt + 1, maxRetries);
await Task.Delay(TimeSpan.FromSeconds(retryAfter), ct).ConfigureAwait(false);
}
}
}
private Task WithRateLimitRetryAsync(Func action, CancellationToken ct) =>
WithRateLimitRetryAsync