using System.Text.Json;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
///
/// Minimal driver-side view of the deployment artifact emitted by
/// ConfigComposer.SnapshotAndFlattenAsync. The artifact JSON is the full snapshot —
/// for driver spawning we only need the DriverInstances array. Reading just the
/// subset keeps allocations cheap on every deploy.
///
public sealed record DriverInstanceSpec(
Guid DriverInstanceRowId,
string DriverInstanceId,
string Name,
string DriverType,
bool Enabled,
string DriverConfig);
public static class DeploymentArtifact
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
};
///
/// Parse a deployment artifact blob into the list of driver-instance specs to spawn.
/// Empty / malformed blobs return an empty list — callers log + treat as "no drivers".
///
public static IReadOnlyList ParseDriverInstances(ReadOnlySpan blob)
{
if (blob.IsEmpty) return Array.Empty();
try
{
using var doc = JsonDocument.Parse(blob.ToArray());
if (!doc.RootElement.TryGetProperty("DriverInstances", out var arr)
|| arr.ValueKind != JsonValueKind.Array)
{
return Array.Empty();
}
var result = new List(arr.GetArrayLength());
foreach (var el in arr.EnumerateArray())
{
if (el.ValueKind != JsonValueKind.Object) continue;
var spec = TryReadSpec(el);
if (spec is not null) result.Add(spec);
}
return result;
}
catch (JsonException)
{
return Array.Empty();
}
}
private static DriverInstanceSpec? TryReadSpec(JsonElement el)
{
var rowId = el.TryGetProperty("DriverInstanceRowId", out var rowEl)
&& rowEl.TryGetGuid(out var rid) ? rid : Guid.Empty;
var id = el.TryGetProperty("DriverInstanceId", out var idEl) ? idEl.GetString() : null;
var name = el.TryGetProperty("Name", out var nameEl) ? nameEl.GetString() : null;
var type = el.TryGetProperty("DriverType", out var typeEl) ? typeEl.GetString() : null;
var enabled = !el.TryGetProperty("Enabled", out var enEl) || enEl.GetBoolean();
var config = el.TryGetProperty("DriverConfig", out var cfgEl) ? cfgEl.GetString() : null;
if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(type)) return null;
return new DriverInstanceSpec(
DriverInstanceRowId: rowId,
DriverInstanceId: id!,
Name: name ?? id!,
DriverType: type!,
Enabled: enabled,
DriverConfig: config ?? "{}");
}
}