diff --git a/docs/requirements/Component-CentralUI.md b/docs/requirements/Component-CentralUI.md index 63cf3b58..1a97b4c8 100644 --- a/docs/requirements/Component-CentralUI.md +++ b/docs/requirements/Component-CentralUI.md @@ -164,7 +164,7 @@ Central cluster only. Sites have no user interface. - **Search** — a search box runs a bounded recursive address-space search (depth + result caps) at the site, matching a case-insensitive substring against node DisplayName/path; clicking a result selects it. The dialog surfaces a "showing first N — refine" note when a result cap is hit. - **Type column** — Variable rows display best-effort type info (data type friendly name, scalar/array value rank, writable flag) read from the server during browse. - Set instance-level attribute overrides (non-locked attributes only). - - **Bulk override CSV import** (`InstanceConfigure`): a Blazor `InputFile` upload accepts a CSV of `AttributeName, Value, ElementType?` rows (`ElementType` only for `List` attributes). Each row is validated against the instance's flattened attribute schema (name exists + value type-compatible, reusing the existing override validation); the import is **all-or-nothing** — any per-row error aborts the whole upload with a per-row error summary and nothing is applied. On success the rows are upserted through the same ManagementActor add/update-override handlers used by the inline editor. The same import is available from the CLI (`instance import-overrides --file`, see Component-CLI.md). + - **Bulk override CSV import** (`InstanceConfigure`): a Blazor `InputFile` upload accepts a CSV of `AttributeName, Value, ElementType?` rows (`ElementType` only for `List` attributes). Each row is validated against the instance's flattened attribute schema (name exists + value type-compatible, reusing the existing override validation); the import is **all-or-nothing** — any per-row error aborts the whole upload with a per-row error summary and nothing is applied. One trailing delimiter per row (a spreadsheet export's trailing comma, header included) is tolerated; any other column-count mismatch is still an error. On success the rows are upserted through the same ManagementActor add/update-override handlers used by the inline editor. The same import is available from the CLI (`instance import-overrides --file`, see Component-CLI.md). - **Alarm Overrides card** (`InstanceConfigure`) gained an **"MES reportable override"** tri-state select (2026-09-11) in the per-alarm **override modal** (not on the list row), bound to `InstanceAlarmOverride.IsMesReportableOverride` — the options are "Inherited (reportable | not reportable)" (the parenthetical reflects the template alarm's own flag) → `null`, "Reportable" → `true`, and "Not reportable" → `false`, which is a real override pinning the alarm off for this instance rather than a clear. The list row shows the inherited flag as a green **MES** badge and any override in its override summary. Locked alarms are **filtered out of the override list entirely** (the card only lists non-locked alarms), so there is no disabled-row state for them. `instance alarm-override set --mes-reportable true|false` (omit the flag to inherit) is the CLI equivalent. - **Native Alarm Source Overrides card** (`InstanceConfigure`): a card placed **after the Alarm Overrides card**, listing the template's native alarm sources for per-instance binding. Each row offers **inline override** of the three fields that typically vary per physical instance: - **Connection** — a dropdown (same alarm-capable filtering as the template editor). diff --git a/docs/requirements/Component-DeploymentManager.md b/docs/requirements/Component-DeploymentManager.md index 228d2068..7bf9c3ed 100644 --- a/docs/requirements/Component-DeploymentManager.md +++ b/docs/requirements/Component-DeploymentManager.md @@ -90,6 +90,7 @@ All mutating operations on a single instance (deploy, disable, enable, delete) s - Only one mutating operation per instance can be in-flight at a time. A second operation is rejected with an "operation in progress" error. - **Different instances**: Operations on different instances can proceed **in parallel**, even at the same site. Each tracks status independently. This supports the bulk "deploy all out-of-date instances" operation efficiently. +- **Lock first, then validate.** Each command loads the instance (to learn its name), acquires the lock, then **reloads the instance and runs the state-transition check on the fresh state** (`IDeploymentManagerRepository.ReloadInstanceAsync`; an instance deleted meanwhile reports "not found"). A command that waited behind another one therefore never acts on the state it loaded before the wait — e.g. a Delete queued behind a deploy sees `Enabled`, not the stale `NotDeployed`, and tears the site down instead of orphaning it (review DEP-2). > **`OperationLockManager` scope invariant (recorded decision, arch-review 05).** The > per-instance locks are **per-node, in-memory**. Mutual exclusion therefore holds only @@ -149,7 +150,7 @@ optimistically-concurrent status record. It runs the ordinary deployment pipeline in three phases, of which only the middle one is parallel: -1. **Prepare (serial).** Validate transition, take the operation lock, flatten + +1. **Prepare (serial).** Take the operation lock, validate the transition against the freshly reloaded instance, flatten + validate, run query-before-redeploy reconciliation, insert the `InProgress` record. Every step here touches the scoped, non-thread-safe `DbContext`, so the phase is strictly serial. All instances share ONE `FlattenSession`, so a diff --git a/docs/requirements/Component-InboundAPI.md b/docs/requirements/Component-InboundAPI.md index e2bc85b8..a8f76882 100644 --- a/docs/requirements/Component-InboundAPI.md +++ b/docs/requirements/Component-InboundAPI.md @@ -69,7 +69,7 @@ Each API method definition includes: - **Return Value Definition**: Structure of the response, with: - Field names and (extended-system) data types. Supports returning **lists of objects** and arbitrarily nested structures. - **Implementation Script**: C# script that executes when the method is called. Stored **inline** in the method definition. Follows standard C# authoring patterns but has no template inheritance — it is a standalone script tied to this method. -- **Timeout**: Configurable per method. Defines the maximum time the method is allowed to execute (including any routed calls to sites) before returning a timeout error to the caller. +- **Timeout**: Configurable per method. Defines the maximum time the method is allowed to execute (including any routed calls to sites) before returning a timeout error to the caller. The script is started on the thread pool (not inline on the request thread), so the timeout also bounds the synchronous prefix of the script — CPU work or a blocking call before its first `await` — and a script that overruns is abandoned and counted exactly like one that blocks later (review INB-1). - **TraceAllCalls** (Flow Debugger, 2026-09-05): when set, every call to this method runs its routed site scripts with the trace flag on, so their `ScriptRun` / `AttributeWrite` / `AttributeWait` audit rows (`AuditChannel.ScriptTrace`) are recorded for Replay. Default off — adds 7–10 audit rows per call (3 of them trace-only; a cached DB write and a notification account for the upper end), so it is meant for low-volume integration methods. Set from the method form's *Trace all calls* checkbox or `api-method create|update --trace-all-calls`. > **Authoring note — idempotent methods for at-least-once callers**: some external callers retry @@ -164,7 +164,7 @@ The `sbk__` design already supports zero-downtime rotation — a #### Type Definition Format & Nested Validation -- Parameter and return type definitions are persisted as **JSON Schema** (the canonical format produced by the Central UI schema builder; see the `MigrateParametersToJsonSchema` migration). An object declares its fields via `properties` (+ a `required` array); a list declares its element type via `items`. The legacy flat-array form (`[{name,type,required,itemType?}]`) is still accepted on read for transition safety. +- Parameter and return type definitions are persisted as **JSON Schema** (the canonical format produced by the Central UI schema builder; see the `MigrateParametersToJsonSchema` migration). An object declares its fields via `properties` (+ a `required` array); a list declares its element type via `items`. The legacy flat-array form (`[{name,type,required,itemType?}]`) is still accepted on read for transition safety; an unrecognised `type`/`itemType` token in that form is a parse error naming the field and the valid types (it no longer parses and fails every request later). In the JSON Schema form, a `required` entry matches a property name case-insensitively. - Validation is **recursive and type-aware** for the extended types (request parameters and script return values alike, via a single shared engine so the two cannot drift): - **Object**: each declared field's value is validated against its declared (possibly nested) type; a missing required field and a present-but-wrong type are both reported. - **List**: every element is validated against the declared element type (recursing into nested objects/lists). A list whose element type is left undeclared (`array` without `items`) is shape-checked only. diff --git a/docs/requirements/Component-Security.md b/docs/requirements/Component-Security.md index 7e9270a6..f2ec6597 100644 --- a/docs/requirements/Component-Security.md +++ b/docs/requirements/Component-Security.md @@ -234,4 +234,4 @@ To blunt online password-spray and brute-force against the directory, every LDAP ### Passive traffic and circuit refresh (2026-09-09) -`/auth/ping`, `/auth/activity`, and Blazor transport validation do not advance inactivity timestamps or trigger sliding renewal. The explicit activity endpoint validates antiforgery before renewing the cookie and recording activity by protected session ID. A bounded process-local tracker lets a live circuit observe successful activity renewal. Role refresh preserves the session ID and activity timestamp; current circuit mutation checks re-map stored groups with fail-closed lookup behavior. Display-only auth-state reads reuse the circuit's last revalidation for up to 10 s (review 2026-10-21 07/P-3), so an idle timeout or a revoked grant can show on a read-only surface for at most that long; it never reaches a mutation. +`/auth/ping`, `/auth/activity`, and Blazor transport validation do not advance inactivity timestamps or trigger sliding renewal. The explicit activity endpoint validates antiforgery before renewing the cookie and recording activity by protected session ID. A bounded process-local tracker lets a live circuit observe successful activity renewal. Role refresh preserves the session ID and activity timestamp; a refresh done on a passive request cannot re-issue the cookie, so when it changed no grant the node remembers it per session in the bounded activity tracker and the next ping does not repeat the role re-map / directory query (a refresh that DID change grants is re-derived until a non-passive request persists it, so stale cookie roles never outlive it); current circuit mutation checks re-map stored groups with fail-closed lookup behavior. Display-only auth-state reads reuse the circuit's last revalidation for up to 10 s (review 2026-10-21 07/P-3), so an idle timeout or a revoked grant can show on a read-only surface for at most that long; it never reaches a mutation. diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditCommands.cs index e14676c0..34348859 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditCommands.cs @@ -184,6 +184,16 @@ public static class AuditCommands }; var targetOption = new Option("--target") { Description = "Filter by target" }; var actorOption = new Option("--actor") { Description = "Filter by actor" }; + var timeoutOption = new Option("--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() 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(), 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 diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditExportHelpers.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditExportHelpers.cs index 3a5e46e3..abbf7412 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditExportHelpers.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditExportHelpers.cs @@ -54,6 +54,11 @@ public sealed class AuditExportArgs /// Optional actor/user filter. /// public string? Actor { get; set; } + /// + /// Optional override (seconds) for BOTH the wait for the response headers and the + /// mid-stream inactivity deadline. Null uses the defaults (10 minutes each). + /// + public int? TimeoutSeconds { get; set; } } /// @@ -113,11 +118,12 @@ public static class AuditExportHelpers /// carry on its own — 's HttpClient.Timeout /// is deliberately (see its doc comment) /// and bounds only the TCP/TLS - /// connect phase, not a connected-but-silent server. Reuses - /// 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 --timeout-seconds (CLI-4). /// - public static readonly TimeSpan DefaultHeadersTimeout = ManagementHttpClient.DefaultConnectTimeout; + public static readonly TimeSpan DefaultHeadersTimeout = TimeSpan.FromMinutes(10); /// /// Inactivity deadline for the streaming body copy: reset on every chunk @@ -128,7 +134,7 @@ public static class AuditExportHelpers /// (ManagementHttpClient.DefaultConnectTimeout doc comment) left in this /// one path. /// - public static readonly TimeSpan DefaultInactivityTimeout = ManagementHttpClient.DefaultConnectTimeout; + public static readonly TimeSpan DefaultInactivityTimeout = TimeSpan.FromMinutes(10); /// /// Executes the export: GETs /api/audit/export 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; diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditLogCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditLogCommands.cs index b2b20892..a9db2daf 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditLogCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditLogCommands.cs @@ -69,8 +69,8 @@ public static class AuditLogCommands var userOption = new Option("--user") { Description = "Filter by username" }; var entityTypeOption = new Option("--entity-type") { Description = "Filter by entity type" }; var actionOption = new Option("--action") { Description = "Filter by action" }; - var fromOption = new Option("--from") { Description = "Start date (ISO 8601)" }; - var toOption = new Option("--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("--page") { Description = "Page number" }; pageOption.DefaultValueFactory = _ => 1; var pageSizeOption = new Option("--page-size") { Description = "Page size" }; diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditQueryHelpers.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditQueryHelpers.cs index 51df8a76..82884a4b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditQueryHelpers.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/AuditQueryHelpers.cs @@ -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, diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/BundleCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/BundleCommands.cs index 1a7de401..22582a5f 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/BundleCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/BundleCommands.cs @@ -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 + /// + /// Verifies 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. + /// + /// The requested output file path. + /// A human-readable reason when the path is unusable. + /// true when the path looks writable. + 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; + } + } + /// /// Decodes a base64 string into 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 + /// only after the whole payload decoded and (when supplied) + /// the decoded length equals ; on any failure the temp file is + /// deleted and an existing file at is left untouched. + /// Returns the total number of decoded bytes written. /// /// The base64-encoded content to decode and write. - /// Destination file path; created or overwritten. + /// Destination file path; created or replaced. + /// The server-reported byte count to verify against, or null to skip. + /// The content is not valid base64. + /// The decoded length differs from . /// Total number of bytes written to the output file. - 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?> NameListOption(string name, string description) diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CachedCallCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CachedCallCommands.cs index 70feb5ef..5054666b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CachedCallCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CachedCallCommands.cs @@ -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; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CliOptions.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CliOptions.cs index c130fbec..ddafa176 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CliOptions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CliOptions.cs @@ -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); } + /// + /// 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 --hi 80.5 was silently read + /// as 805 (CLI-3). A value that does not parse is a parse error, never a different number. + /// + /// The option name, including leading dashes. + /// Help text. + /// An optional double option with invariant-culture parsing. + internal static Option 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; + }, + }; + + /// + /// Creates a date/time option parsed with the invariant culture, treating a value with no + /// explicit offset as UTC (matching audit query --since) rather than machine-local time (CLI-3). + /// + /// The option name, including leading dashes. + /// Help text. + /// An optional option with invariant, UTC-assuming parsing. + internal static Option 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 CreateFormatOption() { var formatOption = new Option("--format") diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CommandHelpers.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CommandHelpers.cs index 15ac938f..1c7d4707 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CommandHelpers.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/CommandHelpers.cs @@ -222,6 +222,79 @@ internal static class CommandHelpers return IsAuthorizationFailure(response) ? 2 : 1; } + /// + /// Success handler for commands whose HTTP 200 body is a site-relayed result record carrying + /// a success flag (cached-call retry|discard, data-connection certs ...). + /// The management API returns those records unchanged with a 200 even when the site reported + /// failure, so the default rendering path exited 0 for "success": false (CLI-1). Renders + /// the body exactly as does, then returns 1 with the reported + /// error text when success is false. A body with no success property is + /// treated as success (exit 0), so this never changes the outcome for a payload that does + /// not carry the flag. + /// + /// The JSON response body from the management API. + /// The output format (e.g. json or table). + /// 0 unless the body reports success: false, then 1. + 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; + } + + /// + /// 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). + /// + /// The command body. + /// The body's exit code, or 1 after writing the error envelope. + internal static async Task GuardInputErrorsAsync(Func> 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; + } + } + /// /// Determines whether an error response represents an authorization failure /// (insufficient role), which the documented exit-code table maps to exit code 2. diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ConnectionBrowseCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ConnectionBrowseCommands.cs index d9268e69..36fcf95b 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ConnectionBrowseCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ConnectionBrowseCommands.cs @@ -60,13 +60,20 @@ public static class ConnectionBrowseCommands Option usernameOption, Option passwordOption, object command, - Func? commandInterceptor) + Func? 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 urlOption, Option formatOption, Option usernameOption, Option passwordOption, Func? 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; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DebugCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DebugCommands.cs index 6c893407..0721cca1 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DebugCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DebugCommands.cs @@ -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 diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DebugStreamHelpers.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DebugStreamHelpers.cs index 5f3c5270..56842e25 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DebugStreamHelpers.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DebugStreamHelpers.cs @@ -56,4 +56,51 @@ internal static class DebugStreamHelpers return 0; } + + /// Attempts made to re-subscribe after a reconnect before the stream is abandoned. + internal const int ResubscribeAttempts = 3; + + /// + /// 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). + /// + /// The subscribe invocation. + /// Delay before retry N (1-based); injectable for tests. + /// Called with the failure and the attempt number after each failed attempt. + /// Cancellation (Ctrl+C). + /// The last failure when every attempt failed; null on success or cancellation. + internal static async Task ResubscribeWithRetryAsync( + Func subscribe, + Func delayFor, + Action 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; + } } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/HealthCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/HealthCommands.cs index 0962cbae..de8c62f7 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/HealthCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/HealthCommands.cs @@ -72,8 +72,8 @@ public static class HealthCommands var eventTypeOption = new Option("--event-type") { Description = "Filter by event type" }; var severityOption = new Option("--severity") { Description = "Filter by severity" }; var keywordOption = new Option("--keyword") { Description = "Keyword search" }; - var fromOption = new Option("--from") { Description = "Start date (ISO 8601)" }; - var toOption = new Option("--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("--page") { Description = "Page number" }; pageOption.DefaultValueFactory = _ => 1; var pageSizeOption = new Option("--page-size") { Description = "Page size" }; diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/NotificationCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/NotificationCommands.cs index 321d3117..1230ebf0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/NotificationCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/NotificationCommands.cs @@ -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); diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/TemplateCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/TemplateCommands.cs index cc863ba1..faf5e823 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/TemplateCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/TemplateCommands.cs @@ -693,15 +693,15 @@ public static class TemplateCommands var matchValueOption = new Option("--match-value") { Description = "ValueMatch: value to compare against" }; var notEqualsOption = new Option("--not-equals") { Description = "ValueMatch: match when the value is NOT equal (emits !=)" }; notEqualsOption.DefaultValueFactory = _ => false; - var minOption = new Option("--min") { Description = "RangeViolation: minimum allowed value" }; - var maxOption = new Option("--max") { Description = "RangeViolation: maximum allowed value" }; - var thresholdOption = new Option("--threshold-per-second") { Description = "RateOfChange: rate threshold per second" }; - var windowOption = new Option("--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("--direction") { Description = "RateOfChange: direction (rising|falling|either)" }; - var loLoOption = new Option("--lolo") { Description = "HiLo: low-low setpoint" }; - var loOption = new Option("--lo") { Description = "HiLo: low setpoint" }; - var hiOption = new Option("--hi") { Description = "HiLo: high setpoint" }; - var hiHiOption = new Option("--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("--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( diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/ManagementHttpClient.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/ManagementHttpClient.cs index f215dc1c..22a892b1 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/ManagementHttpClient.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/ManagementHttpClient.cs @@ -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); + } + + /// + /// Builds the error for a non-success HTTP response. + /// The server's {"error","code"} 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 HTTP {status} {reason} so the operator is never + /// shown an empty error (CLI-6). + /// + 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); } /// @@ -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); } /// @@ -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); } /// diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md index 01388f3c..4097c2e5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md @@ -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 ` 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 @@ -1958,7 +1966,7 @@ scadabridge --url debug stream --id 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. @@ -2051,6 +2059,7 @@ scadabridge --url audit export --since