using System.Globalization;
using System.Xml;
using System.Xml.Linq;
namespace ZB.MOM.WW.OtOpcUa.Driver.MTConnect;
///
/// The element/attribute reading rules shared by and
/// . Both documents are the same dialect of XML and must be
/// read by the same rules; keeping one copy is what stops the two parsers drifting apart on the
/// two rules below, either of which fails silently rather than loudly.
///
///
///
/// Rule 1: elements are matched on , ignoring the
/// namespace. The namespace URI carries the MTConnect version
/// (urn:mtconnect.org:MTConnectDevices:1.3 … :2.0), so a fully-qualified match
/// would hard-code a version. It also silently drops vendor-extension elements declared in
/// their own namespace, whose standard children still inherit the default MTConnect
/// namespace — the browse tree simply comes back short, with no error anywhere.
///
///
/// Rule 2: attributes are read unqualified. A prefixed attribute
/// (xsi:type on a document root, a vendor's x:dataItemId) must never be
/// mistaken for the real type / dataItemId, which would invent a data item the
/// probe never declared.
///
///
internal static class MTConnectXml
{
///
/// The reader settings every tree-building parse of an Agent document uses (the
/// /probe model, an error body, a write answer). The Agent is an unauthenticated peer on
/// the plant network, so a DOCTYPE is refused outright and nothing external is ever resolved —
/// no legitimate MTConnect document carries one. on its own
/// parses DTDs (it expands internal entities up to ten million characters); the streams
/// parser already prohibited them, and this is what brings the other parses into line (#804).
/// reproduces XDocument.Parse's default.
///
private static readonly XmlReaderSettings HardenedTreeSettings = new()
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null,
IgnoreWhitespace = true,
CloseInput = false,
};
/// Parses into a tree with DTDs prohibited (see ).
/// The document text.
/// The parsed document.
/// The text is not well-formed, or carries a DOCTYPE.
public static XDocument ParseHardened(string xml)
{
using var text = new StringReader(xml);
using var reader = XmlReader.Create(text, HardenedTreeSettings);
return XDocument.Load(reader);
}
/// Loads into a tree with DTDs prohibited (see ).
/// The document bytes; not closed.
/// The parsed document.
/// The bytes are not well-formed, or carry a DOCTYPE.
public static XDocument LoadHardened(Stream stream)
{
using var reader = XmlReader.Create(stream, HardenedTreeSettings);
return XDocument.Load(reader);
}
///
/// The Agent's MTConnectError document in , rendered as the
/// refusal-marked every caller already routes (see
/// ), or when the body is not one.
///
///
/// Why this exists (#804). A modern Agent (cppagent 2.x, the fixture's
/// mtconnect/agent:2.7) does not serve its error documents under HTTP 200 the way older
/// ones did: it answers an out-of-range /sample?from= — and a count at or above its
/// buffer — with HTTP 400, and an unknown device with 404, each carrying a
/// well-formed MTConnectError body. A status check alone turns those into an
/// , which the pump treats as a transient transport loss and
/// reconnects at the SAME evicted cursor, so the OUT_OF_RANGE re-baseline never ran
/// against a real 2.x Agent. Lifting the document is what routes it.
///
/// The (already size-bounded) response body.
/// The HTTP status the body arrived under, for the message.
/// The root the request expected.
/// How to describe the document.
/// The refusal to throw, or .
public static InvalidDataException? AgentRefusalFromErrorBody(
string? body, int status, string expectedRootName, string subject)
{
if (string.IsNullOrWhiteSpace(body))
{
return null;
}
XElement? root;
try
{
root = ParseHardened(body.Trim('', ' ', '\t', '\r', '\n')).Root;
}
catch (XmlException)
{
return null;
}
if (root is null || !IsNamed(root, "MTConnectError"))
{
return null;
}
var ex = new InvalidDataException(
$"{DescribeUnexpectedRoot(root, expectedRootName, subject)} (served under HTTP {status})");
ex.Data[AgentRefusalDataKey] = true;
return ex;
}
/// Does have the given local name, whatever its namespace?
/// The element to test.
/// The unqualified name to match.
/// if the element has the given local name.
public static bool IsNamed(XElement element, string localName) =>
string.Equals(element.Name.LocalName, localName, StringComparison.Ordinal);
///
/// Does the element the reader is positioned on have the given local name, whatever its
/// namespace?
///
///
/// reads its documents through a forward-only
/// rather than a materialised tree — one sample chunk is read once
/// and thrown away, so building an for it is pure waste. The reader
/// overloads here exist so that going forward-only did not fork the two silent rules in the
/// type-level remarks: both flavours match on the local name, read attributes unqualified,
/// and produce the same error text.
///
/// A reader positioned on an element.
/// The unqualified name to match.
/// if the current element has the given local name.
public static bool IsNamed(XmlReader reader, string localName) =>
string.Equals(reader.LocalName, localName, StringComparison.Ordinal);
/// Direct element children of with the given local name.
/// The element whose children to filter.
/// The unqualified name to match.
/// The matching child elements.
public static IEnumerable ChildrenNamed(XElement parent, string localName) =>
parent.Elements().Where(child => IsNamed(child, localName));
///
/// Reads an unqualified attribute, normalizing a present-but-empty value to null.
/// See the type-level remarks for why only unqualified attributes are considered.
///
/// The element carrying the attribute.
/// The unqualified attribute name.
/// The attribute value, or when absent or blank.
public static string? OptionalAttribute(XElement element, string name)
{
var value = element.Attribute(name)?.Value;
return string.IsNullOrWhiteSpace(value) ? null : value;
}
///
/// Reads an unqualified attribute off the element the reader is positioned on, normalizing a
/// present-but-empty value to null. See for
/// why the reader overloads exist.
///
///
/// matches on the attribute's qualified
/// name, so a prefixed x:dataItemId does not answer to dataItemId — exactly
/// what rule 2 in the type-level remarks requires, and what
/// does for a namespace-free .
///
/// A reader positioned on an element.
/// The unqualified attribute name.
/// The attribute value, or when absent or blank.
public static string? OptionalAttribute(XmlReader reader, string name)
{
var value = reader.GetAttribute(name);
return string.IsNullOrWhiteSpace(value) ? null : value;
}
/// Reads a required unqualified attribute, or throws naming the owner and the attribute.
/// The element carrying the attribute.
/// The unqualified attribute name.
/// How to describe the element in the error message.
/// How to describe the document in the error message (e.g. "/probe response").
/// The attribute value.
/// The attribute is absent or blank.
public static string RequiredAttribute(XElement element, string name, string owner, string subject) =>
OptionalAttribute(element, name) ?? throw MissingAttribute(name, owner, subject);
///
/// Reads a required unqualified attribute off the element the reader is positioned on, or
/// throws naming the owner and the attribute.
///
/// A reader positioned on an element.
/// The unqualified attribute name.
/// How to describe the element in the error message.
/// How to describe the document in the error message.
/// The attribute value.
/// The attribute is absent or blank.
public static string RequiredAttribute(XmlReader reader, string name, string owner, string subject) =>
OptionalAttribute(reader, name) ?? throw MissingAttribute(name, owner, subject);
/// Reads an optional unqualified attribute as an .
/// The element carrying the attribute.
/// The unqualified attribute name.
/// How to describe the element in the error message.
/// How to describe the document in the error message.
/// The parsed integer, or when the attribute is absent or blank.
/// The attribute is present but not an integer.
public static int? OptionalIntAttribute(XElement element, string name, string owner, string subject)
{
var raw = OptionalAttribute(element, name);
if (raw is null)
{
return null;
}
if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
throw new InvalidDataException(
$"MTConnect {subject} is malformed: {owner} has a non-numeric '{name}' attribute ('{raw}').");
}
return value;
}
/// Reads a required unqualified attribute as a .
/// The element carrying the attribute.
/// The unqualified attribute name.
/// How to describe the element in the error message.
/// How to describe the document in the error message.
/// The parsed long value.
/// The attribute is absent, blank, or not an integer.
public static long RequiredLongAttribute(XElement element, string name, string owner, string subject) =>
AsLong(RequiredAttribute(element, name, owner, subject), name, owner, subject);
///
/// Reads a required unqualified attribute off the element the reader is positioned on, as a
/// .
///
/// A reader positioned on an element.
/// The unqualified attribute name.
/// How to describe the element in the error message.
/// How to describe the document in the error message.
/// The parsed long value.
/// The attribute is absent, blank, or not an integer.
public static long RequiredLongAttribute(XmlReader reader, string name, string owner, string subject) =>
AsLong(RequiredAttribute(reader, name, owner, subject), name, owner, subject);
/// The one spelling of "that attribute is missing", shared by both flavours.
private static InvalidDataException MissingAttribute(string name, string owner, string subject) =>
new($"MTConnect {subject} is malformed: {owner} has no '{name}' attribute.");
/// The one spelling of "that attribute is not a number", shared by both flavours.
private static long AsLong(string raw, string name, string owner, string subject)
{
if (!long.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
{
throw new InvalidDataException(
$"MTConnect {subject} is malformed: {owner} has a non-numeric '{name}' attribute ('{raw}').");
}
return value;
}
///
/// Builds the error message for a document whose root is not what was expected, lifting the
/// Agent's own error text when the response is an MTConnectError document — which
/// Agents return under HTTP 200, so EnsureSuccessStatusCode never fires and
/// this is the only place the operator can learn what the Agent objected to.
///
/// The document's actual root element.
/// The root element name the caller required.
/// How to describe the document in the error message.
///
/// The exception to throw. For an MTConnectError root (the Agent REFUSED the request) it is marked
/// with — see .
///
public static InvalidDataException UnexpectedRoot(XElement root, string expectedRootName, string subject)
{
var ex = new InvalidDataException(DescribeUnexpectedRoot(root, expectedRootName, subject));
// Marked (InvalidDataException is sealed, so not a subtype) so the read path can tell a refusal — the
// Agent answered — from an answer it could not parse at all. Every other handler sees the same exception.
if (IsNamed(root, "MTConnectError"))
{
ex.Data[AgentRefusalDataKey] = true;
}
return ex;
}
/// key marking an MTConnectError answer (see ).
internal const string AgentRefusalDataKey = "MTConnect.AgentRefusal";
///
/// Whether is the Agent answering with an MTConnectError document (e.g.
/// NO_DEVICE, INVALID_REQUEST) — a refusal, as opposed to an answer that could not be parsed.
///
/// The exception a parse raised.
/// for a refusal.
public static bool IsAgentRefusal(Exception ex) =>
ex is InvalidDataException && ex.Data[AgentRefusalDataKey] is true;
///
/// The text of : the unexpected root, plus the Agent's own error text for an
/// MTConnectError document.
///
/// The document's root element.
/// The root the caller expected.
/// How to describe the document.
/// The message.
public static string DescribeUnexpectedRoot(XElement root, string expectedRootName, string subject)
{
var message =
$"MTConnect {subject} root element is <{root.Name.LocalName}>, expected <{expectedRootName}>.";
if (!IsNamed(root, "MTConnectError"))
{
return message;
}
var errors = ExtractErrorText(root);
return errors is null ? message : $"{message} The Agent reported: {errors}";
}
///
/// The Agent's own words from an MTConnectError document: every <Error>
/// beneath , rendered errorCode: text where a code is present
/// and joined with "; ". null when the document carries no readable error
/// detail at all (no <Error> elements, or only blank ones).
///
///
///
/// Shared because both callers must read the same document the same way. An
/// Agent's objection reaches this driver through two unrelated doors — a read path that
/// got an error document where it expected a model
/// (), and the write path deciding whether a 200
/// actually accepted the observation. Two copies of this walk would drift on the same
/// two silent rules the type-level remarks describe, and on the write side a missed
/// <Error> does not merely degrade a message: it reads as a successful
/// write.
///
///
/// null means "no readable detail", NOT "not an error document". Only the
/// caller knows which document it is holding — check the root name first. A caller that
/// treats a null here as "no error occurred" turns a hollow
/// <MTConnectError/> into a success.
///
///
/// The MTConnectError document's root element.
/// The Agent's error text, or when no readable detail is present.
public static string? ExtractErrorText(XElement root)
{
ArgumentNullException.ThrowIfNull(root);
var errors = root.Descendants()
.Where(e => IsNamed(e, "Error"))
.Select(e =>
{
var code = OptionalAttribute(e, "errorCode");
var text = e.Value.Trim();
return code is null ? text : $"{code}: {text}";
})
.Where(text => text.Length > 0)
.ToList();
return errors.Count == 0 ? null : string.Join("; ", errors);
}
}