diff --git a/docs/Telemetry.md b/docs/Telemetry.md index 49dd3be53..bbf8b9b85 100644 --- a/docs/Telemetry.md +++ b/docs/Telemetry.md @@ -302,6 +302,13 @@ for the full keys table. In brief: - **`TelemetryDial`** (central side): `Mode` (`Dps`|`Grpc`), `ApiKey` (must equal the nodes' `Telemetry:ApiKey`), `ContactRefreshSeconds` (default `60`), `CallTimeoutSeconds` (default `30`). +A dial counts as **established** when the node's response headers arrive (the node flushes them as soon as +its hub subscription is attached), not on the first record — a node with no driver instances has nothing to +replay and may stay silent indefinitely, so `CallTimeoutSeconds` bounds only the time to establish, never a +quiet established stream (#997 A-7). Against a node that predates the header flush the old behaviour holds +(the deadline applies until its first event). The deadline-cut warning is throttled by the dialer's failure +streak (first miss, then every 10th). + A driver-role node with `Telemetry:Mode=Grpc` must set `GrpcListenPort > 0` (nothing to serve otherwise), and `Grpc` mode on either side requires a non-empty `ApiKey` — both are enforced by `ValidateOnStart` validators, fail-fast at boot. diff --git a/docs/Uns.md b/docs/Uns.md index ffd5e38ed..760fe0336 100644 --- a/docs/Uns.md +++ b/docs/Uns.md @@ -81,6 +81,19 @@ than whoever typed it. In the CSV import a bad name is reported as an **error**, not a skip: a skip means "you already have this row", which would say the equipment exists when it does not. +**Sibling names are unique (#997 A-3).** The ConfigDb enforces unique +`(ClusterId, Name)` areas, `(UnsAreaId, Name)` lines and `(UnsLineId, Name)` +equipment. `UnsTreeService` pre-checks all three on create **and** update +(excluding the row itself, and honouring a move to another cluster/area/line), +answering `UnsMutationResult(false, "An area named 'x' already exists in this +cluster.")` instead of letting a `DbUpdateException` escape to +`PageErrorBoundary`. A concurrent-insert race that slips past the pre-check is +caught as `DbUpdateException` and reported as a friendly retry message. The CSV +import tracks `(UnsLineId, Name)` (DB rows + earlier rows in the file) and +reports a clash, or a field longer than its column (`Manufacturer`, `Model`, …), +as a per-row **error**; a lost race fails the whole atomic batch with one message +and imports nothing. + ## Equipment page (`/uns/equipment/{id}`) Clicking **Open** on an Equipment row (or **+ Equipment** on a Line) navigates diff --git a/docs/security.md b/docs/security.md index bd2c4e1db..9dc8ffaf7 100644 --- a/docs/security.md +++ b/docs/security.md @@ -589,7 +589,9 @@ identity"). It is held only in the encrypted Secrets store (`otopcua/apikeys//galaxy-ack-{user,password}`), never in the ConfigDb or the artifact; keys without one and anonymous sessions use the Galaxy driver's `AlarmAck` fallback account, and with neither the ack is refused before it reaches the gateway. Deleting a key on `/apikeys` removes its -identity. See [docs/drivers/Galaxy.md § Alarm acknowledge credential](drivers/Galaxy.md#alarm-acknowledge-credential). +identity (if the Secrets store is down at that moment the list still refreshes and the error names the two +leftover secrets to remove by hand). Re-saving an existing identity with the password box **blank keeps the +stored password** (the editor never renders it back); a first-time save needs a password (#997 A-4/A-9). See [docs/drivers/Galaxy.md § Alarm acknowledge credential](drivers/Galaxy.md#alarm-acknowledge-credential). ### Anonymous is a normal principal diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ApiKeyAck/ApiKeyGalaxyAckIdentityService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ApiKeyAck/ApiKeyGalaxyAckIdentityService.cs index e54114737..6130d6018 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ApiKeyAck/ApiKeyGalaxyAckIdentityService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ApiKeyAck/ApiKeyGalaxyAckIdentityService.cs @@ -26,7 +26,10 @@ public interface IApiKeyGalaxyAckIdentityService /// The public key id. /// Galaxy user; required. /// Optional domain. - /// Password; may be empty (Galaxy accounts can have empty passwords). + /// + /// The new password. Null/empty on an existing identity keeps the stored password untouched (the editor + /// never renders it back); null/empty with no existing identity is refused with . + /// /// The admin performing the change, for audit. /// The cancellation token. /// A task representing the operation. @@ -105,10 +108,22 @@ public sealed class ApiKeyGalaxyAckIdentityService : IApiKeyGalaxyAckIdentitySer var userName = new SecretName(GalaxyAckIdentitySecrets.UserSecretName(apiKeyId)); var passwordName = new SecretName(GalaxyAckIdentitySecrets.PasswordSecretName(apiKeyId)); - // Password FIRST: the driver refuses a user without a password, so writing in this order means a - // concurrent ack never sees a half-written identity it would act on. - await UpsertAsync(passwordName, password ?? string.Empty, $"Galaxy ack password for API key {apiKeyId}", actor, ct) - .ConfigureAwait(false); + if (string.IsNullOrEmpty(password)) + { + // The editor never renders a stored password back, so a blank box means "keep the current one" - + // overwriting it with an empty value would silently break every ack on this key (#997 A-4). With no + // existing identity there is nothing to keep, so a blank password is refused instead (as is a half-configured identity whose password secret is gone). + var existing = await _store.GetAsync(passwordName, ct).ConfigureAwait(false); + if (existing is null || existing.IsDeleted) + throw new ArgumentException("A password is required when setting a Galaxy ack identity.", nameof(password)); + } + else + { + // Password FIRST: the driver refuses a user without a password, so writing in this order means a + // concurrent ack never sees a half-written identity it would act on. + await UpsertAsync(passwordName, password, $"Galaxy ack password for API key {apiKeyId}", actor, ct) + .ConfigureAwait(false); + } await UpsertAsync(userName, GalaxyAckIdentitySecrets.FormatIdentity(user, domain), $"Galaxy ack user for API key {apiKeyId}", actor, ct) .ConfigureAwait(false); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Browsing/BrowseSessionReaper.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Browsing/BrowseSessionReaper.cs index 251d9df87..d3be7df03 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Browsing/BrowseSessionReaper.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Browsing/BrowseSessionReaper.cs @@ -20,20 +20,39 @@ public sealed class BrowseSessionReaper( /// How often the reaper checks the registry. public static readonly TimeSpan TickInterval = TimeSpan.FromSeconds(30); + private readonly TaskCompletionSource _loopStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); + + /// Completes once is actually running. The host may schedule it on the + /// pool, so a stop that races the start can cancel it before it ever runs; tests wait on this first. + internal Task LoopStarted => _loopStarted.Task; + /// protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var timer = new PeriodicTimer(TickInterval); - while (!stoppingToken.IsCancellationRequested && - await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)) + _loopStarted.TrySetResult(); + try { - try { await ReapOnceAsync(stoppingToken).ConfigureAwait(false); } - catch (Exception ex) + // WaitForNextTickAsync THROWS OperationCanceledException on stop (it does not return false), so the + // drain must live in a finally: code after the loop is never reached on a host shutdown (#997 A-6). + while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)) { - logger.LogWarning(ex, "Browse-session reaper iteration failed; will retry next tick."); + try { await ReapOnceAsync(stoppingToken).ConfigureAwait(false); } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { throw; } + catch (Exception ex) + { + logger.LogWarning(ex, "Browse-session reaper iteration failed; will retry next tick."); + } } } - await DrainAllAsync().ConfigureAwait(false); + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + // Normal shutdown. + } + finally + { + await DrainAllAsync().ConfigureAwait(false); + } } /// Evicts every session whose diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ApiKeys.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ApiKeys.razor index 7216ba0b7..9ef9630d5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ApiKeys.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ApiKeys.razor @@ -78,6 +78,7 @@
@@ -289,16 +290,30 @@ { _busy = true; _error = null; + string? cleanupError = null; try { await Keys.DeleteAsync(apiKeyId, default); - // A deleted key's ack identity must not linger in the Secrets store. - await AckIdentities.ClearAsync(apiKeyId, await ActorAsync(), default); + // A deleted key's ack identity must not linger in the Secrets store. The key row is already gone, + // so a Secrets failure here must neither skip the reload (the page would keep listing a dead key) + // nor stay anonymous: name the leftovers so the operator can remove them by hand (#997 A-9). + try { await AckIdentities.ClearAsync(apiKeyId, await ActorAsync(), default); } + catch (Exception ex) + { + cleanupError = + $"Key {apiKeyId} was deleted, but its Galaxy ack identity could not be cleared ({ex.Message}). " + + $"Remove the Secrets '{ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyAckIdentitySecrets.UserSecretName(apiKeyId)}' and " + + $"'{ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyAckIdentitySecrets.PasswordSecretName(apiKeyId)}' manually."; + } if (_ackEditKeyId == apiKeyId) CloseAckEditor(); - await ReloadAsync(); } catch (Exception ex) { _error = ex.Message; } - finally { _busy = false; } + finally + { + await ReloadAsync(); + if (cleanupError is not null) _error = _error is null ? cleanupError : $"{cleanupError} {_error}"; + _busy = false; + } } private void OpenAckEditor(string apiKeyId) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Telemetry/TelemetryDialSupervisor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Telemetry/TelemetryDialSupervisor.cs index 4d542e7a9..0ec134ff2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Telemetry/TelemetryDialSupervisor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Telemetry/TelemetryDialSupervisor.cs @@ -16,6 +16,16 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Telemetry; /// The http://{Host}:{GrpcPort} h2c telemetry endpoint. public sealed record TelemetryDialTarget(string NodeId, string Endpoint); +/// +/// Marker the production dial loop passes to onMapped when the stream's response headers arrive: the +/// stream is established even if the node has no telemetry to replay (#997 A-7). Never routed to a sink. +/// +public sealed record TelemetryStreamEstablished +{ + /// The singleton marker. + public static readonly TelemetryStreamEstablished Instance = new(); +} + /// /// The dial-loop seam: opens one telemetry stream to and pumps mapped /// domain records to until the stream ends or @@ -241,6 +251,14 @@ public sealed class TelemetryDialSupervisor : ReceiveActor, IWithTimers RecomputePill(); } + // The establishment marker carries no data: it only flips Connected above (a node with nothing to + // replay never sends a first record, #997 A-7). + if (msg.Record is TelemetryStreamEstablished) + { + Timers.Cancel(DeadlineTimerKey(msg.NodeId)); + return; + } + Route(msg.NodeId, msg.Record); } @@ -315,9 +333,12 @@ public sealed class TelemetryDialSupervisor : ReceiveActor, IWithTimers return; } - _log.Warning( + // Debug here: HandleStreamStopped (below) logs the TimeoutException at Warning under the failure-streak + // throttle (first miss, then every 10th), so this line no longer floods the log on a silent node. + _log.Debug( "Telemetry dial to node {NodeId} ({Endpoint}) delivered nothing within {Deadline}s; cancelling it and re-dialing", msg.NodeId, dialer.Target.Endpoint, DialDeadlineFor().TotalSeconds); + dialer.Cancel(); HandleStreamStopped(new StreamStopped( msg.NodeId, msg.Generation, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Telemetry/TelemetryNodeSource.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Telemetry/TelemetryNodeSource.cs index 2c465815e..a7b2ebfa6 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Telemetry/TelemetryNodeSource.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Telemetry/TelemetryNodeSource.cs @@ -89,7 +89,8 @@ public static class TelemetryNodeSource correlationId, onEvent: evt => onMapped(TelemetryProtoMapCentral.MapEvent(evt)), onError: onError, - ct).ConfigureAwait(false); + ct, + onEstablished: () => onMapped(TelemetryStreamEstablished.Instance)).ConfigureAwait(false); }; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsTreeService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsTreeService.cs index edb1a713e..39b1ed0e5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsTreeService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsTreeService.cs @@ -640,6 +640,11 @@ public sealed class UnsTreeService( return new UnsMutationResult(false, $"Area '{unsAreaId}' already exists."); } + if (await db.UnsAreas.AnyAsync(a => a.ClusterId == clusterId && a.Name == name, ct)) + { + return new UnsMutationResult(false, DuplicateAreaName(name)); + } + db.UnsAreas.Add(new UnsArea { UnsAreaId = unsAreaId, @@ -647,8 +652,17 @@ public sealed class UnsTreeService( Name = name, Notes = string.IsNullOrWhiteSpace(notes) ? null : notes, }); - await db.SaveChangesAsync(ct); - return new UnsMutationResult(true, null); + try + { + await db.SaveChangesAsync(ct); + return new UnsMutationResult(true, null); + } + catch (DbUpdateException) + { + // The pre-check narrows but does not close the race against a concurrent same-name create; + // UX_UnsArea_ClusterName is the backstop. Never surface the raw SQL text. + return new UnsMutationResult(false, DuplicateAreaName(name) + " (created concurrently - reload and retry)."); + } } /// @@ -672,6 +686,11 @@ public sealed class UnsTreeService( db.Entry(entity).Property(e => e.RowVersion).OriginalValue = rowVersion; + if (await db.UnsAreas.AnyAsync(a => a.ClusterId == newClusterId && a.Name == name && a.UnsAreaId != unsAreaId, ct)) + { + return new UnsMutationResult(false, DuplicateAreaName(name)); + } + // The equipment↔driver binding was retired in v3, so a cluster move can no longer // orphan driver-bound equipment — the old cross-cluster binding guard is gone. entity.Name = name; @@ -687,6 +706,10 @@ public sealed class UnsTreeService( { return new UnsMutationResult(false, "Another user changed this area while you were editing. Reload to see the latest values."); } + catch (DbUpdateException) + { + return new UnsMutationResult(false, DuplicateAreaName(name) + " (created concurrently - reload and retry)."); + } } /// @@ -738,6 +761,11 @@ public sealed class UnsTreeService( return new UnsMutationResult(false, $"Line '{unsLineId}' already exists."); } + if (await db.UnsLines.AnyAsync(l => l.UnsAreaId == unsAreaId && l.Name == name, ct)) + { + return new UnsMutationResult(false, DuplicateLineName(name)); + } + db.UnsLines.Add(new UnsLine { UnsLineId = unsLineId, @@ -745,8 +773,15 @@ public sealed class UnsTreeService( Name = name, Notes = string.IsNullOrWhiteSpace(notes) ? null : notes, }); - await db.SaveChangesAsync(ct); - return new UnsMutationResult(true, null); + try + { + await db.SaveChangesAsync(ct); + return new UnsMutationResult(true, null); + } + catch (DbUpdateException) + { + return new UnsMutationResult(false, DuplicateLineName(name) + " (created concurrently - reload and retry)."); + } } /// @@ -770,6 +805,11 @@ public sealed class UnsTreeService( db.Entry(entity).Property(e => e.RowVersion).OriginalValue = rowVersion; + if (await db.UnsLines.AnyAsync(l => l.UnsAreaId == newUnsAreaId && l.Name == name && l.UnsLineId != unsLineId, ct)) + { + return new UnsMutationResult(false, DuplicateLineName(name)); + } + // The equipment↔driver binding was retired in v3, so a line reparent can no longer // orphan driver-bound equipment — the old cross-cluster binding guard is gone. entity.UnsAreaId = newUnsAreaId; @@ -785,6 +825,10 @@ public sealed class UnsTreeService( { return new UnsMutationResult(false, "Another user changed this line while you were editing."); } + catch (DbUpdateException) + { + return new UnsMutationResult(false, DuplicateLineName(name) + " (created concurrently - reload and retry)."); + } } /// @@ -836,6 +880,13 @@ public sealed class UnsTreeService( return new UnsMutationResult(false, $"MachineCode '{input.MachineCode}' already exists in this fleet."); } + if (await db.Equipment.AnyAsync(e => e.UnsLineId == input.UnsLineId && e.Name == input.Name, ct)) + { + return new UnsMutationResult(false, DuplicateEquipmentName(input.Name)); + } + + if (EquipmentLengthError(input) is { } tooLong) return new UnsMutationResult(false, tooLong); + // v3: equipment no longer binds a driver — the reference-only Tags tab points at raw tags — so // the old driver-cluster guard is gone. @@ -863,8 +914,15 @@ public sealed class UnsTreeService( DeviceManualUri = input.DeviceManualUri, Enabled = input.Enabled, }); - await db.SaveChangesAsync(ct); - return new UnsMutationResult(true, null, equipmentId); + try + { + await db.SaveChangesAsync(ct); + return new UnsMutationResult(true, null, equipmentId); + } + catch (DbUpdateException) + { + return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or a value was rejected by the database) - reload and retry."); + } } /// @@ -882,6 +940,13 @@ public sealed class UnsTreeService( var existing = (await db.Equipment.AsNoTracking().Select(e => e.MachineCode).ToListAsync(ct)) .ToHashSet(StringComparer.OrdinalIgnoreCase); + // (UnsLineId, Name) pairs already in the DB, plus those added earlier in this batch — the + // UX_Equipment_LinePath index would otherwise fail the WHOLE batch with no row named. + var existingNames = (await db.Equipment.AsNoTracking() + .Select(e => new { e.UnsLineId, e.Name }).ToListAsync(ct)) + .Select(e => (e.UnsLineId, e.Name)) + .ToHashSet(LineNameComparer.Instance); + var inserted = 0; var skipped = 0; var errors = new List(); @@ -910,6 +975,18 @@ public sealed class UnsTreeService( continue; } + if (existingNames.Contains((row.UnsLineId, row.Name))) + { + errors.Add($"Row '{row.MachineCode}': {DuplicateEquipmentName(row.Name)}"); + continue; + } + + if (EquipmentLengthError(row) is { } tooLong) + { + errors.Add($"Row '{row.MachineCode}': {tooLong}"); + continue; + } + // v3: equipment no longer binds a driver, so there is no per-row driver-cluster guard. var uuid = Guid.NewGuid(); @@ -937,11 +1014,24 @@ public sealed class UnsTreeService( Enabled = row.Enabled, }); existing.Add(row.MachineCode); + existingNames.Add((row.UnsLineId, row.Name)); inserted++; } if (inserted > 0) - await db.SaveChangesAsync(ct); + { + try + { + await db.SaveChangesAsync(ct); + } + catch (DbUpdateException) + { + // A concurrent writer slipped a clashing row past the pre-checks: the batch is atomic, so + // nothing was imported. + errors.Add("Import failed - a concurrent change clashed with this file (duplicate name or MachineCode). Nothing was imported; reload and retry."); + return new EquipmentImportResult(0, skipped, errors); + } + } return new EquipmentImportResult(inserted, skipped, errors); } @@ -969,6 +1059,13 @@ public sealed class UnsTreeService( return new UnsMutationResult(false, $"MachineCode '{input.MachineCode}' already exists in this fleet."); } + if (await db.Equipment.AnyAsync(e => e.UnsLineId == input.UnsLineId && e.Name == input.Name && e.EquipmentId != equipmentId, ct)) + { + return new UnsMutationResult(false, DuplicateEquipmentName(input.Name)); + } + + if (EquipmentLengthError(input) is { } tooLong) return new UnsMutationResult(false, tooLong); + // v3: equipment no longer binds a driver — no driver-cluster guard. // Equipment↔driver binding retired in v3 — no DriverInstanceId column remains. @@ -997,6 +1094,10 @@ public sealed class UnsTreeService( { return new UnsMutationResult(false, "Another user changed this equipment while you were editing."); } + catch (DbUpdateException) + { + return new UnsMutationResult(false, DuplicateEquipmentName(input.Name) + " (or a value was rejected by the database) - reload and retry."); + } } /// @@ -1796,4 +1897,51 @@ public sealed class UnsTreeService( /// A failed mutation result carrying the reason. private static UnsMutationResult SegmentRejected(string level, string? value) => new(false, $"{UnsSegment.Describe(level, value)}. {UnsSegment.Message}"); + + private static string DuplicateAreaName(string name) => $"An area named '{name}' already exists in this cluster."; + + private static string DuplicateLineName(string name) => $"A line named '{name}' already exists in this area."; + + private static string DuplicateEquipmentName(string name) => $"Equipment named '{name}' already exists on this line."; + + /// The ConfigDb column limits for the free-text equipment fields (OtOpcUaConfigDbContext). + private static readonly (string Label, int Max, Func Get)[] EquipmentColumnLimits = + [ + ("Name", 32, i => i.Name), + ("MachineCode", 64, i => i.MachineCode), + ("ZTag", 64, i => i.ZTag), + ("SAPID", 64, i => i.SAPID), + ("Manufacturer", 64, i => i.Manufacturer), + ("Model", 64, i => i.Model), + ("SerialNumber", 64, i => i.SerialNumber), + ("HardwareRevision", 32, i => i.HardwareRevision), + ("SoftwareRevision", 32, i => i.SoftwareRevision), + ("AssetLocation", 256, i => i.AssetLocation), + ("ManufacturerUri", 512, i => i.ManufacturerUri), + ("DeviceManualUri", 512, i => i.DeviceManualUri), + ]; + + /// Returns a friendly message for the first over-long equipment field, else null. + private static string? EquipmentLengthError(EquipmentInput input) + { + foreach (var (label, max, get) in EquipmentColumnLimits) + { + if (get(input) is { } v && v.Length > max) + return $"{label} is {v.Length} characters; the limit is {max}."; + } + return null; + } + + /// (UnsLineId, Name) comparer matching the database's case-insensitive unique index. + private sealed class LineNameComparer : IEqualityComparer<(string UnsLineId, string Name)> + { + public static readonly LineNameComparer Instance = new(); + + public bool Equals((string UnsLineId, string Name) x, (string UnsLineId, string Name) y) => + string.Equals(x.UnsLineId, y.UnsLineId, StringComparison.Ordinal) && + string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase); + + public int GetHashCode((string UnsLineId, string Name) o) => + HashCode.Combine(o.UnsLineId, StringComparer.OrdinalIgnoreCase.GetHashCode(o.Name)); + } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Telemetry/TelemetryStreamClient.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Telemetry/TelemetryStreamClient.cs index 70d0a00ee..be6276e2d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Telemetry/TelemetryStreamClient.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/Telemetry/TelemetryStreamClient.cs @@ -115,6 +115,12 @@ public sealed class TelemetryStreamClient : IDisposable /// Sink for each received raw . /// Invoked once on an abnormal transport failure (the reconnect trigger). /// Cancels the stream (normal shutdown). + /// + /// Optional. Invoked once when the server's response headers arrive (the node sends them as soon as the + /// subscription is attached), i.e. the stream is established even if no event ever follows - a node + /// with no driver instances has nothing to replay (#997 A-7). Not invoked against an older node that + /// only flushes headers with its first event until that event arrives; exceptions it throws are logged. + /// /// A task that represents the asynchronous operation. /// is null or empty. /// or is null. @@ -123,7 +129,8 @@ public sealed class TelemetryStreamClient : IDisposable string correlationId, Action onEvent, Action onError, - CancellationToken ct) + CancellationToken ct, + Action? onEstablished = null) { // Programming faults are validated BEFORE the pump so they throw synchronously out of RunAsync // rather than funnelling to onError and masquerading as a transport fault (supervisor spin). @@ -139,6 +146,19 @@ public sealed class TelemetryStreamClient : IDisposable using var call = _client.Subscribe( new TelemetryStreamRequest { CorrelationId = correlationId }, headers, cancellationToken: ct); + if (onEstablished is not null) + { + await call.ResponseHeadersAsync.WaitAsync(ct).ConfigureAwait(false); + try + { + onEstablished(); + } + catch (Exception ex) + { + _log.LogWarning(ex, "The stream-established callback threw on stream {CorrelationId}.", correlationId); + } + } + await foreach (var evt in call.ResponseStream.ReadAllAsync(ct)) { // Isolate the consumer callback: a poison/unmappable event is a code/version fault, not diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/TelemetryStreamGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/TelemetryStreamGrpcService.cs index b2e7c634f..76cc671cd 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/TelemetryStreamGrpcService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/TelemetryStreamGrpcService.cs @@ -89,6 +89,12 @@ public sealed class TelemetryStreamGrpcService : GeneratedServiceBase lifetime.CancelAfter(MaxStreamLifetime); using var sub = _hub.Subscribe(SubscriptionCapacity); + // Flush the response headers NOW rather than with the first event: a node with no driver + // instances has nothing to replay and may stay silent indefinitely, and central treats the + // headers as "stream established" (#997 A-7). An old node that skips this behaves as before + // (the dial deadline applies until its first event). + await context.WriteResponseHeadersAsync(new Metadata()).ConfigureAwait(false); + _log.LogDebug("Telemetry stream opened (correlationId={CorrelationId})", correlationId); try diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ApiKeyAck/ApiKeyGalaxyAckIdentityServiceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ApiKeyAck/ApiKeyGalaxyAckIdentityServiceTests.cs index 09c9ab5a2..e75c16cb0 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ApiKeyAck/ApiKeyGalaxyAckIdentityServiceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ApiKeyAck/ApiKeyGalaxyAckIdentityServiceTests.cs @@ -49,7 +49,7 @@ public sealed class ApiKeyGalaxyAckIdentityServiceTests { var svc = Service(); await svc.SetAsync(KeyId, "alice", "CORP", Password, "admin", TestContext.Current.CancellationToken); - await svc.SetAsync("ffff0000ffff0000", "bob", null, "", "admin", TestContext.Current.CancellationToken); + await svc.SetAsync("ffff0000ffff0000", "bob", null, "pw-bob", "admin", TestContext.Current.CancellationToken); _store.GetCalls.Clear(); var list = await svc.ListAsync(TestContext.Current.CancellationToken); @@ -83,6 +83,47 @@ public sealed class ApiKeyGalaxyAckIdentityServiceTests _store.Rows.ShouldBeEmpty(); } + /// #997 A-4: the editor never renders the stored password, so a blank box means "keep it". + [Theory] + [InlineData("")] + [InlineData(null)] + public async Task Set_with_a_blank_password_keeps_the_stored_password_and_updates_the_domain(string? blank) + { + var svc = Service(); + var ct = TestContext.Current.CancellationToken; + await svc.SetAsync(KeyId, "alice", "CORP", Password, "admin", ct); + _store.UpsertOrder.Clear(); + + await svc.SetAsync(KeyId, "alice", "NEWDOM", blank, "admin", ct); + + _cipher.Decrypt(_store.Rows[GalaxyAckIdentitySecrets.PasswordSecretName(KeyId)]).ShouldBe(Password); + _cipher.Decrypt(_store.Rows[GalaxyAckIdentitySecrets.UserSecretName(KeyId)]).ShouldBe("NEWDOM\\alice"); + _store.UpsertOrder.ShouldBe([GalaxyAckIdentitySecrets.UserSecretName(KeyId)]); // the password row was never rewritten + } + + /// Positive control for the test above: a NON-blank password still replaces the stored one. + [Fact] + public async Task Set_with_a_new_password_replaces_the_stored_password() + { + var svc = Service(); + var ct = TestContext.Current.CancellationToken; + await svc.SetAsync(KeyId, "alice", "CORP", Password, "admin", ct); + + await svc.SetAsync(KeyId, "alice", "CORP", "rotated", "admin", ct); + + _cipher.Decrypt(_store.Rows[GalaxyAckIdentitySecrets.PasswordSecretName(KeyId)]).ShouldBe("rotated"); + } + + [Theory] + [InlineData("")] + [InlineData(null)] + public async Task First_time_set_with_a_blank_password_is_refused(string? blank) + { + await Should.ThrowAsync(() => Service().SetAsync(KeyId, "alice", "CORP", blank, "admin", TestContext.Current.CancellationToken)); + + _store.Rows.ShouldBeEmpty(); + } + [Fact] public async Task Set_rejects_a_malformed_key_id() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Browsing/BrowseSessionReaperTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Browsing/BrowseSessionReaperTests.cs index 076aa933f..96c6225c4 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Browsing/BrowseSessionReaperTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Browsing/BrowseSessionReaperTests.cs @@ -83,4 +83,28 @@ public sealed class BrowseSessionReaperTests registry.TryGet(good.Token, out _).ShouldBeFalse(); good.Disposed.ShouldBeTrue(); } + + /// #997 A-6: stopping the host used to leave ExecuteAsync by an + /// from the timer wait, so the post-loop drain never ran and every + /// open browse session (OPC UA / MQTT / gateway) was abandoned instead of closed. + [Fact] + public async Task Stopping_the_service_drains_every_open_session_including_recent_ones() + { + var registry = new BrowseSessionRegistry(); + var recent = new FakeBrowseSession { LastUsedUtc = DateTime.UtcNow }; // NOT idle: only the shutdown drain can close it + var throwing = new FakeBrowseSession { LastUsedUtc = DateTime.UtcNow, ThrowOnDispose = true }; + registry.Register(recent); + registry.Register(throwing); + var reaper = NewReaper(registry); + + await reaper.StartAsync(CancellationToken.None); + // Stopping before ExecuteAsync has actually begun cancels it unrun (the host may schedule it on the pool). + await reaper.LoopStarted.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + await reaper.StopAsync(CancellationToken.None); + await (reaper.ExecuteTask ?? Task.CompletedTask); // a faulted/cancelled ExecuteAsync would surface here + + recent.Disposed.ShouldBeTrue(); + registry.TryGet(recent.Token, out _).ShouldBeFalse(); + registry.TryGet(throwing.Token, out _).ShouldBeFalse(); // a dispose failure does not strand the rest + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ApiKeysDeleteTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ApiKeysDeleteTests.cs new file mode 100644 index 000000000..df9f8d425 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ApiKeysDeleteTests.cs @@ -0,0 +1,124 @@ +using Bunit; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.ApiKeyAck; +using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages; + +/// +/// #997 A-9: deleting a key removed the row, then cleared its Galaxy ack identity, then reloaded - all in one +/// try. A Secrets-store failure in the middle skipped the reload (the page kept listing a key that no +/// longer exists, with live buttons) and left the ack secrets behind with no way to find them. +/// +[Trait("Category", "Unit")] +public sealed class ApiKeysDeleteTests : BunitContext +{ + private const string KeyId = "0a1b2c3d4e5f6071"; + + public ApiKeysDeleteTests() + { + JSInterop.Setup("otDialog.activate", _ => true).SetResult(true); + JSInterop.SetupVoid("otDialog.update", _ => true).SetVoidResult(); + JSInterop.SetupVoid("otDialog.deactivate", _ => true).SetVoidResult(); + Services.AddSingleton(new FakeAuth()); + } + + private IRenderedComponent RenderPage(FakeKeys keys, FakeAck ack) + { + Services.AddSingleton(keys); + Services.AddSingleton(ack); + return Render(); + } + + private static void DeleteAndConfirm(IRenderedComponent cut) + { + cut.Find("table button.btn-outline-danger").Click(); + cut.Find(".modal-footer .btn-danger").Click(); + } + + [Fact] + public void A_failing_ack_cleanup_still_reloads_the_list_and_names_the_leftover_secrets() + { + var keys = new FakeKeys(); + var ack = new FakeAck { ThrowOnClear = true }; + var cut = RenderPage(keys, ack); + cut.Markup.ShouldContain(KeyId); + + DeleteAndConfirm(cut); + + cut.WaitForAssertion(() => + { + cut.FindAll("table").ShouldBeEmpty("the deleted key must no longer be listed"); + var alert = cut.Find(".alert-danger").TextContent; + alert.ShouldContain(GalaxyAckIdentitySecrets.UserSecretName(KeyId)); + alert.ShouldContain(GalaxyAckIdentitySecrets.PasswordSecretName(KeyId)); + alert.ShouldContain("secret store unavailable"); + }); + keys.DeleteCalls.ShouldBe(1); + } + + /// Positive control: with a healthy Secrets store the same flow lists nothing and shows no error. + [Fact] + public void A_clean_delete_reloads_the_list_and_shows_no_error() + { + var keys = new FakeKeys(); + var ack = new FakeAck(); + var cut = RenderPage(keys, ack); + + DeleteAndConfirm(cut); + + cut.WaitForAssertion(() => cut.FindAll("table").ShouldBeEmpty()); + cut.FindAll(".alert-danger").ShouldBeEmpty(); + ack.ClearCalls.ShouldBe(1); + } + + private sealed class FakeKeys : IApiKeyAdminService + { + private readonly List _rows = + [ + new() { ApiKeyId = KeyId, Name = "ScadaBridge", SecretHash = "x", Principal = "sb", Enabled = true, CreatedUtc = DateTime.UtcNow }, + ]; + + public int DeleteCalls { get; private set; } + public Task> ListAsync(CancellationToken ct) => Task.FromResult>(_rows.ToList()); + public Task CreateAsync(string name, string principal, DateTime? expiresUtc, string? notes, CancellationToken ct) => throw new NotSupportedException(); + public Task SetEnabledAsync(string apiKeyId, bool enabled, CancellationToken ct) => throw new NotSupportedException(); + public Task DeleteAsync(string apiKeyId, CancellationToken ct) + { + DeleteCalls++; + _rows.RemoveAll(r => r.ApiKeyId == apiKeyId); + return Task.CompletedTask; + } + } + + private sealed class FakeAck : IApiKeyGalaxyAckIdentityService + { + public bool ThrowOnClear { get; init; } + public int ClearCalls { get; private set; } + + public Task> ListAsync(CancellationToken ct) => + Task.FromResult>(new Dictionary()); + + public Task SetAsync(string apiKeyId, string user, string? domain, string? password, string actor, CancellationToken ct) => + throw new NotSupportedException(); + + public Task ClearAsync(string apiKeyId, string actor, CancellationToken ct) + { + ClearCalls++; + return ThrowOnClear ? throw new InvalidOperationException("secret store unavailable") : Task.CompletedTask; + } + } + + private sealed class FakeAuth : AuthenticationStateProvider + { + public override Task GetAuthenticationStateAsync() => + Task.FromResult(new AuthenticationState(new System.Security.Claims.ClaimsPrincipal( + new System.Security.Claims.ClaimsIdentity("test")))); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Telemetry/TelemetryDialDeadlineTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Telemetry/TelemetryDialDeadlineTests.cs index 1d591abe5..8eeec8c32 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Telemetry/TelemetryDialDeadlineTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Telemetry/TelemetryDialDeadlineTests.cs @@ -61,6 +61,25 @@ public sealed class TelemetryDialDeadlineTests : TestKit dial.Invocations.Count.ShouldBe(1); } + /// #997 A-7: a node with no driver instances has nothing to replay, so its established stream stays + /// silent. The establishment marker (response headers) must stop the deadline from cutting it forever. + [Fact] + public async Task An_established_but_silent_stream_is_not_cut_and_marks_the_pill_connected() + { + var dial = new FakeDialLoop { EstablishOnOpen = true }; + var sinks = new Sinks(); + Spawn(dial, callTimeoutSeconds: 1, sinks); + + var first = dial.WaitForCount(1, Timeout).Single(); + AwaitCondition(() => sinks.AlarmBroadcaster.IsConnected, Timeout, PollInterval, cancellationToken: TestContext.Current.CancellationToken); + + await Task.Delay(TimeSpan.FromSeconds(2.5), TestContext.Current.CancellationToken); + first.Ct.IsCancellationRequested.ShouldBeFalse("an established stream must not be cut just because the node is silent"); + dial.Invocations.Count.ShouldBe(1); + sinks.AlarmBroadcaster.IsConnected.ShouldBeTrue(); + sinks.HealthStore.Upserts.ShouldBeEmpty("the marker is not a telemetry record and must never reach a sink"); + } + private IActorRef Spawn(FakeDialLoop dial, int callTimeoutSeconds, Sinks? sinks = null) { sinks ??= new Sinks(); @@ -95,12 +114,16 @@ public sealed class TelemetryDialDeadlineTests : TestKit public bool DeliverOnOpen { get; init; } + /// Signals "stream established" (the response headers arrived) with no event ever following. + public bool EstablishOnOpen { get; init; } + public IReadOnlyList Invocations => _invocations.ToArray(); public TelemetryDialLoop Loop => async (_, correlationId, onMapped, _, ct) => { var invocation = new DialInvocation { CorrelationId = correlationId, Ct = ct }; _invocations.Enqueue(invocation); + if (EstablishOnOpen) onMapped(TelemetryStreamEstablished.Instance); if (DeliverOnOpen) onMapped(Health("drv-1")); await using var reg = ct.Register(() => invocation.Complete()); await invocation.Completion; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceSiblingNameTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceSiblingNameTests.cs new file mode 100644 index 000000000..700917e89 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceSiblingNameTests.cs @@ -0,0 +1,258 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.Uns; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns; + +/// +/// #997 A-3 — the database enforces unique (ClusterId,Name) areas, (UnsAreaId,Name) lines and +/// (UnsLineId,Name) equipment, but the service only pre-checked logical ids, so a duplicate sibling name +/// escaped as an unhandled DbUpdateException that PageErrorBoundary turned into a blank page. +/// EF InMemory does not enforce unique indexes, so these tests drive the service's own pre-checks, and an +/// interceptor that throws stands in for the SQL Server backstop (the +/// concurrent-insert race the pre-check cannot close). +/// +[Trait("Category", "Unit")] +public sealed class UnsTreeServiceSiblingNameTests +{ + private static (UnsTreeService Service, string DbName) Seeded() + { + var dbName = $"uns-sib-{Guid.NewGuid():N}"; + UnsTreeTestDb.SeedNamed(dbName); + return (new UnsTreeService(UnsTreeTestDb.Factory(dbName)), dbName); + } + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + private static EquipmentInput Eq(string name, string machineCode, string line = "LINE-1", string? manufacturer = null) => + new(name, machineCode, line, + ZTag: null, SAPID: null, Manufacturer: manufacturer, Model: null, SerialNumber: null, + HardwareRevision: null, SoftwareRevision: null, YearOfConstruction: null, + AssetLocation: null, ManufacturerUri: null, DeviceManualUri: null, Enabled: true); + + [Fact] + public async Task CreateArea_with_a_sibling_name_is_refused_with_a_message() + { + var (service, dbName) = Seeded(); + + var result = await service.CreateAreaAsync("MAIN", "AREA-NEW", "assembly", null, Ct); + + result.Ok.ShouldBeFalse(); + result.Error.ShouldNotBeNull().ShouldContain("assembly"); + using var db = UnsTreeTestDb.CreateNamed(dbName); + db.UnsAreas.Count(a => a.ClusterId == "MAIN").ShouldBe(1); + } + + [Fact] + public async Task CreateArea_with_the_same_name_in_ANOTHER_cluster_is_allowed() + { + var (service, _) = Seeded(); + + (await service.CreateAreaAsync(UnsTreeTestDb.EmptyClusterId, "AREA-NEW", "assembly", null, Ct)).Ok.ShouldBeTrue(); + } + + [Fact] + public async Task UpdateArea_onto_a_sibling_name_is_refused_but_keeping_its_own_name_is_fine() + { + var (service, dbName) = Seeded(); + (await service.CreateAreaAsync("MAIN", "AREA-2", "packaging", null, Ct)).Ok.ShouldBeTrue(); + byte[] rv; + using (var db = UnsTreeTestDb.CreateNamed(dbName)) rv = db.UnsAreas.Single(a => a.UnsAreaId == "AREA-2").RowVersion; + + var clash = await service.UpdateAreaAsync("AREA-2", "assembly", null, "MAIN", rv, Ct); + var self = await service.UpdateAreaAsync("AREA-2", "packaging", "n", "MAIN", rv, Ct); + + clash.Ok.ShouldBeFalse(); + clash.Error.ShouldNotBeNull().ShouldContain("assembly"); + self.Ok.ShouldBeTrue(); // positive control: the self-exclusion must not block an ordinary save + } + + [Fact] + public async Task UpdateArea_moved_into_a_cluster_that_has_that_name_is_refused() + { + var (service, dbName) = Seeded(); + (await service.CreateAreaAsync(UnsTreeTestDb.EmptyClusterId, "AREA-2", "assembly", null, Ct)).Ok.ShouldBeTrue(); + byte[] rv; + using (var db = UnsTreeTestDb.CreateNamed(dbName)) rv = db.UnsAreas.Single(a => a.UnsAreaId == "AREA-2").RowVersion; + + var result = await service.UpdateAreaAsync("AREA-2", "assembly", null, "MAIN", rv, Ct); + + result.Ok.ShouldBeFalse(); + } + + [Fact] + public async Task CreateLine_with_a_sibling_name_is_refused() + { + var (service, _) = Seeded(); + + var result = await service.CreateLineAsync("AREA-1", "LINE-NEW", "line-a", null, Ct); + + result.Ok.ShouldBeFalse(); + result.Error.ShouldNotBeNull().ShouldContain("line-a"); + (await service.CreateLineAsync("AREA-1", "LINE-NEW", "line-b", null, Ct)).Ok.ShouldBeTrue(); + } + + [Fact] + public async Task UpdateLine_onto_a_sibling_name_or_into_an_area_holding_it_is_refused() + { + var (service, dbName) = Seeded(); + (await service.CreateLineAsync("AREA-1", "LINE-2", "line-b", null, Ct)).Ok.ShouldBeTrue(); + (await service.CreateAreaAsync("MAIN", "AREA-2", "packaging", null, Ct)).Ok.ShouldBeTrue(); + byte[] rv; + using (var db = UnsTreeTestDb.CreateNamed(dbName)) rv = db.UnsLines.Single(l => l.UnsLineId == "LINE-2").RowVersion; + + (await service.UpdateLineAsync("LINE-2", "line-a", null, "AREA-1", rv, Ct)).Ok.ShouldBeFalse(); + // Re-homing to an area that has no 'line-b' is fine; keeping its own name is not a clash. + (await service.UpdateLineAsync("LINE-2", "line-b", null, "AREA-1", rv, Ct)).Ok.ShouldBeTrue(); + (await service.UpdateLineAsync("LINE-2", "line-a", null, "AREA-2", rv, Ct)).Ok.ShouldBeTrue(); + // ...but moving a 'line-a' back under AREA-1 collides with the seeded line-a. + (await service.UpdateLineAsync("LINE-2", "line-a", null, "AREA-1", rv, Ct)).Ok.ShouldBeFalse(); + } + + [Fact] + public async Task CreateEquipment_with_a_sibling_name_is_refused() + { + var (service, dbName) = Seeded(); + + var clash = await service.CreateEquipmentAsync(Eq("machine-1", "mc_new"), Ct); + var ok = await service.CreateEquipmentAsync(Eq("machine-2", "mc_new"), Ct); + + clash.Ok.ShouldBeFalse(); + clash.Error.ShouldNotBeNull().ShouldContain("machine-1"); + ok.Ok.ShouldBeTrue(); + using var db = UnsTreeTestDb.CreateNamed(dbName); + db.Equipment.Count().ShouldBe(2); + } + + [Fact] + public async Task UpdateEquipment_onto_a_sibling_name_is_refused() + { + var (service, dbName) = Seeded(); + var created = await service.CreateEquipmentAsync(Eq("machine-2", "mc_2"), Ct); + byte[] rv; + using (var db = UnsTreeTestDb.CreateNamed(dbName)) rv = db.Equipment.Single(e => e.EquipmentId == created.CreatedId).RowVersion; + + var clash = await service.UpdateEquipmentAsync(created.CreatedId!, Eq("machine-1", "mc_2"), rv, Ct); + var self = await service.UpdateEquipmentAsync(created.CreatedId!, Eq("machine-2", "mc_2"), rv, Ct); + + clash.Ok.ShouldBeFalse(); + clash.Error.ShouldNotBeNull().ShouldContain("machine-1"); + self.Ok.ShouldBeTrue(); + } + + [Fact] + public async Task UpdateEquipment_moved_to_a_line_that_has_that_name_is_refused() + { + var (service, dbName) = Seeded(); + (await service.CreateLineAsync("AREA-1", "LINE-2", "line-b", null, Ct)).Ok.ShouldBeTrue(); + var created = await service.CreateEquipmentAsync(Eq("machine-1", "mc_2", "LINE-2"), Ct); // same name, other line: allowed + created.Ok.ShouldBeTrue(); + byte[] rv; + using (var db = UnsTreeTestDb.CreateNamed(dbName)) rv = db.Equipment.Single(e => e.EquipmentId == created.CreatedId).RowVersion; + + var result = await service.UpdateEquipmentAsync(created.CreatedId!, Eq("machine-1", "mc_2", "LINE-1"), rv, Ct); + + result.Ok.ShouldBeFalse(); + } + + [Fact] + public async Task Import_reports_a_duplicate_name_as_a_row_error_instead_of_failing_the_batch() + { + var (service, dbName) = Seeded(); + + var result = await service.ImportEquipmentAsync( + [ + Eq("machine-1", "mc_a"), // clashes with the seeded row on the same line + Eq("fresh", "mc_b"), // good + Eq("fresh", "mc_c"), // duplicates the previous row inside the batch + Eq("Fresh", "mc_d"), // case-insensitive, as the SQL index is + ], Ct); + + result.Inserted.ShouldBe(1); + result.Errors.Count.ShouldBe(3); + result.Errors.ShouldContain(e => e.Contains("mc_a") && e.Contains("machine-1")); + result.Errors.ShouldContain(e => e.Contains("mc_c")); + result.Errors.ShouldContain(e => e.Contains("mc_d")); + using var db = UnsTreeTestDb.CreateNamed(dbName); + db.Equipment.Count().ShouldBe(2); + } + + [Fact] + public async Task Import_and_create_reject_an_over_long_column_with_a_message() + { + var (service, _) = Seeded(); + var tooLong = new string('x', 65); + + var import = await service.ImportEquipmentAsync([Eq("e1", "mc_a", manufacturer: tooLong), Eq("e2", "mc_b")], Ct); + var create = await service.CreateEquipmentAsync(Eq("e3", "mc_c", manufacturer: tooLong), Ct); + + import.Inserted.ShouldBe(1); + import.Errors.ShouldHaveSingleItem().ShouldContain("Manufacturer"); + create.Ok.ShouldBeFalse(); + create.Error.ShouldNotBeNull().ShouldContain("Manufacturer"); + } + + // --- the concurrent-insert backstop ------------------------------------------------------------------- + + private static UnsTreeService ServiceWhoseSaveThrows(string dbName) => + new(new ThrowingFactory(dbName)); + + [Fact] + public async Task A_DbUpdateException_from_the_unique_index_race_becomes_a_friendly_result_everywhere() + { + var dbName = $"uns-sib-{Guid.NewGuid():N}"; + UnsTreeTestDb.SeedNamed(dbName); + var service = ServiceWhoseSaveThrows(dbName); + byte[] areaRv, lineRv, eqRv; + using (var db = UnsTreeTestDb.CreateNamed(dbName)) + { + areaRv = db.UnsAreas.Single().RowVersion; + lineRv = db.UnsLines.Single().RowVersion; + eqRv = db.Equipment.Single().RowVersion; + } + + var results = new[] + { + await service.CreateAreaAsync("MAIN", "AREA-X", "x", null, Ct), + await service.UpdateAreaAsync("AREA-1", "y", null, "MAIN", areaRv, Ct), + await service.CreateLineAsync("AREA-1", "LINE-X", "x", null, Ct), + await service.UpdateLineAsync("LINE-1", "y", null, "AREA-1", lineRv, Ct), + await service.CreateEquipmentAsync(Eq("x", "mc_x"), Ct), + await service.UpdateEquipmentAsync(UnsTreeTestDb.SeededEquipmentId, Eq("y", "mc_y"), eqRv, Ct), + }; + + foreach (var r in results) + { + r.Ok.ShouldBeFalse(); + r.Error.ShouldNotBeNull(); + r.Error.ShouldNotContain("SaveChanges"); // never the raw EF text + } + + var import = await service.ImportEquipmentAsync([Eq("z", "mc_z")], Ct); + import.Inserted.ShouldBe(0); + import.Errors.ShouldNotBeEmpty(); + } + + private sealed class ThrowOnSave : SaveChangesInterceptor + { + public override ValueTask> SavingChangesAsync( + DbContextEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) => + throw new DbUpdateException("SaveChanges failed: simulated unique-index violation"); + } + + private sealed class ThrowingFactory(string name) : IDbContextFactory + { + public OtOpcUaConfigDbContext CreateDbContext() => + new(new DbContextOptionsBuilder() + .UseInMemoryDatabase(name) + .AddInterceptors(new ThrowOnSave()) + .Options); + + public Task CreateDbContextAsync(CancellationToken ct = default) => + Task.FromResult(CreateDbContext()); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Telemetry/TelemetryStreamClientTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Telemetry/TelemetryStreamClientTests.cs index 3c1b65449..9a9d475d4 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Telemetry/TelemetryStreamClientTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Telemetry/TelemetryStreamClientTests.cs @@ -38,6 +38,37 @@ public sealed class TelemetryStreamClientTests errored.ShouldBeNull(); } + /// #997 A-7: the response headers mean "established" even when no event ever follows. + [Fact] + public async Task RunAsync_signals_established_when_headers_arrive_even_with_no_events() + { + var fake = new FakeClient(new FakeStreamReader([])); + using var sut = new TelemetryStreamClient(fake, "key"); + var established = 0; + var received = new List(); + + await sut.RunAsync("corr-1", received.Add, _ => { }, CancellationToken.None, onEstablished: () => established++); + + established.ShouldBe(1); + received.ShouldBeEmpty(); + } + + [Fact] + public async Task RunAsync_signals_established_before_the_first_event_and_a_throwing_callback_does_not_stop_the_pump() + { + var fake = new FakeClient(new FakeStreamReader([new TelemetryEvent { ScriptLog = Script("one") }])); + using var sut = new TelemetryStreamClient(fake, "key"); + var order = new List(); + Exception? errored = null; + + await sut.RunAsync( + "corr-1", e => order.Add("event:" + e.ScriptLog.Message), ex => errored = ex, CancellationToken.None, + onEstablished: () => { order.Add("established"); throw new InvalidOperationException("callback bug"); }); + + order.ShouldBe(["established", "event:one"]); + errored.ShouldBeNull(); + } + [Fact] public async Task RunAsync_swallows_rpc_cancelled_without_calling_onError() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Grpc/TelemetryStreamGrpcServiceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Grpc/TelemetryStreamGrpcServiceTests.cs index 97bbfe6bc..f3af7fc6b 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Grpc/TelemetryStreamGrpcServiceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Grpc/TelemetryStreamGrpcServiceTests.cs @@ -42,6 +42,25 @@ public sealed class TelemetryStreamGrpcServiceTests throw new TimeoutException($"Timed out waiting: {because}"); } + /// #997 A-7: a node with nothing to replay (no driver instances) must still tell central the stream is + /// established, by flushing the response headers before any event is written. + [Fact] + public async Task Flushes_the_response_headers_before_any_event_so_a_silent_node_still_reads_as_established() + { + var hub = new TelemetryLocalHub(); // nothing emitted: nothing to replay + var service = NewService(hub); + var writer = new CapturingStreamWriter(); + using var cts = new CancellationTokenSource(); + var ctx = new FakeServerCallContext(cts.Token); + + var pump = service.Subscribe(new TelemetryStreamRequest { CorrelationId = "corr-hdr" }, writer, ctx); + await WaitUntilAsync(() => ctx.HeadersWritten == 1, "the response headers to be flushed"); + + writer.Count.ShouldBe(0); + cts.Cancel(); + await pump; + } + [Fact] public async Task Streams_one_of_each_kind_with_fields_transcribed() { @@ -348,6 +367,8 @@ public sealed class TelemetryStreamGrpcServiceTests /// Minimal exposing a caller-controlled cancellation token. private sealed class FakeServerCallContext(CancellationToken token) : ServerCallContext { + public int HeadersWritten { get; private set; } + protected override string MethodCore => "/telemetry.v1.TelemetryStreamService/Subscribe"; protected override string HostCore => "localhost"; protected override string PeerCore => "ipv4:127.0.0.1:0"; @@ -362,7 +383,11 @@ public sealed class TelemetryStreamGrpcServiceTests protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException(); - protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask; + protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) + { + HeadersWritten++; + return Task.CompletedTask; + } } ///