fix(cli): site/data-connection/api-method update are preserve-if-null partial updates (CLI-2, WP2 task 2.8)

Decision 2.8: preserve-if-null on the server. UpdateSiteCommand,
UpdateDataConnectionCommand and UpdateApiMethodCommand fields (except the id)
are now nullable; the ManagementActor handlers apply only non-null values and
treat an empty string as 'clear this optional field'. The CLI update commands
no longer require --name/--protocol/--script and drop the --failover-retry-count
(3) and --timeout (30) defaults, so an omitted option travels as null instead of
overwriting the stored value (site update --name used to null both gRPC
addresses). The site gRPC-address validation now runs on the merged values.

Additive/compatible: the fields only became nullable, so an older CLI that
always sends every field still deserializes (pinned by a test) and now simply
updates every field as before. The Central UI full-entity forms send "" for a
field the operator cleared (description/addresses, removed backup endpoint,
cleared parameter/return definitions) so clearing keeps working.
This commit is contained in:
Joseph Doherty
2026-12-03 09:48:00 -05:00
parent c207809ef3
commit 61c6278bd0
17 changed files with 533 additions and 93 deletions
+4 -2
View File
@@ -171,6 +171,8 @@ scadabridge site area delete --id <id>
scadabridge site deploy-artifacts [--site-id <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 <id>
@@ -185,7 +187,7 @@ scadabridge deploy status [--instance-id <id>] [--status <status>] [--page <n>]
scadabridge data-connection list [--site-id <id>]
scadabridge data-connection get --id <id>
scadabridge data-connection create --site-id <id> --name <name> --protocol <protocol> [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <n>]
scadabridge data-connection update --id <id> --name <name> --protocol <protocol> [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <n>]
scadabridge data-connection update --id <id> [--name <name>] [--protocol <protocol>] [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <n>]
scadabridge data-connection delete --id <id>
scadabridge data-connection move --id <id> --site-id <destination-site-id>
```
@@ -423,7 +425,7 @@ scadabridge db-connection delete --id <id>
scadabridge api-method list
scadabridge api-method get --id <id>
scadabridge api-method create --name <name> --script <code> [--timeout <seconds>] [--parameters <json>] [--return-def <json>]
scadabridge api-method update --id <id> --script <code> [--timeout <seconds>] [--parameters <json>] [--return-def <json>]
scadabridge api-method update --id <id> [--script <code>] [--timeout <seconds>] [--parameters <json>] [--return-def <json>]
scadabridge api-method delete --id <id>
scadabridge api-method validate --id <id>
scadabridge api-method recompile --id <id>
@@ -123,21 +123,27 @@ public static class ApiMethodCommands
return cmd;
}
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
/// <summary>
/// Builds the partial <c>update</c> subcommand (CLI-2): only the options actually
/// passed are sent; an omitted option travels as <c>null</c> and the server keeps
/// the stored value. <paramref name="commandInterceptor"/> is a test seam that
/// receives the built command record instead of sending it.
/// </summary>
internal static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption,
Func<object, int>? commandInterceptor = null)
{
var idOption = new Option<int>("--id") { Description = "API method ID", Required = true };
var scriptOption = new Option<string>("--script") { Description = "Script code", Required = true };
var timeoutOption = new Option<int>("--timeout") { Description = "Timeout in seconds" };
timeoutOption.DefaultValueFactory = _ => 30;
var parametersOption = new Option<string?>("--parameters") { Description = "Parameter definitions JSON" };
var returnDefOption = new Option<string?>("--return-def") { Description = "Return type definition" };
var scriptOption = new Option<string?>("--script") { Description = "Script code (omitted = unchanged)" };
var timeoutOption = new Option<int?>("--timeout") { Description = "Timeout in seconds (omitted = unchanged)" };
var parametersOption = new Option<string?>("--parameters") { Description = "Parameter definitions JSON (omitted = unchanged; \"\" clears)" };
var returnDefOption = new Option<string?>("--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<bool?>("--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;
}
@@ -58,18 +58,25 @@ public static class DataConnectionCommands
return cmd;
}
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
/// <summary>
/// Builds the partial <c>update</c> subcommand (CLI-2): only the options actually
/// passed are sent; an omitted option travels as <c>null</c> and the server keeps
/// the stored value. <paramref name="commandInterceptor"/> is a test seam that
/// receives the built command record instead of sending it.
/// </summary>
internal static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption,
Func<object, int>? commandInterceptor = null)
{
var idOption = new Option<int>("--id") { Description = "Data connection ID", Required = true };
var nameOption = new Option<string>("--name") { Description = "Connection name", Required = true };
var protocolOption = new Option<string>("--protocol") { Description = "Protocol", Required = true };
var configOption = new Option<string?>("--primary-config", "--configuration") { Description = "Primary configuration JSON" };
var backupConfigOption = new Option<string?>("--backup-config") { Description = "Backup configuration JSON" };
var nameOption = new Option<string?>("--name") { Description = "Connection name (omitted = unchanged)" };
var protocolOption = new Option<string?>("--protocol") { Description = "Protocol (omitted = unchanged)" };
var configOption = new Option<string?>("--primary-config", "--configuration") { Description = "Primary configuration JSON (omitted = unchanged)" };
var backupConfigOption = new Option<string?>("--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<int>("--failover-retry-count") { Description = "Number of retries before failover to backup", DefaultValueFactory = _ => 3 };
var failoverRetryOption = new Option<int?>("--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;
}
@@ -88,17 +88,24 @@ public static class SiteCommands
return cmd;
}
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
/// <summary>
/// Builds the partial <c>update</c> subcommand (CLI-2): only the options actually
/// passed are sent; an omitted option travels as <c>null</c> and the server keeps
/// the stored value. <paramref name="commandInterceptor"/> is a test seam that
/// receives the built command record instead of sending it.
/// </summary>
internal static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption,
Func<object, int>? commandInterceptor = null)
{
var idOption = new Option<int>("--id") { Description = "Site ID", Required = true };
var nameOption = new Option<string>("--name") { Description = "Site name", Required = true };
var descOption = new Option<string?>("--description") { Description = "Site description" };
var nodeAOption = new Option<string?>("--node-a-address") { Description = "Akka address for Node A" };
var nodeBOption = new Option<string?>("--node-b-address") { Description = "Akka address for Node B" };
var grpcNodeAOption = new Option<string?>("--grpc-node-a-address") { Description = "gRPC address for Node A" };
var grpcNodeBOption = new Option<string?>("--grpc-node-b-address") { Description = "gRPC address for Node B" };
var nameOption = new Option<string?>("--name") { Description = "Site name (omitted = unchanged)" };
var descOption = new Option<string?>("--description") { Description = "Site description (omitted = unchanged; \"\" clears)" };
var nodeAOption = new Option<string?>("--node-a-address") { Description = "Akka address for Node A (omitted = unchanged; \"\" clears)" };
var nodeBOption = new Option<string?>("--node-b-address") { Description = "Akka address for Node B (omitted = unchanged; \"\" clears)" };
var grpcNodeAOption = new Option<string?>("--grpc-node-a-address") { Description = "gRPC address for Node A (omitted = unchanged; \"\" clears)" };
var grpcNodeBOption = new Option<string?>("--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;
}
+22 -25
View File
@@ -976,22 +976,21 @@ scadabridge --url <url> site create --name <string> --identifier <string> [--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 <url> site update --id <int> --name <string> [--description <string>] [--node-a-address <string>] [--node-b-address <string>] [--grpc-node-a-address <string>] [--grpc-node-b-address <string>]
scadabridge --url <url> site update --id <int> [--name <string>] [--description <string>] [--node-a-address <string>] [--node-b-address <string>] [--grpc-node-a-address <string>] [--grpc-node-b-address <string>]
```
| 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 <url> data-connection create --site-id <int> --name <string> -
#### `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 <url> data-connection update --id <int> --name <string> --protocol <string> [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <int>]
scadabridge --url <url> data-connection update --id <int> [--name <string>] [--protocol <string>] [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <int>]
```
| 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 <url> api-method create --name <string> --script <string> [--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 <url> api-method update --id <int> --script <string> [--timeout <int>] [--parameters <json>] [--return-def <json>] [--trace-all-calls <true|false>]
scadabridge --url <url> api-method update --id <int> [--script <string>] [--timeout <int>] [--parameters <json>] [--return-def <json>] [--trace-all-calls <true|false>]
```
| 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.
@@ -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();
@@ -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).
@@ -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");
}
@@ -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);
/// <summary>
/// Partial update (CLI-2): every field except the id is preserve-if-null — <c>null</c> 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).
/// </summary>
public record UpdateDataConnectionCommand(int DataConnectionId, string? Name, string? Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int? FailoverRetryCount = null);
public record DeleteDataConnectionCommand(int DataConnectionId);
/// <summary>
@@ -4,8 +4,13 @@ public record ListApiMethodsCommand;
public record GetApiMethodCommand(int ApiMethodId);
/// <param name="TraceAllCalls">Flow Debugger (design 2026-09-05 §5.2): trace every production call to this method. Additive; defaults to off.</param>
public record CreateApiMethodCommand(string Name, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool TraceAllCalls = false);
/// <summary>
/// Partial update (CLI-2): every field except the id is preserve-if-null — <c>null</c> 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).
/// </summary>
/// <param name="TraceAllCalls">Flow Debugger (design 2026-09-05 §5.2): <c>null</c> leaves the stored value unchanged so an older CLI never resets it.</param>
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);
/// <summary>
/// Compiles the method's stored script on the receiving central node and returns the
@@ -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);
/// <summary>
/// Partial update (CLI-2): every field except the id is preserve-if-null — <c>null</c> 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).
/// </summary>
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);
@@ -2062,16 +2062,25 @@ public class ManagementActor : ReceiveActor
private static async Task<object?> HandleUpdateSite(IServiceProvider sp, UpdateSiteCommand cmd, string user)
{
ValidateSiteGrpcAddresses(cmd.GrpcNodeAAddress, cmd.GrpcNodeBAddress);
var repo = sp.GetRequiredService<ISiteRepository>();
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<CommunicationService>();
@@ -2234,14 +2243,33 @@ public class ManagementActor : ReceiveActor
var repo = sp.GetRequiredService<ISiteRepository>();
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<IInboundApiRepository>();
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);
@@ -0,0 +1,19 @@
namespace ZB.MOM.WW.ScadaBridge.ManagementService;
/// <summary>
/// Preserve-if-null merge rules for the partial update commands (CLI-2):
/// <c>UpdateSiteCommand</c>, <c>UpdateDataConnectionCommand</c> and
/// <c>UpdateApiMethodCommand</c>. A <c>null</c> 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.
/// </summary>
internal static class PartialUpdate
{
/// <summary>Merges an optional (nullable) string field.</summary>
/// <param name="incoming">The value carried by the command, or <c>null</c> when not supplied.</param>
/// <param name="stored">The value currently stored.</param>
/// <returns><paramref name="stored"/> when <paramref name="incoming"/> is null; null when it is blank; otherwise <paramref name="incoming"/>.</returns>
public static string? Optional(string? incoming, string? stored) =>
incoming is null ? stored : string.IsNullOrWhiteSpace(incoming) ? null : incoming;
}
@@ -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;
/// <summary>
/// CLI-2 (WP2 task 2.8): <c>site update</c>, <c>data-connection update</c> and
/// <c>api-method update</c> send only the options actually passed. Before the fix an
/// omitted option was sent as null (or as a default: <c>--failover-retry-count</c> 3,
/// <c>--timeout</c> 30) and the server overwrote the stored value — e.g.
/// <c>site update --id 3 --name X</c> nulled both gRPC addresses. The server now treats
/// null as "keep"; these tests pin that the CLI sends null for every omitted option.
/// </summary>
public class PartialUpdateCommandTests
{
private static readonly Option<string> Url = new("--url") { Recursive = true };
private static readonly Option<string> Username = new("--username") { Recursive = true };
private static readonly Option<string> Password = new("--password") { Recursive = true };
private static readonly Option<string> Format = CliOptions.CreateFormatOption();
private static async Task<T> ParseAsync<T>(
Func<Option<string>, Option<string>, Option<string>, Option<string>, Func<object, int>, Command> build,
params string[] args)
{
var captured = new List<object>();
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<T>(Assert.Single(captured));
}
/// <summary>A name-only site update leaves every other field null (= unchanged).</summary>
[Fact]
public async Task SiteUpdate_NameOnly_SendsNullForEveryOtherField()
{
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate, "update", "--id", "3", "--name", "Plant 3");
Assert.Equal(new UpdateSiteCommand(3, "Plant 3", null, null, null, null, null), cmd);
}
/// <summary>A site update can change one address without supplying the name.</summary>
[Fact]
public async Task SiteUpdate_AddressOnly_SendsNullName()
{
var cmd = await ParseAsync<UpdateSiteCommand>(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);
}
/// <summary>An explicitly empty option is sent as "" (the server clears the field).</summary>
[Fact]
public async Task SiteUpdate_EmptyDescription_SendsEmptyStringToClear()
{
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate, "update", "--id", "3", "--description", "");
Assert.Equal("", cmd.Description);
Assert.Null(cmd.Name);
}
/// <summary>A name-only data-connection update sends no protocol, configs or retry count.</summary>
[Fact]
public async Task DataConnectionUpdate_NameOnly_SendsNullForEveryOtherField()
{
var cmd = await ParseAsync<UpdateDataConnectionCommand>(DataConnectionCommands.BuildUpdate,
"update", "--id", "7", "--name", "X");
Assert.Equal(new UpdateDataConnectionCommand(7, "X", null, null, null, null), cmd);
}
/// <summary>A passed retry count and protocol are forwarded.</summary>
[Fact]
public async Task DataConnectionUpdate_PassedOptions_AreForwarded()
{
var cmd = await ParseAsync<UpdateDataConnectionCommand>(DataConnectionCommands.BuildUpdate,
"update", "--id", "7", "--protocol", "OpcUa", "--failover-retry-count", "5", "--backup-config", "");
Assert.Equal(new UpdateDataConnectionCommand(7, null, "OpcUa", null, "", 5), cmd);
}
/// <summary>A script-only api-method update keeps the timeout and both definitions.</summary>
[Fact]
public async Task ApiMethodUpdate_ScriptOnly_SendsNullTimeoutAndDefinitions()
{
var cmd = await ParseAsync<UpdateApiMethodCommand>(ApiMethodCommands.BuildUpdate,
"update", "--id", "5", "--script", "return 1;");
Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", null, null, null, null), cmd);
}
/// <summary>A timeout-only api-method update sends no script.</summary>
[Fact]
public async Task ApiMethodUpdate_TimeoutOnly_SendsNullScript()
{
var cmd = await ParseAsync<UpdateApiMethodCommand>(ApiMethodCommands.BuildUpdate,
"update", "--id", "5", "--timeout", "120");
Assert.Null(cmd.Script);
Assert.Equal(120, cmd.TimeoutSeconds);
}
}
@@ -4,7 +4,9 @@ using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// Regression tests for the update commands. The <c>Update*Command</c> 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 <see cref="PartialUpdateCommandTests"/>); the
/// remaining <c>Update*Command</c> records in Commons carry
/// non-nullable "core" fields (e.g. <c>string Name</c>, <c>string Protocol</c>,
/// <c>string Script</c>) — an update is a <em>whole-entity replace</em>, not a sparse
/// patch. The CLI must therefore mark those core flags as <c>Required</c>: 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");
/// <summary>Verifies that the site update command marks its core fields as required.</summary>
/// <summary>CLI-2: site update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
[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");
}
/// <summary>Verifies that the data connection update command marks its core fields as required.</summary>
/// <summary>CLI-2: data-connection update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
[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");
}
/// <summary>Verifies that the external system update command marks its core fields as required.</summary>
[Fact]
@@ -110,10 +121,25 @@ public class UpdateCommandContractTests
}
}
/// <summary>Verifies that the API method update command marks its script as required.</summary>
/// <summary>CLI-2: api-method update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
[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.");
}
}
/// <summary>Verifies that the external system method update command keeps all of its fields optional because it is a sparse update.</summary>
[Fact]
@@ -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);
}
}
@@ -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;
/// <summary>
/// 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 <c>site update --id 3 --name X</c> nulled both gRPC addresses and
/// <c>api-method update --script …</c> reset the timeout to 30 and dropped both
/// definitions.
/// </summary>
public class PartialUpdateHandlerTests : TestKit, IDisposable
{
private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction();
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
private readonly IInboundApiRepository _apiRepo = Substitute.For<IInboundApiRepository>();
/// <summary>Initializes the harness with stubbed repositories.</summary>
public PartialUpdateHandlerTests()
{
_services.AddScoped(_ => _siteRepo);
_services.AddScoped(_ => _apiRepo);
_services.AddScoped(_ => Substitute.For<IAuditService>());
_apiRepo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
}
/// <inheritdoc />
void IDisposable.Dispose() => Shutdown();
private IActorRef CreateActor() =>
Sys.ActorOf(Props.Create(() => new ManagementActor(
_services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
private static ManagementEnvelope Admin(object command) =>
new(new AuthenticatedUser("admin", "Admin", new[] { "Administrator", "Designer" }, Array.Empty<string>()),
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",
};
/// <summary>A name-only site update keeps the description and all four addresses.</summary>
[Fact]
public void UpdateSite_NameOnly_PreservesEveryOtherField()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, "Plant 3", null)));
ExpectMsg<ManagementSuccess>(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);
}
/// <summary>An address-only site update keeps the name; an empty string clears a field.</summary>
[Fact]
public void UpdateSite_EmptyString_ClearsField_NullNameKeepsName()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, "", GrpcNodeBAddress: "")));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Equal("Plant", site.Name);
Assert.Null(site.Description);
Assert.Null(site.GrpcNodeBAddress);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
}
/// <summary>A preserved address is still validated; a malformed incoming one is refused.</summary>
[Fact]
public void UpdateSite_MalformedIncomingAddress_IsRefused()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, null, GrpcNodeAAddress: "a:8083")));
var error = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(10));
Assert.Contains("GrpcNodeAAddress", error.Error);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
}
/// <summary>A name-only data-connection update keeps protocol, both configs and the retry count.</summary>
[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<CancellationToken>()).Returns(conn);
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, "renamed", null, null)));
ExpectMsg<ManagementSuccess>(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);
}
/// <summary>An empty backup configuration removes the backup endpoint.</summary>
[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<CancellationToken>()).Returns(conn);
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, null, null, null, "", 3)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Null(conn.BackupConfiguration);
Assert.Equal("""{"Endpoint":"opc.tcp://p"}""", conn.PrimaryConfiguration);
Assert.Equal(3, conn.FailoverRetryCount);
}
/// <summary>A script-only api-method update keeps the timeout and both definitions.</summary>
[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<CancellationToken>()).Returns(method);
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, "return 2;", null, null, null)));
ExpectMsg<ManagementSuccess>(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);
}
/// <summary>A timeout-only api-method update keeps the script; "" clears a definition.</summary>
[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<CancellationToken>()).Returns(method);
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, null, 90, "", null)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Equal("return 1;", method.Script);
Assert.Equal(90, method.TimeoutSeconds);
Assert.Null(method.ParameterDefinitions);
}
/// <summary>
/// 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.
/// </summary>
[Fact]
public void OlderClientPayloads_StillDeserialize()
{
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var dc = JsonSerializer.Deserialize<UpdateDataConnectionCommand>(
"""{"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<UpdateApiMethodCommand>(
"""{"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<UpdateSiteCommand>(
"""{"SiteId":3,"Name":"S","Description":null}""", options)!;
Assert.Equal(new UpdateSiteCommand(3, "S", null), site);
}
}