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.
This commit is contained in:
@@ -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`).
|
- **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).
|
- **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).
|
- **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.
|
- **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)
|
### EWS Transport (on-prem Exchange)
|
||||||
|
|||||||
@@ -181,13 +181,16 @@ public static class NotificationCommands
|
|||||||
|
|
||||||
var createCmd = new Command("create") { Description = "Create SMTP configuration" };
|
var createCmd = new Command("create") { Description = "Create SMTP configuration" };
|
||||||
foreach (var option in new Option[] { SmtpServerOption, SmtpPortOption, SmtpAuthModeOption, SmtpFromOption, SmtpTlsModeOption,
|
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));
|
ValueSourceOptions.AddFileOptions(createCmd, (SmtpCredentialsOption, SmtpCredentialsFileOption, false));
|
||||||
createCmd.SetAction(async result => await CommandHelpers.ExecuteCommandAsync(result, urlOption, formatOption, usernameOption, passwordOption,
|
createCmd.SetAction(async result => await CommandHelpers.ExecuteCommandAsync(result, urlOption, formatOption, usernameOption, passwordOption,
|
||||||
new CreateSmtpConfigCommand(result.GetValue(SmtpServerOption)!, result.GetValue(SmtpPortOption), result.GetValue(SmtpAuthModeOption)!,
|
new CreateSmtpConfigCommand(result.GetValue(SmtpServerOption)!, result.GetValue(SmtpPortOption), result.GetValue(SmtpAuthModeOption)!,
|
||||||
result.GetValue(SmtpFromOption)!, result.GetValue(SmtpTlsModeOption),
|
result.GetValue(SmtpFromOption)!, result.GetValue(SmtpTlsModeOption),
|
||||||
ValueSourceOptions.GetValue(result, SmtpCredentialsOption, SmtpCredentialsFileOption),
|
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);
|
group.Add(createCmd);
|
||||||
|
|
||||||
var updateCmd = new Command("update") { Description = "Update SMTP configuration" };
|
var updateCmd = new Command("update") { Description = "Update SMTP configuration" };
|
||||||
@@ -201,6 +204,10 @@ public static class NotificationCommands
|
|||||||
updateCmd.Add(SmtpOAuth2AuthorityOption);
|
updateCmd.Add(SmtpOAuth2AuthorityOption);
|
||||||
updateCmd.Add(SmtpOAuth2ScopeOption);
|
updateCmd.Add(SmtpOAuth2ScopeOption);
|
||||||
updateCmd.Add(SmtpTransportOption);
|
updateCmd.Add(SmtpTransportOption);
|
||||||
|
updateCmd.Add(SmtpTimeoutOption);
|
||||||
|
updateCmd.Add(SmtpMaxConcurrentOption);
|
||||||
|
updateCmd.Add(SmtpMaxRetriesOption);
|
||||||
|
updateCmd.Add(SmtpRetryDelayOption);
|
||||||
ValueSourceOptions.AddFileOptions(updateCmd, (SmtpCredentialsOption, SmtpCredentialsFileOption, false));
|
ValueSourceOptions.AddFileOptions(updateCmd, (SmtpCredentialsOption, SmtpCredentialsFileOption, false));
|
||||||
updateCmd.SetAction(async (ParseResult result) =>
|
updateCmd.SetAction(async (ParseResult result) =>
|
||||||
{
|
{
|
||||||
@@ -250,6 +257,16 @@ public static class NotificationCommands
|
|||||||
|
|
||||||
private static readonly Option<string?> SmtpTransportOption = CreateTransportOption();
|
private static readonly Option<string?> 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<int?> SmtpTimeoutOption = PolicyOption("--connection-timeout-seconds", "SMTP connect timeout in seconds (zero uses the NotificationService fallback; unused under Ews)", 0);
|
||||||
|
private static readonly Option<int?> SmtpMaxConcurrentOption = PolicyOption("--max-concurrent-connections", "Email delivery parallelism cap (zero = no per-config cap; unused under Ews)", 0);
|
||||||
|
private static readonly Option<int?> SmtpMaxRetriesOption = PolicyOption("--max-retries", "Retry count for transient failures before parking (zero uses the outbox fallback of 10)", 0);
|
||||||
|
private static readonly Option<int?> 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<string?> CreateTransportOption()
|
private static Option<string?> CreateTransportOption()
|
||||||
{
|
{
|
||||||
var option = new Option<string?>("--transport")
|
var option = new Option<string?>("--transport")
|
||||||
@@ -275,8 +292,8 @@ public static class NotificationCommands
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Builds the <see cref="UpdateSmtpConfigCommand"/> from a parsed <c>smtp update</c>
|
/// Builds the <see cref="UpdateSmtpConfigCommand"/> from a parsed <c>smtp update</c>
|
||||||
/// invocation. The optional <c>--tls-mode</c> / <c>--credentials</c> /
|
/// invocation. The optional <c>--tls-mode</c> / <c>--credentials</c> /
|
||||||
/// <c>--oauth2-authority</c> / <c>--oauth2-scope</c> / <c>--transport</c> flags map to
|
/// <c>--oauth2-authority</c> / <c>--oauth2-scope</c> / <c>--transport</c> and the four
|
||||||
/// null when omitted so the server-side handler preserves the existing values.
|
/// delivery-policy flags map to null when omitted so the server-side handler preserves the existing values.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="result">The parsed command-line result from the <c>smtp update</c> invocation.</param>
|
/// <param name="result">The parsed command-line result from the <c>smtp update</c> invocation.</param>
|
||||||
/// <returns>An <see cref="UpdateSmtpConfigCommand"/> populated from the parsed result.</returns>
|
/// <returns>An <see cref="UpdateSmtpConfigCommand"/> populated from the parsed result.</returns>
|
||||||
@@ -292,7 +309,9 @@ public static class NotificationCommands
|
|||||||
var oauth2Authority = result.GetValue(SmtpOAuth2AuthorityOption);
|
var oauth2Authority = result.GetValue(SmtpOAuth2AuthorityOption);
|
||||||
var oauth2Scope = result.GetValue(SmtpOAuth2ScopeOption);
|
var oauth2Scope = result.GetValue(SmtpOAuth2ScopeOption);
|
||||||
var transport = result.GetValue(SmtpTransportOption);
|
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<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
private static Command BuildSms(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
|
||||||
@@ -347,11 +366,11 @@ public static class NotificationCommands
|
|||||||
return group;
|
return group;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static readonly Option<int?> SmsTimeoutOption = SmsPolicyOption("--connection-timeout-seconds", "Connection timeout in seconds", 1);
|
private static readonly Option<int?> SmsTimeoutOption = PolicyOption("--connection-timeout-seconds", "Connection timeout in seconds", 1);
|
||||||
private static readonly Option<int?> SmsMaxRetriesOption = SmsPolicyOption("--max-retries", "Retry count (zero uses the outbox fallback)", 0);
|
private static readonly Option<int?> SmsMaxRetriesOption = PolicyOption("--max-retries", "Retry count (zero uses the outbox fallback)", 0);
|
||||||
private static readonly Option<int?> SmsRetryDelayOption = SmsPolicyOption("--retry-delay-seconds", "Retry delay in seconds (zero uses the outbox fallback)", 0);
|
private static readonly Option<int?> SmsRetryDelayOption = PolicyOption("--retry-delay-seconds", "Retry delay in seconds (zero uses the outbox fallback)", 0);
|
||||||
|
|
||||||
private static Option<int?> SmsPolicyOption(string name, string description, int minimum)
|
private static Option<int?> PolicyOption(string name, string description, int minimum)
|
||||||
{
|
{
|
||||||
var option = new Option<int?>(name) { Description = description + "; omission preserves updates or uses create defaults" };
|
var option = new Option<int?>(name) { Description = description + "; omission preserves updates or uses create defaults" };
|
||||||
option.Validators.Add(result =>
|
option.Validators.Add(result =>
|
||||||
|
|||||||
@@ -1639,7 +1639,7 @@ scadabridge --url <url> notification smtp list
|
|||||||
Create a new SMTP configuration. Requires Administrator access.
|
Create a new SMTP configuration. Requires Administrator access.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
scadabridge notification smtp create --server <host> --port <int> --auth-mode <mode> --from-address <email> [--tls-mode <mode>] [--credentials <value> | --credentials-file <path|->] [--oauth2-authority <url>] [--oauth2-scope <scope>] [--transport <Smtp|Ews>]
|
scadabridge notification smtp create --server <host> --port <int> --auth-mode <mode> --from-address <email> [--tls-mode <mode>] [--credentials <value> | --credentials-file <path|->] [--oauth2-authority <url>] [--oauth2-scope <scope>] [--transport <Smtp|Ews>] [--max-retries <int>] [--retry-delay-seconds <int>] [--connection-timeout-seconds <int>] [--max-concurrent-connections <int>]
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
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.
|
Update the SMTP configuration.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
scadabridge --url <url> notification smtp update --id <int> --server <string> --port <int> --auth-mode <string> --from-address <string> [--tls-mode <string>] [--credentials <string> | --credentials-file <path|->] [--oauth2-authority <string>] [--oauth2-scope <string>] [--transport <string>]
|
scadabridge --url <url> notification smtp update --id <int> --server <string> --port <int> --auth-mode <string> --from-address <string> [--tls-mode <string>] [--credentials <string> | --credentials-file <path|->] [--oauth2-authority <string>] [--oauth2-scope <string>] [--transport <string>] [--max-retries <int>] [--retry-delay-seconds <int>] [--connection-timeout-seconds <int>] [--max-concurrent-connections <int>]
|
||||||
```
|
```
|
||||||
|
|
||||||
| Option | Required | Description |
|
| Option | Required | Description |
|
||||||
@@ -1665,6 +1665,10 @@ scadabridge --url <url> notification smtp update --id <int> --server <string> --
|
|||||||
| `--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-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) |
|
| `--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) |
|
| `--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`,
|
Under `--transport Ews`, `--server` carries the full EWS URL, `--auth-mode` must be `Basic`,
|
||||||
and `--port` / `--tls-mode` are unused.
|
and `--port` / `--tls-mode` are unused.
|
||||||
|
|||||||
+60
-4
@@ -94,6 +94,17 @@
|
|||||||
<span class="cell-clip cell-clip-lg" title="@smtp.OAuth2Scope">@(string.IsNullOrWhiteSpace(smtp.OAuth2Scope) ? "(M365 default)" : smtp.OAuth2Scope)</span>
|
<span class="cell-clip cell-clip-lg" title="@smtp.OAuth2Scope">@(string.IsNullOrWhiteSpace(smtp.OAuth2Scope) ? "(M365 default)" : smtp.OAuth2Scope)</span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
<div class="col-md-4 text-muted">Retries</div>
|
||||||
|
<div class="col-md-8">@(smtp.MaxRetries > 0 ? smtp.MaxRetries.ToString() : "(default: 10)")</div>
|
||||||
|
<div class="col-md-4 text-muted">Retry Delay</div>
|
||||||
|
<div class="col-md-8">@(smtp.RetryDelay > TimeSpan.Zero ? $"{smtp.RetryDelay.TotalSeconds:0} s" : "(default: 60 s)")</div>
|
||||||
|
@if (!IsEws(smtp.Transport))
|
||||||
|
{
|
||||||
|
<div class="col-md-4 text-muted">Connect Timeout</div>
|
||||||
|
<div class="col-md-8">@(smtp.ConnectionTimeoutSeconds > 0 ? $"{smtp.ConnectionTimeoutSeconds} s" : "(default)")</div>
|
||||||
|
<div class="col-md-4 text-muted">Max Connections</div>
|
||||||
|
<div class="col-md-8">@(smtp.MaxConcurrentConnections > 0 ? smtp.MaxConcurrentConnections.ToString() : "(no cap)")</div>
|
||||||
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -165,6 +176,28 @@
|
|||||||
<div class="form-text" id="@($"{_helpScope}-2")">Scope requested from the token endpoint; leave blank for the Microsoft 365 default.</div>
|
<div class="form-text" id="@($"{_helpScope}-2")">Scope requested from the token endpoint; leave blank for the Microsoft 365 default.</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label" for="@($"{_fieldScope}-field-10")">Max Retries</label>
|
||||||
|
<input aria-describedby="@($"{_helpScope}-3")" id="@($"{_fieldScope}-field-10")" type="number" class="form-control" @bind="_maxRetries" min="0" />
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label" for="@($"{_fieldScope}-field-11")">Retry Delay (s)</label>
|
||||||
|
<input aria-describedby="@($"{_helpScope}-3")" id="@($"{_fieldScope}-field-11")" type="number" class="form-control" @bind="_retryDelaySeconds" min="0" />
|
||||||
|
</div>
|
||||||
|
@if (!IsEwsForm)
|
||||||
|
{
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label" for="@($"{_fieldScope}-field-12")">Connect Timeout (s)</label>
|
||||||
|
<input aria-describedby="@($"{_helpScope}-3")" id="@($"{_fieldScope}-field-12")" type="number" class="form-control" @bind="_connectionTimeoutSeconds" min="0" />
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label" for="@($"{_fieldScope}-field-13")">Max Connections</label>
|
||||||
|
<input aria-describedby="@($"{_helpScope}-3")" id="@($"{_fieldScope}-field-13")" type="number" class="form-control" @bind="_maxConcurrentConnections" min="0" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
<div class="col-12">
|
||||||
|
<div class="form-text" id="@($"{_helpScope}-3")">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).</div>
|
||||||
|
</div>
|
||||||
@if (_formError != null)
|
@if (_formError != null)
|
||||||
{
|
{
|
||||||
<div class="col-12"><div class="text-danger small">@_formError</div></div>
|
<div class="col-12"><div class="text-danger small">@_formError</div></div>
|
||||||
@@ -207,6 +240,10 @@
|
|||||||
private string _fromAddress = string.Empty;
|
private string _fromAddress = string.Empty;
|
||||||
private string? _oauth2Authority;
|
private string? _oauth2Authority;
|
||||||
private string? _oauth2Scope;
|
private string? _oauth2Scope;
|
||||||
|
private int _maxRetries = 10;
|
||||||
|
private int _retryDelaySeconds = 60;
|
||||||
|
private int _connectionTimeoutSeconds;
|
||||||
|
private int _maxConcurrentConnections;
|
||||||
private string? _formError;
|
private string? _formError;
|
||||||
|
|
||||||
private ToastNotification _toast = default!;
|
private ToastNotification _toast = default!;
|
||||||
@@ -280,6 +317,12 @@
|
|||||||
_fromAddress = string.Empty;
|
_fromAddress = string.Empty;
|
||||||
_oauth2Authority = null;
|
_oauth2Authority = null;
|
||||||
_oauth2Scope = 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;
|
_formError = null;
|
||||||
_showForm = true;
|
_showForm = true;
|
||||||
}
|
}
|
||||||
@@ -297,6 +340,10 @@
|
|||||||
_fromAddress = smtp.FromAddress;
|
_fromAddress = smtp.FromAddress;
|
||||||
_oauth2Authority = smtp.OAuth2Authority;
|
_oauth2Authority = smtp.OAuth2Authority;
|
||||||
_oauth2Scope = smtp.OAuth2Scope;
|
_oauth2Scope = smtp.OAuth2Scope;
|
||||||
|
_maxRetries = smtp.MaxRetries;
|
||||||
|
_retryDelaySeconds = (int)smtp.RetryDelay.TotalSeconds;
|
||||||
|
_connectionTimeoutSeconds = smtp.ConnectionTimeoutSeconds;
|
||||||
|
_maxConcurrentConnections = smtp.MaxConcurrentConnections;
|
||||||
_formError = null;
|
_formError = null;
|
||||||
_showForm = true;
|
_showForm = true;
|
||||||
}
|
}
|
||||||
@@ -316,8 +363,15 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// This page writes through the repository, so the ManagementActor's EWS shape gate
|
if (_maxRetries < 0 || _retryDelaySeconds < 0 || _connectionTimeoutSeconds < 0 || _maxConcurrentConnections < 0)
|
||||||
// is not on this path — mirror its Host rule here (auth type is already forced to
|
{
|
||||||
|
_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.
|
// Basic by the Transport setter) so an unusable row cannot be saved from the UI.
|
||||||
if (IsEwsForm
|
if (IsEwsForm
|
||||||
&& (!Uri.TryCreate(_host.Trim(), UriKind.Absolute, out var ewsEndpoint)
|
&& (!Uri.TryCreate(_host.Trim(), UriKind.Absolute, out var ewsEndpoint)
|
||||||
@@ -350,9 +404,11 @@
|
|||||||
{
|
{
|
||||||
await MutationServices.ExecuteConfigurationAsync(_editingSmtp is not null
|
await MutationServices.ExecuteConfigurationAsync(_editingSmtp is not null
|
||||||
? new UpdateSmtpConfigCommand(_editingSmtp.Id, _host.Trim(), _port, _authType, _fromAddress.Trim(), _tlsMode,
|
? 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,
|
: 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;
|
_showForm = false;
|
||||||
_toast.ShowSuccess("SMTP configuration saved.");
|
_toast.ShowSuccess("SMTP configuration saved.");
|
||||||
await LoadAsync();
|
await LoadAsync();
|
||||||
|
|||||||
@@ -10,7 +10,9 @@ public record DeleteNotificationListCommand(int NotificationListId);
|
|||||||
public record ListSmtpConfigsCommand;
|
public record ListSmtpConfigsCommand;
|
||||||
// Transport is a trailing additive parameter (Smtp or Ews; null = preserve the
|
// 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).
|
// 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;
|
public record ListSmsConfigsCommand;
|
||||||
// FromNumber is optional: a Twilio Messaging-Service-only config supplies MessagingServiceSid
|
// 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.
|
// 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
|
|||||||
/// <summary>Deletes one recipient without rewriting unrelated list membership.</summary>
|
/// <summary>Deletes one recipient without rewriting unrelated list membership.</summary>
|
||||||
public record DeleteNotificationRecipientCommand(int RecipientId);
|
public record DeleteNotificationRecipientCommand(int RecipientId);
|
||||||
/// <summary>Creates an email configuration using the update path's validation and secret projection.</summary>
|
/// <summary>Creates an email configuration using the update path's validation and secret projection.</summary>
|
||||||
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)
|
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);
|
: UpdateSmtpConfigCommand(0, Server, Port, AuthMode, FromAddress, TlsMode, Credentials, OAuth2Authority, OAuth2Scope, Transport, ConnectionTimeoutSeconds, MaxConcurrentConnections, MaxRetries, RetryDelay);
|
||||||
/// <summary>Creates an SMS configuration using the same validation as updates.</summary>
|
/// <summary>Creates an SMS configuration using the same validation as updates.</summary>
|
||||||
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)
|
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);
|
: UpdateSmsConfigCommand(0, AccountSid, FromNumber, MessagingServiceSid, ApiBaseUrl, AuthToken, ConnectionTimeoutSeconds, MaxRetries, RetryDelay);
|
||||||
|
|||||||
@@ -2753,6 +2753,17 @@ public class ManagementActor : ReceiveActor
|
|||||||
// Preserve-if-null for the transport too: an omitted value keeps the stored
|
// Preserve-if-null for the transport too: an omitted value keeps the stored
|
||||||
// one (null on every pre-EWS row, which means SMTP).
|
// one (null on every pre-EWS row, which means SMTP).
|
||||||
if (cmd.Transport is not null) config.Transport = cmd.Transport;
|
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);
|
ValidateSmtpConfigTransportShape(config);
|
||||||
if (cmd is CreateSmtpConfigCommand) await repo.AddSmtpConfigurationAsync(config);
|
if (cmd is CreateSmtpConfigCommand) await repo.AddSmtpConfigurationAsync(config);
|
||||||
else await repo.UpdateSmtpConfigurationAsync(config);
|
else await repo.UpdateSmtpConfigurationAsync(config);
|
||||||
@@ -2765,6 +2776,9 @@ public class ManagementActor : ReceiveActor
|
|||||||
return publicShape;
|
return publicShape;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static int RequireNonNegative(int value, string field) =>
|
||||||
|
value >= 0 ? value : throw new ManagementCommandException($"{field} must not be negative.");
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Write-path gate for the email transport: validates the EFFECTIVE
|
/// Write-path gate for the email transport: validates the EFFECTIVE
|
||||||
/// post-assignment state of an SmtpConfiguration so an operator cannot persist a
|
/// post-assignment state of an SmtpConfiguration so an operator cannot persist a
|
||||||
|
|||||||
@@ -153,4 +153,55 @@ public class SmtpUpdateCommandTests
|
|||||||
Assert.False(tls.Required, "--tls-mode must be optional (preserve-if-omitted).");
|
Assert.False(tls.Required, "--tls-mode must be optional (preserve-if-omitted).");
|
||||||
Assert.False(creds.Required, "--credentials must be optional (preserve-if-omitted).");
|
Assert.False(creds.Required, "--credentials must be optional (preserve-if-omitted).");
|
||||||
}
|
}
|
||||||
|
/// <summary>#149: the delivery-policy flags parse onto the command (retry delay in seconds).</summary>
|
||||||
|
[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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#149: omitted delivery-policy flags map to null so the server preserves the stored values.</summary>
|
||||||
|
[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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#149: a negative delivery-policy flag is a parse error.</summary>
|
||||||
|
[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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -182,7 +182,7 @@ public class SmtpConfigurationPageTests : BunitContext
|
|||||||
SelectWithOption(cut, "Ews").Change("Ews");
|
SelectWithOption(cut, "Ews").Change("Ews");
|
||||||
|
|
||||||
// Port input, TLS select and Auth Type select are all gone under 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, "StartTLS"));
|
||||||
Assert.False(HasSelectWithOption(cut, "OAuth2"));
|
Assert.False(HasSelectWithOption(cut, "OAuth2"));
|
||||||
Assert.Contains("EWS URL", cut.Markup);
|
Assert.Contains("EWS URL", cut.Markup);
|
||||||
@@ -212,7 +212,7 @@ public class SmtpConfigurationPageTests : BunitContext
|
|||||||
SelectWithOption(cut, "Ews").Change("Smtp");
|
SelectWithOption(cut, "Ews").Change("Smtp");
|
||||||
|
|
||||||
// Port and TLS controls are back...
|
// 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, "StartTLS"));
|
||||||
Assert.True(HasSelectWithOption(cut, "OAuth2"));
|
Assert.True(HasSelectWithOption(cut, "OAuth2"));
|
||||||
|
|
||||||
|
|||||||
@@ -3356,6 +3356,107 @@ public class ManagementActorTests : TestKit, IDisposable
|
|||||||
Assert.Contains("username:password", response.Error);
|
Assert.Contains("username:password", response.Error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private (INotificationRepository Repo, Commons.Entities.Notifications.SmtpConfiguration Existing) SmtpPolicyFixture()
|
||||||
|
{
|
||||||
|
var notifRepo = Substitute.For<INotificationRepository>();
|
||||||
|
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<CancellationToken>()).Returns(existing);
|
||||||
|
_services.AddScoped(_ => notifRepo);
|
||||||
|
return (notifRepo, existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#149: the delivery-policy fields on an update are applied to the stored row.</summary>
|
||||||
|
[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<ManagementSuccess>(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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#149: an update that omits the delivery-policy fields preserves the stored values.</summary>
|
||||||
|
[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<ManagementSuccess>(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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#149: a negative delivery-policy value is refused and nothing is saved.</summary>
|
||||||
|
[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<ManagementError>(TimeSpan.FromSeconds(5));
|
||||||
|
Assert.Contains(field, response.Error);
|
||||||
|
repo.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>#149: a create carries the delivery-policy fields onto the new row.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void CreateSmtpConfig_CarriesDeliveryPolicyFields()
|
||||||
|
{
|
||||||
|
var notifRepo = Substitute.For<INotificationRepository>();
|
||||||
|
Commons.Entities.Notifications.SmtpConfiguration? added = null;
|
||||||
|
notifRepo.AddSmtpConfigurationAsync(Arg.Do<Commons.Entities.Notifications.SmtpConfiguration>(c => added = c), Arg.Any<CancellationToken>())
|
||||||
|
.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<ManagementSuccess>(TimeSpan.FromSeconds(5));
|
||||||
|
Assert.NotNull(added);
|
||||||
|
Assert.Equal(10, added!.MaxRetries);
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(1), added.RetryDelay);
|
||||||
|
Assert.Equal(0, added.ConnectionTimeoutSeconds);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Verifies that update smtp config, when with null transport, preserves existing value.</summary>
|
/// <summary>Verifies that update smtp config, when with null transport, preserves existing value.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
public void UpdateSmtpConfig_WithNullTransport_PreservesExistingValue()
|
public void UpdateSmtpConfig_WithNullTransport_PreservesExistingValue()
|
||||||
|
|||||||
Reference in New Issue
Block a user