From a4523e090ebc65b7ca1a6e8239040a954f944913 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Wed, 25 Nov 2026 10:54:20 -0500 Subject: [PATCH] feat(notifications): SMTP delivery policy settable via management/CLI/UI (#149) SmtpConfiguration.MaxRetries/RetryDelay (and ConnectionTimeoutSeconds/ MaxConcurrentConnections) drive the outbox Email policy but had no write path, so every row sat at 0/0 and was clamped with a Warning; DEV vd03 had to be fixed by direct SQL. - Update/CreateSmtpConfigCommand: four trailing additive nullable fields (null = preserve on update / entity default on create; 0 = fallback). - ManagementActor: preserve-if-null, negatives refused. - CLI notification smtp create|update: --max-retries, --retry-delay-seconds, --connection-timeout-seconds, --max-concurrent-connections (>= 0). - Central UI /notifications/smtp: fields on the form + read-only panel; new rows pre-fill 10 retries / 60 s. - README + Component-NotificationService; tests for apply/preserve/reject. --- .../Component-NotificationService.md | 2 +- .../Commands/NotificationCommands.cs | 37 +++++-- src/ZB.MOM.WW.ScadaBridge.CLI/README.md | 8 +- .../Notifications/SmtpConfiguration.razor | 64 ++++++++++- .../Management/NotificationCommands.cs | 8 +- .../ManagementActor.cs | 14 +++ .../Commands/SmtpUpdateCommandTests.cs | 51 +++++++++ .../Pages/SmtpConfigurationPageTests.cs | 4 +- .../ManagementActorTests.cs | 101 ++++++++++++++++++ 9 files changed, 268 insertions(+), 21 deletions(-) diff --git a/docs/requirements/Component-NotificationService.md b/docs/requirements/Component-NotificationService.md index 62ce1ac1..b6f07a9c 100644 --- a/docs/requirements/Component-NotificationService.md +++ b/docs/requirements/Component-NotificationService.md @@ -52,7 +52,7 @@ The SMTP configuration is defined centrally and used by the central Email delive - **From address**: The sender email address for all notifications (e.g., `scada-notifications@company.com`). - **Connection timeout**: Maximum time to wait for SMTP connection (default: 30 seconds). - **Max concurrent connections**: Maximum simultaneous SMTP connections from the central cluster (default: 5). Enforced by the Notification Outbox dispatcher, which clamps each sweep's Email parallelism to `min(MaxParallelDeliveries, MaxConcurrentConnections)` for the SMTP transport (a non-positive value applies no clamp). -- **Retry settings**: Max retry count, fixed time between retries. The Notification Outbox reuses these for delivery retry of transient failures. +- **Retry settings**: Max retry count, fixed time between retries. The Notification Outbox reuses these for delivery retry of transient failures. Set via CLI `notification smtp create|update --max-retries/--retry-delay-seconds` (also `--connection-timeout-seconds`/`--max-concurrent-connections`) or the Central UI `/notifications/smtp` form; omitted values are preserved on update and negatives are refused. A zero value means the outbox fallback (10 retries / 1-minute delay, clamped with a Warning); the UI pre-fills 10 / 60 s on a new row so the policy is explicit (#149). - **Transport**: The submission mechanism — `Smtp` (default) or `Ews`. Null/empty means `Smtp`, so every pre-existing row keeps its behavior. See EWS Transport below. ### EWS Transport (on-prem Exchange) diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/NotificationCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/NotificationCommands.cs index 3ceff78d..321d3117 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/NotificationCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/NotificationCommands.cs @@ -181,13 +181,16 @@ public static class NotificationCommands var createCmd = new Command("create") { Description = "Create SMTP configuration" }; foreach (var option in new Option[] { SmtpServerOption, SmtpPortOption, SmtpAuthModeOption, SmtpFromOption, SmtpTlsModeOption, - SmtpCredentialsOption, SmtpOAuth2AuthorityOption, SmtpOAuth2ScopeOption, SmtpTransportOption }) createCmd.Add(option); + SmtpCredentialsOption, SmtpOAuth2AuthorityOption, SmtpOAuth2ScopeOption, SmtpTransportOption, + SmtpTimeoutOption, SmtpMaxConcurrentOption, SmtpMaxRetriesOption, SmtpRetryDelayOption }) createCmd.Add(option); ValueSourceOptions.AddFileOptions(createCmd, (SmtpCredentialsOption, SmtpCredentialsFileOption, false)); createCmd.SetAction(async result => await CommandHelpers.ExecuteCommandAsync(result, urlOption, formatOption, usernameOption, passwordOption, new CreateSmtpConfigCommand(result.GetValue(SmtpServerOption)!, result.GetValue(SmtpPortOption), result.GetValue(SmtpAuthModeOption)!, result.GetValue(SmtpFromOption)!, result.GetValue(SmtpTlsModeOption), ValueSourceOptions.GetValue(result, SmtpCredentialsOption, SmtpCredentialsFileOption), - result.GetValue(SmtpOAuth2AuthorityOption), result.GetValue(SmtpOAuth2ScopeOption), result.GetValue(SmtpTransportOption)))); + result.GetValue(SmtpOAuth2AuthorityOption), result.GetValue(SmtpOAuth2ScopeOption), result.GetValue(SmtpTransportOption), + result.GetValue(SmtpTimeoutOption), result.GetValue(SmtpMaxConcurrentOption), result.GetValue(SmtpMaxRetriesOption), + SmtpRetryDelay(result)))); group.Add(createCmd); var updateCmd = new Command("update") { Description = "Update SMTP configuration" }; @@ -201,6 +204,10 @@ public static class NotificationCommands updateCmd.Add(SmtpOAuth2AuthorityOption); updateCmd.Add(SmtpOAuth2ScopeOption); updateCmd.Add(SmtpTransportOption); + updateCmd.Add(SmtpTimeoutOption); + updateCmd.Add(SmtpMaxConcurrentOption); + updateCmd.Add(SmtpMaxRetriesOption); + updateCmd.Add(SmtpRetryDelayOption); ValueSourceOptions.AddFileOptions(updateCmd, (SmtpCredentialsOption, SmtpCredentialsFileOption, false)); updateCmd.SetAction(async (ParseResult result) => { @@ -250,6 +257,16 @@ public static class NotificationCommands private static readonly Option SmtpTransportOption = CreateTransportOption(); + // Delivery policy (#149). Zero means "use the outbox/options fallback", so the + // floor is 0 for every field; omission preserves on update. + private static readonly Option SmtpTimeoutOption = PolicyOption("--connection-timeout-seconds", "SMTP connect timeout in seconds (zero uses the NotificationService fallback; unused under Ews)", 0); + private static readonly Option SmtpMaxConcurrentOption = PolicyOption("--max-concurrent-connections", "Email delivery parallelism cap (zero = no per-config cap; unused under Ews)", 0); + private static readonly Option SmtpMaxRetriesOption = PolicyOption("--max-retries", "Retry count for transient failures before parking (zero uses the outbox fallback of 10)", 0); + private static readonly Option SmtpRetryDelayOption = PolicyOption("--retry-delay-seconds", "Retry delay in seconds (zero uses the outbox fallback of 60)", 0); + + private static TimeSpan? SmtpRetryDelay(ParseResult result) => + result.GetValue(SmtpRetryDelayOption) is { } seconds ? TimeSpan.FromSeconds(seconds) : null; + private static Option CreateTransportOption() { var option = new Option("--transport") @@ -275,8 +292,8 @@ public static class NotificationCommands /// /// Builds the from a parsed smtp update /// invocation. The optional --tls-mode / --credentials / - /// --oauth2-authority / --oauth2-scope / --transport flags map to - /// null when omitted so the server-side handler preserves the existing values. + /// --oauth2-authority / --oauth2-scope / --transport and the four + /// delivery-policy flags map to null when omitted so the server-side handler preserves the existing values. /// /// The parsed command-line result from the smtp update invocation. /// An populated from the parsed result. @@ -292,7 +309,9 @@ public static class NotificationCommands var oauth2Authority = result.GetValue(SmtpOAuth2AuthorityOption); var oauth2Scope = result.GetValue(SmtpOAuth2ScopeOption); var transport = result.GetValue(SmtpTransportOption); - return new UpdateSmtpConfigCommand(id, server, port, authMode, from, tlsMode, credentials, oauth2Authority, oauth2Scope, transport); + return new UpdateSmtpConfigCommand(id, server, port, authMode, from, tlsMode, credentials, oauth2Authority, oauth2Scope, transport, + result.GetValue(SmtpTimeoutOption), result.GetValue(SmtpMaxConcurrentOption), result.GetValue(SmtpMaxRetriesOption), + SmtpRetryDelay(result)); } private static Command BuildSms(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) @@ -347,11 +366,11 @@ public static class NotificationCommands return group; } - private static readonly Option SmsTimeoutOption = SmsPolicyOption("--connection-timeout-seconds", "Connection timeout in seconds", 1); - private static readonly Option SmsMaxRetriesOption = SmsPolicyOption("--max-retries", "Retry count (zero uses the outbox fallback)", 0); - private static readonly Option SmsRetryDelayOption = SmsPolicyOption("--retry-delay-seconds", "Retry delay in seconds (zero uses the outbox fallback)", 0); + private static readonly Option SmsTimeoutOption = PolicyOption("--connection-timeout-seconds", "Connection timeout in seconds", 1); + private static readonly Option SmsMaxRetriesOption = PolicyOption("--max-retries", "Retry count (zero uses the outbox fallback)", 0); + private static readonly Option SmsRetryDelayOption = PolicyOption("--retry-delay-seconds", "Retry delay in seconds (zero uses the outbox fallback)", 0); - private static Option SmsPolicyOption(string name, string description, int minimum) + private static Option PolicyOption(string name, string description, int minimum) { var option = new Option(name) { Description = description + "; omission preserves updates or uses create defaults" }; option.Validators.Add(result => diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md index 2abc1141..73e2fa41 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md @@ -1639,7 +1639,7 @@ scadabridge --url notification smtp list Create a new SMTP configuration. Requires Administrator access. ```sh -scadabridge notification smtp create --server --port --auth-mode --from-address [--tls-mode ] [--credentials | --credentials-file ] [--oauth2-authority ] [--oauth2-scope ] [--transport ] +scadabridge notification smtp create --server --port --auth-mode --from-address [--tls-mode ] [--credentials | --credentials-file ] [--oauth2-authority ] [--oauth2-scope ] [--transport ] [--max-retries ] [--retry-delay-seconds ] [--connection-timeout-seconds ] [--max-concurrent-connections ] ``` Uses the same settings as `smtp update`, without `--id`. This sends the distinct create contract; update with ID zero is not a creation operation. The server validates transport/authentication compatibility. @@ -1649,7 +1649,7 @@ Uses the same settings as `smtp update`, without `--id`. This sends the distinct Update the SMTP configuration. ```sh -scadabridge --url notification smtp update --id --server --port --auth-mode --from-address [--tls-mode ] [--credentials | --credentials-file ] [--oauth2-authority ] [--oauth2-scope ] [--transport ] +scadabridge --url notification smtp update --id --server --port --auth-mode --from-address [--tls-mode ] [--credentials | --credentials-file ] [--oauth2-authority ] [--oauth2-scope ] [--transport ] [--max-retries ] [--retry-delay-seconds ] [--connection-timeout-seconds ] [--max-concurrent-connections ] ``` | Option | Required | Description | @@ -1665,6 +1665,10 @@ scadabridge --url notification smtp update --id --server -- | `--oauth2-authority` | no | OAuth2 token-endpoint URL — a `{tenant}` placeholder is substituted from the credential (preserves existing / Microsoft 365 default if omitted; OAuth2 auth mode only) | | `--oauth2-scope` | no | OAuth2 scope requested from the token endpoint (preserves existing / Microsoft 365 default if omitted; OAuth2 auth mode only) | | `--transport` | no | Email transport: `Smtp` or `Ews` (preserves existing if omitted) | +| `--max-retries` | no | Transient-failure retries before the notification is parked (`0` = outbox fallback of 10; preserves existing if omitted) | +| `--retry-delay-seconds` | no | Fixed delay between retries in seconds (`0` = outbox fallback of 60; preserves existing if omitted) | +| `--connection-timeout-seconds` | no | SMTP connect timeout (`0` = NotificationService fallback; unused under Ews; preserves existing if omitted) | +| `--max-concurrent-connections` | no | Email delivery parallelism cap (`0` = no per-config cap; unused under Ews; preserves existing if omitted) | Under `--transport Ews`, `--server` carries the full EWS URL, `--auth-mode` must be `Basic`, and `--port` / `--tls-mode` are unused. diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/SmtpConfiguration.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/SmtpConfiguration.razor index c4a38dfd..2520883a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/SmtpConfiguration.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Notifications/SmtpConfiguration.razor @@ -94,6 +94,17 @@ @(string.IsNullOrWhiteSpace(smtp.OAuth2Scope) ? "(M365 default)" : smtp.OAuth2Scope) } +
Retries
+
@(smtp.MaxRetries > 0 ? smtp.MaxRetries.ToString() : "(default: 10)")
+
Retry Delay
+
@(smtp.RetryDelay > TimeSpan.Zero ? $"{smtp.RetryDelay.TotalSeconds:0} s" : "(default: 60 s)")
+ @if (!IsEws(smtp.Transport)) + { +
Connect Timeout
+
@(smtp.ConnectionTimeoutSeconds > 0 ? $"{smtp.ConnectionTimeoutSeconds} s" : "(default)")
+
Max Connections
+
@(smtp.MaxConcurrentConnections > 0 ? smtp.MaxConcurrentConnections.ToString() : "(no cap)")
+ } @@ -165,6 +176,28 @@
Scope requested from the token endpoint; leave blank for the Microsoft 365 default.
} +
+ + +
+
+ + +
+ @if (!IsEwsForm) + { +
+ + +
+
+ + +
+ } +
+
Transient failures are retried this many times, this far apart, before the notification is parked. 0 uses the built-in default (10 retries, 60 s; connect timeout from NotificationService options; no connection cap).
+
@if (_formError != null) {
@_formError
@@ -207,6 +240,10 @@ private string _fromAddress = string.Empty; private string? _oauth2Authority; private string? _oauth2Scope; + private int _maxRetries = 10; + private int _retryDelaySeconds = 60; + private int _connectionTimeoutSeconds; + private int _maxConcurrentConnections; private string? _formError; private ToastNotification _toast = default!; @@ -280,6 +317,12 @@ _fromAddress = string.Empty; _oauth2Authority = null; _oauth2Scope = null; + // New rows state the retry policy explicitly rather than relying on the + // outbox's clamp of a zero row to the same values (#149). + _maxRetries = 10; + _retryDelaySeconds = 60; + _connectionTimeoutSeconds = 0; + _maxConcurrentConnections = 0; _formError = null; _showForm = true; } @@ -297,6 +340,10 @@ _fromAddress = smtp.FromAddress; _oauth2Authority = smtp.OAuth2Authority; _oauth2Scope = smtp.OAuth2Scope; + _maxRetries = smtp.MaxRetries; + _retryDelaySeconds = (int)smtp.RetryDelay.TotalSeconds; + _connectionTimeoutSeconds = smtp.ConnectionTimeoutSeconds; + _maxConcurrentConnections = smtp.MaxConcurrentConnections; _formError = null; _showForm = true; } @@ -316,8 +363,15 @@ return; } - // This page writes through the repository, so the ManagementActor's EWS shape gate - // is not on this path — mirror its Host rule here (auth type is already forced to + if (_maxRetries < 0 || _retryDelaySeconds < 0 || _connectionTimeoutSeconds < 0 || _maxConcurrentConnections < 0) + { + _formError = "Retries, retry delay, connect timeout and max connections must not be negative."; + return; + } + + // The ManagementActor's EWS shape gate also runs on save (this page dispatches through + // ManagementActor.ExecuteConfigurationCommandAsync); mirror its Host rule here for an + // inline error (auth type is already forced to // Basic by the Transport setter) so an unusable row cannot be saved from the UI. if (IsEwsForm && (!Uri.TryCreate(_host.Trim(), UriKind.Absolute, out var ewsEndpoint) @@ -350,9 +404,11 @@ { await MutationServices.ExecuteConfigurationAsync(_editingSmtp is not null ? new UpdateSmtpConfigCommand(_editingSmtp.Id, _host.Trim(), _port, _authType, _fromAddress.Trim(), _tlsMode, - _credentials?.Trim() ?? "", NormalizeOptional(_oauth2Authority) ?? "", NormalizeOptional(_oauth2Scope) ?? "", _transport) + _credentials?.Trim() ?? "", NormalizeOptional(_oauth2Authority) ?? "", NormalizeOptional(_oauth2Scope) ?? "", _transport, + _connectionTimeoutSeconds, _maxConcurrentConnections, _maxRetries, TimeSpan.FromSeconds(_retryDelaySeconds)) : new CreateSmtpConfigCommand(_host.Trim(), _port, _authType, _fromAddress.Trim(), _tlsMode, - _credentials?.Trim(), NormalizeOptional(_oauth2Authority), NormalizeOptional(_oauth2Scope), _transport)); + _credentials?.Trim(), NormalizeOptional(_oauth2Authority), NormalizeOptional(_oauth2Scope), _transport, + _connectionTimeoutSeconds, _maxConcurrentConnections, _maxRetries, TimeSpan.FromSeconds(_retryDelaySeconds))); _showForm = false; _toast.ShowSuccess("SMTP configuration saved."); await LoadAsync(); diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/NotificationCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/NotificationCommands.cs index 15595d18..e3646396 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/NotificationCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/NotificationCommands.cs @@ -10,7 +10,9 @@ public record DeleteNotificationListCommand(int NotificationListId); public record ListSmtpConfigsCommand; // Transport is a trailing additive parameter (Smtp or Ews; null = preserve the // stored value, which is itself null for every pre-EWS row and means Smtp). -public record UpdateSmtpConfigCommand(int SmtpConfigId, string Server, int Port, string AuthMode, string FromAddress, string? TlsMode = null, string? Credentials = null, string? OAuth2Authority = null, string? OAuth2Scope = null, string? Transport = null); +// The four delivery-policy fields (#149) are trailing additive too: null = preserve +// on update / entity default on create; 0 = use the outbox/options fallback. +public record UpdateSmtpConfigCommand(int SmtpConfigId, string Server, int Port, string AuthMode, string FromAddress, string? TlsMode = null, string? Credentials = null, string? OAuth2Authority = null, string? OAuth2Scope = null, string? Transport = null, int? ConnectionTimeoutSeconds = null, int? MaxConcurrentConnections = null, int? MaxRetries = null, TimeSpan? RetryDelay = null); public record ListSmsConfigsCommand; // FromNumber is optional: a Twilio Messaging-Service-only config supplies MessagingServiceSid // instead. At-least-one-of (FromNumber, MessagingServiceSid) is validated at the CLI/UI boundary. @@ -23,8 +25,8 @@ public record AddNotificationRecipientCommand(int NotificationListId, string Nam /// Deletes one recipient without rewriting unrelated list membership. public record DeleteNotificationRecipientCommand(int RecipientId); /// Creates an email configuration using the update path's validation and secret projection. -public record CreateSmtpConfigCommand(string Server, int Port, string AuthMode, string FromAddress, string? TlsMode = null, string? Credentials = null, string? OAuth2Authority = null, string? OAuth2Scope = null, string? Transport = null) - : UpdateSmtpConfigCommand(0, Server, Port, AuthMode, FromAddress, TlsMode, Credentials, OAuth2Authority, OAuth2Scope, Transport); +public record CreateSmtpConfigCommand(string Server, int Port, string AuthMode, string FromAddress, string? TlsMode = null, string? Credentials = null, string? OAuth2Authority = null, string? OAuth2Scope = null, string? Transport = null, int? ConnectionTimeoutSeconds = null, int? MaxConcurrentConnections = null, int? MaxRetries = null, TimeSpan? RetryDelay = null) + : UpdateSmtpConfigCommand(0, Server, Port, AuthMode, FromAddress, TlsMode, Credentials, OAuth2Authority, OAuth2Scope, Transport, ConnectionTimeoutSeconds, MaxConcurrentConnections, MaxRetries, RetryDelay); /// Creates an SMS configuration using the same validation as updates. public record CreateSmsConfigCommand(string AccountSid, string? FromNumber, string? MessagingServiceSid = null, string? ApiBaseUrl = null, string? AuthToken = null, int? ConnectionTimeoutSeconds = null, int? MaxRetries = null, TimeSpan? RetryDelay = null) : UpdateSmsConfigCommand(0, AccountSid, FromNumber, MessagingServiceSid, ApiBaseUrl, AuthToken, ConnectionTimeoutSeconds, MaxRetries, RetryDelay); diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs index 45cda871..923e6e47 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs @@ -2753,6 +2753,17 @@ public class ManagementActor : ReceiveActor // Preserve-if-null for the transport too: an omitted value keeps the stored // one (null on every pre-EWS row, which means SMTP). if (cmd.Transport is not null) config.Transport = cmd.Transport; + // Delivery policy (#149): preserve-if-null, 0 = the outbox/options fallback. + // Negative values are refused here rather than silently clamped downstream. + if (cmd.ConnectionTimeoutSeconds is { } timeout) config.ConnectionTimeoutSeconds = RequireNonNegative(timeout, "ConnectionTimeoutSeconds"); + if (cmd.MaxConcurrentConnections is { } concurrency) config.MaxConcurrentConnections = RequireNonNegative(concurrency, "MaxConcurrentConnections"); + if (cmd.MaxRetries is { } retries) config.MaxRetries = RequireNonNegative(retries, "MaxRetries"); + if (cmd.RetryDelay is { } retryDelay) + { + if (retryDelay < TimeSpan.Zero) + throw new ManagementCommandException("RetryDelay must not be negative."); + config.RetryDelay = retryDelay; + } ValidateSmtpConfigTransportShape(config); if (cmd is CreateSmtpConfigCommand) await repo.AddSmtpConfigurationAsync(config); else await repo.UpdateSmtpConfigurationAsync(config); @@ -2765,6 +2776,9 @@ public class ManagementActor : ReceiveActor return publicShape; } + private static int RequireNonNegative(int value, string field) => + value >= 0 ? value : throw new ManagementCommandException($"{field} must not be negative."); + /// /// Write-path gate for the email transport: validates the EFFECTIVE /// post-assignment state of an SmtpConfiguration so an operator cannot persist a diff --git a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/Commands/SmtpUpdateCommandTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/Commands/SmtpUpdateCommandTests.cs index 8aad8e6c..7b3717df 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/Commands/SmtpUpdateCommandTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/Commands/SmtpUpdateCommandTests.cs @@ -153,4 +153,55 @@ public class SmtpUpdateCommandTests Assert.False(tls.Required, "--tls-mode must be optional (preserve-if-omitted)."); Assert.False(creds.Required, "--credentials must be optional (preserve-if-omitted)."); } + /// #149: the delivery-policy flags parse onto the command (retry delay in seconds). + [Fact] + public void Update_WithDeliveryPolicyFlags_ProducesCommandCarryingThem() + { + var parse = ParseUpdate( + "--id", "1", "--server", "https://mail.example.com/ews/exchange.asmx", "--port", "587", + "--auth-mode", "Basic", "--from-address", "noreply@example.com", + "--max-retries", "10", "--retry-delay-seconds", "60", + "--connection-timeout-seconds", "20", "--max-concurrent-connections", "0"); + + Assert.Empty(parse.Errors); + var cmd = NotificationCommands.BuildUpdateSmtpConfigCommand(parse); + + Assert.Equal(10, cmd.MaxRetries); + Assert.Equal(TimeSpan.FromSeconds(60), cmd.RetryDelay); + Assert.Equal(20, cmd.ConnectionTimeoutSeconds); + Assert.Equal(0, cmd.MaxConcurrentConnections); + } + + /// #149: omitted delivery-policy flags map to null so the server preserves the stored values. + [Fact] + public void Update_WithoutDeliveryPolicyFlags_ProducesNulls() + { + var parse = ParseUpdate( + "--id", "1", "--server", "smtp.example.com", "--port", "587", + "--auth-mode", "Basic", "--from-address", "noreply@example.com"); + + Assert.Empty(parse.Errors); + var cmd = NotificationCommands.BuildUpdateSmtpConfigCommand(parse); + + Assert.Null(cmd.MaxRetries); + Assert.Null(cmd.RetryDelay); + Assert.Null(cmd.ConnectionTimeoutSeconds); + Assert.Null(cmd.MaxConcurrentConnections); + } + + /// #149: a negative delivery-policy flag is a parse error. + [Theory] + [InlineData("--max-retries")] + [InlineData("--retry-delay-seconds")] + [InlineData("--connection-timeout-seconds")] + [InlineData("--max-concurrent-connections")] + public void Update_NegativeDeliveryPolicyFlag_IsRejected(string flag) + { + var parse = ParseUpdate( + "--id", "1", "--server", "smtp.example.com", "--port", "587", + "--auth-mode", "Basic", "--from-address", "noreply@example.com", + flag, "-1"); + + Assert.NotEmpty(parse.Errors); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SmtpConfigurationPageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SmtpConfigurationPageTests.cs index 72c8d291..d5fed7d2 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SmtpConfigurationPageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/SmtpConfigurationPageTests.cs @@ -182,7 +182,7 @@ public class SmtpConfigurationPageTests : BunitContext SelectWithOption(cut, "Ews").Change("Ews"); // Port input, TLS select and Auth Type select are all gone under EWS. - Assert.Empty(cut.FindAll("input[type=number]")); + Assert.Empty(cut.FindAll("input[type=number][max=\"65535\"]")); Assert.False(HasSelectWithOption(cut, "StartTLS")); Assert.False(HasSelectWithOption(cut, "OAuth2")); Assert.Contains("EWS URL", cut.Markup); @@ -212,7 +212,7 @@ public class SmtpConfigurationPageTests : BunitContext SelectWithOption(cut, "Ews").Change("Smtp"); // Port and TLS controls are back... - Assert.Single(cut.FindAll("input[type=number]")); + Assert.Single(cut.FindAll("input[type=number][max=\"65535\"]")); Assert.True(HasSelectWithOption(cut, "StartTLS")); Assert.True(HasSelectWithOption(cut, "OAuth2")); diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs index c2555e32..a754a4f9 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementActorTests.cs @@ -3356,6 +3356,107 @@ public class ManagementActorTests : TestKit, IDisposable Assert.Contains("username:password", response.Error); } + private (INotificationRepository Repo, Commons.Entities.Notifications.SmtpConfiguration Existing) SmtpPolicyFixture() + { + var notifRepo = Substitute.For(); + var existing = new Commons.Entities.Notifications.SmtpConfiguration( + "smtp.example.com", "Basic", "ops@example.com") + { + Id = 1, + Port = 587, + ConnectionTimeoutSeconds = 15, + MaxConcurrentConnections = 3, + MaxRetries = 4, + RetryDelay = TimeSpan.FromSeconds(30), + }; + notifRepo.GetSmtpConfigurationByIdAsync(1, Arg.Any()).Returns(existing); + _services.AddScoped(_ => notifRepo); + return (notifRepo, existing); + } + + /// #149: the delivery-policy fields on an update are applied to the stored row. + [Fact] + public void UpdateSmtpConfig_AppliesDeliveryPolicyFields() + { + var (_, existing) = SmtpPolicyFixture(); + var actor = CreateActor(); + + actor.Tell(Envelope( + new UpdateSmtpConfigCommand(1, "smtp.example.com", 587, "Basic", "ops@example.com", + ConnectionTimeoutSeconds: 20, MaxConcurrentConnections: 0, MaxRetries: 10, RetryDelay: TimeSpan.FromMinutes(1)), + "Administrator")); + + ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal(20, existing.ConnectionTimeoutSeconds); + Assert.Equal(0, existing.MaxConcurrentConnections); + Assert.Equal(10, existing.MaxRetries); + Assert.Equal(TimeSpan.FromMinutes(1), existing.RetryDelay); + } + + /// #149: an update that omits the delivery-policy fields preserves the stored values. + [Fact] + public void UpdateSmtpConfig_WithoutDeliveryPolicyFields_PreservesExistingValues() + { + var (_, existing) = SmtpPolicyFixture(); + var actor = CreateActor(); + + actor.Tell(Envelope( + new UpdateSmtpConfigCommand(1, "smtp.example.com", 587, "Basic", "ops@example.com"), + "Administrator")); + + ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Equal(15, existing.ConnectionTimeoutSeconds); + Assert.Equal(3, existing.MaxConcurrentConnections); + Assert.Equal(4, existing.MaxRetries); + Assert.Equal(TimeSpan.FromSeconds(30), existing.RetryDelay); + } + + /// #149: a negative delivery-policy value is refused and nothing is saved. + [Theory] + [InlineData(-1, null, null, null, "ConnectionTimeoutSeconds")] + [InlineData(null, -1, null, null, "MaxConcurrentConnections")] + [InlineData(null, null, -1, null, "MaxRetries")] + [InlineData(null, null, null, -1, "RetryDelay")] + public void UpdateSmtpConfig_NegativeDeliveryPolicyValue_ReturnsManagementError( + int? timeout, int? concurrency, int? retries, int? delaySeconds, string field) + { + var (repo, _) = SmtpPolicyFixture(); + var actor = CreateActor(); + + actor.Tell(Envelope( + new UpdateSmtpConfigCommand(1, "smtp.example.com", 587, "Basic", "ops@example.com", + ConnectionTimeoutSeconds: timeout, MaxConcurrentConnections: concurrency, MaxRetries: retries, + RetryDelay: delaySeconds is { } d ? TimeSpan.FromSeconds(d) : null), + "Administrator")); + + var response = ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.Contains(field, response.Error); + repo.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + /// #149: a create carries the delivery-policy fields onto the new row. + [Fact] + public void CreateSmtpConfig_CarriesDeliveryPolicyFields() + { + var notifRepo = Substitute.For(); + Commons.Entities.Notifications.SmtpConfiguration? added = null; + notifRepo.AddSmtpConfigurationAsync(Arg.Do(c => added = c), Arg.Any()) + .Returns(Task.CompletedTask); + _services.AddScoped(_ => notifRepo); + var actor = CreateActor(); + + actor.Tell(Envelope( + new CreateSmtpConfigCommand("smtp.example.com", 587, "Basic", "ops@example.com", + MaxRetries: 10, RetryDelay: TimeSpan.FromMinutes(1)), + "Administrator")); + + ExpectMsg(TimeSpan.FromSeconds(5)); + Assert.NotNull(added); + Assert.Equal(10, added!.MaxRetries); + Assert.Equal(TimeSpan.FromMinutes(1), added.RetryDelay); + Assert.Equal(0, added.ConnectionTimeoutSeconds); + } + /// Verifies that update smtp config, when with null transport, preserves existing value. [Fact] public void UpdateSmtpConfig_WithNullTransport_PreservesExistingValue()