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
@@ -414,6 +414,16 @@ public interface IDeploymentManagerRepository
/// <returns>The instance, or null if not found.</returns>
Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
/// <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.
/// </summary>
/// <param name="uniqueName">The unique instance name.</param>
@@ -180,7 +180,7 @@ public static class AuditRowProjection
}
/// <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,
/// or does not match any declared member name — so callers never throw on an
/// 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>
/// <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
=> !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
: fallback;
}
@@ -22,6 +22,25 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Types;
/// </remarks>
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>
/// 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
@@ -376,9 +376,10 @@ public static class FlowGraphBuilder
}
/// <summary>
/// Orders the rows of one outbound operation when timestamps tie: submit before attempts before the
/// resolve, then non-terminal before terminal statuses — so "first" and "latest" never fall back
/// to GUID order for rows written in the same tick.
/// Orders the rows of one outbound operation: submit before attempts before the resolve, then
/// non-terminal before terminal statuses. This is the PRIMARY sort key of the fold (time only breaks
/// ties between rows of equal rank, e.g. repeated attempts), so cross-node clock skew cannot put a
/// non-terminal row last.
/// </summary>
/// <param name="kind">The audit row kind.</param>
/// <param name="status">The audit row status.</param>
@@ -446,8 +447,12 @@ public static class FlowGraphBuilder
var key = ((FlowStepKind, Guid))item;
var rows = groups[key]
.OrderBy(r => r.Row.OccurredAtUtc)
.ThenBy(r => LifecycleRank(r.Row.Kind, r.Row.Status))
// Lifecycle rank FIRST, time only as a tiebreaker (CMN-6): the rows of one cached
// 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)
.ToList();
var first = rows[0].Step;
@@ -202,7 +202,10 @@ public sealed class InboundApiSchema
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)
{
foreach (var r in req.EnumerateArray())
@@ -384,10 +387,16 @@ public sealed class InboundApiSchema
StringComparison.OrdinalIgnoreCase));
var normalized = NormalizeType(rawType);
EnsureKnownLegacyType(name!, rawType, normalized);
InboundApiSchema schema;
if (normalized == "array")
{
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
{
Type = "array",
@@ -405,6 +414,26 @@ public sealed class InboundApiSchema
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>
/// Case-insensitive object-member lookup, used only on the legacy flat-array
/// path so both PascalCase and lowercase legacy keys resolve.
@@ -92,7 +92,9 @@ public static class NativeAlarmSourceOverrideCsvParser
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);
return new NativeAlarmSourceOverrideCsvParseResult(rows, errors);
@@ -103,6 +105,9 @@ public static class NativeAlarmSourceOverrideCsvParser
}
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)
{
errors.Add(
@@ -68,7 +68,9 @@ public static class OverrideCsvParser
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);
return new OverrideCsvParseResult(rows, errors);
@@ -79,6 +81,10 @@ public static class OverrideCsvParser
}
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)
{
errors.Add(