diff --git a/docs/requirements/Component-CLI.md b/docs/requirements/Component-CLI.md index 0a07e74f..c22023d6 100644 --- a/docs/requirements/Component-CLI.md +++ b/docs/requirements/Component-CLI.md @@ -171,6 +171,8 @@ scadabridge site area delete --id scadabridge site deploy-artifacts [--site-id ] ``` +`site update`, `data-connection update` and `api-method update` are **partial** updates (CLI-2, 2026-12-03): only the options passed are sent; an omitted option travels as null and the server keeps the stored value (preserve-if-null in the `ManagementActor` handler), and an empty string (`""`) clears an optional field. Previously every omitted option was sent as null or a default (`--failover-retry-count` 3, `--timeout` 30) and overwrote the stored value — `site update --id 3 --name X` nulled both gRPC addresses. An older CLI that always sends every field still deserializes unchanged. + ### Deployment Commands ``` scadabridge deploy instance --id @@ -185,7 +187,7 @@ scadabridge deploy status [--instance-id ] [--status ] [--page ] scadabridge data-connection list [--site-id ] scadabridge data-connection get --id scadabridge data-connection create --site-id --name --protocol [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] -scadabridge data-connection update --id --name --protocol [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] +scadabridge data-connection update --id [--name ] [--protocol ] [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] scadabridge data-connection delete --id scadabridge data-connection move --id --site-id ``` @@ -423,7 +425,7 @@ scadabridge db-connection delete --id scadabridge api-method list scadabridge api-method get --id scadabridge api-method create --name --script [--timeout ] [--parameters ] [--return-def ] -scadabridge api-method update --id --script [--timeout ] [--parameters ] [--return-def ] +scadabridge api-method update --id [--script ] [--timeout ] [--parameters ] [--return-def ] scadabridge api-method delete --id scadabridge api-method validate --id scadabridge api-method recompile --id diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs index 546075e6..3ef8dbcf 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/ApiMethodCommands.cs @@ -123,21 +123,27 @@ public static class ApiMethodCommands return cmd; } - private static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + /// + /// Builds the partial update subcommand (CLI-2): only the options actually + /// passed are sent; an omitted option travels as null and the server keeps + /// the stored value. is a test seam that + /// receives the built command record instead of sending it. + /// + internal static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption, + Func? commandInterceptor = null) { var idOption = new Option("--id") { Description = "API method ID", Required = true }; - var scriptOption = new Option("--script") { Description = "Script code", Required = true }; - var timeoutOption = new Option("--timeout") { Description = "Timeout in seconds" }; - timeoutOption.DefaultValueFactory = _ => 30; - var parametersOption = new Option("--parameters") { Description = "Parameter definitions JSON" }; - var returnDefOption = new Option("--return-def") { Description = "Return type definition" }; + var scriptOption = new Option("--script") { Description = "Script code (omitted = unchanged)" }; + var timeoutOption = new Option("--timeout") { Description = "Timeout in seconds (omitted = unchanged)" }; + var parametersOption = new Option("--parameters") { Description = "Parameter definitions JSON (omitted = unchanged; \"\" clears)" }; + var returnDefOption = new Option("--return-def") { Description = "Return type definition (omitted = unchanged; \"\" clears)" }; // bool? so an update that omits the flag leaves the stored value unchanged. var traceAllCallsOption = new Option("--trace-all-calls") { Description = "Trace every production call to this method for the Flow Debugger (true/false; omitted = unchanged; adds 7-10 audit rows per call)" }; - var cmd = new Command("update") { Description = "Update an API method" }; + var cmd = new Command("update") { Description = "Update an API method (partial: only the options passed are changed)" }; cmd.Add(idOption); cmd.Add(scriptOption); cmd.Add(timeoutOption); @@ -147,14 +153,16 @@ public static class ApiMethodCommands cmd.SetAction(async (ParseResult result) => { var id = result.GetValue(idOption); - var script = result.GetValue(scriptOption)!; + var script = result.GetValue(scriptOption); var timeout = result.GetValue(timeoutOption); var parameters = result.GetValue(parametersOption); var returnDef = result.GetValue(returnDefOption); var traceAllCalls = result.GetValue(traceAllCallsOption); + var command = new UpdateApiMethodCommand(id, script, timeout, parameters, returnDef, traceAllCalls); + if (commandInterceptor is not null) + return commandInterceptor(command); return await CommandHelpers.ExecuteCommandAsync( - result, urlOption, formatOption, usernameOption, passwordOption, - new UpdateApiMethodCommand(id, script, timeout, parameters, returnDef, traceAllCalls)); + result, urlOption, formatOption, usernameOption, passwordOption, command); }); return cmd; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs index 4a06dd19..8839b319 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/DataConnectionCommands.cs @@ -58,18 +58,25 @@ public static class DataConnectionCommands return cmd; } - private static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + /// + /// Builds the partial update subcommand (CLI-2): only the options actually + /// passed are sent; an omitted option travels as null and the server keeps + /// the stored value. is a test seam that + /// receives the built command record instead of sending it. + /// + internal static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption, + Func? commandInterceptor = null) { var idOption = new Option("--id") { Description = "Data connection ID", Required = true }; - var nameOption = new Option("--name") { Description = "Connection name", Required = true }; - var protocolOption = new Option("--protocol") { Description = "Protocol", Required = true }; - var configOption = new Option("--primary-config", "--configuration") { Description = "Primary configuration JSON" }; - var backupConfigOption = new Option("--backup-config") { Description = "Backup configuration JSON" }; + var nameOption = new Option("--name") { Description = "Connection name (omitted = unchanged)" }; + var protocolOption = new Option("--protocol") { Description = "Protocol (omitted = unchanged)" }; + var configOption = new Option("--primary-config", "--configuration") { Description = "Primary configuration JSON (omitted = unchanged)" }; + var backupConfigOption = new Option("--backup-config") { Description = "Backup configuration JSON (omitted = unchanged; \"\" removes the backup)" }; var configFileOption = ValueSourceOptions.CreateFileOption(configOption, "the primary configuration JSON"); var backupConfigFileOption = ValueSourceOptions.CreateFileOption(backupConfigOption, "the backup configuration JSON"); - var failoverRetryOption = new Option("--failover-retry-count") { Description = "Number of retries before failover to backup", DefaultValueFactory = _ => 3 }; + var failoverRetryOption = new Option("--failover-retry-count") { Description = "Number of retries before failover to backup (omitted = unchanged)" }; - var cmd = new Command("update") { Description = "Update a data connection" }; + var cmd = new Command("update") { Description = "Update a data connection (partial: only the options passed are changed)" }; cmd.Add(idOption); cmd.Add(nameOption); cmd.Add(protocolOption); @@ -80,14 +87,16 @@ public static class DataConnectionCommands cmd.SetAction(async (ParseResult result) => { var id = result.GetValue(idOption); - var name = result.GetValue(nameOption)!; - var protocol = result.GetValue(protocolOption)!; + var name = result.GetValue(nameOption); + var protocol = result.GetValue(protocolOption); var config = ValueSourceOptions.GetValue(result, configOption, configFileOption); var backupConfig = ValueSourceOptions.GetValue(result, backupConfigOption, backupConfigFileOption); var failoverRetryCount = result.GetValue(failoverRetryOption); + var command = new UpdateDataConnectionCommand(id, name, protocol, config, backupConfig, failoverRetryCount); + if (commandInterceptor is not null) + return commandInterceptor(command); return await CommandHelpers.ExecuteCommandAsync( - result, urlOption, formatOption, usernameOption, passwordOption, - new UpdateDataConnectionCommand(id, name, protocol, config, backupConfig, failoverRetryCount)); + result, urlOption, formatOption, usernameOption, passwordOption, command); }); return cmd; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs index 6c0a900f..efd76b5d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/Commands/SiteCommands.cs @@ -88,17 +88,24 @@ public static class SiteCommands return cmd; } - private static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption) + /// + /// Builds the partial update subcommand (CLI-2): only the options actually + /// passed are sent; an omitted option travels as null and the server keeps + /// the stored value. is a test seam that + /// receives the built command record instead of sending it. + /// + internal static Command BuildUpdate(Option urlOption, Option formatOption, Option usernameOption, Option passwordOption, + Func? commandInterceptor = null) { var idOption = new Option("--id") { Description = "Site ID", Required = true }; - var nameOption = new Option("--name") { Description = "Site name", Required = true }; - var descOption = new Option("--description") { Description = "Site description" }; - var nodeAOption = new Option("--node-a-address") { Description = "Akka address for Node A" }; - var nodeBOption = new Option("--node-b-address") { Description = "Akka address for Node B" }; - var grpcNodeAOption = new Option("--grpc-node-a-address") { Description = "gRPC address for Node A" }; - var grpcNodeBOption = new Option("--grpc-node-b-address") { Description = "gRPC address for Node B" }; + var nameOption = new Option("--name") { Description = "Site name (omitted = unchanged)" }; + var descOption = new Option("--description") { Description = "Site description (omitted = unchanged; \"\" clears)" }; + var nodeAOption = new Option("--node-a-address") { Description = "Akka address for Node A (omitted = unchanged; \"\" clears)" }; + var nodeBOption = new Option("--node-b-address") { Description = "Akka address for Node B (omitted = unchanged; \"\" clears)" }; + var grpcNodeAOption = new Option("--grpc-node-a-address") { Description = "gRPC address for Node A (omitted = unchanged; \"\" clears)" }; + var grpcNodeBOption = new Option("--grpc-node-b-address") { Description = "gRPC address for Node B (omitted = unchanged; \"\" clears)" }; - var cmd = new Command("update") { Description = "Update an existing site" }; + var cmd = new Command("update") { Description = "Update an existing site (partial: only the options passed are changed)" }; cmd.Add(idOption); cmd.Add(nameOption); cmd.Add(descOption); @@ -109,15 +116,17 @@ public static class SiteCommands cmd.SetAction(async (ParseResult result) => { var id = result.GetValue(idOption); - var name = result.GetValue(nameOption)!; + var name = result.GetValue(nameOption); var desc = result.GetValue(descOption); var nodeA = result.GetValue(nodeAOption); var nodeB = result.GetValue(nodeBOption); var grpcNodeA = result.GetValue(grpcNodeAOption); var grpcNodeB = result.GetValue(grpcNodeBOption); + var command = new UpdateSiteCommand(id, name, desc, nodeA, nodeB, grpcNodeA, grpcNodeB); + if (commandInterceptor is not null) + return commandInterceptor(command); return await CommandHelpers.ExecuteCommandAsync( - result, urlOption, formatOption, usernameOption, passwordOption, - new UpdateSiteCommand(id, name, desc, nodeA, nodeB, grpcNodeA, grpcNodeB)); + result, urlOption, formatOption, usernameOption, passwordOption, command); }); return cmd; } diff --git a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md index 73e2fa41..01388f3c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CLI/README.md +++ b/src/ZB.MOM.WW.ScadaBridge.CLI/README.md @@ -976,22 +976,21 @@ scadabridge --url site create --name --identifier [--des #### `site update` -Update an existing site. An update **replaces** the whole entity — every required field -below must be supplied with its post-update value, even if unchanged. +Update an existing site. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field. ```sh -scadabridge --url site update --id --name [--description ] [--node-a-address ] [--node-b-address ] [--grpc-node-a-address ] [--grpc-node-b-address ] +scadabridge --url site update --id [--name ] [--description ] [--node-a-address ] [--node-b-address ] [--grpc-node-a-address ] [--grpc-node-b-address ] ``` | Option | Required | Description | |--------|----------|-------------| | `--id` | yes | Site ID | -| `--name` | yes | Human-readable site name | -| `--description` | no | Site description | -| `--node-a-address` | no | Akka.NET cluster address for Node A | -| `--node-b-address` | no | Akka.NET cluster address for Node B | -| `--grpc-node-a-address` | no | gRPC streaming address for Node A | -| `--grpc-node-b-address` | no | gRPC streaming address for Node B | +| `--name` | no | Human-readable site name (omitted = unchanged) | +| `--description` | no | Site description (omitted = unchanged; `""` clears) | +| `--node-a-address` | no | Akka.NET cluster address for Node A (omitted = unchanged; `""` clears) | +| `--node-b-address` | no | Akka.NET cluster address for Node B (omitted = unchanged; `""` clears) | +| `--grpc-node-a-address` | no | gRPC streaming address for Node A (omitted = unchanged; `""` clears) | +| `--grpc-node-b-address` | no | gRPC streaming address for Node B (omitted = unchanged; `""` clears) | #### `site delete` @@ -1263,23 +1262,22 @@ scadabridge --url data-connection create --site-id --name - #### `data-connection update` -Update a data connection definition. An update **replaces** the whole entity — every -required field below must be supplied, even if unchanged. +Update a data connection definition. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field. ```sh -scadabridge --url data-connection update --id --name --protocol [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] +scadabridge --url data-connection update --id [--name ] [--protocol ] [--primary-config | --primary-config-file ] [--backup-config | --backup-config-file ] [--failover-retry-count ] ``` | Option | Required | Description | |--------|----------|-------------| | `--id` | yes | Data connection ID | -| `--name` | yes | Connection name | -| `--protocol` | yes | Protocol identifier | -| `--primary-config` | no | Primary protocol-specific configuration as a JSON string (alias `--configuration`) | +| `--name` | no | Connection name (omitted = unchanged) | +| `--protocol` | no | Protocol identifier (omitted = unchanged) | +| `--primary-config` | no | Primary protocol-specific configuration as a JSON string (alias `--configuration`; omitted = unchanged) | | `--primary-config-file` | no | Read the primary configuration from a file, or stdin with `-` — use it when the config carries a secret (MxGateway `apiKey`, OPC UA password). Not together with `--primary-config`. | -| `--backup-config` | no | Backup protocol-specific configuration as a JSON string | +| `--backup-config` | no | Backup protocol-specific configuration as a JSON string (omitted = unchanged; `""` removes the backup) | | `--backup-config-file` | no | Read the backup configuration from a file, or stdin with `-`. Not together with `--backup-config`. | -| `--failover-retry-count` | no | Retries before failover to the backup configuration (default: `3`) | +| `--failover-retry-count` | no | Retries before failover to the backup configuration (omitted = unchanged) | #### `data-connection move` @@ -2497,21 +2495,20 @@ scadabridge --url api-method create --name --script [--t #### `api-method update` -Update an inbound API method. An update **replaces** the whole entity — every required -field below must be supplied, even if unchanged. +Update an inbound API method. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field. ```sh -scadabridge --url api-method update --id --script [--timeout ] [--parameters ] [--return-def ] [--trace-all-calls ] +scadabridge --url api-method update --id [--script ] [--timeout ] [--parameters ] [--return-def ] [--trace-all-calls ] ``` | Option | Required | Default | Description | |--------|----------|---------|-------------| | `--id` | yes | — | API method ID | -| `--script` | yes | — | Script source code implementing the method | -| `--timeout` | no | `30` | Timeout in seconds | -| `--parameters` | no | — | Parameter definitions JSON | -| `--return-def` | no | — | Return type definition JSON | -| `--trace-all-calls` | no | unchanged | `true`/`false` — trace every production call for the Flow Debugger. **Adds 7–10 audit rows per call** (3 of them trace-only). Omitted = the stored value is left as-is (the one field the replace-all rule does not apply to) | +| `--script` | no | unchanged | Script source code implementing the method | +| `--timeout` | no | unchanged | Timeout in seconds | +| `--parameters` | no | unchanged | Parameter definitions JSON (`""` clears) | +| `--return-def` | no | unchanged | Return type definition JSON (`""` clears) | +| `--trace-all-calls` | no | unchanged | `true`/`false` — trace every production call for the Flow Debugger. **Adds 7–10 audit rows per call** (3 of them trace-only) | Script changes take effect immediately — the updated code is recompiled in-memory on the active central node. No restart is required. diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor index 9c325214..11d3b548 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Admin/SiteForm.razor @@ -168,8 +168,11 @@ return; } await MutationServices.ExecuteConfigurationAsync(_editingSite is not null - ? new UpdateSiteCommand(_editingSite.Id, _formName.Trim(), _formDescription?.Trim(), - _formNodeAAddress?.Trim(), _formNodeBAddress?.Trim(), _formGrpcNodeAAddress?.Trim(), _formGrpcNodeBAddress?.Trim()) + // Update is preserve-if-null (CLI-2): this full-entity form sends "" for a + // field the operator cleared so the server clears it rather than keeping it. + ? new UpdateSiteCommand(_editingSite.Id, _formName.Trim(), _formDescription?.Trim() ?? "", + _formNodeAAddress?.Trim() ?? "", _formNodeBAddress?.Trim() ?? "", + _formGrpcNodeAAddress?.Trim() ?? "", _formGrpcNodeBAddress?.Trim() ?? "") : new CreateSiteCommand(_formName.Trim(), _formIdentifier.Trim(), _formDescription?.Trim(), _formNodeAAddress?.Trim(), _formNodeBAddress?.Trim(), _formGrpcNodeAAddress?.Trim(), _formGrpcNodeBAddress?.Trim())); CommunicationService.RefreshSiteAddresses(); diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor index e36eddfd..d68ddd86 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/ApiMethodForm.razor @@ -399,7 +399,8 @@ { var methodName = _existing?.Name ?? _name.Trim(); await MutationServices.ExecuteConfigurationAsync(_existing is not null - ? new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls) + // Update is preserve-if-null (CLI-2): "" clears a removed definition. + ? new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim() ?? "", _returns?.Trim() ?? "", _traceAllCalls) : new CreateApiMethodCommand(methodName, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)); // Reconcile per-key method-scopes for the affected keys (added/removed vs. load time). diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor index 6f40918e..913839ab 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/DataConnectionForm.razor @@ -382,7 +382,8 @@ try { await MutationServices.ExecuteConfigurationAsync(_editingConnection is not null - ? new UpdateDataConnectionCommand(_editingConnection.Id, _formName.Trim(), _protocol, primaryJson, backupJson, _showBackup ? _formFailoverRetryCount : 3) + // Update is preserve-if-null (CLI-2): "" clears a removed backup endpoint. + ? new UpdateDataConnectionCommand(_editingConnection.Id, _formName.Trim(), _protocol, primaryJson, backupJson ?? "", _showBackup ? _formFailoverRetryCount : 3) : new CreateDataConnectionCommand(_formSiteId, _formName.Trim(), _protocol, primaryJson, backupJson, _showBackup ? _formFailoverRetryCount : 3)); NavigationManager.NavigateTo("/design/connections"); } diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs index 08881df9..0fd06067 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/DataConnectionCommands.cs @@ -3,7 +3,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; public record ListDataConnectionsCommand(int? SiteId = null); public record GetDataConnectionCommand(int DataConnectionId); public record CreateDataConnectionCommand(int SiteId, string Name, string Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int FailoverRetryCount = 3); -public record UpdateDataConnectionCommand(int DataConnectionId, string Name, string Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int FailoverRetryCount = 3); +/// +/// Partial update (CLI-2): every field except the id is preserve-if-null — null leaves the +/// stored value unchanged; an empty string clears an optional field. Older clients that always +/// send every field keep deserializing unchanged (the fields only became nullable). +/// +public record UpdateDataConnectionCommand(int DataConnectionId, string? Name, string? Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int? FailoverRetryCount = null); public record DeleteDataConnectionCommand(int DataConnectionId); /// diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs index 1119f586..63435f79 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/InboundApiCommands.cs @@ -4,8 +4,13 @@ public record ListApiMethodsCommand; public record GetApiMethodCommand(int ApiMethodId); /// Flow Debugger (design 2026-09-05 §5.2): trace every production call to this method. Additive; defaults to off. public record CreateApiMethodCommand(string Name, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool TraceAllCalls = false); +/// +/// Partial update (CLI-2): every field except the id is preserve-if-null — null leaves the +/// stored value unchanged; an empty string clears an optional field. Older clients that always +/// send every field keep deserializing unchanged (the fields only became nullable). +/// /// Flow Debugger (design 2026-09-05 §5.2): null leaves the stored value unchanged so an older CLI never resets it. -public record UpdateApiMethodCommand(int ApiMethodId, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool? TraceAllCalls = null); +public record UpdateApiMethodCommand(int ApiMethodId, string? Script, int? TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool? TraceAllCalls = null); public record DeleteApiMethodCommand(int ApiMethodId); /// /// Compiles the method's stored script on the receiving central node and returns the diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs index 4fac1070..284c73f5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Messages/Management/SiteCommands.cs @@ -3,7 +3,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; public record ListSitesCommand; public record GetSiteCommand(int SiteId); public record CreateSiteCommand(string Name, string SiteIdentifier, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null); -public record UpdateSiteCommand(int SiteId, string Name, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null); +/// +/// Partial update (CLI-2): every field except the id is preserve-if-null — null leaves the +/// stored value unchanged; an empty string clears an optional field. Older clients that always +/// send every field keep deserializing unchanged (the fields only became nullable). +/// +public record UpdateSiteCommand(int SiteId, string? Name, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null); public record DeleteSiteCommand(int SiteId); public record ListAreasCommand(int SiteId); public record CreateAreaCommand(int SiteId, string Name, int? ParentAreaId); diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs index 923e6e47..951c65b0 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs @@ -2062,16 +2062,25 @@ public class ManagementActor : ReceiveActor private static async Task HandleUpdateSite(IServiceProvider sp, UpdateSiteCommand cmd, string user) { - ValidateSiteGrpcAddresses(cmd.GrpcNodeAAddress, cmd.GrpcNodeBAddress); var repo = sp.GetRequiredService(); var site = await repo.GetSiteByIdAsync(cmd.SiteId) ?? throw new ManagementCommandException($"Site with ID {cmd.SiteId} not found."); - site.Name = cmd.Name; - site.Description = cmd.Description; - site.NodeAAddress = cmd.NodeAAddress; - site.NodeBAddress = cmd.NodeBAddress; - site.GrpcNodeAAddress = cmd.GrpcNodeAAddress; - site.GrpcNodeBAddress = cmd.GrpcNodeBAddress; + // CLI-2: preserve-if-null partial update. Validate the EFFECTIVE addresses + // (the merge of the command and the stored row) before anything is written. + var grpcNodeA = PartialUpdate.Optional(cmd.GrpcNodeAAddress, site.GrpcNodeAAddress); + var grpcNodeB = PartialUpdate.Optional(cmd.GrpcNodeBAddress, site.GrpcNodeBAddress); + ValidateSiteGrpcAddresses(grpcNodeA, grpcNodeB); + if (cmd.Name is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Name)) + throw new ManagementCommandException("Site name must not be empty."); + site.Name = cmd.Name; + } + site.Description = PartialUpdate.Optional(cmd.Description, site.Description); + site.NodeAAddress = PartialUpdate.Optional(cmd.NodeAAddress, site.NodeAAddress); + site.NodeBAddress = PartialUpdate.Optional(cmd.NodeBAddress, site.NodeBAddress); + site.GrpcNodeAAddress = grpcNodeA; + site.GrpcNodeBAddress = grpcNodeB; await repo.UpdateSiteAsync(site); await repo.SaveChangesAsync(); var commService = sp.GetService(); @@ -2234,14 +2243,33 @@ public class ManagementActor : ReceiveActor var repo = sp.GetRequiredService(); var conn = await repo.GetDataConnectionByIdAsync(cmd.DataConnectionId) ?? throw new ManagementCommandException($"DataConnection with ID {cmd.DataConnectionId} not found."); - conn.Name = cmd.Name; - conn.Protocol = cmd.Protocol; + // CLI-2: preserve-if-null partial update — an omitted field keeps the stored + // value; an empty string clears an optional configuration. + if (cmd.Name is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Name)) + throw new ManagementCommandException("Data connection name must not be empty."); + conn.Name = cmd.Name; + } + if (cmd.Protocol is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Protocol)) + throw new ManagementCommandException("Data connection protocol must not be empty."); + conn.Protocol = cmd.Protocol; + } // Sentinel-preserving merge: a client that round-trips a scrubbed config // (secrets replaced with the redaction sentinel) keeps the stored secret // rather than wiping it. Non-sentinel values overwrite as usual. - conn.PrimaryConfiguration = ConfigSecretScrubber.MergeSentinels(cmd.PrimaryConfiguration, conn.PrimaryConfiguration); - conn.BackupConfiguration = ConfigSecretScrubber.MergeSentinels(cmd.BackupConfiguration, conn.BackupConfiguration); - conn.FailoverRetryCount = cmd.FailoverRetryCount; + if (cmd.PrimaryConfiguration is not null) + conn.PrimaryConfiguration = string.IsNullOrWhiteSpace(cmd.PrimaryConfiguration) + ? null + : ConfigSecretScrubber.MergeSentinels(cmd.PrimaryConfiguration, conn.PrimaryConfiguration); + if (cmd.BackupConfiguration is not null) + conn.BackupConfiguration = string.IsNullOrWhiteSpace(cmd.BackupConfiguration) + ? null + : ConfigSecretScrubber.MergeSentinels(cmd.BackupConfiguration, conn.BackupConfiguration); + if (cmd.FailoverRetryCount is { } failoverRetryCount) + conn.FailoverRetryCount = failoverRetryCount; await repo.UpdateDataConnectionAsync(conn); await repo.SaveChangesAsync(); var publicShape = DataConnectionPublicShape(conn); @@ -3975,10 +4003,19 @@ public class ManagementActor : ReceiveActor var repo = sp.GetRequiredService(); var method = await repo.GetApiMethodByIdAsync(cmd.ApiMethodId) ?? throw new ManagementCommandException($"ApiMethod with ID {cmd.ApiMethodId} not found."); - method.Script = cmd.Script; - method.TimeoutSeconds = cmd.TimeoutSeconds; - method.ParameterDefinitions = cmd.ParameterDefinitions; - method.ReturnDefinition = cmd.ReturnDefinition; + // CLI-2: preserve-if-null partial update — an omitted field keeps the stored + // value (an omitted --timeout used to reset it to 30 and drop both + // definitions); an empty string clears an optional definition. + if (cmd.Script is not null) + { + if (string.IsNullOrWhiteSpace(cmd.Script)) + throw new ManagementCommandException("API method script must not be empty."); + method.Script = cmd.Script; + } + if (cmd.TimeoutSeconds is { } timeoutSeconds) + method.TimeoutSeconds = timeoutSeconds; + method.ParameterDefinitions = PartialUpdate.Optional(cmd.ParameterDefinitions, method.ParameterDefinitions); + method.ReturnDefinition = PartialUpdate.Optional(cmd.ReturnDefinition, method.ReturnDefinition); if (cmd.TraceAllCalls is { } traceAllCalls) method.TraceAllCalls = traceAllCalls; await repo.UpdateApiMethodAsync(method); diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs new file mode 100644 index 00000000..c317a242 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/PartialUpdate.cs @@ -0,0 +1,19 @@ +namespace ZB.MOM.WW.ScadaBridge.ManagementService; + +/// +/// Preserve-if-null merge rules for the partial update commands (CLI-2): +/// UpdateSiteCommand, UpdateDataConnectionCommand and +/// UpdateApiMethodCommand. A null field means "not supplied — keep the +/// stored value"; an empty (or whitespace-only) string means "clear this optional +/// field". The CLI sends only the options that were actually passed, and the Central +/// UI's full-entity forms send an empty string for a field the operator cleared. +/// +internal static class PartialUpdate +{ + /// Merges an optional (nullable) string field. + /// The value carried by the command, or null when not supplied. + /// The value currently stored. + /// when is null; null when it is blank; otherwise . + public static string? Optional(string? incoming, string? stored) => + incoming is null ? stored : string.IsNullOrWhiteSpace(incoming) ? null : incoming; +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/PartialUpdateCommandTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/PartialUpdateCommandTests.cs new file mode 100644 index 00000000..7f24715c --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/PartialUpdateCommandTests.cs @@ -0,0 +1,98 @@ +using System.CommandLine; +using ZB.MOM.WW.ScadaBridge.CLI.Commands; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; + +namespace ZB.MOM.WW.ScadaBridge.CLI.Tests; + +/// +/// CLI-2 (WP2 task 2.8): site update, data-connection update and +/// api-method update send only the options actually passed. Before the fix an +/// omitted option was sent as null (or as a default: --failover-retry-count 3, +/// --timeout 30) and the server overwrote the stored value — e.g. +/// site update --id 3 --name X nulled both gRPC addresses. The server now treats +/// null as "keep"; these tests pin that the CLI sends null for every omitted option. +/// +public class PartialUpdateCommandTests +{ + private static readonly Option Url = new("--url") { Recursive = true }; + private static readonly Option Username = new("--username") { Recursive = true }; + private static readonly Option Password = new("--password") { Recursive = true }; + private static readonly Option Format = CliOptions.CreateFormatOption(); + + private static async Task ParseAsync( + Func, Option, Option, Option, Func, Command> build, + params string[] args) + { + var captured = new List(); + var root = new RootCommand { Url, Username, Password, Format }; + root.Add(build(Url, Format, Username, Password, cmd => { captured.Add(cmd); return 0; })); + var exit = await root.Parse(args).InvokeAsync(); + Assert.Equal(0, exit); + return Assert.IsType(Assert.Single(captured)); + } + + /// A name-only site update leaves every other field null (= unchanged). + [Fact] + public async Task SiteUpdate_NameOnly_SendsNullForEveryOtherField() + { + var cmd = await ParseAsync(SiteCommands.BuildUpdate, "update", "--id", "3", "--name", "Plant 3"); + Assert.Equal(new UpdateSiteCommand(3, "Plant 3", null, null, null, null, null), cmd); + } + + /// A site update can change one address without supplying the name. + [Fact] + public async Task SiteUpdate_AddressOnly_SendsNullName() + { + var cmd = await ParseAsync(SiteCommands.BuildUpdate, + "update", "--id", "3", "--grpc-node-a-address", "http://a:8083"); + Assert.Null(cmd.Name); + Assert.Equal("http://a:8083", cmd.GrpcNodeAAddress); + Assert.Null(cmd.GrpcNodeBAddress); + } + + /// An explicitly empty option is sent as "" (the server clears the field). + [Fact] + public async Task SiteUpdate_EmptyDescription_SendsEmptyStringToClear() + { + var cmd = await ParseAsync(SiteCommands.BuildUpdate, "update", "--id", "3", "--description", ""); + Assert.Equal("", cmd.Description); + Assert.Null(cmd.Name); + } + + /// A name-only data-connection update sends no protocol, configs or retry count. + [Fact] + public async Task DataConnectionUpdate_NameOnly_SendsNullForEveryOtherField() + { + var cmd = await ParseAsync(DataConnectionCommands.BuildUpdate, + "update", "--id", "7", "--name", "X"); + Assert.Equal(new UpdateDataConnectionCommand(7, "X", null, null, null, null), cmd); + } + + /// A passed retry count and protocol are forwarded. + [Fact] + public async Task DataConnectionUpdate_PassedOptions_AreForwarded() + { + var cmd = await ParseAsync(DataConnectionCommands.BuildUpdate, + "update", "--id", "7", "--protocol", "OpcUa", "--failover-retry-count", "5", "--backup-config", ""); + Assert.Equal(new UpdateDataConnectionCommand(7, null, "OpcUa", null, "", 5), cmd); + } + + /// A script-only api-method update keeps the timeout and both definitions. + [Fact] + public async Task ApiMethodUpdate_ScriptOnly_SendsNullTimeoutAndDefinitions() + { + var cmd = await ParseAsync(ApiMethodCommands.BuildUpdate, + "update", "--id", "5", "--script", "return 1;"); + Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", null, null, null, null), cmd); + } + + /// A timeout-only api-method update sends no script. + [Fact] + public async Task ApiMethodUpdate_TimeoutOnly_SendsNullScript() + { + var cmd = await ParseAsync(ApiMethodCommands.BuildUpdate, + "update", "--id", "5", "--timeout", "120"); + Assert.Null(cmd.Script); + Assert.Equal(120, cmd.TimeoutSeconds); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/UpdateCommandContractTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/UpdateCommandContractTests.cs index aade40e8..2f4dd3fb 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/UpdateCommandContractTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CLI.Tests/UpdateCommandContractTests.cs @@ -4,7 +4,9 @@ using ZB.MOM.WW.ScadaBridge.CLI.Commands; namespace ZB.MOM.WW.ScadaBridge.CLI.Tests; /// -/// Regression tests for the update commands. The Update*Command records in Commons carry +/// Regression tests for the update commands. Site, data-connection and api-method updates are +/// preserve-if-null partial updates (CLI-2, see ); the +/// remaining Update*Command records in Commons carry /// non-nullable "core" fields (e.g. string Name, string Protocol, /// string Script) — an update is a whole-entity replace, not a sparse /// patch. The CLI must therefore mark those core flags as Required: making them @@ -57,15 +59,24 @@ public class UpdateCommandContractTests public void TemplateScriptUpdate_CoreFieldsRequired() => AssertRequired(UpdateCommand(TemplateCommands.Build(Url, Format, Username, Password), "script", "update"), "--name", "--code"); - /// Verifies that the site update command marks its core fields as required. + /// CLI-2: site update is a preserve-if-null partial update, so only --id is required. [Fact] - public void SiteUpdate_CoreFieldsRequired() - => AssertRequired(UpdateCommand(SiteCommands.Build(Url, Format, Username, Password), "update"), "--name"); + public void SiteUpdate_IsPartial_OnlyIdRequired() + { + var update = UpdateCommand(SiteCommands.Build(Url, Format, Username, Password), "update"); + AssertRequired(update, "--id"); + AssertOptional(update, "--name", "--description", "--node-a-address", "--node-b-address", + "--grpc-node-a-address", "--grpc-node-b-address"); + } - /// Verifies that the data connection update command marks its core fields as required. + /// CLI-2: data-connection update is a preserve-if-null partial update, so only --id is required. [Fact] - public void DataConnectionUpdate_CoreFieldsRequired() - => AssertRequired(UpdateCommand(DataConnectionCommands.Build(Url, Format, Username, Password), "update"), "--name", "--protocol"); + public void DataConnectionUpdate_IsPartial_OnlyIdRequired() + { + var update = UpdateCommand(DataConnectionCommands.Build(Url, Format, Username, Password), "update"); + AssertRequired(update, "--id"); + AssertOptional(update, "--name", "--protocol", "--primary-config", "--backup-config", "--failover-retry-count"); + } /// Verifies that the external system update command marks its core fields as required. [Fact] @@ -110,10 +121,25 @@ public class UpdateCommandContractTests } } - /// Verifies that the API method update command marks its script as required. + /// CLI-2: api-method update is a preserve-if-null partial update, so only --id is required. [Fact] - public void ApiMethodUpdate_CoreFieldsRequired() - => AssertRequired(UpdateCommand(ApiMethodCommands.Build(Url, Format, Username, Password), "update"), "--script"); + public void ApiMethodUpdate_IsPartial_OnlyIdRequired() + { + var update = UpdateCommand(ApiMethodCommands.Build(Url, Format, Username, Password), "update"); + AssertRequired(update, "--id"); + AssertOptional(update, "--script", "--timeout", "--parameters", "--return-def", "--trace-all-calls"); + } + + private static void AssertOptional(Command command, params string[] optionNames) + { + foreach (var name in optionNames) + { + var option = command.Options.SingleOrDefault(o => o.Name == name); + Assert.True(option != null, $"'{command.Name}' is missing expected option '{name}'."); + Assert.False(option!.Required, $"'{command.Name}' option '{name}' must be optional (partial update)."); + Assert.False(option.HasDefaultValue, $"'{command.Name}' option '{name}' must have no default — an omitted option must travel as null."); + } + } /// Verifies that the external system method update command keeps all of its fields optional because it is a sparse update. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Audit/FlowDebuggerDrillinTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Audit/FlowDebuggerDrillinTests.cs index b6ebd097..b56cd7a0 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Audit/FlowDebuggerDrillinTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Audit/FlowDebuggerDrillinTests.cs @@ -96,7 +96,7 @@ public class FlowDebuggerDrillinTests : BunitContext Assert.Contains("7–10 audit rows per call", markup); // Load, update and create paths all carry the flag. Assert.Contains("_traceAllCalls = _existing.TraceAllCalls;", markup); - Assert.Contains("new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)", markup); + Assert.Contains("new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim() ?? \"\", _returns?.Trim() ?? \"\", _traceAllCalls)", markup); Assert.Contains("new CreateApiMethodCommand(methodName, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)", markup); } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/PartialUpdateHandlerTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/PartialUpdateHandlerTests.cs new file mode 100644 index 00000000..9aac1a41 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/PartialUpdateHandlerTests.cs @@ -0,0 +1,215 @@ +using System.Text.Json; +using Akka.Actor; +using Akka.TestKit.Xunit2; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; +using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services; +using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management; + +namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests; + +/// +/// CLI-2 (WP2 task 2.8): the site, data-connection and api-method update handlers are +/// preserve-if-null. A null command field keeps the stored value; an empty string +/// clears an optional field. Before the fix every field was assigned unconditionally, +/// so site update --id 3 --name X nulled both gRPC addresses and +/// api-method update --script … reset the timeout to 30 and dropped both +/// definitions. +/// +public class PartialUpdateHandlerTests : TestKit, IDisposable +{ + private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction(); + private readonly ISiteRepository _siteRepo = Substitute.For(); + private readonly IInboundApiRepository _apiRepo = Substitute.For(); + + /// Initializes the harness with stubbed repositories. + public PartialUpdateHandlerTests() + { + _services.AddScoped(_ => _siteRepo); + _services.AddScoped(_ => _apiRepo); + _services.AddScoped(_ => Substitute.For()); + _apiRepo.SaveChangesAsync(Arg.Any()).Returns(1); + } + + /// + void IDisposable.Dispose() => Shutdown(); + + private IActorRef CreateActor() => + Sys.ActorOf(Props.Create(() => new ManagementActor( + _services.BuildServiceProvider(), NullLogger.Instance))); + + private static ManagementEnvelope Admin(object command) => + new(new AuthenticatedUser("admin", "Admin", new[] { "Administrator", "Designer" }, Array.Empty()), + command, Guid.NewGuid().ToString("N")); + + private static Site StoredSite() => new("Plant", "site-3") + { + Id = 3, + Description = "desc", + NodeAAddress = "akka.tcp://scadabridge@a:8081", + NodeBAddress = "akka.tcp://scadabridge@b:8081", + GrpcNodeAAddress = "http://a:8083", + GrpcNodeBAddress = "http://b:8083", + }; + + /// A name-only site update keeps the description and all four addresses. + [Fact] + public void UpdateSite_NameOnly_PreservesEveryOtherField() + { + var site = StoredSite(); + _siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); + + CreateActor().Tell(Admin(new UpdateSiteCommand(3, "Plant 3", null))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("Plant 3", site.Name); + Assert.Equal("desc", site.Description); + Assert.Equal("akka.tcp://scadabridge@a:8081", site.NodeAAddress); + Assert.Equal("akka.tcp://scadabridge@b:8081", site.NodeBAddress); + Assert.Equal("http://a:8083", site.GrpcNodeAAddress); + Assert.Equal("http://b:8083", site.GrpcNodeBAddress); + } + + /// An address-only site update keeps the name; an empty string clears a field. + [Fact] + public void UpdateSite_EmptyString_ClearsField_NullNameKeepsName() + { + var site = StoredSite(); + _siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); + + CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, "", GrpcNodeBAddress: ""))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("Plant", site.Name); + Assert.Null(site.Description); + Assert.Null(site.GrpcNodeBAddress); + Assert.Equal("http://a:8083", site.GrpcNodeAAddress); + } + + /// A preserved address is still validated; a malformed incoming one is refused. + [Fact] + public void UpdateSite_MalformedIncomingAddress_IsRefused() + { + var site = StoredSite(); + _siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); + + CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, null, GrpcNodeAAddress: "a:8083"))); + var error = ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Contains("GrpcNodeAAddress", error.Error); + Assert.Equal("http://a:8083", site.GrpcNodeAAddress); + } + + /// A name-only data-connection update keeps protocol, both configs and the retry count. + [Fact] + public void UpdateDataConnection_NameOnly_PreservesConfigsAndRetryCount() + { + var conn = new DataConnection("c1", "OpcUa", 1) + { + Id = 7, + PrimaryConfiguration = """{"Endpoint":"opc.tcp://p","UserIdentity":{"Password":"pw"}}""", + BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""", + FailoverRetryCount = 9, + }; + _siteRepo.GetDataConnectionByIdAsync(7, Arg.Any()).Returns(conn); + + CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, "renamed", null, null))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("renamed", conn.Name); + Assert.Equal("OpcUa", conn.Protocol); + Assert.Contains("\"pw\"", conn.PrimaryConfiguration); + Assert.Equal("""{"Endpoint":"opc.tcp://b"}""", conn.BackupConfiguration); + Assert.Equal(9, conn.FailoverRetryCount); + } + + /// An empty backup configuration removes the backup endpoint. + [Fact] + public void UpdateDataConnection_EmptyBackup_RemovesBackup() + { + var conn = new DataConnection("c1", "OpcUa", 1) + { + Id = 7, + PrimaryConfiguration = """{"Endpoint":"opc.tcp://p"}""", + BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""", + }; + _siteRepo.GetDataConnectionByIdAsync(7, Arg.Any()).Returns(conn); + + CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, null, null, null, "", 3))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Null(conn.BackupConfiguration); + Assert.Equal("""{"Endpoint":"opc.tcp://p"}""", conn.PrimaryConfiguration); + Assert.Equal(3, conn.FailoverRetryCount); + } + + /// A script-only api-method update keeps the timeout and both definitions. + [Fact] + public void UpdateApiMethod_ScriptOnly_PreservesTimeoutAndDefinitions() + { + var method = new ApiMethod("M", "return 1;") + { + Id = 5, + TimeoutSeconds = 120, + ParameterDefinitions = """[{"name":"x","type":"Integer"}]""", + ReturnDefinition = """[{"name":"y","type":"Integer"}]""", + }; + _apiRepo.GetApiMethodByIdAsync(5, Arg.Any()).Returns(method); + + CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, "return 2;", null, null, null))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("return 2;", method.Script); + Assert.Equal(120, method.TimeoutSeconds); + Assert.Equal("""[{"name":"x","type":"Integer"}]""", method.ParameterDefinitions); + Assert.Equal("""[{"name":"y","type":"Integer"}]""", method.ReturnDefinition); + } + + /// A timeout-only api-method update keeps the script; "" clears a definition. + [Fact] + public void UpdateApiMethod_TimeoutOnly_KeepsScript_EmptyClearsDefinition() + { + var method = new ApiMethod("M", "return 1;") + { + Id = 5, + TimeoutSeconds = 30, + ParameterDefinitions = """[{"name":"x","type":"Integer"}]""", + }; + _apiRepo.GetApiMethodByIdAsync(5, Arg.Any()).Returns(method); + + CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, null, 90, "", null))); + ExpectMsg(TimeSpan.FromSeconds(10)); + + Assert.Equal("return 1;", method.Script); + Assert.Equal(90, method.TimeoutSeconds); + Assert.Null(method.ParameterDefinitions); + } + + /// + /// Wire compatibility: an older CLI always sends every field (non-null ints included); + /// that payload must still deserialize into the now-nullable records with its values. + /// + [Fact] + public void OlderClientPayloads_StillDeserialize() + { + var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; + + var dc = JsonSerializer.Deserialize( + """{"DataConnectionId":7,"Name":"X","Protocol":"OpcUa","PrimaryConfiguration":"{}","BackupConfiguration":null,"FailoverRetryCount":3}""", + options)!; + Assert.Equal(new UpdateDataConnectionCommand(7, "X", "OpcUa", "{}", null, 3), dc); + + var api = JsonSerializer.Deserialize( + """{"ApiMethodId":5,"Script":"return 1;","TimeoutSeconds":30,"ParameterDefinitions":null,"ReturnDefinition":null}""", + options)!; + Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", 30, null, null), api); + + var site = JsonSerializer.Deserialize( + """{"SiteId":3,"Name":"S","Description":null}""", options)!; + Assert.Equal(new UpdateSiteCommand(3, "S", null), site); + } +}