fix(cli): exit 1 on success:false, atomic bundle export, invariant parsing, export timeout, re-subscribe retry (CLI-1,3,4,5,6,7, WP7 tasks 7.1-7.3)

- cached-call retry|discard and data-connection certs list|trust|remove exit 1 when the relayed record carries success:false
- bundle export probes the output path first, writes a temp file, compares the byte count, then moves it into place
- bodyless / textless HTTP errors report 'HTTP <status> <reason>'; bad --trigger-config, sms update, unreadable bundle file and out-of-range --since give the JSON error envelope
- numeric alarm setpoint options and --from/--to date options parse with the invariant culture (de-DE test); offset-less dates are UTC
- audit export gets --timeout-seconds (default 600) for both the headers wait and the mid-stream idle deadline
- debug stream retries a failed re-subscribe and exits 1 with SUBSCRIBE_FAILED if it cannot recover
This commit is contained in:
Joseph Doherty
2026-12-03 09:43:10 -05:00
parent f7e4f5b4ed
commit 47a7c0dde4
22 changed files with 957 additions and 119 deletions
@@ -184,6 +184,16 @@ public static class AuditCommands
};
var targetOption = new Option<string?>("--target") { Description = "Filter by target" };
var actorOption = new Option<string?>("--actor") { Description = "Filter by actor" };
var timeoutOption = new Option<int?>("--timeout-seconds")
{
Description = "Seconds to wait for the server's first response bytes, and for more data mid-stream, " +
"before giving up (default 600). Raise it for a selective filter over a long window.",
};
timeoutOption.Validators.Add(r =>
{
if (r.GetValueOrDefault<int?>() is { } v && v < 1)
r.AddError("--timeout-seconds must be at least 1.");
});
var cmd = new Command("export") { Description = "Export audit log events to a file" };
cmd.Add(sinceOption);
@@ -196,6 +206,7 @@ public static class AuditCommands
cmd.Add(siteOption);
cmd.Add(targetOption);
cmd.Add(actorOption);
cmd.Add(timeoutOption);
cmd.SetAction(async (ParseResult result) =>
{
@@ -218,6 +229,7 @@ public static class AuditCommands
Site = result.GetValue(siteOption) ?? Array.Empty<string>(),
Target = result.GetValue(targetOption),
Actor = result.GetValue(actorOption),
TimeoutSeconds = result.GetValue(timeoutOption),
};
// Ctrl-C is the one way to abort an in-flight export other than the
@@ -54,6 +54,11 @@ public sealed class AuditExportArgs
/// Optional actor/user filter.
/// </summary>
public string? Actor { get; set; }
/// <summary>
/// Optional override (seconds) for BOTH the wait for the response headers and the
/// mid-stream inactivity deadline. Null uses the defaults (10 minutes each).
/// </summary>
public int? TimeoutSeconds { get; set; }
}
/// <summary>
@@ -113,11 +118,12 @@ public static class AuditExportHelpers
/// carry on its own — <see cref="ManagementHttpClient"/>'s <c>HttpClient.Timeout</c>
/// is deliberately <see cref="Timeout.InfiniteTimeSpan"/> (see its doc comment)
/// and <see cref="SocketsHttpHandler.ConnectTimeout"/> bounds only the TCP/TLS
/// connect phase, not a connected-but-silent server. Reuses
/// <see cref="ManagementHttpClient.DefaultConnectTimeout"/> as the standard CLI
/// per-call default.
/// connect phase, not a connected-but-silent server. The server sends nothing until it
/// has read its first page (CSV/JSONL) or built a full row group (Parquet), which for a
/// selective filter over a long window takes well over the 30 s connect timeout, so the
/// default is minutes and the CLI exposes <c>--timeout-seconds</c> (CLI-4).
/// </summary>
public static readonly TimeSpan DefaultHeadersTimeout = ManagementHttpClient.DefaultConnectTimeout;
public static readonly TimeSpan DefaultHeadersTimeout = TimeSpan.FromMinutes(10);
/// <summary>
/// Inactivity deadline for the streaming body copy: reset on every chunk
@@ -128,7 +134,7 @@ public static class AuditExportHelpers
/// (<c>ManagementHttpClient.DefaultConnectTimeout</c> doc comment) left in this
/// one path.
/// </summary>
public static readonly TimeSpan DefaultInactivityTimeout = ManagementHttpClient.DefaultConnectTimeout;
public static readonly TimeSpan DefaultInactivityTimeout = TimeSpan.FromMinutes(10);
/// <summary>
/// Executes the export: GETs <c>/api/audit/export</c> and copies the response body
@@ -162,6 +168,8 @@ public static class AuditExportHelpers
var qs = BuildQueryString(args, now);
using var headersCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
headersTimeout ??= args.TimeoutSeconds is { } t ? TimeSpan.FromSeconds(t) : null;
inactivityTimeout ??= args.TimeoutSeconds is { } t2 ? TimeSpan.FromSeconds(t2) : null;
headersCts.CancelAfter(headersTimeout ?? DefaultHeadersTimeout);
HttpResponseMessage response;
@@ -69,8 +69,8 @@ public static class AuditLogCommands
var userOption = new Option<string?>("--user") { Description = "Filter by username" };
var entityTypeOption = new Option<string?>("--entity-type") { Description = "Filter by entity type" };
var actionOption = new Option<string?>("--action") { Description = "Filter by action" };
var fromOption = new Option<DateTimeOffset?>("--from") { Description = "Start date (ISO 8601)" };
var toOption = new Option<DateTimeOffset?>("--to") { Description = "End date (ISO 8601)" };
var fromOption = CliOptions.CreateInvariantDateOption("--from", "Start date (ISO 8601)");
var toOption = CliOptions.CreateInvariantDateOption("--to", "End date (ISO 8601)");
var pageOption = new Option<int>("--page") { Description = "Page number" };
pageOption.DefaultValueFactory = _ => 1;
var pageSizeOption = new Option<int>("--page-size") { Description = "Page size" };
@@ -70,16 +70,24 @@ public static class AuditQueryHelpers
var match = RelativeSpec.Match(spec.Trim());
if (match.Success)
{
var amount = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
var offset = match.Groups[2].Value switch
if (!int.TryParse(match.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out var amount))
throw new FormatException($"Time value '{spec}' is out of range.");
try
{
"s" => TimeSpan.FromSeconds(amount),
"m" => TimeSpan.FromMinutes(amount),
"h" => TimeSpan.FromHours(amount),
"d" => TimeSpan.FromDays(amount),
_ => throw new FormatException($"Unknown time unit in '{spec}'."),
};
return now - offset;
var offset = match.Groups[2].Value switch
{
"s" => TimeSpan.FromSeconds(amount),
"m" => TimeSpan.FromMinutes(amount),
"h" => TimeSpan.FromHours(amount),
"d" => TimeSpan.FromDays(amount),
_ => throw new FormatException($"Unknown time unit in '{spec}'."),
};
return now - offset;
}
catch (Exception ex) when (ex is OverflowException or ArgumentOutOfRangeException)
{
throw new FormatException($"Time value '{spec}' is out of range.");
}
}
if (DateTimeOffset.TryParse(spec, CultureInfo.InvariantCulture,
@@ -109,6 +109,13 @@ public static class BundleCommands
var includeDeps = result.GetValue(includeDepsOption);
var sourceEnv = result.GetValue(sourceEnvOption) ?? "cli";
// Fail on a bad output path BEFORE the (multi-minute) server export, not after it (CLI-5).
if (!TryProbeOutputPath(output, out var outputError))
{
OutputFormatter.WriteError(outputError!, "INVALID_OUTPUT_PATH");
return 1;
}
var payload = new ExportBundleCommand(
All: all,
TemplateNames: result.GetValue(templatesOption),
@@ -168,7 +175,10 @@ public static class BundleCommands
long written;
try
{
written = StreamBase64ToFile(base64, output);
// Written to a temp file and moved into place only once the decoded
// byte count matches the server's, so a truncated or undecodable
// response can never destroy an existing good bundle (CLI-5).
written = StreamBase64ToFile(base64, output, byteCount);
}
catch (FormatException ex)
{
@@ -177,6 +187,16 @@ public static class BundleCommands
"INVALID_RESPONSE");
return 1;
}
catch (InvalidDataException ex)
{
OutputFormatter.WriteError(ex.Message, "INVALID_RESPONSE");
return 1;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
OutputFormatter.WriteError($"Could not write the bundle to '{output}': {ex.Message}", "FILE_ERROR");
return 1;
}
Console.WriteLine($"Wrote {written:N0} bytes to {output} (server reported {byteCount:N0}).");
return 0;
});
@@ -216,7 +236,16 @@ public static class BundleCommands
OutputFormatter.WriteError($"Bundle file not found: {input}", "FILE_NOT_FOUND");
return 1;
}
var bytes = await File.ReadAllBytesAsync(input);
byte[] bytes;
try
{
bytes = await File.ReadAllBytesAsync(input);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
OutputFormatter.WriteError($"Could not read bundle file '{input}': {ex.Message}", "FILE_ERROR");
return 1;
}
var payload = new PreviewBundleCommand(
Base64Bundle: Convert.ToBase64String(bytes),
Passphrase: result.GetValue(passphraseOption));
@@ -373,7 +402,16 @@ public static class BundleCommands
return 1;
}
var bytes = await File.ReadAllBytesAsync(input);
byte[] bytes;
try
{
bytes = await File.ReadAllBytesAsync(input);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
OutputFormatter.WriteError($"Could not read bundle file '{input}': {ex.Message}", "FILE_ERROR");
return 1;
}
var payload = new ImportBundleCommand(
Base64Bundle: Convert.ToBase64String(bytes),
Passphrase: result.GetValue(passphraseOption),
@@ -425,14 +463,59 @@ public static class BundleCommands
// for the post-write summary line.
internal const int Base64StreamChunkChars = 1024 * 1024; // 1 MB of base64 chars ≈ 768 KB decoded
/// <summary>
/// Verifies <paramref name="outputPath"/> can be written before any server work is done:
/// it must not be an existing directory, and its parent directory must exist and accept a
/// new file.
/// </summary>
/// <param name="outputPath">The requested output file path.</param>
/// <param name="error">A human-readable reason when the path is unusable.</param>
/// <returns><c>true</c> when the path looks writable.</returns>
internal static bool TryProbeOutputPath(string outputPath, out string? error)
{
try
{
var full = Path.GetFullPath(outputPath);
if (Directory.Exists(full))
{
error = $"Output path '{outputPath}' is a directory; supply a file path.";
return false;
}
var dir = Path.GetDirectoryName(full);
if (string.IsNullOrEmpty(dir) || !Directory.Exists(dir))
{
error = $"Output directory '{dir}' does not exist.";
return false;
}
var probe = Path.Combine(dir, $".{Path.GetFileName(full)}.{Guid.NewGuid():N}.probe");
using (new FileStream(probe, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1, FileOptions.DeleteOnClose))
{
}
error = null;
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
error = $"Cannot write to '{outputPath}': {ex.Message}";
return false;
}
}
/// <summary>
/// Decodes a base64 string into <paramref name="outputPath"/> in chunked fashion to avoid
/// large intermediate allocations. Returns the total number of decoded bytes written.
/// large intermediate allocations. The bytes go to a sibling temp file which replaces
/// <paramref name="outputPath"/> only after the whole payload decoded and (when supplied)
/// the decoded length equals <paramref name="expectedBytes"/>; on any failure the temp file is
/// deleted and an existing file at <paramref name="outputPath"/> is left untouched.
/// Returns the total number of decoded bytes written.
/// </summary>
/// <param name="base64">The base64-encoded content to decode and write.</param>
/// <param name="outputPath">Destination file path; created or overwritten.</param>
/// <param name="outputPath">Destination file path; created or replaced.</param>
/// <param name="expectedBytes">The server-reported byte count to verify against, or null to skip.</param>
/// <exception cref="FormatException">The content is not valid base64.</exception>
/// <exception cref="InvalidDataException">The decoded length differs from <paramref name="expectedBytes"/>.</exception>
/// <returns>Total number of bytes written to the output file.</returns>
internal static long StreamBase64ToFile(string base64, string outputPath)
internal static long StreamBase64ToFile(string base64, string outputPath, long? expectedBytes = null)
{
if (base64 is null) throw new ArgumentNullException(nameof(base64));
if (string.IsNullOrEmpty(outputPath)) throw new ArgumentException("Output path required.", nameof(outputPath));
@@ -445,30 +528,51 @@ public static class BundleCommands
var totalChars = base64.Length;
var totalWritten = 0L;
using var fileStream = new FileStream(
outputPath, FileMode.Create, FileAccess.Write, FileShare.None,
bufferSize: 81920, useAsync: false);
var fullPath = Path.GetFullPath(outputPath);
var tempPath = Path.Combine(
Path.GetDirectoryName(fullPath)!, $".{Path.GetFileName(fullPath)}.{Guid.NewGuid():N}.tmp");
// 4 base64 chars = 3 bytes, so the decoded buffer is sized accordingly.
var byteBuffer = new byte[(chunkChars / 4) * 3];
for (var offset = 0; offset < totalChars; offset += chunkChars)
try
{
var take = Math.Min(chunkChars, totalChars - offset);
var slice = base64.AsSpan(offset, take);
// The final slice may be shorter than chunkChars and may carry
// trailing '=' padding; TryFromBase64Chars handles that.
if (!Convert.TryFromBase64Chars(slice, byteBuffer, out var written))
using (var fileStream = new FileStream(
tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None,
bufferSize: 81920, useAsync: false))
{
throw new FormatException(
$"Bundle response contained invalid base64 at character offset {offset}.");
}
fileStream.Write(byteBuffer, 0, written);
totalWritten += written;
}
// 4 base64 chars = 3 bytes, so the decoded buffer is sized accordingly.
var byteBuffer = new byte[(chunkChars / 4) * 3];
return totalWritten;
for (var offset = 0; offset < totalChars; offset += chunkChars)
{
var take = Math.Min(chunkChars, totalChars - offset);
var slice = base64.AsSpan(offset, take);
// The final slice may be shorter than chunkChars and may carry
// trailing '=' padding; TryFromBase64Chars handles that.
if (!Convert.TryFromBase64Chars(slice, byteBuffer, out var written))
{
throw new FormatException(
$"Bundle response contained invalid base64 at character offset {offset}.");
}
fileStream.Write(byteBuffer, 0, written);
totalWritten += written;
}
}
if (expectedBytes is { } expected && expected != totalWritten)
{
throw new InvalidDataException(
$"Bundle size mismatch: decoded {totalWritten:N0} bytes but the server reported {expected:N0}. " +
"The existing output file was not modified.");
}
File.Move(tempPath, fullPath, overwrite: true);
return totalWritten;
}
catch
{
try { File.Delete(tempPath); } catch (IOException) { } catch (UnauthorizedAccessException) { }
throw;
}
}
private static Option<IReadOnlyList<string>?> NameListOption(string name, string description)
@@ -49,7 +49,9 @@ public static class CachedCallCommands
{
return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption,
BuildRetryCommand(result));
BuildRetryCommand(result),
onSuccess: json => CommandHelpers.HandleSuccessFlagResponse(
json, CommandHelpers.ResolveFormat(result, formatOption, CliConfig.Load())));
});
return cmd;
}
@@ -63,7 +65,9 @@ public static class CachedCallCommands
{
return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption,
BuildDiscardCommand(result));
BuildDiscardCommand(result),
onSuccess: json => CommandHelpers.HandleSuccessFlagResponse(
json, CommandHelpers.ResolveFormat(result, formatOption, CliConfig.Load())));
});
return cmd;
}
@@ -1,4 +1,5 @@
using System.CommandLine;
using System.Globalization;
namespace ZB.MOM.WW.ScadaBridge.CLI.Commands;
@@ -52,6 +53,55 @@ internal static class CliOptions
AddTo(root);
}
/// <summary>
/// Creates a numeric option that is always parsed with the invariant culture and plain
/// float syntax (no thousands separators). System.CommandLine's built-in conversion uses
/// the machine culture, so on a comma-decimal workstation <c>--hi 80.5</c> was silently read
/// as 805 (CLI-3). A value that does not parse is a parse error, never a different number.
/// </summary>
/// <param name="name">The option name, including leading dashes.</param>
/// <param name="description">Help text.</param>
/// <returns>An optional double option with invariant-culture parsing.</returns>
internal static Option<double?> CreateInvariantDoubleOption(string name, string description)
=> new(name)
{
Description = description,
CustomParser = arg =>
{
if (arg.Tokens.Count == 0)
return null;
var text = arg.Tokens[0].Value;
if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value)
&& double.IsFinite(value))
return value;
arg.AddError($"Cannot parse '{text}' as a number for {name}. Use '.' as the decimal separator (e.g. 80.5).");
return null;
},
};
/// <summary>
/// Creates a date/time option parsed with the invariant culture, treating a value with no
/// explicit offset as UTC (matching <c>audit query --since</c>) rather than machine-local time (CLI-3).
/// </summary>
/// <param name="name">The option name, including leading dashes.</param>
/// <param name="description">Help text.</param>
/// <returns>An optional <see cref="DateTimeOffset"/> option with invariant, UTC-assuming parsing.</returns>
internal static Option<DateTimeOffset?> CreateInvariantDateOption(string name, string description)
=> new(name)
{
Description = description,
CustomParser = arg =>
{
if (arg.Tokens.Count == 0)
return null;
var text = arg.Tokens[0].Value;
if (DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var value))
return value;
arg.AddError($"Cannot parse '{text}' as a date/time for {name}. Use ISO 8601 (e.g. 2026-11-01T00:00:00Z); a value with no offset is treated as UTC.");
return null;
},
};
internal static Option<string> CreateFormatOption()
{
var formatOption = new Option<string>("--format")
@@ -222,6 +222,79 @@ internal static class CommandHelpers
return IsAuthorizationFailure(response) ? 2 : 1;
}
/// <summary>
/// Success handler for commands whose HTTP 200 body is a site-relayed result record carrying
/// a <c>success</c> flag (<c>cached-call retry|discard</c>, <c>data-connection certs ...</c>).
/// The management API returns those records unchanged with a 200 even when the site reported
/// failure, so the default rendering path exited 0 for <c>"success": false</c> (CLI-1). Renders
/// the body exactly as <see cref="HandleResponse"/> does, then returns 1 with the reported
/// error text when <c>success</c> is <c>false</c>. A body with no <c>success</c> property is
/// treated as success (exit 0), so this never changes the outcome for a payload that does
/// not carry the flag.
/// </summary>
/// <param name="json">The JSON response body from the management API.</param>
/// <param name="format">The output format (e.g. json or table).</param>
/// <returns>0 unless the body reports <c>success: false</c>, then 1.</returns>
internal static int HandleSuccessFlagResponse(string json, string format)
{
HandleResponse(new ManagementResponse(200, json, null, null), format);
try
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object)
return 0;
foreach (var prop in root.EnumerateObject())
{
if (!string.Equals(prop.Name, "success", StringComparison.OrdinalIgnoreCase)
|| prop.Value.ValueKind != JsonValueKind.False)
continue;
string? detail = null;
foreach (var other in root.EnumerateObject())
{
if ((string.Equals(other.Name, "error", StringComparison.OrdinalIgnoreCase)
|| string.Equals(other.Name, "errorMessage", StringComparison.OrdinalIgnoreCase))
&& other.Value.ValueKind == JsonValueKind.String
&& !string.IsNullOrWhiteSpace(other.Value.GetString()))
{
detail = other.Value.GetString();
break;
}
}
OutputFormatter.WriteError(detail ?? "The operation reported success: false.", "OPERATION_FAILED");
return 1;
}
}
catch (JsonException) { }
return 0;
}
/// <summary>
/// Runs a command body and converts the exceptions a bad operator input produces
/// (malformed JSON, an out-of-range number, an unreadable or unwritable file, an invalid
/// argument) into the standard JSON error envelope with exit code 1, instead of an
/// unhandled stack trace (CLI-6).
/// </summary>
/// <param name="body">The command body.</param>
/// <returns>The body's exit code, or 1 after writing the error envelope.</returns>
internal static async Task<int> GuardInputErrorsAsync(Func<Task<int>> body)
{
try
{
return await body();
}
catch (Exception ex) when (ex is FormatException or ArgumentException or JsonException
or OverflowException or IOException or UnauthorizedAccessException)
{
OutputFormatter.WriteError(ex.Message, ex is IOException or UnauthorizedAccessException
? "FILE_ERROR"
: "INVALID_ARGUMENT");
return 1;
}
}
/// <summary>
/// Determines whether an error response represents an authorization failure
/// (insufficient role), which the documented exit-code table maps to exit code 2.
@@ -60,13 +60,20 @@ public static class ConnectionBrowseCommands
Option<string> usernameOption,
Option<string> passwordOption,
object command,
Func<object, int>? commandInterceptor)
Func<object, int>? commandInterceptor,
bool checkSuccessFlag = false)
{
if (commandInterceptor is not null)
return Task.FromResult(commandInterceptor(command));
// Site-relayed results (certs list/trust/remove) come back as a 200 carrying a
// `success` flag; surface success:false as exit 1 (CLI-1).
return CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption, command);
result, urlOption, formatOption, usernameOption, passwordOption, command,
onSuccess: checkSuccessFlag
? json => CommandHelpers.HandleSuccessFlagResponse(
json, CommandHelpers.ResolveFormat(result, formatOption, CliConfig.Load()))
: null);
}
private static Command BuildBrowse(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption, Func<object, int>? interceptor)
@@ -168,7 +175,7 @@ public static class ConnectionBrowseCommands
{
var site = result.GetValue(siteOption)!;
return await DispatchAsync(result, urlOption, formatOption, usernameOption, passwordOption,
new ListServerCertsCommand(site), interceptor);
new ListServerCertsCommand(site), interceptor, checkSuccessFlag: true);
});
return cmd;
}
@@ -193,7 +200,7 @@ public static class ConnectionBrowseCommands
var thumbprint = result.GetValue(thumbprintOption)!;
var derBase64 = Convert.ToBase64String(await File.ReadAllBytesAsync(derFile));
return await DispatchAsync(result, urlOption, formatOption, usernameOption, passwordOption,
new TrustServerCertCommand(connection, derBase64, thumbprint, site), interceptor);
new TrustServerCertCommand(connection, derBase64, thumbprint, site), interceptor, checkSuccessFlag: true);
});
return cmd;
}
@@ -214,7 +221,7 @@ public static class ConnectionBrowseCommands
var site = result.GetValue(siteOption)!;
var thumbprint = result.GetValue(thumbprintOption)!;
return await DispatchAsync(result, urlOption, formatOption, usernameOption, passwordOption,
new RemoveServerCertCommand(thumbprint, site), interceptor);
new RemoveServerCertCommand(thumbprint, site), interceptor, checkSuccessFlag: true);
});
return cmd;
}
@@ -222,10 +222,21 @@ public static class DebugCommands
return Task.CompletedTask;
};
connection.Reconnected += _ =>
connection.Reconnected += async _ =>
{
Console.Error.WriteLine("Reconnected. Re-subscribing...");
return connection.InvokeAsync("SubscribeInstance", instanceId);
var failure = await DebugStreamHelpers.ResubscribeWithRetryAsync(
() => connection.InvokeAsync("SubscribeInstance", instanceId, cts.Token),
attempt => TimeSpan.FromSeconds(attempt),
(ex, attempt) => Console.Error.WriteLine(
$"Re-subscribe attempt {attempt}/{DebugStreamHelpers.ResubscribeAttempts} failed: {ex.Message}"),
cts.Token);
if (failure is not null)
{
// Never leave the CLI silently subscribed to nothing: report and exit non-zero (CLI-7).
OutputFormatter.WriteError($"Re-subscribe failed after reconnect: {failure.Message}", "SUBSCRIBE_FAILED");
exitTcs.TrySetResult(1);
}
};
// Connect and subscribe
@@ -56,4 +56,51 @@ internal static class DebugStreamHelpers
return 0;
}
/// <summary>Attempts made to re-subscribe after a reconnect before the stream is abandoned.</summary>
internal const int ResubscribeAttempts = 3;
/// <summary>
/// Re-subscribes after a SignalR reconnect, retrying a failed subscribe with a growing
/// delay. A reconnect can land on a central node that is not yet ready to take the
/// subscription (a failover); previously the failure was swallowed and the stream went
/// silent with no non-zero exit (CLI-7).
/// </summary>
/// <param name="subscribe">The subscribe invocation.</param>
/// <param name="delayFor">Delay before retry N (1-based); injectable for tests.</param>
/// <param name="onAttemptFailed">Called with the failure and the attempt number after each failed attempt.</param>
/// <param name="cancellationToken">Cancellation (Ctrl+C).</param>
/// <returns>The last failure when every attempt failed; <c>null</c> on success or cancellation.</returns>
internal static async Task<Exception?> ResubscribeWithRetryAsync(
Func<Task> subscribe,
Func<int, TimeSpan> delayFor,
Action<Exception, int> onAttemptFailed,
CancellationToken cancellationToken)
{
Exception? last = null;
for (var attempt = 1; attempt <= ResubscribeAttempts; attempt++)
{
try
{
await subscribe();
return null;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return null;
}
catch (Exception ex)
{
last = ex;
onAttemptFailed(ex, attempt);
}
if (attempt < ResubscribeAttempts)
{
try { await Task.Delay(delayFor(attempt), cancellationToken); }
catch (OperationCanceledException) { return null; }
}
}
return last;
}
}
@@ -72,8 +72,8 @@ public static class HealthCommands
var eventTypeOption = new Option<string?>("--event-type") { Description = "Filter by event type" };
var severityOption = new Option<string?>("--severity") { Description = "Filter by severity" };
var keywordOption = new Option<string?>("--keyword") { Description = "Keyword search" };
var fromOption = new Option<DateTimeOffset?>("--from") { Description = "Start date (ISO 8601)" };
var toOption = new Option<DateTimeOffset?>("--to") { Description = "End date (ISO 8601)" };
var fromOption = CliOptions.CreateInvariantDateOption("--from", "Start date (ISO 8601)");
var toOption = CliOptions.CreateInvariantDateOption("--to", "End date (ISO 8601)");
var pageOption = new Option<int>("--page") { Description = "Page number" };
pageOption.DefaultValueFactory = _ => 1;
var pageSizeOption = new Option<int>("--page-size") { Description = "Page size" };
@@ -357,9 +357,19 @@ public static class NotificationCommands
ValueSourceOptions.AddFileOptions(updateCmd, (SmsAuthTokenOption, SmsAuthTokenFileOption, false));
updateCmd.SetAction(async (ParseResult result) =>
{
UpdateSmsConfigCommand command;
try
{
command = BuildUpdateSmsConfigCommand(result);
}
catch (ArgumentException ex)
{
// A missing sender identity is a user error: JSON error envelope, not a stack trace (CLI-6).
OutputFormatter.WriteError(ex.Message, "INVALID_ARGUMENT");
return 1;
}
return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption,
BuildUpdateSmsConfigCommand(result));
result, urlOption, formatOption, usernameOption, passwordOption, command);
});
group.Add(updateCmd);
@@ -693,15 +693,15 @@ public static class TemplateCommands
var matchValueOption = new Option<string?>("--match-value") { Description = "ValueMatch: value to compare against" };
var notEqualsOption = new Option<bool>("--not-equals") { Description = "ValueMatch: match when the value is NOT equal (emits !=)" };
notEqualsOption.DefaultValueFactory = _ => false;
var minOption = new Option<double?>("--min") { Description = "RangeViolation: minimum allowed value" };
var maxOption = new Option<double?>("--max") { Description = "RangeViolation: maximum allowed value" };
var thresholdOption = new Option<double?>("--threshold-per-second") { Description = "RateOfChange: rate threshold per second" };
var windowOption = new Option<double?>("--window-seconds") { Description = "RateOfChange: sliding window in seconds" };
var minOption = CliOptions.CreateInvariantDoubleOption("--min", "RangeViolation: minimum allowed value");
var maxOption = CliOptions.CreateInvariantDoubleOption("--max", "RangeViolation: maximum allowed value");
var thresholdOption = CliOptions.CreateInvariantDoubleOption("--threshold-per-second", "RateOfChange: rate threshold per second");
var windowOption = CliOptions.CreateInvariantDoubleOption("--window-seconds", "RateOfChange: sliding window in seconds");
var directionOption = new Option<string?>("--direction") { Description = "RateOfChange: direction (rising|falling|either)" };
var loLoOption = new Option<double?>("--lolo") { Description = "HiLo: low-low setpoint" };
var loOption = new Option<double?>("--lo") { Description = "HiLo: low setpoint" };
var hiOption = new Option<double?>("--hi") { Description = "HiLo: high setpoint" };
var hiHiOption = new Option<double?>("--hihi") { Description = "HiLo: high-high setpoint" };
var loLoOption = CliOptions.CreateInvariantDoubleOption("--lolo", "HiLo: low-low setpoint");
var loOption = CliOptions.CreateInvariantDoubleOption("--lo", "HiLo: low setpoint");
var hiOption = CliOptions.CreateInvariantDoubleOption("--hi", "HiLo: high setpoint");
var hiHiOption = CliOptions.CreateInvariantDoubleOption("--hihi", "HiLo: high-high setpoint");
var expressionOption = new Option<string?>("--expression") { Description = "Expression: boolean trigger expression" };
// Analysis kind for Expression triggers (advisory|strict; default advisory).
// Writes "analysisKind":"Strict" into the trigger config when set to strict.
@@ -792,9 +792,11 @@ public static class TemplateCommands
{
var rawConfig = result.GetValue(updateTriggerConfigOption);
WarnIfTriggerKindIgnored(rawConfig, result.GetValue(updateTriggerKindOption));
var triggerConfig = TriggerConfigJson.InjectAnalysisKind(
if (!TriggerConfigJson.TryInjectAnalysisKind(
rawConfig,
result.GetValue(updateTriggerKindOption));
result.GetValue(updateTriggerKindOption),
out var triggerConfig))
return 1;
return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption,
new UpdateTemplateAlarmCommand(
@@ -940,9 +942,11 @@ public static class TemplateCommands
var rawConfig = result.GetValue(triggerConfigOption);
WarnIfTriggerKindIgnored(rawConfig, result.GetValue(scriptTriggerKindOption));
var triggerConfig = TriggerConfigJson.InjectAnalysisKind(
if (!TriggerConfigJson.TryInjectAnalysisKind(
rawConfig,
result.GetValue(scriptTriggerKindOption));
result.GetValue(scriptTriggerKindOption),
out var triggerConfig))
return 1;
return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption,
new AddTemplateScriptCommand(
@@ -999,9 +1003,11 @@ public static class TemplateCommands
var rawConfig = result.GetValue(updateTriggerConfigOption);
WarnIfTriggerKindIgnored(rawConfig, result.GetValue(updateScriptTriggerKindOption));
var triggerConfig = TriggerConfigJson.InjectAnalysisKind(
if (!TriggerConfigJson.TryInjectAnalysisKind(
rawConfig,
result.GetValue(updateScriptTriggerKindOption));
result.GetValue(updateScriptTriggerKindOption),
out var triggerConfig))
return 1;
return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption,
new UpdateTemplateScriptCommand(
@@ -400,19 +400,50 @@ public class ManagementHttpClient : IDisposable
if (response.IsSuccessStatusCode)
return new ManagementResponse((int)response.StatusCode, responseBody, null, null);
string? error;
return ToErrorResponse(response, responseBody);
}
/// <summary>
/// Builds the error <see cref="ManagementResponse"/> for a non-success HTTP response.
/// The server's <c>{"error","code"}</c> envelope is used when present; when the body is
/// empty or carries no usable error text (a bodyless 502, an http-to-https 307), the
/// message is synthesised as <c>HTTP {status} {reason}</c> so the operator is never
/// shown an empty error (CLI-6).
/// </summary>
internal static ManagementResponse ToErrorResponse(HttpResponseMessage response, string? responseBody)
{
string? error = null;
string? code = null;
try
{
using var doc = JsonDocument.Parse(responseBody);
error = doc.RootElement.TryGetProperty("error", out var e) ? e.GetString() : responseBody;
code = doc.RootElement.TryGetProperty("code", out var c) ? c.GetString() : null;
using var doc = JsonDocument.Parse(responseBody ?? "");
if (doc.RootElement.ValueKind == JsonValueKind.Object)
{
error = doc.RootElement.TryGetProperty("error", out var e) && e.ValueKind == JsonValueKind.String
? e.GetString()
: responseBody;
code = doc.RootElement.TryGetProperty("code", out var c) && c.ValueKind == JsonValueKind.String
? c.GetString()
: null;
}
else
{
error = responseBody;
}
}
catch
catch (JsonException)
{
error = responseBody;
}
if (string.IsNullOrWhiteSpace(error))
{
var status = (int)response.StatusCode;
error = string.IsNullOrWhiteSpace(response.ReasonPhrase)
? $"HTTP {status}"
: $"HTTP {status} {response.ReasonPhrase}";
}
return new ManagementResponse((int)response.StatusCode, null, error, code);
}
@@ -456,21 +487,7 @@ public class ManagementHttpClient : IDisposable
return new ManagementResponse((int)httpResponse.StatusCode, responseBody, null, null);
}
// Parse error response
string? error = null;
string? code = null;
try
{
using var doc = JsonDocument.Parse(responseBody);
error = doc.RootElement.TryGetProperty("error", out var e) ? e.GetString() : responseBody;
code = doc.RootElement.TryGetProperty("code", out var c) ? c.GetString() : null;
}
catch
{
error = responseBody;
}
return new ManagementResponse((int)httpResponse.StatusCode, null, error, code);
return ToErrorResponse(httpResponse, responseBody);
}
/// <summary>
@@ -510,20 +527,7 @@ public class ManagementHttpClient : IDisposable
return new ManagementResponse((int)httpResponse.StatusCode, responseBody, null, null);
}
string? error = null;
string? code = null;
try
{
using var doc = JsonDocument.Parse(responseBody);
error = doc.RootElement.TryGetProperty("error", out var e) ? e.GetString() : responseBody;
code = doc.RootElement.TryGetProperty("code", out var c) ? c.GetString() : null;
}
catch
{
error = responseBody;
}
return new ManagementResponse((int)httpResponse.StatusCode, null, error, code);
return ToErrorResponse(httpResponse, responseBody);
}
/// <summary>
@@ -567,20 +571,7 @@ public class ManagementHttpClient : IDisposable
return new ManagementResponse((int)httpResponse.StatusCode, responseBody, null, null);
}
string? error = null;
string? code = null;
try
{
using var doc = JsonDocument.Parse(responseBody);
error = doc.RootElement.TryGetProperty("error", out var e) ? e.GetString() : responseBody;
code = doc.RootElement.TryGetProperty("code", out var c) ? c.GetString() : null;
}
catch
{
error = responseBody;
}
return new ManagementResponse((int)httpResponse.StatusCode, null, error, code);
return ToErrorResponse(httpResponse, responseBody);
}
/// <summary>
+15 -1
View File
@@ -125,6 +125,14 @@ Exit codes:
| `1` | Command error |
| `2` | Authorization failure |
Commands whose server reply is a site-relayed result record (`cached-call retry|discard`,
`data-connection certs list|trust|remove`) return HTTP 200 even when the site reports failure;
the CLI prints the record and exits `1` when it carries `"success": false`. An HTTP error with no
body (a bodyless 502, an http-to-https 307) is reported as `HTTP <status> <reason>` rather than an
empty message. Numeric options (`--hi`, `--lo`, `--min`, ...) are parsed with the invariant culture
(`.` decimal separator, regardless of the workstation locale) and `--from`/`--to` date options read an
offset-less timestamp as UTC. Individual command sections document any additional exit codes.
---
## Command Reference
@@ -1960,7 +1968,7 @@ scadabridge --url <url> debug stream --id <int>
The default JSON format outputs one NDJSON object per event line with a `type` field (`snapshot`, `attributeChanged`, or `alarmChanged`). Table format (`--format table`) shows a formatted initial snapshot followed by streaming rows prefixed with `ATTR` or `ALARM`.
Features:
- Automatic reconnection on connection loss with re-subscribe.
- Automatic reconnection on connection loss with re-subscribe. A failed re-subscribe is retried (3 attempts); if every attempt fails the CLI prints a `SUBSCRIBE_FAILED` error and exits `1` rather than going silent.
- Works through the Traefik load balancer (WebSocket upgrade proxied natively).
- Requires the `Deployment` role.
@@ -2053,6 +2061,7 @@ scadabridge --url <url> audit export --since <time> --until <time> --format <fmt
| `--site` | no | — | Filter by source site ID |
| `--target` | no | — | Filter by target |
| `--actor` | no | — | Filter by actor |
| `--timeout-seconds` | no | `600` | Seconds to wait for the server's first response bytes, and for more data mid-stream, before giving up. The server sends nothing until it has read its first page (CSV/JSONL) or built a full row group (Parquet), so a selective filter over a long window can take longer than the ordinary 30 s command timeout. |
> `--format parquet` (ScadaBridge#42) writes one Parquet file with the same 24 columns
> as `csv`/`jsonl` (ids as strings, UTC microsecond timestamps, enums as names). A
@@ -2566,6 +2575,11 @@ scadabridge --url <url> bundle export --output <path> [--passphrase <string>] [-
| `--instances` | no | Comma-separated instance unique-names to include (also pulls their site + bound data connections) |
| `--source-environment` | no | `SourceEnvironment` value stamped into the bundle manifest (default: `cli`) |
The output path is checked before the server export starts (the directory must exist and be
writable). The bundle is written to a temporary file next to `--output` and moved into place only after
it decoded completely and its size equals the byte count the server reported, so a truncated response
never replaces an existing good bundle; a size mismatch or decode failure exits `1`.
**Example** — export two templates and all their dependencies:
```sh
@@ -1,5 +1,6 @@
using System.Text;
using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI;
@@ -37,7 +38,7 @@ internal static class TriggerConfigJson
var isStrict = string.Equals(analysisKind?.Trim(), "Strict", StringComparison.OrdinalIgnoreCase);
using var inputDoc = JsonDocument.Parse(json);
using var inputDoc = ParseObject(json);
using var stream = new MemoryStream();
using (var writer = new Utf8JsonWriter(stream))
{
@@ -58,4 +59,50 @@ internal static class TriggerConfigJson
return Encoding.UTF8.GetString(stream.ToArray());
}
/// <summary>
/// Non-throwing wrapper over <see cref="InjectAnalysisKind"/> for command actions: a
/// malformed or non-object <c>--trigger-config</c> is reported through the JSON error
/// envelope and returns <c>false</c> (the caller exits 1) instead of throwing (CLI-6).
/// </summary>
/// <param name="json">Raw trigger-config JSON object, or null.</param>
/// <param name="analysisKind">Value of <c>--trigger-kind</c>.</param>
/// <param name="result">The rewritten config, or null when none was supplied.</param>
/// <returns><c>false</c> when the config was invalid (the error has been written).</returns>
internal static bool TryInjectAnalysisKind(string? json, string? analysisKind, out string? result)
{
try
{
result = InjectAnalysisKind(json, analysisKind);
return true;
}
catch (FormatException ex)
{
OutputFormatter.WriteError(ex.Message, "INVALID_ARGUMENT");
result = null;
return false;
}
}
// A malformed or non-object --trigger-config surfaces as a FormatException, which the
// command turns into the JSON error envelope instead of a stack trace (CLI-6).
private static JsonDocument ParseObject(string json)
{
JsonDocument doc;
try
{
doc = JsonDocument.Parse(json);
}
catch (JsonException ex)
{
throw new FormatException($"--trigger-config is not valid JSON: {ex.Message}", ex);
}
if (doc.RootElement.ValueKind != JsonValueKind.Object)
{
doc.Dispose();
throw new FormatException("--trigger-config must be a JSON object.");
}
return doc;
}
}