fix(commons): flow fold ranks lifecycle before time, schema required/legacy-type checks, CSV trailing comma, case-insensitive audit enum parse (CMN-6,7,8,9,12, WP7 task 7.5)

This commit is contained in:
Joseph Doherty
2026-12-03 09:48:24 -05:00
parent 517f093ce9
commit 76c50a29c2
13 changed files with 214 additions and 12 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).
+1 -1
View File
@@ -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.
@@ -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(
@@ -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);
}
}