|
| 1 | +using System.Globalization; |
| 2 | +using System.Net.Http.Json; |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | +using Microsoft.Extensions.Options; |
| 5 | +using TradingSystem.Core.Configuration; |
| 6 | +using TradingSystem.Core.Interfaces; |
| 7 | +using TradingSystem.Core.Models; |
| 8 | + |
| 9 | +namespace TradingSystem.Functions; |
| 10 | + |
| 11 | +/// <summary> |
| 12 | +/// S6-001 (Default D6): renders the monthly income reinvest plan as a digest-class NEUTRAL |
| 13 | +/// embed — deliberately NOT risk red or operational orange, because this message is routine |
| 14 | +/// evidence, not an alarm. Same webhook/config as the other Discord senders (no new secret) |
| 15 | +/// but its OWN named client ("DiscordIncomeReport", 8s timeout in Program.cs) so the senders' |
| 16 | +/// handlers/telemetry stay distinguishable. Reuses the S3-004 hardening verbatim via |
| 17 | +/// <see cref="DiscordWebhookGuard"/>: https-only Discord host allow-list, token-redacted |
| 18 | +/// logging ({scheme}://{host} only), bounded 429/Retry-After retry with an injectable delay |
| 19 | +/// (zero-wait in tests), and the Enabled==false skip (one-time ctor Information notice, |
| 20 | +/// per-call Debug skip — B-006 pattern). |
| 21 | +/// |
| 22 | +/// Content contract: the posture line (recommendation-only vs orders-placed — locked |
| 23 | +/// decision 1), the D4 available-cash input labeled as an estimate, sleeve total value, |
| 24 | +/// per-category drift, and the proposed buys (capped render). An empty plan renders an |
| 25 | +/// explicit "No buys proposed" line (Default D8 — proof the timer ran). No secrets and no |
| 26 | +/// exception messages ever appear in any embed or log. Delivery failure degrades to a loud |
| 27 | +/// AlertDropped=true log and returns — a missed report is never an operational stop. |
| 28 | +/// </summary> |
| 29 | +public class DiscordIncomeReportService : IIncomeReportService |
| 30 | +{ |
| 31 | + // Retries are bounded by BOTH a retry count and a cumulative wait budget (S3-004 pattern). |
| 32 | + private const int MaxRetries = 3; |
| 33 | + private const double MaxTotalWaitSeconds = 10.0; |
| 34 | + |
| 35 | + // Cap on rendered buy lines (Discord field limit is 1024 chars; the report is a digest). |
| 36 | + private const int MaxRenderedBuys = 10; |
| 37 | + |
| 38 | + // Digest-class neutral grey — never risk red (15158332) or ops orange (15105570). |
| 39 | + private const int NeutralColor = 9807270; |
| 40 | + |
| 41 | + private readonly HttpClient _httpClient; |
| 42 | + private readonly DiscordConfig _config; |
| 43 | + private readonly IncomeSleeveConfig _sleeveConfig; |
| 44 | + private readonly ILogger<DiscordIncomeReportService> _logger; |
| 45 | + private readonly Func<TimeSpan, CancellationToken, Task> _delay; |
| 46 | + |
| 47 | + public DiscordIncomeReportService( |
| 48 | + IHttpClientFactory httpClientFactory, |
| 49 | + IOptions<DiscordConfig> config, |
| 50 | + IOptions<IncomeSleeveConfig> sleeveConfig, |
| 51 | + ILogger<DiscordIncomeReportService> logger) |
| 52 | + : this(httpClientFactory, config, sleeveConfig, logger, Task.Delay) |
| 53 | + { |
| 54 | + } |
| 55 | + |
| 56 | + // Internal ctor: the delay is injectable so tests run with zero real wait. |
| 57 | + internal DiscordIncomeReportService( |
| 58 | + IHttpClientFactory httpClientFactory, |
| 59 | + IOptions<DiscordConfig> config, |
| 60 | + IOptions<IncomeSleeveConfig> sleeveConfig, |
| 61 | + ILogger<DiscordIncomeReportService> logger, |
| 62 | + Func<TimeSpan, CancellationToken, Task> delay) |
| 63 | + { |
| 64 | + _httpClient = httpClientFactory.CreateClient("DiscordIncomeReport"); |
| 65 | + _config = config.Value; |
| 66 | + _sleeveConfig = sleeveConfig.Value; |
| 67 | + _logger = logger; |
| 68 | + _delay = delay; |
| 69 | + |
| 70 | + if (!_config.Enabled) |
| 71 | + { |
| 72 | + // ONE-TIME Information-level notice at construction (B-006 pattern): without this |
| 73 | + // the disabled state of the reinvest report path would be invisible at the |
| 74 | + // Information minimum level; the per-call skip stays at Debug. |
| 75 | + _logger.LogInformation( |
| 76 | + "Discord income reinvest reports are disabled (Enabled=false); reinvest plan reports will NOT be delivered until enabled."); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + public async Task SendReinvestmentPlanReportAsync( |
| 81 | + ReinvestmentPlan plan, |
| 82 | + IncomeSleeveState state, |
| 83 | + int ordersPlaced, |
| 84 | + CancellationToken cancellationToken = default) |
| 85 | + { |
| 86 | + var day = plan.PlanDate.Date; |
| 87 | + |
| 88 | + if (!_config.Enabled) |
| 89 | + { |
| 90 | + _logger.LogDebug( |
| 91 | + "Discord income reinvest reports are disabled; skipping report for {Date}", day); |
| 92 | + return; |
| 93 | + } |
| 94 | + |
| 95 | + if (string.IsNullOrWhiteSpace(_config.WebhookUrl)) |
| 96 | + { |
| 97 | + _logger.LogWarning( |
| 98 | + "Discord webhook URL is not configured; cannot send income reinvest report for {Date}", day); |
| 99 | + return; |
| 100 | + } |
| 101 | + |
| 102 | + // Host allow-list + scheme check. On rejection only a redacted {scheme}://{host} (or |
| 103 | + // an <empty>/<malformed> sentinel) is logged — never the token-bearing path. |
| 104 | + if (!DiscordWebhookGuard.TryValidateWebhook(_config.WebhookUrl, out var redacted)) |
| 105 | + { |
| 106 | + _logger.LogWarning( |
| 107 | + "Discord webhook URL is not an allowed https Discord endpoint ({Redacted}); skipping income reinvest report for {Date}", |
| 108 | + redacted, |
| 109 | + day); |
| 110 | + return; |
| 111 | + } |
| 112 | + |
| 113 | + var payload = new |
| 114 | + { |
| 115 | + username = _config.Username, |
| 116 | + // Disable mention parsing so report content can never ping @everyone/@here. |
| 117 | + allowed_mentions = new { parse = Array.Empty<string>() }, |
| 118 | + embeds = new[] { BuildPlanEmbed(plan, state, ordersPlaced) } |
| 119 | + }; |
| 120 | + |
| 121 | + await PostWithRetryAsync(payload, day, cancellationToken); |
| 122 | + } |
| 123 | + |
| 124 | + private Embed BuildPlanEmbed(ReinvestmentPlan plan, IncomeSleeveState state, int ordersPlaced) |
| 125 | + { |
| 126 | + // Posture leads (locked decision 1): the owner's first read must answer "did this |
| 127 | + // place orders?". The exact flag key renders so the runbook check is unambiguous. |
| 128 | + var posture = _sleeveConfig.OrderPlacementEnabled |
| 129 | + ? $"Order placement ENABLED — {ordersPlaced.ToString(CultureInfo.InvariantCulture)} paper order(s) placed (IncomeSleeve:OrderPlacementEnabled=true)." |
| 130 | + : "Recommendation-only; IncomeSleeve:OrderPlacementEnabled=false. NO orders were placed."; |
| 131 | + |
| 132 | + var fields = new List<EmbedField> |
| 133 | + { |
| 134 | + new("Posture", posture, false), |
| 135 | + // Default D4: the cash input is a heuristic estimate (TotalCashValue × |
| 136 | + // IncomeTargetPercent) — labeled so nobody mistakes it for dividend tracking. |
| 137 | + new("Available Cash (estimate)", |
| 138 | + $"{Money(plan.AvailableCash)} — TotalCashValue × IncomeTargetPercent (estimate; dividend/interest tracking not yet wired)", |
| 139 | + true), |
| 140 | + new("Sleeve Total Value", Money(state.TotalValue), true) |
| 141 | + }; |
| 142 | + |
| 143 | + if (state.CategoryDrift.Count > 0) |
| 144 | + { |
| 145 | + var driftLines = state.CategoryDrift |
| 146 | + .OrderBy(kv => kv.Value) |
| 147 | + .Select(kv => $"{kv.Key}: {kv.Value.ToString("+0.0%;-0.0%;0.0%", CultureInfo.InvariantCulture)}"); |
| 148 | + fields.Add(new EmbedField("Category Drift (current − target)", |
| 149 | + string.Join(Environment.NewLine, driftLines), false)); |
| 150 | + } |
| 151 | + |
| 152 | + if (plan.ProposedBuys.Count == 0) |
| 153 | + { |
| 154 | + // Default D8: an empty plan is a legitimate outcome (e.g. an unfunded sleeve) — |
| 155 | + // say so explicitly; this message existing at all is proof the timer ran. |
| 156 | + fields.Add(new EmbedField("Proposed Buys", "No buys proposed.", false)); |
| 157 | + } |
| 158 | + else |
| 159 | + { |
| 160 | + var lines = plan.ProposedBuys |
| 161 | + .Take(MaxRenderedBuys) |
| 162 | + .Select(b => string.Create( |
| 163 | + CultureInfo.InvariantCulture, |
| 164 | + $"{b.Symbol} ({b.Category}): {Money(b.Amount)} — {b.Rationale}")); |
| 165 | + var overflow = plan.ProposedBuys.Count > MaxRenderedBuys |
| 166 | + ? $"{Environment.NewLine}... and {(plan.ProposedBuys.Count - MaxRenderedBuys).ToString(CultureInfo.InvariantCulture)} more" |
| 167 | + : string.Empty; |
| 168 | + fields.Add(new EmbedField("Proposed Buys", |
| 169 | + string.Join(Environment.NewLine, lines) + overflow, false)); |
| 170 | + } |
| 171 | + |
| 172 | + var description = plan.ProposedBuys.Count == 0 |
| 173 | + ? "No buys proposed — sleeve is unfunded or fully on-target." |
| 174 | + : $"{plan.ProposedBuys.Count.ToString(CultureInfo.InvariantCulture)} proposed buy(s) totaling {Money(plan.TotalProposedAmount)}."; |
| 175 | + |
| 176 | + return new Embed( |
| 177 | + title: $"Income Reinvest Plan — {plan.PlanDate.ToString("ddd MMM d, yyyy", CultureInfo.InvariantCulture)}", |
| 178 | + description: description, |
| 179 | + color: NeutralColor, |
| 180 | + timestamp: plan.PlanDate.Date.ToString("O", CultureInfo.InvariantCulture), |
| 181 | + fields: fields.ToArray()); |
| 182 | + } |
| 183 | + |
| 184 | + // POSTs the payload, honoring a 429 Retry-After with a bounded backoff (count + cumulative |
| 185 | + // wait budget). Degrades to a loud AlertDropped=true log and returns (no throw) on non-2xx |
| 186 | + // exhaustion, timeout, or transport failure. Status code / exception TYPE only is logged — |
| 187 | + // never the webhook URL, token, or an exception message (which can echo the request URI). |
| 188 | + private async Task PostWithRetryAsync(object payload, DateTime day, CancellationToken cancellationToken) |
| 189 | + { |
| 190 | + var start = DateTime.UtcNow; |
| 191 | + var attempt = 0; |
| 192 | + while (true) |
| 193 | + { |
| 194 | + try |
| 195 | + { |
| 196 | + using var response = await _httpClient.PostAsJsonAsync(_config.WebhookUrl, payload, cancellationToken); |
| 197 | + if (response.IsSuccessStatusCode) |
| 198 | + { |
| 199 | + _logger.LogInformation("Sent Discord income reinvest report for {Date}", day); |
| 200 | + return; |
| 201 | + } |
| 202 | + |
| 203 | + var remaining = MaxTotalWaitSeconds - (DateTime.UtcNow - start).TotalSeconds; |
| 204 | + if ((int)response.StatusCode != 429 || attempt >= MaxRetries || remaining <= 0) |
| 205 | + { |
| 206 | + // Terminal failure: the report is gone and will NOT be retried — make it |
| 207 | + // loud and log-searchable (AlertDropped=true) so the 2026-07-01 run-record |
| 208 | + // check ("did the plan report arrive?") has a definitive negative signal. |
| 209 | + _logger.LogError( |
| 210 | + "Income reinvest report NOT delivered and will not be retried. AlertDropped={AlertDropped}, StatusCode={StatusCode}, Attempts={Attempt}/{MaxRetries}, Date={Date}", |
| 211 | + true, |
| 212 | + (int)response.StatusCode, |
| 213 | + attempt + 1, |
| 214 | + MaxRetries, |
| 215 | + day); |
| 216 | + return; |
| 217 | + } |
| 218 | + |
| 219 | + var wait = Math.Max(0, Math.Min(DiscordWebhookGuard.RetryAfterSeconds(response), remaining)); |
| 220 | + _logger.LogWarning( |
| 221 | + "Discord rate-limited (429); retrying income reinvest report for {Date} after {WaitSeconds:F2}s (attempt {Attempt}/{Max})", |
| 222 | + day, |
| 223 | + wait, |
| 224 | + attempt + 1, |
| 225 | + MaxRetries); |
| 226 | + await _delay(TimeSpan.FromSeconds(wait), cancellationToken); |
| 227 | + attempt++; |
| 228 | + } |
| 229 | + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| 230 | + { |
| 231 | + // Caller cancelled — propagate cancellation, it carries no token. |
| 232 | + throw; |
| 233 | + } |
| 234 | + catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested) |
| 235 | + { |
| 236 | + // HttpClient timeout (the 8s named-client bound): the report never reached |
| 237 | + // Discord and will NOT be retried. Type names only. |
| 238 | + _logger.LogError( |
| 239 | + "Income reinvest report NOT delivered and will not be retried — send timed out. AlertDropped={AlertDropped}, ErrorType={ErrorType}, InnerErrorType={InnerErrorType}, Date={Date}", |
| 240 | + true, |
| 241 | + ex.GetType().Name, |
| 242 | + ex.InnerException?.GetType().Name, |
| 243 | + day); |
| 244 | + return; |
| 245 | + } |
| 246 | + catch (HttpRequestException ex) |
| 247 | + { |
| 248 | + // Transport failure. NEVER log ex.Message / ex.ToString() — those can echo |
| 249 | + // the token-bearing request URI. |
| 250 | + _logger.LogError( |
| 251 | + "Income reinvest report NOT delivered and will not be retried — transport error. AlertDropped={AlertDropped}, ErrorType={ErrorType}, StatusCode={StatusCode}, InnerErrorType={InnerErrorType}, Date={Date}", |
| 252 | + true, |
| 253 | + ex.GetType().Name, |
| 254 | + ex.StatusCode, |
| 255 | + ex.InnerException?.GetType().Name, |
| 256 | + day); |
| 257 | + return; |
| 258 | + } |
| 259 | + } |
| 260 | + } |
| 261 | + |
| 262 | + private static string Money(decimal value) => |
| 263 | + value < 0 |
| 264 | + ? string.Create(CultureInfo.InvariantCulture, $"-${Math.Abs(value):N2}") |
| 265 | + : string.Create(CultureInfo.InvariantCulture, $"${value:N2}"); |
| 266 | + |
| 267 | + // Discord embed shapes (lowercase property names match the webhook JSON contract). |
| 268 | + private sealed record Embed( |
| 269 | + string title, |
| 270 | + string description, |
| 271 | + int color, |
| 272 | + string timestamp, |
| 273 | + EmbedField[] fields); |
| 274 | + |
| 275 | + private sealed record EmbedField(string name, string value, bool inline); |
| 276 | +} |
0 commit comments