feat(esg): {param} path-template substitution with consumed-param removal — implements the spec'd /recipes/{id} form

Claude-Session: https://claude.ai/code/session_01MtdgwpEeCUn6cUA5f1LMPj
This commit is contained in:
Joseph Doherty
2026-07-10 04:14:13 -04:00
parent d0b27b8957
commit eb7a913d22
3 changed files with 134 additions and 7 deletions
@@ -2,6 +2,7 @@ using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems;
@@ -274,7 +275,7 @@ public class ExternalSystemClient : IExternalSystemClient
// Timeout property is per-instance.
client.Timeout = Timeout.InfiniteTimeSpan;
var url = BuildUrl(system.EndpointUrl, method.Path, parameters, method.HttpMethod);
var url = BuildUrl(system.EndpointUrl, method.Path, parameters, method.HttpMethod, out var consumedParams);
// The request and response own IDisposable resources (StringContent, the
// response content stream). Dispose both, including on the exception paths.
@@ -288,10 +289,18 @@ public class ExternalSystemClient : IExternalSystemClient
method.HttpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase) ||
method.HttpMethod.Equals("PATCH", StringComparison.OrdinalIgnoreCase))
{
if (parameters != null && parameters.Count > 0)
// Parameters consumed by `{param}` path-template substitution are
// already carried in the URL — exclude them from the JSON body so a
// path parameter is not duplicated as a body field.
var bodyParameters = consumedParams.Count == 0
? parameters
: parameters?.Where(p => !consumedParams.Contains(p.Key))
.ToDictionary(p => p.Key, p => p.Value);
if (bodyParameters != null && bodyParameters.Count > 0)
{
request.Content = new StringContent(
JsonSerializer.Serialize(parameters),
JsonSerializer.Serialize(bodyParameters),
Encoding.UTF8,
"application/json");
}
@@ -432,14 +441,56 @@ public class ExternalSystemClient : IExternalSystemClient
return value.Substring(0, maxChars) + $"… [truncated, {value.Length} chars total]";
}
private static string BuildUrl(string baseUrl, string path, IReadOnlyDictionary<string, object?>? parameters, string httpMethod)
/// <summary>
/// Matches a `{param}` path-template placeholder. The name must be a valid
/// identifier (letter/underscore start, then letters/digits/underscores) so the
/// pattern cannot accidentally swallow JSON-ish braces in a hand-authored path.
/// </summary>
private static readonly Regex PathParamRegex = new(
@"\{([A-Za-z_][A-Za-z0-9_]*)\}", RegexOptions.Compiled);
private static string BuildUrl(
string baseUrl,
string path,
IReadOnlyDictionary<string, object?>? parameters,
string httpMethod,
out ISet<string> consumedParams)
{
consumedParams = new HashSet<string>(StringComparer.Ordinal);
// A method that targets the base URL itself has an empty (or "/") path.
// Appending a trailing "/" in that case yields ".../api/" which some
// servers treat as a distinct resource — only append a segment when the
// method actually defines a non-empty relative path.
var trimmedBase = baseUrl.TrimEnd('/');
var trimmedPath = path.Trim().TrimStart('/');
// Substitute `{param}` placeholders in the path with escaped parameter
// values. Each substituted name is recorded so it is excluded from BOTH
// the query string (GET/DELETE) and the JSON body (POST/PUT/PATCH) — a
// path parameter must not be duplicated. A placeholder with no matching
// parameter (or a null value) is an authoring error: throw a clear
// ArgumentException naming it, mirroring ValidateHttpMethod.
if (trimmedPath.Length > 0 && trimmedPath.Contains('{'))
{
var consumed = consumedParams;
trimmedPath = PathParamRegex.Replace(trimmedPath, match =>
{
var name = match.Groups[1].Value;
if (parameters == null ||
!parameters.TryGetValue(name, out var value) ||
value == null)
{
throw new ArgumentException(
$"Path template parameter '{{{name}}}' has no value — supply a non-null '{name}' parameter for this method.",
nameof(path));
}
consumed.Add(name);
return Uri.EscapeDataString(value.ToString() ?? string.Empty);
});
}
var url = string.IsNullOrEmpty(trimmedPath)
? trimmedBase
: trimmedBase + "/" + trimmedPath;
@@ -449,8 +500,9 @@ public class ExternalSystemClient : IExternalSystemClient
httpMethod.Equals("DELETE", StringComparison.OrdinalIgnoreCase)) &&
parameters != null && parameters.Count > 0)
{
var consumed = consumedParams;
var queryString = string.Join("&",
parameters.Where(p => p.Value != null)
parameters.Where(p => p.Value != null && !consumed.Contains(p.Key))
.Select(p => $"{Uri.EscapeDataString(p.Key)}={Uri.EscapeDataString(p.Value?.ToString() ?? "")}"));
// Only append "?" when the effective query string is non-empty — a method