Merge branch 'review/wp7' into review/integration

This commit is contained in:
Joseph Doherty
2026-12-03 10:41:19 -05:00
47 changed files with 1584 additions and 152 deletions
+1 -1
View File
@@ -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. - **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. - **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). - 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. - **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: - **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). - **Connection** — a dropdown (same alarm-capable filtering as the template editor).
@@ -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. - 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. - **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 > **`OperationLockManager` scope invariant (recorded decision, arch-review 05).** The
> per-instance locks are **per-node, in-memory**. Mutual exclusion therefore holds only > 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 It runs the ordinary deployment pipeline in three phases, of which only the middle
one is parallel: 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` validate, run query-before-redeploy reconciliation, insert the `InProgress`
record. Every step here touches the scoped, non-thread-safe `DbContext`, so the record. Every step here touches the scoped, non-thread-safe `DbContext`, so the
phase is strictly serial. All instances share ONE `FlattenSession`, so a phase is strictly serial. All instances share ONE `FlattenSession`, so a
+2 -2
View File
@@ -69,7 +69,7 @@ Each API method definition includes:
- **Return Value Definition**: Structure of the response, with: - **Return Value Definition**: Structure of the response, with:
- Field names and (extended-system) data types. Supports returning **lists of objects** and arbitrarily nested structures. - 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. - **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`. - **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 > **Authoring note — idempotent methods for at-least-once callers**: some external callers retry
@@ -164,7 +164,7 @@ The `sbk_<keyId>_<secret>` design already supports zero-downtime rotation — a
#### Type Definition Format & Nested Validation #### 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): - 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. - **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. - **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.
+1 -1
View File
@@ -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) ### 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.
@@ -184,6 +184,16 @@ public static class AuditCommands
}; };
var targetOption = new Option<string?>("--target") { Description = "Filter by target" }; var targetOption = new Option<string?>("--target") { Description = "Filter by target" };
var actorOption = new Option<string?>("--actor") { Description = "Filter by actor" }; 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" }; var cmd = new Command("export") { Description = "Export audit log events to a file" };
cmd.Add(sinceOption); cmd.Add(sinceOption);
@@ -196,6 +206,7 @@ public static class AuditCommands
cmd.Add(siteOption); cmd.Add(siteOption);
cmd.Add(targetOption); cmd.Add(targetOption);
cmd.Add(actorOption); cmd.Add(actorOption);
cmd.Add(timeoutOption);
cmd.SetAction(async (ParseResult result) => cmd.SetAction(async (ParseResult result) =>
{ {
@@ -218,6 +229,7 @@ public static class AuditCommands
Site = result.GetValue(siteOption) ?? Array.Empty<string>(), Site = result.GetValue(siteOption) ?? Array.Empty<string>(),
Target = result.GetValue(targetOption), Target = result.GetValue(targetOption),
Actor = result.GetValue(actorOption), Actor = result.GetValue(actorOption),
TimeoutSeconds = result.GetValue(timeoutOption),
}; };
// Ctrl-C is the one way to abort an in-flight export other than the // 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. /// Optional actor/user filter.
/// </summary> /// </summary>
public string? Actor { get; set; } 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> /// <summary>
@@ -113,11 +118,12 @@ public static class AuditExportHelpers
/// carry on its own — <see cref="ManagementHttpClient"/>'s <c>HttpClient.Timeout</c> /// carry on its own — <see cref="ManagementHttpClient"/>'s <c>HttpClient.Timeout</c>
/// is deliberately <see cref="Timeout.InfiniteTimeSpan"/> (see its doc comment) /// is deliberately <see cref="Timeout.InfiniteTimeSpan"/> (see its doc comment)
/// and <see cref="SocketsHttpHandler.ConnectTimeout"/> bounds only the TCP/TLS /// and <see cref="SocketsHttpHandler.ConnectTimeout"/> bounds only the TCP/TLS
/// connect phase, not a connected-but-silent server. Reuses /// connect phase, not a connected-but-silent server. The server sends nothing until it
/// <see cref="ManagementHttpClient.DefaultConnectTimeout"/> as the standard CLI /// has read its first page (CSV/JSONL) or built a full row group (Parquet), which for a
/// per-call default. /// 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> /// </summary>
public static readonly TimeSpan DefaultHeadersTimeout = ManagementHttpClient.DefaultConnectTimeout; public static readonly TimeSpan DefaultHeadersTimeout = TimeSpan.FromMinutes(10);
/// <summary> /// <summary>
/// Inactivity deadline for the streaming body copy: reset on every chunk /// 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 /// (<c>ManagementHttpClient.DefaultConnectTimeout</c> doc comment) left in this
/// one path. /// one path.
/// </summary> /// </summary>
public static readonly TimeSpan DefaultInactivityTimeout = ManagementHttpClient.DefaultConnectTimeout; public static readonly TimeSpan DefaultInactivityTimeout = TimeSpan.FromMinutes(10);
/// <summary> /// <summary>
/// Executes the export: GETs <c>/api/audit/export</c> and copies the response body /// 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); var qs = BuildQueryString(args, now);
using var headersCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); 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); headersCts.CancelAfter(headersTimeout ?? DefaultHeadersTimeout);
HttpResponseMessage response; HttpResponseMessage response;
@@ -69,8 +69,8 @@ public static class AuditLogCommands
var userOption = new Option<string?>("--user") { Description = "Filter by username" }; var userOption = new Option<string?>("--user") { Description = "Filter by username" };
var entityTypeOption = new Option<string?>("--entity-type") { Description = "Filter by entity type" }; var entityTypeOption = new Option<string?>("--entity-type") { Description = "Filter by entity type" };
var actionOption = new Option<string?>("--action") { Description = "Filter by action" }; var actionOption = new Option<string?>("--action") { Description = "Filter by action" };
var fromOption = new Option<DateTimeOffset?>("--from") { Description = "Start date (ISO 8601)" }; var fromOption = CliOptions.CreateInvariantDateOption("--from", "Start date (ISO 8601)");
var toOption = new Option<DateTimeOffset?>("--to") { Description = "End date (ISO 8601)" }; var toOption = CliOptions.CreateInvariantDateOption("--to", "End date (ISO 8601)");
var pageOption = new Option<int>("--page") { Description = "Page number" }; var pageOption = new Option<int>("--page") { Description = "Page number" };
pageOption.DefaultValueFactory = _ => 1; pageOption.DefaultValueFactory = _ => 1;
var pageSizeOption = new Option<int>("--page-size") { Description = "Page size" }; var pageSizeOption = new Option<int>("--page-size") { Description = "Page size" };
@@ -70,16 +70,24 @@ public static class AuditQueryHelpers
var match = RelativeSpec.Match(spec.Trim()); var match = RelativeSpec.Match(spec.Trim());
if (match.Success) if (match.Success)
{ {
var amount = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); if (!int.TryParse(match.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture, out var amount))
var offset = match.Groups[2].Value switch throw new FormatException($"Time value '{spec}' is out of range.");
try
{ {
"s" => TimeSpan.FromSeconds(amount), var offset = match.Groups[2].Value switch
"m" => TimeSpan.FromMinutes(amount), {
"h" => TimeSpan.FromHours(amount), "s" => TimeSpan.FromSeconds(amount),
"d" => TimeSpan.FromDays(amount), "m" => TimeSpan.FromMinutes(amount),
_ => throw new FormatException($"Unknown time unit in '{spec}'."), "h" => TimeSpan.FromHours(amount),
}; "d" => TimeSpan.FromDays(amount),
return now - offset; _ => 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, if (DateTimeOffset.TryParse(spec, CultureInfo.InvariantCulture,
@@ -109,6 +109,13 @@ public static class BundleCommands
var includeDeps = result.GetValue(includeDepsOption); var includeDeps = result.GetValue(includeDepsOption);
var sourceEnv = result.GetValue(sourceEnvOption) ?? "cli"; 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( var payload = new ExportBundleCommand(
All: all, All: all,
TemplateNames: result.GetValue(templatesOption), TemplateNames: result.GetValue(templatesOption),
@@ -168,7 +175,10 @@ public static class BundleCommands
long written; long written;
try 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) catch (FormatException ex)
{ {
@@ -177,6 +187,16 @@ public static class BundleCommands
"INVALID_RESPONSE"); "INVALID_RESPONSE");
return 1; 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})."); Console.WriteLine($"Wrote {written:N0} bytes to {output} (server reported {byteCount:N0}).");
return 0; return 0;
}); });
@@ -216,7 +236,16 @@ public static class BundleCommands
OutputFormatter.WriteError($"Bundle file not found: {input}", "FILE_NOT_FOUND"); OutputFormatter.WriteError($"Bundle file not found: {input}", "FILE_NOT_FOUND");
return 1; 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( var payload = new PreviewBundleCommand(
Base64Bundle: Convert.ToBase64String(bytes), Base64Bundle: Convert.ToBase64String(bytes),
Passphrase: result.GetValue(passphraseOption)); Passphrase: result.GetValue(passphraseOption));
@@ -373,7 +402,16 @@ public static class BundleCommands
return 1; 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( var payload = new ImportBundleCommand(
Base64Bundle: Convert.ToBase64String(bytes), Base64Bundle: Convert.ToBase64String(bytes),
Passphrase: result.GetValue(passphraseOption), Passphrase: result.GetValue(passphraseOption),
@@ -425,14 +463,59 @@ public static class BundleCommands
// for the post-write summary line. // for the post-write summary line.
internal const int Base64StreamChunkChars = 1024 * 1024; // 1 MB of base64 chars ≈ 768 KB decoded 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> /// <summary>
/// Decodes a base64 string into <paramref name="outputPath"/> in chunked fashion to avoid /// 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> /// </summary>
/// <param name="base64">The base64-encoded content to decode and write.</param> /// <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> /// <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 (base64 is null) throw new ArgumentNullException(nameof(base64));
if (string.IsNullOrEmpty(outputPath)) throw new ArgumentException("Output path required.", nameof(outputPath)); 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 totalChars = base64.Length;
var totalWritten = 0L; var totalWritten = 0L;
using var fileStream = new FileStream( var fullPath = Path.GetFullPath(outputPath);
outputPath, FileMode.Create, FileAccess.Write, FileShare.None, var tempPath = Path.Combine(
bufferSize: 81920, useAsync: false); Path.GetDirectoryName(fullPath)!, $".{Path.GetFileName(fullPath)}.{Guid.NewGuid():N}.tmp");
// 4 base64 chars = 3 bytes, so the decoded buffer is sized accordingly. try
var byteBuffer = new byte[(chunkChars / 4) * 3];
for (var offset = 0; offset < totalChars; offset += chunkChars)
{ {
var take = Math.Min(chunkChars, totalChars - offset); using (var fileStream = new FileStream(
var slice = base64.AsSpan(offset, take); tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None,
bufferSize: 81920, useAsync: false))
// 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( // 4 base64 chars = 3 bytes, so the decoded buffer is sized accordingly.
$"Bundle response contained invalid base64 at character offset {offset}."); var byteBuffer = new byte[(chunkChars / 4) * 3];
}
fileStream.Write(byteBuffer, 0, written);
totalWritten += written;
}
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) private static Option<IReadOnlyList<string>?> NameListOption(string name, string description)
@@ -49,7 +49,9 @@ public static class CachedCallCommands
{ {
return await CommandHelpers.ExecuteCommandAsync( return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption, result, urlOption, formatOption, usernameOption, passwordOption,
BuildRetryCommand(result)); BuildRetryCommand(result),
onSuccess: json => CommandHelpers.HandleSuccessFlagResponse(
json, CommandHelpers.ResolveFormat(result, formatOption, CliConfig.Load())));
}); });
return cmd; return cmd;
} }
@@ -63,7 +65,9 @@ public static class CachedCallCommands
{ {
return await CommandHelpers.ExecuteCommandAsync( return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption, result, urlOption, formatOption, usernameOption, passwordOption,
BuildDiscardCommand(result)); BuildDiscardCommand(result),
onSuccess: json => CommandHelpers.HandleSuccessFlagResponse(
json, CommandHelpers.ResolveFormat(result, formatOption, CliConfig.Load())));
}); });
return cmd; return cmd;
} }
@@ -1,4 +1,5 @@
using System.CommandLine; using System.CommandLine;
using System.Globalization;
namespace ZB.MOM.WW.ScadaBridge.CLI.Commands; namespace ZB.MOM.WW.ScadaBridge.CLI.Commands;
@@ -52,6 +53,55 @@ internal static class CliOptions
AddTo(root); 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() internal static Option<string> CreateFormatOption()
{ {
var formatOption = new Option<string>("--format") var formatOption = new Option<string>("--format")
@@ -222,6 +222,79 @@ internal static class CommandHelpers
return IsAuthorizationFailure(response) ? 2 : 1; 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> /// <summary>
/// Determines whether an error response represents an authorization failure /// Determines whether an error response represents an authorization failure
/// (insufficient role), which the documented exit-code table maps to exit code 2. /// (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> usernameOption,
Option<string> passwordOption, Option<string> passwordOption,
object command, object command,
Func<object, int>? commandInterceptor) Func<object, int>? commandInterceptor,
bool checkSuccessFlag = false)
{ {
if (commandInterceptor is not null) if (commandInterceptor is not null)
return Task.FromResult(commandInterceptor(command)); 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( 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) 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)!; var site = result.GetValue(siteOption)!;
return await DispatchAsync(result, urlOption, formatOption, usernameOption, passwordOption, return await DispatchAsync(result, urlOption, formatOption, usernameOption, passwordOption,
new ListServerCertsCommand(site), interceptor); new ListServerCertsCommand(site), interceptor, checkSuccessFlag: true);
}); });
return cmd; return cmd;
} }
@@ -193,7 +200,7 @@ public static class ConnectionBrowseCommands
var thumbprint = result.GetValue(thumbprintOption)!; var thumbprint = result.GetValue(thumbprintOption)!;
var derBase64 = Convert.ToBase64String(await File.ReadAllBytesAsync(derFile)); var derBase64 = Convert.ToBase64String(await File.ReadAllBytesAsync(derFile));
return await DispatchAsync(result, urlOption, formatOption, usernameOption, passwordOption, 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; return cmd;
} }
@@ -214,7 +221,7 @@ public static class ConnectionBrowseCommands
var site = result.GetValue(siteOption)!; var site = result.GetValue(siteOption)!;
var thumbprint = result.GetValue(thumbprintOption)!; var thumbprint = result.GetValue(thumbprintOption)!;
return await DispatchAsync(result, urlOption, formatOption, usernameOption, passwordOption, return await DispatchAsync(result, urlOption, formatOption, usernameOption, passwordOption,
new RemoveServerCertCommand(thumbprint, site), interceptor); new RemoveServerCertCommand(thumbprint, site), interceptor, checkSuccessFlag: true);
}); });
return cmd; return cmd;
} }
@@ -222,10 +222,21 @@ public static class DebugCommands
return Task.CompletedTask; return Task.CompletedTask;
}; };
connection.Reconnected += _ => connection.Reconnected += async _ =>
{ {
Console.Error.WriteLine("Reconnected. Re-subscribing..."); 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 // Connect and subscribe
@@ -56,4 +56,51 @@ internal static class DebugStreamHelpers
return 0; 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 eventTypeOption = new Option<string?>("--event-type") { Description = "Filter by event type" };
var severityOption = new Option<string?>("--severity") { Description = "Filter by severity" }; var severityOption = new Option<string?>("--severity") { Description = "Filter by severity" };
var keywordOption = new Option<string?>("--keyword") { Description = "Keyword search" }; var keywordOption = new Option<string?>("--keyword") { Description = "Keyword search" };
var fromOption = new Option<DateTimeOffset?>("--from") { Description = "Start date (ISO 8601)" }; var fromOption = CliOptions.CreateInvariantDateOption("--from", "Start date (ISO 8601)");
var toOption = new Option<DateTimeOffset?>("--to") { Description = "End date (ISO 8601)" }; var toOption = CliOptions.CreateInvariantDateOption("--to", "End date (ISO 8601)");
var pageOption = new Option<int>("--page") { Description = "Page number" }; var pageOption = new Option<int>("--page") { Description = "Page number" };
pageOption.DefaultValueFactory = _ => 1; pageOption.DefaultValueFactory = _ => 1;
var pageSizeOption = new Option<int>("--page-size") { Description = "Page size" }; var pageSizeOption = new Option<int>("--page-size") { Description = "Page size" };
@@ -357,9 +357,19 @@ public static class NotificationCommands
ValueSourceOptions.AddFileOptions(updateCmd, (SmsAuthTokenOption, SmsAuthTokenFileOption, false)); ValueSourceOptions.AddFileOptions(updateCmd, (SmsAuthTokenOption, SmsAuthTokenFileOption, false));
updateCmd.SetAction(async (ParseResult result) => 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( return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption, result, urlOption, formatOption, usernameOption, passwordOption, command);
BuildUpdateSmsConfigCommand(result));
}); });
group.Add(updateCmd); 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 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 !=)" }; var notEqualsOption = new Option<bool>("--not-equals") { Description = "ValueMatch: match when the value is NOT equal (emits !=)" };
notEqualsOption.DefaultValueFactory = _ => false; notEqualsOption.DefaultValueFactory = _ => false;
var minOption = new Option<double?>("--min") { Description = "RangeViolation: minimum allowed value" }; var minOption = CliOptions.CreateInvariantDoubleOption("--min", "RangeViolation: minimum allowed value");
var maxOption = new Option<double?>("--max") { Description = "RangeViolation: maximum allowed value" }; var maxOption = CliOptions.CreateInvariantDoubleOption("--max", "RangeViolation: maximum allowed value");
var thresholdOption = new Option<double?>("--threshold-per-second") { Description = "RateOfChange: rate threshold per second" }; var thresholdOption = CliOptions.CreateInvariantDoubleOption("--threshold-per-second", "RateOfChange: rate threshold per second");
var windowOption = new Option<double?>("--window-seconds") { Description = "RateOfChange: sliding window in seconds" }; var windowOption = CliOptions.CreateInvariantDoubleOption("--window-seconds", "RateOfChange: sliding window in seconds");
var directionOption = new Option<string?>("--direction") { Description = "RateOfChange: direction (rising|falling|either)" }; var directionOption = new Option<string?>("--direction") { Description = "RateOfChange: direction (rising|falling|either)" };
var loLoOption = new Option<double?>("--lolo") { Description = "HiLo: low-low setpoint" }; var loLoOption = CliOptions.CreateInvariantDoubleOption("--lolo", "HiLo: low-low setpoint");
var loOption = new Option<double?>("--lo") { Description = "HiLo: low setpoint" }; var loOption = CliOptions.CreateInvariantDoubleOption("--lo", "HiLo: low setpoint");
var hiOption = new Option<double?>("--hi") { Description = "HiLo: high setpoint" }; var hiOption = CliOptions.CreateInvariantDoubleOption("--hi", "HiLo: high setpoint");
var hiHiOption = new Option<double?>("--hihi") { Description = "HiLo: high-high setpoint" }; var hiHiOption = CliOptions.CreateInvariantDoubleOption("--hihi", "HiLo: high-high setpoint");
var expressionOption = new Option<string?>("--expression") { Description = "Expression: boolean trigger expression" }; var expressionOption = new Option<string?>("--expression") { Description = "Expression: boolean trigger expression" };
// Analysis kind for Expression triggers (advisory|strict; default advisory). // Analysis kind for Expression triggers (advisory|strict; default advisory).
// Writes "analysisKind":"Strict" into the trigger config when set to strict. // Writes "analysisKind":"Strict" into the trigger config when set to strict.
@@ -792,9 +792,11 @@ public static class TemplateCommands
{ {
var rawConfig = result.GetValue(updateTriggerConfigOption); var rawConfig = result.GetValue(updateTriggerConfigOption);
WarnIfTriggerKindIgnored(rawConfig, result.GetValue(updateTriggerKindOption)); WarnIfTriggerKindIgnored(rawConfig, result.GetValue(updateTriggerKindOption));
var triggerConfig = TriggerConfigJson.InjectAnalysisKind( if (!TriggerConfigJson.TryInjectAnalysisKind(
rawConfig, rawConfig,
result.GetValue(updateTriggerKindOption)); result.GetValue(updateTriggerKindOption),
out var triggerConfig))
return 1;
return await CommandHelpers.ExecuteCommandAsync( return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption, result, urlOption, formatOption, usernameOption, passwordOption,
new UpdateTemplateAlarmCommand( new UpdateTemplateAlarmCommand(
@@ -940,9 +942,11 @@ public static class TemplateCommands
var rawConfig = result.GetValue(triggerConfigOption); var rawConfig = result.GetValue(triggerConfigOption);
WarnIfTriggerKindIgnored(rawConfig, result.GetValue(scriptTriggerKindOption)); WarnIfTriggerKindIgnored(rawConfig, result.GetValue(scriptTriggerKindOption));
var triggerConfig = TriggerConfigJson.InjectAnalysisKind( if (!TriggerConfigJson.TryInjectAnalysisKind(
rawConfig, rawConfig,
result.GetValue(scriptTriggerKindOption)); result.GetValue(scriptTriggerKindOption),
out var triggerConfig))
return 1;
return await CommandHelpers.ExecuteCommandAsync( return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption, result, urlOption, formatOption, usernameOption, passwordOption,
new AddTemplateScriptCommand( new AddTemplateScriptCommand(
@@ -999,9 +1003,11 @@ public static class TemplateCommands
var rawConfig = result.GetValue(updateTriggerConfigOption); var rawConfig = result.GetValue(updateTriggerConfigOption);
WarnIfTriggerKindIgnored(rawConfig, result.GetValue(updateScriptTriggerKindOption)); WarnIfTriggerKindIgnored(rawConfig, result.GetValue(updateScriptTriggerKindOption));
var triggerConfig = TriggerConfigJson.InjectAnalysisKind( if (!TriggerConfigJson.TryInjectAnalysisKind(
rawConfig, rawConfig,
result.GetValue(updateScriptTriggerKindOption)); result.GetValue(updateScriptTriggerKindOption),
out var triggerConfig))
return 1;
return await CommandHelpers.ExecuteCommandAsync( return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption, result, urlOption, formatOption, usernameOption, passwordOption,
new UpdateTemplateScriptCommand( new UpdateTemplateScriptCommand(
@@ -400,19 +400,50 @@ public class ManagementHttpClient : IDisposable
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
return new ManagementResponse((int)response.StatusCode, responseBody, null, null); 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; string? code = null;
try try
{ {
using var doc = JsonDocument.Parse(responseBody); using var doc = JsonDocument.Parse(responseBody ?? "");
error = doc.RootElement.TryGetProperty("error", out var e) ? e.GetString() : responseBody; if (doc.RootElement.ValueKind == JsonValueKind.Object)
code = doc.RootElement.TryGetProperty("code", out var c) ? c.GetString() : null; {
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; 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); 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); return new ManagementResponse((int)httpResponse.StatusCode, responseBody, null, null);
} }
// Parse error response return ToErrorResponse(httpResponse, 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;
}
catch
{
error = responseBody;
}
return new ManagementResponse((int)httpResponse.StatusCode, null, error, code);
} }
/// <summary> /// <summary>
@@ -510,20 +527,7 @@ public class ManagementHttpClient : IDisposable
return new ManagementResponse((int)httpResponse.StatusCode, responseBody, null, null); return new ManagementResponse((int)httpResponse.StatusCode, responseBody, null, null);
} }
string? error = null; return ToErrorResponse(httpResponse, responseBody);
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);
} }
/// <summary> /// <summary>
@@ -567,20 +571,7 @@ public class ManagementHttpClient : IDisposable
return new ManagementResponse((int)httpResponse.StatusCode, responseBody, null, null); return new ManagementResponse((int)httpResponse.StatusCode, responseBody, null, null);
} }
string? error = null; return ToErrorResponse(httpResponse, responseBody);
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);
} }
/// <summary> /// <summary>
+15 -1
View File
@@ -125,6 +125,14 @@ Exit codes:
| `1` | Command error | | `1` | Command error |
| `2` | Authorization failure | | `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 ## Command Reference
@@ -1958,7 +1966,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`. 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: 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). - Works through the Traefik load balancer (WebSocket upgrade proxied natively).
- Requires the `Deployment` role. - Requires the `Deployment` role.
@@ -2051,6 +2059,7 @@ scadabridge --url <url> audit export --since <time> --until <time> --format <fmt
| `--site` | no | — | Filter by source site ID | | `--site` | no | — | Filter by source site ID |
| `--target` | no | — | Filter by target | | `--target` | no | — | Filter by target |
| `--actor` | no | — | Filter by actor | | `--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 > `--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 > as `csv`/`jsonl` (ids as strings, UTC microsecond timestamps, enums as names). A
@@ -2563,6 +2572,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) | | `--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`) | | `--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: **Example** — export two templates and all their dependencies:
```sh ```sh
@@ -1,5 +1,6 @@
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI; namespace ZB.MOM.WW.ScadaBridge.CLI;
@@ -37,7 +38,7 @@ internal static class TriggerConfigJson
var isStrict = string.Equals(analysisKind?.Trim(), "Strict", StringComparison.OrdinalIgnoreCase); 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 stream = new MemoryStream();
using (var writer = new Utf8JsonWriter(stream)) using (var writer = new Utf8JsonWriter(stream))
{ {
@@ -58,4 +59,50 @@ internal static class TriggerConfigJson
return Encoding.UTF8.GetString(stream.ToArray()); 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;
}
} }
@@ -414,6 +414,16 @@ public interface IDeploymentManagerRepository
/// <returns>The instance, or null if not found.</returns> /// <returns>The instance, or null if not found.</returns>
Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default); Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
/// <summary> /// <summary>
/// Refreshes <paramref name="instance"/> in place from the database so a caller that
/// waited for the per-instance operation lock can validate the state the command ahead
/// of it left behind (DEP-2). A tracked entity is reloaded; an untracked one has its
/// <see cref="Instance.State"/> re-read.
/// </summary>
/// <param name="instance">The instance previously loaded by <see cref="GetInstanceByIdAsync"/>.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
/// <returns><see langword="true"/> when the instance no longer exists (it was deleted meanwhile); otherwise <see langword="false"/>.</returns>
Task<bool> ReloadInstanceAsync(Instance instance, CancellationToken cancellationToken = default);
/// <summary>
/// Gets an instance by unique name. /// Gets an instance by unique name.
/// </summary> /// </summary>
/// <param name="uniqueName">The unique instance name.</param> /// <param name="uniqueName">The unique instance name.</param>
@@ -180,7 +180,7 @@ public static class AuditRowProjection
} }
/// <summary> /// <summary>
/// Case-sensitive <see cref="Enum.TryParse{TEnum}"/> with a caller-supplied fallback. /// Case-insensitive <see cref="Enum.TryParse{TEnum}"/> (matching <c>AuditQueryParamParsers</c>) with a caller-supplied fallback.
/// Returns <paramref name="fallback"/> when <paramref name="value"/> is null, empty, /// Returns <paramref name="fallback"/> when <paramref name="value"/> is null, empty,
/// or does not match any declared member name — so callers never throw on an /// or does not match any declared member name — so callers never throw on an
/// unknown/renamed enum string (legacy or corrupt rows degrade gracefully). /// unknown/renamed enum string (legacy or corrupt rows degrade gracefully).
@@ -190,7 +190,7 @@ public static class AuditRowProjection
/// <param name="fallback">Value returned when <paramref name="value"/> is null, empty, or unrecognised.</param> /// <param name="fallback">Value returned when <paramref name="value"/> is null, empty, or unrecognised.</param>
/// <returns>The parsed <typeparamref name="TEnum"/> value, or <paramref name="fallback"/> when the input is null, empty, or unrecognised.</returns> /// <returns>The parsed <typeparamref name="TEnum"/> value, or <paramref name="fallback"/> when the input is null, empty, or unrecognised.</returns>
public static TEnum ParseEnum<TEnum>(string? value, TEnum fallback) where TEnum : struct, Enum public static TEnum ParseEnum<TEnum>(string? value, TEnum fallback) where TEnum : struct, Enum
=> !string.IsNullOrEmpty(value) && Enum.TryParse<TEnum>(value, ignoreCase: false, out var parsed) => !string.IsNullOrEmpty(value) && Enum.TryParse<TEnum>(value, ignoreCase: true, out var parsed)
? parsed ? parsed
: fallback; : fallback;
} }
@@ -22,6 +22,25 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types;
/// </remarks> /// </remarks>
public static class CsvLineSplitter public static class CsvLineSplitter
{ {
/// <summary>
/// Drops ONE empty last field from <paramref name="fields"/> (a spreadsheet's trailing
/// delimiter). Returns <c>false</c>, leaving nothing to use, when the last field is not empty.
/// </summary>
/// <param name="fields">The split fields of one line.</param>
/// <param name="trimmed">The fields without the empty trailing one.</param>
/// <returns><c>true</c> when an empty trailing field was dropped.</returns>
public static bool TryDropTrailingEmptyField(IReadOnlyList<string> fields, out List<string> trimmed)
{
if (fields.Count > 0 && fields[^1].Length == 0)
{
trimmed = fields.Take(fields.Count - 1).ToList();
return true;
}
trimmed = [];
return false;
}
/// <summary> /// <summary>
/// Splits a single physical CSV line into its fields, applying the quoting rules /// Splits a single physical CSV line into its fields, applying the quoting rules
/// described on <see cref="CsvLineSplitter"/>. Returns <c>true</c> with the split /// described on <see cref="CsvLineSplitter"/>. Returns <c>true</c> with the split
@@ -376,9 +376,10 @@ public static class FlowGraphBuilder
} }
/// <summary> /// <summary>
/// Orders the rows of one outbound operation when timestamps tie: submit before attempts before the /// Orders the rows of one outbound operation: submit before attempts before the resolve, then
/// resolve, then non-terminal before terminal statuses — so "first" and "latest" never fall back /// non-terminal before terminal statuses. This is the PRIMARY sort key of the fold (time only breaks
/// to GUID order for rows written in the same tick. /// ties between rows of equal rank, e.g. repeated attempts), so cross-node clock skew cannot put a
/// non-terminal row last.
/// </summary> /// </summary>
/// <param name="kind">The audit row kind.</param> /// <param name="kind">The audit row kind.</param>
/// <param name="status">The audit row status.</param> /// <param name="status">The audit row status.</param>
@@ -446,8 +447,12 @@ public static class FlowGraphBuilder
var key = ((FlowStepKind, Guid))item; var key = ((FlowStepKind, Guid))item;
var rows = groups[key] var rows = groups[key]
.OrderBy(r => r.Row.OccurredAtUtc) // Lifecycle rank FIRST, time only as a tiebreaker (CMN-6): the rows of one cached
.ThenBy(r => LifecycleRank(r.Row.Kind, r.Row.Status)) // operation are written on different nodes (submit at the site, resolve centrally)
// whose clocks skew by 1-2 s, so ordering by time could place Submitted after
// Delivered and fold a completed operation as Pending.
.OrderBy(r => LifecycleRank(r.Row.Kind, r.Row.Status))
.ThenBy(r => r.Row.OccurredAtUtc)
.ThenBy(r => r.Row.EventId) .ThenBy(r => r.Row.EventId)
.ToList(); .ToList();
var first = rows[0].Step; var first = rows[0].Step;
@@ -202,7 +202,10 @@ public sealed class InboundApiSchema
if (type == "object") if (type == "object")
{ {
var requiredSet = new HashSet<string>(StringComparer.Ordinal); // Case-insensitive: a "required" entry spelled with different casing than the
// property it names (hand-edited / legacy-authored schemas) still marks it required
// instead of silently making the field optional (CMN-7).
var requiredSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (el.TryGetProperty("required", out var req) && req.ValueKind == JsonValueKind.Array) if (el.TryGetProperty("required", out var req) && req.ValueKind == JsonValueKind.Array)
{ {
foreach (var r in req.EnumerateArray()) foreach (var r in req.EnumerateArray())
@@ -384,10 +387,16 @@ public sealed class InboundApiSchema
StringComparison.OrdinalIgnoreCase)); StringComparison.OrdinalIgnoreCase));
var normalized = NormalizeType(rawType); var normalized = NormalizeType(rawType);
EnsureKnownLegacyType(name!, rawType, normalized);
InboundApiSchema schema; InboundApiSchema schema;
if (normalized == "array") if (normalized == "array")
{ {
var inner = TryGetMember(item, "itemType", out var it) ? it.GetString() : null; var inner = TryGetMember(item, "itemType", out var it) ? it.GetString() : null;
if (!string.IsNullOrEmpty(inner))
{
EnsureKnownLegacyType(name!, inner, NormalizeType(inner), isItemType: true);
}
schema = new InboundApiSchema schema = new InboundApiSchema
{ {
Type = "array", Type = "array",
@@ -405,6 +414,26 @@ public sealed class InboundApiSchema
return new InboundApiSchema { Type = "object", Fields = fields }; return new InboundApiSchema { Type = "object", Fields = fields };
} }
private static readonly string[] KnownTypes = ["string", "integer", "number", "boolean", "object", "array"];
/// <summary>
/// Rejects a legacy-array parameter whose <c>type</c> (or <c>itemType</c>) is not a known
/// type, at parse time, with the field and the accepted vocabulary — instead of letting a
/// typo such as <c>strign</c> parse cleanly and fail every request later with "unknown
/// declared type" (CMN-8).
/// </summary>
private static void EnsureKnownLegacyType(string fieldName, string? rawType, string normalized, bool isItemType = false)
{
if (Array.IndexOf(KnownTypes, normalized) >= 0)
{
return;
}
var what = isItemType ? "item type" : "type";
throw new JsonException(
$"Parameter '{fieldName}' has unknown {what} '{rawType}'. Valid types: String, Integer, Float (Number), Boolean, Object, List (Array), DateTime.");
}
/// <summary> /// <summary>
/// Case-insensitive object-member lookup, used only on the legacy flat-array /// Case-insensitive object-member lookup, used only on the legacy flat-array
/// path so both PascalCase and lowercase legacy keys resolve. /// path so both PascalCase and lowercase legacy keys resolve.
@@ -92,7 +92,9 @@ public static class NativeAlarmSourceOverrideCsvParser
if (!headerSeen) if (!headerSeen)
{ {
if (!TryMatchHeader(fields, out hasMes)) if (!TryMatchHeader(fields, out hasMes)
&& !(CsvLineSplitter.TryDropTrailingEmptyField(fields, out var trimmedHeader)
&& TryMatchHeader(trimmedHeader, out hasMes)))
{ {
errors.Add(HeaderError); errors.Add(HeaderError);
return new NativeAlarmSourceOverrideCsvParseResult(rows, errors); return new NativeAlarmSourceOverrideCsvParseResult(rows, errors);
@@ -103,6 +105,9 @@ public static class NativeAlarmSourceOverrideCsvParser
} }
var expected = hasMes ? BaseColumns + 1 : BaseColumns; var expected = hasMes ? BaseColumns + 1 : BaseColumns;
// Tolerate exactly one empty trailing field (spreadsheet trailing delimiter) (CMN-9).
if (fields.Count == expected + 1 && CsvLineSplitter.TryDropTrailingEmptyField(fields, out var trimmed))
fields = trimmed;
if (fields.Count != expected) if (fields.Count != expected)
{ {
errors.Add( errors.Add(
@@ -68,7 +68,9 @@ public static class OverrideCsvParser
if (!headerSeen) if (!headerSeen)
{ {
if (!TryMatchHeader(fields, out hasElementTypeColumn)) if (!TryMatchHeader(fields, out hasElementTypeColumn)
&& !(CsvLineSplitter.TryDropTrailingEmptyField(fields, out var trimmedHeader)
&& TryMatchHeader(trimmedHeader, out hasElementTypeColumn)))
{ {
errors.Add(HeaderError); errors.Add(HeaderError);
return new OverrideCsvParseResult(rows, errors); return new OverrideCsvParseResult(rows, errors);
@@ -79,6 +81,10 @@ public static class OverrideCsvParser
} }
var expectedColumns = hasElementTypeColumn ? 3 : 2; var expectedColumns = hasElementTypeColumn ? 3 : 2;
// A spreadsheet export often leaves one trailing delimiter on every row; an empty
// extra last field carries no data, so tolerate exactly one (CMN-9).
if (fields.Count == expectedColumns + 1 && CsvLineSplitter.TryDropTrailingEmptyField(fields, out var trimmed))
fields = trimmed;
if (fields.Count != expectedColumns) if (fields.Count != expectedColumns)
{ {
errors.Add( errors.Add(
@@ -778,6 +778,29 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
// --- Instance lookups for deployment pipeline --- // --- Instance lookups for deployment pipeline ---
/// <inheritdoc /> /// <inheritdoc />
public async Task<bool> ReloadInstanceAsync(Instance instance, CancellationToken cancellationToken = default)
{
var entry = _dbContext.Entry(instance);
if (entry.State == EntityState.Detached)
{
// Loaded without tracking (a NoTracking circuit context): there is no entry to
// reload, so re-read the one column the transition check depends on.
var fresh = await _dbContext.Set<Instance>()
.AsNoTracking()
.Where(i => i.Id == instance.Id)
.Select(i => (InstanceState?)i.State)
.FirstOrDefaultAsync(cancellationToken);
if (fresh is null)
return true;
instance.State = fresh.Value;
return false;
}
// EF detaches the entity when the row has been deleted meanwhile.
await entry.ReloadAsync(cancellationToken);
return entry.State == EntityState.Detached;
}
public async Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default) public async Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default)
{ {
return await _dbContext.Set<Instance>() return await _dbContext.Set<Instance>()
@@ -281,17 +281,27 @@ public class DeploymentService
if (instance == null) if (instance == null)
return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure($"Instance with ID {instanceId} not found.")); return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure($"Instance with ID {instanceId} not found."));
// Validate state transition // Acquire the per-instance operation lock BEFORE validating the state transition:
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "deploy"); // a command that waited behind another one must judge the state that command left
if (transitionError != null) // behind, not the copy loaded before the wait (DEP-2).
return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure(transitionError));
// Acquire per-instance operation lock
var lockHandle = await _lockManager.AcquireAsync( var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken); instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
try try
{ {
if (await _repository.ReloadInstanceAsync(instance, cancellationToken))
{
lockHandle.Dispose();
return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure($"Instance with ID {instanceId} not found."));
}
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "deploy");
if (transitionError != null)
{
lockHandle.Dispose();
return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure(transitionError));
}
return await PrepareUnderLockAsync( return await PrepareUnderLockAsync(
instance, user, session, reconcileGate, lockHandle, cancellationToken); instance, user, session, reconcileGate, lockHandle, cancellationToken);
} }
@@ -1626,13 +1636,18 @@ public class DeploymentService
if (instance == null) if (instance == null)
return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found."); return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found.");
// Lock first, then validate against the state as it is NOW (DEP-2): a command that
// waited behind another one must not act on the copy loaded before the wait.
using var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
if (await _repository.ReloadInstanceAsync(instance, cancellationToken))
return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found.");
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "disable"); var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "disable");
if (transitionError != null) if (transitionError != null)
return Result<InstanceLifecycleResponse>.Failure(transitionError); return Result<InstanceLifecycleResponse>.Failure(transitionError);
using var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
var commandId = Guid.NewGuid().ToString("N"); var commandId = Guid.NewGuid().ToString("N");
var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken); var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken);
var command = new DisableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow); var command = new DisableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow);
@@ -1696,13 +1711,18 @@ public class DeploymentService
if (instance == null) if (instance == null)
return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found."); return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found.");
// Lock first, then validate against the state as it is NOW (DEP-2): a command that
// waited behind another one must not act on the copy loaded before the wait.
using var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
if (await _repository.ReloadInstanceAsync(instance, cancellationToken))
return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found.");
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "enable"); var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "enable");
if (transitionError != null) if (transitionError != null)
return Result<InstanceLifecycleResponse>.Failure(transitionError); return Result<InstanceLifecycleResponse>.Failure(transitionError);
using var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
var commandId = Guid.NewGuid().ToString("N"); var commandId = Guid.NewGuid().ToString("N");
var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken); var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken);
var command = new EnableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow); var command = new EnableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow);
@@ -1765,13 +1785,18 @@ public class DeploymentService
if (instance == null) if (instance == null)
return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found."); return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found.");
// Lock first, then validate against the state as it is NOW (DEP-2): a command that
// waited behind another one must not act on the copy loaded before the wait.
using var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
if (await _repository.ReloadInstanceAsync(instance, cancellationToken))
return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found.");
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "delete"); var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "delete");
if (transitionError != null) if (transitionError != null)
return Result<InstanceLifecycleResponse>.Failure(transitionError); return Result<InstanceLifecycleResponse>.Failure(transitionError);
using var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
var commandId = Guid.NewGuid().ToString("N"); var commandId = Guid.NewGuid().ToString("N");
// A NotDeployed instance has no live Instance Actor at any site, so Delete is // A NotDeployed instance has no live Instance Actor at any site, so Delete is
@@ -625,7 +625,15 @@ public class InboundScriptExecutor
_scriptHandlers[method.Name] = cached; // last-write-wins; concurrent first-callers race benignly _scriptHandlers[method.Name] = cached; // last-write-wins; concurrent first-callers race benignly
} }
handlerTask = cached.Handler(context); // Start the handler OFF the request thread (INB-1). Script.RunAsync runs the script
// synchronously up to its first incomplete await, so invoking the handler inline would
// hold the request thread with no deadline for any script that does CPU work or a
// blocking call before its first await (TimeoutSeconds and client disconnect both
// ignored, no TIMEOUT, abandoned-execution count stuck at 0). Running it on the pool
// lets WaitAsync bound the WHOLE run; a non-cooperative script is then abandoned and
// counted exactly like one that blocks after an await.
var handler = cached.Handler;
handlerTask = Task.Run(() => handler(context), cts.Token);
var result = await handlerTask.WaitAsync(cts.Token); var result = await handlerTask.WaitAsync(cts.Token);
var resultJson = result != null var resultJson = result != null
@@ -285,6 +285,17 @@ public sealed class CookieSessionValidator
identity.AddClaim(new Claim(JwtTokenService.LastActivityClaimType, lastActivity)); identity.AddClaim(new Claim(JwtTokenService.LastActivityClaimType, lastActivity));
} }
else _activity?.Record(rebuilt, now); else _activity?.Record(rebuilt, now);
// SEC-1: a passive request cannot persist the rebuilt ticket, so remember on this node that the
// refresh ran - but only when it changed nothing, so a changed grant keeps being re-derived
// until a non-passive request writes it into the cookie.
if (!recordActivity && _activity is not null && SameGrants(principal, rebuilt))
{
var roleAnchor = ReadAnchor(rebuilt, JwtTokenService.LastRoleRefreshClaimType) ?? now;
var groupAnchor2 = ReadAnchor(rebuilt, JwtTokenService.LastGroupRefreshClaimType) ?? now;
_activity.RecordRefresh(principal, roleAnchor, groupAnchor2);
}
return SessionValidationResult.Replace(rebuilt); return SessionValidationResult.Replace(rebuilt);
} }
@@ -304,9 +315,25 @@ public sealed class CookieSessionValidator
return false; return false;
var anchor = ReadAnchor(principal, JwtTokenService.LastGroupRefreshClaimType); var anchor = ReadAnchor(principal, JwtTokenService.LastGroupRefreshClaimType);
if (_activity?.LastRefreshes(principal) is { } seen && (anchor is null || seen.Group > anchor))
anchor = seen.Group;
return anchor is null || now - anchor.Value >= _directory.Interval; return anchor is null || now - anchor.Value >= _directory.Interval;
} }
// True when two principals carry the same grant claims (roles, groups, scope, identity), ignoring
// the refresh/activity timestamps and the session id.
private static bool SameGrants(ClaimsPrincipal before, ClaimsPrincipal after)
{
static HashSet<string> Grants(ClaimsPrincipal p) => p.Claims
.Where(c => c.Type is not (JwtTokenService.LastActivityClaimType
or JwtTokenService.LastRoleRefreshClaimType
or JwtTokenService.LastGroupRefreshClaimType
or SessionActivityTracker.SessionIdClaim))
.Select(c => c.Type + "\u0000" + c.Value)
.ToHashSet(StringComparer.Ordinal);
return Grants(before).SetEquals(Grants(after));
}
private static DateTimeOffset? ReadAnchor(ClaimsPrincipal principal, string claimType) private static DateTimeOffset? ReadAnchor(ClaimsPrincipal principal, string claimType)
=> principal.FindFirst(claimType) is { } claim && DateTimeOffset.TryParse(claim.Value, out var value) ? value : null; => principal.FindFirst(claimType) is { } claim && DateTimeOffset.TryParse(claim.Value, out var value) ? value : null;
@@ -321,11 +348,14 @@ public sealed class CookieSessionValidator
public bool IsRoleRefreshDue(ClaimsPrincipal principal, DateTimeOffset now) public bool IsRoleRefreshDue(ClaimsPrincipal principal, DateTimeOffset now)
{ {
var claim = principal.FindFirst(JwtTokenService.LastRoleRefreshClaimType); var claim = principal.FindFirst(JwtTokenService.LastRoleRefreshClaimType);
if (claim is null || !DateTimeOffset.TryParse(claim.Value, out var lastRefresh)) DateTimeOffset? lastRefresh = claim is not null && DateTimeOffset.TryParse(claim.Value, out var parsed) ? parsed : null;
if (_activity?.LastRefreshes(principal) is { } seen && (lastRefresh is null || seen.Role > lastRefresh))
lastRefresh = seen.Role;
if (lastRefresh is null)
{ {
return true; return true;
} }
return (now - lastRefresh).TotalMinutes > _options.RoleRefreshThresholdMinutes; return (now - lastRefresh.Value).TotalMinutes > _options.RoleRefreshThresholdMinutes;
} }
} }
@@ -14,6 +14,7 @@ public sealed class SessionActivityTracker
private const int Capacity = 10_000; private const int Capacity = 10_000;
private readonly object _sync = new(); private readonly object _sync = new();
private readonly Dictionary<string, DateTimeOffset> _activity = new(StringComparer.Ordinal); private readonly Dictionary<string, DateTimeOffset> _activity = new(StringComparer.Ordinal);
private readonly Dictionary<string, (DateTimeOffset Role, DateTimeOffset Group)> _refreshes = new(StringComparer.Ordinal);
/// <summary>Returns the newer of the protected cookie anchor and this node's observed activity.</summary> /// <summary>Returns the newer of the protected cookie anchor and this node's observed activity.</summary>
/// <param name="principal">The principal whose session activity is queried.</param> /// <param name="principal">The principal whose session activity is queried.</param>
@@ -42,4 +43,40 @@ public sealed class SessionActivityTracker
_activity[id] = now; _activity[id] = now;
} }
} }
/// <summary>
/// Returns the refresh anchors this node recorded for the principal's session, or
/// <see langword="null"/> when none (SEC-1). They supersede the older anchors in the cookie.
/// </summary>
/// <param name="principal">The principal whose session is queried.</param>
/// <returns>The recorded role and group refresh instants, if any.</returns>
public (DateTimeOffset Role, DateTimeOffset Group)? LastRefreshes(ClaimsPrincipal principal)
{
var id = principal.FindFirst(SessionIdClaim)?.Value;
if (id is null) return null;
lock (_sync)
return _refreshes.TryGetValue(id, out var seen) ? seen : null;
}
/// <summary>
/// Records that a role/group refresh ran for the session without changing its grants. A passive
/// request (<c>/auth/ping</c>, <c>/_blazor</c>) never re-issues the cookie, so without this the old
/// anchors in the cookie made every later ping repeat the refresh (SEC-1). Only an UNCHANGED outcome
/// may be recorded: a changed one must keep being re-derived until a non-passive request persists it
/// in the cookie, otherwise the stale cookie roles would outlive the refresh.
/// </summary>
/// <param name="principal">The principal whose session is recorded.</param>
/// <param name="role">The role-refresh anchor now in effect.</param>
/// <param name="group">The group-refresh anchor now in effect.</param>
public void RecordRefresh(ClaimsPrincipal principal, DateTimeOffset role, DateTimeOffset group)
{
var id = principal.FindFirst(SessionIdClaim)?.Value;
if (id is null || principal.Identity?.IsAuthenticated != true) return;
lock (_sync)
{
if (!_refreshes.ContainsKey(id) && _refreshes.Count >= Capacity)
_refreshes.Remove(_refreshes.MinBy(p => p.Value.Role).Key);
_refreshes[id] = (role, group);
}
}
} }
@@ -0,0 +1,166 @@
using System.CommandLine;
using ZB.MOM.WW.ScadaBridge.CLI;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>CLI-5 (atomic bundle export), CLI-6 (user input errors) and CLI-7 (re-subscribe retry).</summary>
[Collection("Console")]
public class CliInputAndExportTests : IDisposable
{
private readonly string _dir = Directory.CreateDirectory(
Path.Combine(Path.GetTempPath(), $"cli-wp7-{Guid.NewGuid():N}")).FullName;
/// <summary>Removes the temp directory.</summary>
public void Dispose() => Directory.Delete(_dir, recursive: true);
// ---- CLI-5 ---------------------------------------------------------
/// <summary>Verifies a size mismatch leaves an existing good bundle intact and no temp file behind.</summary>
[Fact]
public void StreamBase64ToFile_SizeMismatch_KeepsExistingFileAndCleansTemp()
{
var target = Path.Combine(_dir, "bundle.scadabundle");
File.WriteAllText(target, "last week's good bundle");
var payload = Convert.ToBase64String(new byte[] { 1, 2, 3, 4 });
Assert.Throws<InvalidDataException>(() => BundleCommands.StreamBase64ToFile(payload, target, expectedBytes: 99));
Assert.Equal("last week's good bundle", File.ReadAllText(target));
Assert.Equal([target], Directory.GetFileSystemEntries(_dir));
}
/// <summary>Verifies an undecodable payload leaves an existing file intact and no temp file behind.</summary>
[Fact]
public void StreamBase64ToFile_InvalidBase64_KeepsExistingFileAndCleansTemp()
{
var target = Path.Combine(_dir, "bundle.scadabundle");
File.WriteAllText(target, "good");
Assert.Throws<FormatException>(() => BundleCommands.StreamBase64ToFile("!!!not base64!!!", target, 3));
Assert.Equal("good", File.ReadAllText(target));
Assert.Equal([target], Directory.GetFileSystemEntries(_dir));
}
/// <summary>Verifies a matching size replaces the destination.</summary>
[Fact]
public void StreamBase64ToFile_MatchingSize_ReplacesFile()
{
var target = Path.Combine(_dir, "bundle.scadabundle");
File.WriteAllText(target, "old");
var bytes = new byte[] { 9, 8, 7 };
var written = BundleCommands.StreamBase64ToFile(Convert.ToBase64String(bytes), target, expectedBytes: 3);
Assert.Equal(3, written);
Assert.Equal(bytes, File.ReadAllBytes(target));
Assert.Equal([target], Directory.GetFileSystemEntries(_dir));
}
/// <summary>Verifies the up-front output path probe.</summary>
[Fact]
public void TryProbeOutputPath_RejectsMissingDirectoryAndDirectoryTargets()
{
Assert.True(BundleCommands.TryProbeOutputPath(Path.Combine(_dir, "ok.bin"), out _));
Assert.Empty(Directory.GetFileSystemEntries(_dir));
Assert.False(BundleCommands.TryProbeOutputPath(Path.Combine(_dir, "nope", "ok.bin"), out var missing));
Assert.Contains("does not exist", missing);
Assert.False(BundleCommands.TryProbeOutputPath(_dir, out var isDir));
Assert.Contains("directory", isDir);
}
// ---- CLI-6 ---------------------------------------------------------
/// <summary>Verifies malformed or non-object trigger config is a clean failure, not a thrown exception.</summary>
/// <param name="json">The --trigger-config value.</param>
[Theory]
[InlineData("{not json")]
[InlineData("[1,2]")]
public void TryInjectAnalysisKind_BadConfig_ReturnsFalseWithEnvelope(string json)
{
var originalErr = Console.Error;
var err = new StringWriter();
Console.SetError(err);
try
{
Assert.False(TriggerConfigJson.TryInjectAnalysisKind(json, null, out var result));
Assert.Null(result);
Assert.Contains("INVALID_ARGUMENT", err.ToString());
}
finally { Console.SetError(originalErr); }
}
/// <summary>Verifies the real script-add command exits 1 on malformed trigger config without contacting a server.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task TemplateScriptAdd_MalformedTriggerConfig_ExitsOneCleanly()
{
var originalErr = Console.Error;
var originalOut = Console.Out;
Console.SetError(TextWriter.Null);
Console.SetOut(TextWriter.Null);
try
{
var root = new RootCommand();
var u = new Option<string>("--url") { Recursive = true };
var f = new Option<string>("--format") { Recursive = true };
var user = new Option<string>("--username") { Recursive = true };
var pw = new Option<string>("--password") { Recursive = true };
root.Add(u); root.Add(f); root.Add(user); root.Add(pw);
root.Add(TemplateCommands.Build(u, f, user, pw));
var exit = await root.Parse([
"template", "script", "add", "--template-id", "1", "--name", "S", "--code", "return 1;",
"--trigger-type", "ValueChange", "--trigger-config", "{oops",
"--url", "http://127.0.0.1:1", "--username", "t", "--password", "t"]).InvokeAsync();
Assert.Equal(1, exit);
}
finally { Console.SetError(originalErr); Console.SetOut(originalOut); }
}
// ---- CLI-7 ---------------------------------------------------------
/// <summary>Verifies a re-subscribe that fails twice and then succeeds is retried to success.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Resubscribe_TransientFailures_AreRetried()
{
var attempts = 0;
var failure = await DebugStreamHelpers.ResubscribeWithRetryAsync(
() => ++attempts < 3 ? Task.FromException(new InvalidOperationException("not ready")) : Task.CompletedTask,
_ => TimeSpan.Zero, (_, _) => { }, CancellationToken.None);
Assert.Null(failure);
Assert.Equal(3, attempts);
}
/// <summary>Verifies that a persistent re-subscribe failure is reported to the caller after bounded attempts.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Resubscribe_PersistentFailure_IsReturnedAfterBoundedAttempts()
{
var attempts = 0;
var failure = await DebugStreamHelpers.ResubscribeWithRetryAsync(
() => { attempts++; return Task.FromException(new InvalidOperationException("rejected")); },
_ => TimeSpan.Zero, (_, _) => { }, CancellationToken.None);
Assert.NotNull(failure);
Assert.Equal("rejected", failure!.Message);
Assert.Equal(DebugStreamHelpers.ResubscribeAttempts, attempts);
}
/// <summary>Verifies cancellation during re-subscribe is not reported as a failure.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Resubscribe_Cancelled_IsNotAFailure()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
var failure = await DebugStreamHelpers.ResubscribeWithRetryAsync(
() => Task.FromCanceled(cts.Token), _ => TimeSpan.Zero, (_, _) => { }, cts.Token);
Assert.Null(failure);
}
}
@@ -0,0 +1,37 @@
using System.Net;
using ZB.MOM.WW.ScadaBridge.CLI;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>CLI-6: a bodyless or textless HTTP error must still produce a readable message.</summary>
public class ErrorMessageTests
{
/// <summary>Verifies that an empty error body synthesises "HTTP {status} {reason}".</summary>
/// <param name="code">The HTTP status.</param>
/// <param name="body">The response body.</param>
/// <param name="expected">The expected error text.</param>
[Theory]
[InlineData(502, "", "HTTP 502 Bad Gateway")]
[InlineData(307, "", "HTTP 307 Temporary Redirect")]
[InlineData(500, "{\"error\":\"\",\"code\":\"X\"}", "HTTP 500 Internal Server Error")]
[InlineData(400, "{\"error\":\"bad thing\",\"code\":\"BAD\"}", "bad thing")]
[InlineData(400, "plain text", "plain text")]
public void ToErrorResponse_NeverReturnsEmptyError(int code, string body, string expected)
{
using var response = new HttpResponseMessage((HttpStatusCode)code);
var result = ManagementHttpClient.ToErrorResponse(response, body);
Assert.Equal(expected, result.Error);
Assert.Equal(code, result.StatusCode);
Assert.Null(result.JsonData);
}
/// <summary>Verifies that the server's error code is preserved.</summary>
[Fact]
public void ToErrorResponse_KeepsServerErrorCode()
{
using var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
var result = ManagementHttpClient.ToErrorResponse(response, "{\"error\":\"e\",\"code\":\"BAD\"}");
Assert.Equal("BAD", result.ErrorCode);
}
}
@@ -0,0 +1,53 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// Single-request fake management endpoint: accepts one connection, records the request line
/// and body, and answers with a fixed status and body. The CLI tests are pinned to HTTP Basic
/// (<see cref="CliTestAssemblySetup"/>) so one accepted socket is the whole conversation.
/// </summary>
internal static class FakeManagementServer
{
/// <summary>Runs <paramref name="invoke"/> against a one-shot fake server.</summary>
/// <param name="status">HTTP status line text, e.g. <c>200 OK</c>.</param>
/// <param name="responseBody">The response body (may be empty).</param>
/// <param name="invoke">Receives the base URL; returns the CLI exit code.</param>
/// <returns>The exit code and the request body the server saw.</returns>
public static async Task<(int Exit, string RequestBody)> RunAsync(
string status, string responseBody, Func<string, Task<int>> invoke)
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
try
{
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
var server = Task.Run(async () =>
{
using var client = await listener.AcceptTcpClientAsync();
await using var stream = client.GetStream();
using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true);
await reader.ReadLineAsync();
var length = 0;
while (await reader.ReadLineAsync() is { Length: > 0 } header)
if (header.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase))
length = int.Parse(header.Split(':')[1]);
var buffer = new char[length];
if (length > 0)
await reader.ReadBlockAsync(buffer, 0, length);
var body = Encoding.UTF8.GetBytes(responseBody);
var head = Encoding.ASCII.GetBytes(
$"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
await stream.WriteAsync(head);
await stream.WriteAsync(body);
return new string(buffer);
});
var exit = await invoke($"http://127.0.0.1:{port}");
var requestBody = await server.WaitAsync(TimeSpan.FromSeconds(5));
return (exit, requestBody);
}
finally { listener.Stop(); }
}
}
@@ -0,0 +1,112 @@
using System.CommandLine;
using System.Globalization;
using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// CLI-3: numeric and date options must not depend on the workstation culture. Every test
/// here runs with <c>de-DE</c> as the current culture (comma decimal, day-first dates).
/// </summary>
[Collection("Console")]
public class InvariantCultureOptionTests
{
private static T UnderGerman<T>(Func<T> body)
{
var originalCulture = CultureInfo.CurrentCulture;
var originalUi = CultureInfo.CurrentUICulture;
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
try { return body(); }
finally { CultureInfo.CurrentCulture = originalCulture; CultureInfo.CurrentUICulture = originalUi; }
}
/// <summary>Verifies a dot-decimal setpoint parses as 80.5 (not 805) under de-DE.</summary>
[Fact]
public void DoubleOption_DotDecimal_ParsesInvariantUnderGerman()
{
var value = UnderGerman(() =>
{
var option = CliOptions.CreateInvariantDoubleOption("--hi", "d");
var cmd = new Command("x") { option };
return cmd.Parse(["--hi", "80.5"]).GetValue(option);
});
Assert.Equal(80.5, value);
}
/// <summary>Verifies that a comma-decimal value is a parse error rather than a silently different number.</summary>
[Theory]
[InlineData("80,5")]
[InlineData("1,000")]
[InlineData("abc")]
[InlineData("NaN")]
public void DoubleOption_NonInvariantText_IsParseError(string text)
{
var errors = UnderGerman(() =>
{
var option = CliOptions.CreateInvariantDoubleOption("--hi", "d");
var cmd = new Command("x") { option };
return cmd.Parse(["--hi", text]).Errors.Count;
});
Assert.NotEqual(0, errors);
}
/// <summary>Verifies that a timestamp with no offset is read as UTC, day/month order invariant, under de-DE.</summary>
[Fact]
public void DateOption_NoOffset_IsUtcAndInvariantUnderGerman()
{
var value = UnderGerman(() =>
{
var option = CliOptions.CreateInvariantDateOption("--from", "d");
var cmd = new Command("x") { option };
return cmd.Parse(["--from", "2026-11-01T00:00:00"]).GetValue(option);
});
Assert.Equal(new DateTimeOffset(2026, 11, 1, 0, 0, 0, TimeSpan.Zero), value);
}
/// <summary>Verifies the actual <c>template alarm add --hi 80.5</c> command stores 80.5 under de-DE.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task TemplateAlarmAdd_Hi_SendsInvariantNumberUnderGerman()
{
var originalCulture = CultureInfo.CurrentCulture;
var originalOut = Console.Out;
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
Console.SetOut(TextWriter.Null);
try
{
var (exit, body) = await FakeManagementServer.RunAsync("200 OK", "{}", async url =>
{
var root = new RootCommand();
var u = new Option<string>("--url") { Recursive = true };
var f = new Option<string>("--format") { Recursive = true };
var user = new Option<string>("--username") { Recursive = true };
var pw = new Option<string>("--password") { Recursive = true };
root.Add(u); root.Add(f); root.Add(user); root.Add(pw);
root.Add(TemplateCommands.Build(u, f, user, pw));
return await root.Parse([
"template", "alarm", "add", "--template-id", "1", "--name", "A", "--trigger-type", "HiLo",
"--priority", "500", "--attribute", "Temp", "--hi", "80.5", "--lo", "10.25",
"--url", url, "--username", "t", "--password", "t"]).InvokeAsync();
});
Assert.Equal(0, exit);
using var doc = JsonDocument.Parse(body);
var config = doc.RootElement.GetProperty("payload").GetProperty("triggerConfiguration").GetString()!;
using var cfg = JsonDocument.Parse(config);
Assert.Equal(80.5, cfg.RootElement.GetProperty("hi").GetDouble());
Assert.Equal(10.25, cfg.RootElement.GetProperty("lo").GetDouble());
}
finally
{
Console.SetOut(originalOut);
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = originalCulture;
}
}
/// <summary>Verifies the audit time spec parser rejects out-of-range relative offsets as FormatException.</summary>
[Theory]
[InlineData("99999999999d")]
[InlineData("2147483647d")]
public void ResolveTimeSpec_OutOfRange_IsFormatException(string spec)
=> Assert.Throws<FormatException>(() => AuditQueryHelpers.ResolveTimeSpec(spec, DateTimeOffset.UtcNow));
}
@@ -0,0 +1,78 @@
using System.CommandLine;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// CLI-1: site-relayed commands return their result record as HTTP 200 with the failure in a
/// <c>success</c> flag. The CLI must exit 1 for <c>success:false</c>.
/// </summary>
[Collection("Console")]
public class SuccessFlagExitCodeTests
{
private static RootCommand BuildRoot()
{
var root = new RootCommand();
var url = new Option<string>("--url") { Recursive = true };
var format = new Option<string>("--format") { Recursive = true };
var user = new Option<string>("--username") { Recursive = true };
var password = new Option<string>("--password") { Recursive = true };
root.Add(url); root.Add(format); root.Add(user); root.Add(password);
root.Add(CachedCallCommands.Build(url, format, user, password));
var dc = DataConnectionCommands.Build(url, format, user, password);
ConnectionBrowseCommands.AddTo(dc, url, format, user, password);
root.Add(dc);
return root;
}
/// <summary>Verifies that the shared handler maps the <c>success</c> flag to the exit code.</summary>
/// <param name="json">The response body.</param>
/// <param name="expected">The expected exit code.</param>
[Theory]
[InlineData("{\"correlationId\":\"c\",\"success\":true,\"errorMessage\":null}", 0)]
[InlineData("{\"correlationId\":\"c\",\"success\":false,\"errorMessage\":\"not parked\"}", 1)]
[InlineData("{\"Success\":false,\"Error\":\"one node failed\"}", 1)]
[InlineData("{\"certs\":[]}", 0)]
[InlineData("[1,2]", 0)]
public void HandleSuccessFlagResponse_MapsFlagToExitCode(string json, int expected)
{
var originalOut = Console.Out;
var originalErr = Console.Error;
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
try
{
Assert.Equal(expected, CommandHelpers.HandleSuccessFlagResponse(json, "json"));
}
finally { Console.SetOut(originalOut); Console.SetError(originalErr); }
}
/// <summary>Verifies that each relayed command exits 1 on success:false and 0 on success:true.</summary>
/// <param name="arguments">Command line (without connection options).</param>
/// <param name="response">The response body.</param>
/// <param name="expected">Expected exit code.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData("cached-call retry --site-id s --tracked-operation-id 11111111-2222-3333-4444-555555555555", "{\"correlationId\":\"c\",\"success\":false,\"errorMessage\":\"not parked\"}", 1)]
[InlineData("cached-call retry --site-id s --tracked-operation-id 11111111-2222-3333-4444-555555555555", "{\"correlationId\":\"c\",\"success\":true}", 0)]
[InlineData("cached-call discard --site-id s --tracked-operation-id 11111111-2222-3333-4444-555555555555", "{\"correlationId\":\"c\",\"success\":false,\"errorMessage\":\"gone\"}", 1)]
[InlineData("data-connection certs remove --site s --thumbprint AB", "{\"success\":false,\"error\":\"node B unreachable\",\"certs\":null}", 1)]
[InlineData("data-connection certs remove --site s --thumbprint AB", "{\"success\":true,\"error\":null,\"certs\":[]}", 0)]
public async Task RelayedCommand_ExitCodeFollowsSuccessFlag(string arguments, string response, int expected)
{
var originalOut = Console.Out;
var originalErr = Console.Error;
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
try
{
var (exit, _) = await FakeManagementServer.RunAsync("200 OK", response, async url =>
{
var args = arguments.Split(' ').Concat(new[] { "--url", url, "--username", "t", "--password", "t", "--format", "json" }).ToArray();
return await BuildRoot().Parse(args).InvokeAsync();
});
Assert.Equal(expected, exit);
}
finally { Console.SetOut(originalOut); Console.SetError(originalErr); }
}
}
@@ -655,6 +655,27 @@ public class FlowGraphBuilderTests
Assert.Equal(sa.Lifecycle!.Select(r => r.Kind), sb.Lifecycle!.Select(r => r.Kind)); Assert.Equal(sa.Lifecycle!.Select(r => r.Kind), sb.Lifecycle!.Select(r => r.Kind));
} }
/// <summary>
/// CMN-6: the resolve row is written centrally and the submit row at the site; with the site clock
/// ahead, the submit row's timestamp is LATER than the delivery's. The fold must still treat the
/// resolve as terminal, not render the completed operation as Pending.
/// </summary>
[Fact]
public void Fold_WithCrossNodeClockSkew_StillTreatsResolveAsTerminal()
{
var corr = Guid.NewGuid();
var submit = Outbound(AuditChannel.ApiOutbound, AuditKind.CachedSubmit, AuditStatus.Submitted, 2000, corr, "Delmia.Ack", node: "node-a", request: "req");
var resolve = Outbound(AuditChannel.ApiOutbound, AuditKind.CachedResolve, AuditStatus.Delivered, 1000, corr, "Delmia.Ack", node: "central-a", response: "res");
var graph = FlowGraphBuilder.Build([SiteRunRow(20), submit, resolve]);
var step = Assert.Single(graph.Steps, s => s.Kind == FlowStepKind.ApiCall);
Assert.Equal(FlowStepOutcome.Ok, step.Outcome);
Assert.Equal("res", step.OutputJson);
Assert.Equal(["CachedSubmit", "CachedResolve"], step.Lifecycle!.Select(r => r.Kind));
Assert.True(step.DurationMs >= 0);
}
/// <summary>Verifies that a cached step whose submit row is missing is still treated as asynchronous.</summary> /// <summary>Verifies that a cached step whose submit row is missing is still treated as asynchronous.</summary>
[Fact] [Fact]
public void CachedStep_WhoseSubmitRowIsMissing_IsStillAsync() public void CachedStep_WhoseSubmitRowIsMissing_IsStillAsync()
@@ -197,4 +197,16 @@ public class NativeAlarmSourceOverrideCsvParserTests
Assert.Empty(result.Rows); Assert.Empty(result.Rows);
Assert.Contains(result.Errors, e => e.Contains("Line 2") && e.Contains("MesReportable")); Assert.Contains(result.Errors, e => e.Contains("Line 2") && e.Contains("MesReportable"));
} }
/// <summary>Verifies that one trailing delimiter on every row (a spreadsheet export) is tolerated, header included.</summary>
[Fact]
public void Parse_TrailingCommaOnEveryRow_IsTolerated()
{
const string csv = "SourceName,Connection,SourceReference,Filter,\nPressure,OPC,ns=2;s=P,Active,\n";
var result = NativeAlarmSourceOverrideCsvParser.Parse(csv);
Assert.Empty(result.Errors);
Assert.Equal("Pressure", Assert.Single(result.Rows).SourceName);
}
} }
@@ -262,4 +262,39 @@ public class OverrideCsvParserTests
Assert.Equal("a,b", row.Value); Assert.Equal("a,b", row.Value);
Assert.Equal("Type", row.ElementType); Assert.Equal("Type", row.ElementType);
} }
/// <summary>Verifies that one trailing delimiter on every row (a spreadsheet export) is tolerated, header included.</summary>
[Fact]
public void Parse_TrailingCommaOnEveryRow_IsTolerated()
{
const string csv = "AttributeName,Value,ElementType,\nSetpoint,42,Int32,\nName,Pump A,,\n";
var result = OverrideCsvParser.Parse(csv);
Assert.Empty(result.Errors);
Assert.Equal(2, result.Rows.Count);
Assert.Equal("Int32", result.Rows[0].ElementType);
Assert.Null(result.Rows[1].ElementType);
}
/// <summary>Verifies that a two-column file with a trailing comma is tolerated.</summary>
[Fact]
public void Parse_TwoColumnWithTrailingComma_IsTolerated()
{
var result = OverrideCsvParser.Parse("AttributeName,Value,\nSetpoint,42,\n");
Assert.Empty(result.Errors);
Assert.Equal("42", Assert.Single(result.Rows).Value);
}
/// <summary>Verifies that a genuinely wrong column count, or a NON-empty extra column, stays an error.</summary>
[Fact]
public void Parse_ExtraNonEmptyColumn_StillAnError()
{
var result = OverrideCsvParser.Parse("AttributeName,Value\nSetpoint,42,extra\nA,1,,\n");
Assert.Empty(result.Rows);
Assert.Equal(2, result.Errors.Count);
Assert.All(result.Errors, e => Assert.Contains("expected 2 columns", e));
}
} }
@@ -0,0 +1,26 @@
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Types.Audit;
/// <summary>Review CMN-12: stored enum tokens parse case-insensitively, like the query parsers.</summary>
public class AuditRowProjectionParseEnumTests
{
/// <summary>A mis-cased stored token resolves to its member rather than the fallback.</summary>
/// <param name="stored">The stored token.</param>
[Theory]
[InlineData("DbOutbound")]
[InlineData("dboutbound")]
[InlineData("DBOUTBOUND")]
public void ParseEnum_IsCaseInsensitive(string stored)
=> Assert.Equal(AuditChannel.DbOutbound, AuditRowProjection.ParseEnum(stored, AuditChannel.ApiInbound));
/// <summary>Unknown or empty tokens still fall back.</summary>
/// <param name="stored">The stored token.</param>
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("NoSuchChannel")]
public void ParseEnum_UnknownFallsBack(string? stored)
=> Assert.Equal(AuditChannel.ApiInbound, AuditRowProjection.ParseEnum(stored, AuditChannel.ApiInbound));
}
@@ -0,0 +1,44 @@
using System.Text.Json;
using ZB.MOM.WW.ScadaBridge.Commons.Types.InboundApi;
namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Types.InboundApi;
/// <summary>Review CMN-7 (required matching) and CMN-8 (unknown legacy types).</summary>
public class InboundApiSchemaWp7Tests
{
/// <summary>A "required" entry spelled with different casing than the property still makes it required.</summary>
[Fact]
public void Required_MatchesPropertyNamesCaseInsensitively()
{
const string json = """{"type":"object","properties":{"WorkOrders":{"type":"string"},"Other":{"type":"string"}},"required":["workorders"]}""";
var schema = InboundApiSchema.Parse(json)!;
Assert.True(schema.Fields.Single(f => f.Name == "WorkOrders").Required);
Assert.False(schema.Fields.Single(f => f.Name == "Other").Required);
}
/// <summary>A typo'd legacy type is a parse error naming the field and the valid vocabulary.</summary>
/// <param name="legacy">The legacy parameter array.</param>
[Theory]
[InlineData("""[{"name":"Qty","type":"strign"}]""")]
[InlineData("""[{"name":"Items","type":"List","itemType":"intger"}]""")]
public void LegacyArray_UnknownType_ThrowsClearError(string legacy)
{
var ex = Assert.Throws<JsonException>(() => InboundApiSchema.Parse(legacy));
Assert.Contains("unknown", ex.Message);
Assert.Contains("Valid types", ex.Message);
}
/// <summary>Every legacy alias still parses.</summary>
[Fact]
public void LegacyArray_KnownAliases_StillParse()
{
const string legacy = """[{"name":"a","type":"Integer"},{"name":"b","type":"Float"},{"name":"c","type":"DateTime"},{"name":"d","type":"List","itemType":"String"},{"name":"e","type":"Object"},{"name":"f","type":"Boolean"},{"name":"g"}]""";
var schema = InboundApiSchema.Parse(legacy)!;
Assert.Equal(7, schema.Fields.Count);
}
}
@@ -0,0 +1,94 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;
/// <summary>
/// DEP-2: <see cref="DeploymentManagerRepository.ReloadInstanceAsync"/> refreshes an instance a command
/// loaded before it waited for the per-instance operation lock. The competing write goes through
/// <c>ExecuteUpdate</c>/<c>ExecuteDelete</c> so the tracked copy stays stale, as it would under a
/// second DbContext.
/// </summary>
public class ReloadInstanceRepositoryTests : IDisposable
{
private readonly ScadaBridgeDbContext _context = SqliteTestHelper.CreateInMemoryContext();
private readonly DeploymentManagerRepository _repository;
/// <summary>Initializes the repository under test.</summary>
public ReloadInstanceRepositoryTests() => _repository = new DeploymentManagerRepository(_context);
/// <summary>Releases the database context.</summary>
public void Dispose()
{
_context.Database.CloseConnection();
_context.Dispose();
}
private async Task<int> SeedAsync(InstanceState state)
{
var site = new Site("S", "SI-S");
_context.Sites.Add(site);
var template = new Template("T");
_context.Templates.Add(template);
await _context.SaveChangesAsync();
var instance = new Instance("Inst") { SiteId = site.Id, TemplateId = template.Id, State = state };
_context.Instances.Add(instance);
await _context.SaveChangesAsync();
return instance.Id;
}
/// <summary>A tracked entity picks up a state written behind its back.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReloadInstanceAsync_Tracked_SeesStateWrittenMeanwhile()
{
var id = await SeedAsync(InstanceState.NotDeployed);
var instance = (await _repository.GetInstanceByIdAsync(id))!;
await _context.Instances.Where(i => i.Id == id)
.ExecuteUpdateAsync(s => s.SetProperty(i => i.State, InstanceState.Enabled));
Assert.Equal(InstanceState.NotDeployed, instance.State); // stale, as in the race
var removed = await _repository.ReloadInstanceAsync(instance);
Assert.False(removed);
Assert.Equal(InstanceState.Enabled, instance.State);
Assert.Equal(EntityState.Unchanged, _context.Entry(instance).State);
}
/// <summary>An untracked entity gets its state re-read.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReloadInstanceAsync_Untracked_SeesStateWrittenMeanwhile()
{
var id = await SeedAsync(InstanceState.Enabled);
var instance = await _context.Instances.AsNoTracking().SingleAsync(i => i.Id == id);
await _context.Instances.Where(i => i.Id == id)
.ExecuteUpdateAsync(s => s.SetProperty(i => i.State, InstanceState.Disabled));
var removed = await _repository.ReloadInstanceAsync(instance);
Assert.False(removed);
Assert.Equal(InstanceState.Disabled, instance.State);
}
/// <summary>A row deleted meanwhile is reported as removed, tracked or not.</summary>
/// <param name="tracked">Whether the instance is loaded with tracking.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ReloadInstanceAsync_RowDeleted_ReportsRemoved(bool tracked)
{
var id = await SeedAsync(InstanceState.Enabled);
var instance = tracked
? (await _repository.GetInstanceByIdAsync(id))!
: await _context.Instances.AsNoTracking().SingleAsync(i => i.Id == id);
await _context.Instances.Where(i => i.Id == id).ExecuteDeleteAsync();
Assert.True(await _repository.ReloadInstanceAsync(instance));
}
}
@@ -1326,6 +1326,84 @@ public class DeploymentServiceTests : TestKit
Assert.Equal(1, serializationCounters.MaxConcurrent); Assert.Equal(1, serializationCounters.MaxConcurrent);
} }
// ── DEP-2: validate the state transition AFTER the operation lock is held ──
/// <summary>
/// A command that waited behind another one must judge the state that command left behind:
/// here the instance was Enabled when loaded, but another Disable finished while this one
/// waited for the lock. Validating the stale copy would send a second Disable to the site.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisableInstanceAsync_StateChangedWhileWaitingForLock_FailsTransitionCheckOnFreshState()
{
var instance = new Instance("RaceDisable") { Id = 80, SiteId = 1, State = InstanceState.Enabled };
_repo.GetInstanceByIdAsync(80, Arg.Any<CancellationToken>()).Returns(instance);
// The reload observes what the lock holder committed.
_repo.ReloadInstanceAsync(instance, Arg.Any<CancellationToken>()).Returns(_ =>
{
instance.State = InstanceState.Disabled;
return Task.FromResult(false);
});
using var held = await _lockManager.AcquireAsync("RaceDisable", TimeSpan.FromSeconds(5), CancellationToken.None);
var pending = _service.DisableInstanceAsync(80, "admin");
await Task.Delay(100);
Assert.False(pending.IsCompleted, "the command must wait for the lock before validating");
held.Dispose();
var result = await pending;
// The default _service has no comm actor: reaching the site would throw, so a clean
// failure proves the transition check ran on the fresh Disabled state first.
Assert.True(result.IsFailure);
Assert.Contains("not allowed", result.Error);
}
/// <summary>
/// Instance X was NotDeployed when the Delete loaded it, then a deploy that held the lock left it
/// Enabled. The Delete must take the site round-trip, not the NotDeployed central-only shortcut.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DeleteInstanceAsync_DeployCompletedWhileWaiting_TearsDownSiteInsteadOfSkippingIt()
{
var instance = new Instance("RaceDelete") { Id = 81, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(81, Arg.Any<CancellationToken>()).Returns(instance);
_repo.ReloadInstanceAsync(instance, Arg.Any<CancellationToken>()).Returns(_ =>
{
instance.State = InstanceState.Enabled;
return Task.FromResult(false);
});
var counters = new ReconcileProbeCounters();
var commActor = Sys.ActorOf(Props.Create(() =>
new ReconcileProbeActor(counters, siteHash: "x", failQuery: false)));
var service = CreateServiceWithCommActor(commActor);
var result = await service.DeleteInstanceAsync(81, "admin");
Assert.True(result.IsSuccess);
await _audit.Received().LogAsync(
"admin", "Delete", "Instance", "81", "RaceDelete",
Arg.Is<object>(o => !o.ToString()!.Contains("SiteRoundTripSkipped")), Arg.Any<CancellationToken>());
}
/// <summary>An instance deleted by another command while this one waited is reported as not found.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task EnableInstanceAsync_InstanceDeletedWhileWaiting_ReturnsNotFound()
{
var instance = new Instance("RaceGone") { Id = 82, SiteId = 1, State = InstanceState.Disabled };
_repo.GetInstanceByIdAsync(82, Arg.Any<CancellationToken>()).Returns(instance);
_repo.ReloadInstanceAsync(instance, Arg.Any<CancellationToken>()).Returns(true);
var result = await _service.EnableInstanceAsync(82, "admin");
Assert.True(result.IsFailure);
Assert.Contains("not found", result.Error);
}
// ── Query-the-site-before-redeploy idempotency ── // ── Query-the-site-before-redeploy idempotency ──
/// <summary> /// <summary>
@@ -1106,6 +1106,40 @@ public class InboundScriptExecutorTests
Assert.Equal(0, _executor.AbandonedExecutionCount); // ...and DECREMENTED Assert.Equal(0, _executor.AbandonedExecutionCount); // ...and DECREMENTED
} }
/// <summary>
/// INB-1: a script that blocks BEFORE its first await (CPU loop, <c>.Result</c> on a helper) used to
/// run inline on the request thread, so the method timeout could not fire until it returned. The
/// request must come back with TIMEOUT at the deadline and the orphan must be counted.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ScriptBlockingBeforeFirstAwait_StillTimesOutAtTheDeadline()
{
var release = new ManualResetEventSlim();
_executor.RegisterHandler("spin", _ =>
{
release.Wait(TimeSpan.FromSeconds(30)); // synchronous block: no await has happened yet
return Task.FromResult<object?>(1);
});
var method = new ApiMethod("spin", "unused") { Id = 10, TimeoutSeconds = 1 };
var started = System.Diagnostics.Stopwatch.StartNew();
var execution = _executor.ExecuteAsync(
method, new Dictionary<string, object?>(), _route, TimeSpan.FromMilliseconds(200));
var finished = await Task.WhenAny(execution, Task.Delay(TimeSpan.FromSeconds(10)));
Assert.Same(execution, finished); // pre-fix: the call itself never returned until released
var result = await execution;
Assert.False(result.Success);
Assert.Equal("TIMEOUT", result.ErrorCode);
Assert.True(started.Elapsed < TimeSpan.FromSeconds(5), $"took {started.Elapsed}");
Assert.Equal(1, _executor.AbandonedExecutionCount);
release.Set(); // the orphan finishes; its continuation cleans up
await Task.Delay(300);
Assert.Equal(0, _executor.AbandonedExecutionCount);
}
// --- Flow Debugger step logs (design 2026-09-09 D4/D5/D7): the Log global --- // --- Flow Debugger step logs (design 2026-09-09 D4/D5/D7): the Log global ---
/// <summary>Verifies that a traced run emits one ScriptLog row on the trace sink.</summary> /// <summary>Verifies that a traced run emits one ScriptLog row on the trace sink.</summary>
@@ -257,6 +257,58 @@ public class CookieSessionValidatorTests
Assert.Equal(SessionValidationAction.Reject, result.Action); Assert.Equal(SessionValidationAction.Reject, result.Action);
} }
private static CookieSessionValidator CreateTrackedValidator(
IGroupRoleMapper<string> mapper, TimeProvider clock, SessionActivityTracker tracker) =>
new(mapper, Microsoft.Extensions.Options.Options.Create(Options()), clock,
NullLogger<CookieSessionValidator>.Instance, tracker);
/// <summary>
/// SEC-1: a passive request cannot write the cookie, so an UNCHANGED role refresh is remembered on the
/// node; the next ping (still carrying the old cookie anchors) must not repeat the re-map.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ValidateAsync_PassiveUnchangedRefresh_IsNotRepeatedOnTheNextPing()
{
var clock = new TestTimeProvider(Start);
var mapping = new RoleMappingResult([Roles.Administrator], [], true);
var mapper = new FakeGroupRoleMapper(mapping);
var sut = CreateTrackedValidator(mapper, clock, new SessionActivityTracker());
var cookie = Session(Start, ["SCADA-Admins"], mapping); // the ticket never changes: passive requests cannot re-issue it
clock.Advance(TimeSpan.FromMinutes(16));
var first = await sut.ValidateAsync(cookie, recordActivity: false);
var second = await sut.ValidateAsync(cookie, recordActivity: false);
clock.Advance(TimeSpan.FromMinutes(14)); // 30 min since login, 14 since the remembered refresh
var third = await sut.ValidateAsync(cookie, recordActivity: false);
Assert.Equal(SessionValidationAction.Replace, first.Action);
Assert.Equal(SessionValidationAction.Keep, second.Action);
Assert.Equal(1, mapper.CallCount);
Assert.Equal(SessionValidationAction.Keep, third.Action);
Assert.Equal(1, mapper.CallCount);
}
/// <summary>A passive refresh that CHANGED the grants is not remembered: it is re-derived until a non-passive request persists it.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ValidateAsync_PassiveChangedRefresh_KeepsBeingRederived()
{
var clock = new TestTimeProvider(Start);
var mapper = new FakeGroupRoleMapper(new RoleMappingResult([Roles.Viewer], [], false));
var sut = CreateTrackedValidator(mapper, clock, new SessionActivityTracker());
var cookie = Session(Start, ["SCADA-Admins"], new RoleMappingResult([Roles.Administrator], [], true));
clock.Advance(TimeSpan.FromMinutes(16));
var first = await sut.ValidateAsync(cookie, recordActivity: false);
var second = await sut.ValidateAsync(cookie, recordActivity: false);
Assert.Equal(SessionValidationAction.Replace, first.Action);
Assert.Equal(SessionValidationAction.Replace, second.Action);
Assert.Equal([Roles.Viewer], second.Principal!.FindAll(JwtTokenService.RoleClaimType).Select(c => c.Value));
Assert.Equal(2, mapper.CallCount);
}
/// <summary>A refresh that keeps one role still replaces the principal (the zero-role rule is not over-broad).</summary> /// <summary>A refresh that keeps one role still replaces the principal (the zero-role rule is not over-broad).</summary>
/// <returns>A task that represents the asynchronous operation.</returns> /// <returns>A task that represents the asynchronous operation.</returns>
[Fact] [Fact]