From 302dbd5fbdff885c1b1056435293cc844b5120cd Mon Sep 17 00:00:00 2001 From: Zeynep Delal Mutlu Date: Thu, 12 Nov 2026 10:49:39 +0100 Subject: [PATCH 1/4] The derived properties are included to the data schema. --- SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs | 16 ++++++++++++++-- SySML2.NET.REST/PsmApiClient.cs | 4 ++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs b/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs index 2c8ff879a..5cebb74fc 100644 --- a/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs +++ b/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs @@ -374,15 +374,27 @@ await Assert.ThatAsync(() => this.client.PutProjectByIdAsync(ProjectId, projectR public async Task VerifyMergeAsync() { var mergeUri = $"{BaseAddress}projects/{ProjectId}/branches/{BranchId}/merge"; + string mergeBody = null; this.mockHttp.Expect(HttpMethod.Post, mergeUri) .WithExactQueryString($"sourceCommitId={CommitId},{OtherCommitId}&description=the%20merge%20description") - .With(request => request.Content.ReadAsStringAsync().GetAwaiter().GetResult().Contains(RootNamespaceId.ToString())) + .With(request => + { + mergeBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + return true; + }) .Respond(HttpStatusCode.Created, JsonMediaType, ReadPayload("commit.json")); var mergeCommit = await this.client.MergeAsync(ProjectId, [CommitId, OtherCommitId], BranchId, [new Namespace { Id = RootNamespaceId }], "the merge description"); - Assert.That(mergeCommit.Id, Is.EqualTo(CommitId)); + using (Assert.EnterMultipleScope()) + { + Assert.That(mergeCommit.Id, Is.EqualTo(CommitId)); + Assert.That(mergeBody, Does.Contain(RootNamespaceId.ToString())); + Assert.That(mergeBody, Does.Contain("\"qualifiedName\"")); + Assert.That(mergeBody, Does.Contain("\"owner\"")); + Assert.That(mergeBody, Does.Contain("\"membership\"")); + } await Assert.ThatAsync(() => this.client.MergeAsync(ProjectId, null, BranchId), Throws.TypeOf()); diff --git a/SySML2.NET.REST/PsmApiClient.cs b/SySML2.NET.REST/PsmApiClient.cs index 199224f9e..eef325092 100644 --- a/SySML2.NET.REST/PsmApiClient.cs +++ b/SySML2.NET.REST/PsmApiClient.cs @@ -307,7 +307,7 @@ private async Task CreateContentAsync(IRequest requestBody, Cancell } /// - /// Creates the JSON body of a request from a sequence of data items + /// Creates the JSON body of a request from a sequence of data items, each written as a full Data including its derived properties /// /// /// The items to send, or null to send no body @@ -327,7 +327,7 @@ private async Task CreateContentAsync(IEnumerable requestBod var stream = new MemoryStream(); - await this.serializer.SerializeAsync(requestBody, SerializationModeKind.JSON, false, stream, WriterOptions, cancellationToken); + await this.serializer.SerializeAsync(requestBody, SerializationModeKind.JSON, true, stream, WriterOptions, cancellationToken); return CreateContent(stream); } From a0003bcb916c60f4242cbea4824746249f87ed65 Mon Sep 17 00:00:00 2001 From: Zeynep Delal Mutlu Date: Mon, 30 Nov 2026 11:39:11 +0100 Subject: [PATCH 2/4] optional derived-property parameter is added. --- .../Integration/LiveServerTestHost.cs | 2 +- .../PsmApiClientTestFixture.cs | 28 +++++++++++++++++++ SySML2.NET.REST.Tests/SessionTestFixture.cs | 10 ++++++- SySML2.NET.REST/PsmApiClient.cs | 25 +++++++++++++++-- SySML2.NET.REST/PsmApiClientOptions.cs | 22 +++++++++++++++ SySML2.NET.REST/Session.cs | 12 +++++++- 6 files changed, 93 insertions(+), 6 deletions(-) create mode 100644 SySML2.NET.REST/PsmApiClientOptions.cs diff --git a/SySML2.NET.REST.Tests/Integration/LiveServerTestHost.cs b/SySML2.NET.REST.Tests/Integration/LiveServerTestHost.cs index 5c46b4198..8b5a8b257 100644 --- a/SySML2.NET.REST.Tests/Integration/LiveServerTestHost.cs +++ b/SySML2.NET.REST.Tests/Integration/LiveServerTestHost.cs @@ -91,7 +91,7 @@ public async Task OpenAsync() } } - this.Client = new PsmApiClient(this.httpClient, new DeSerializer(), new Serializer(), this.loggerFactory); + this.Client = new PsmApiClient(this.httpClient, new DeSerializer(), new Serializer(), this.loggerFactory, new PsmApiClientOptions { IncludeDerivedProperties = true }); } } } diff --git a/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs b/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs index 5cebb74fc..068d02ace 100644 --- a/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs +++ b/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs @@ -89,6 +89,7 @@ public void VerifyConstructor() Assert.That(() => new PsmApiClient(httpClient, null, new Serializer()), Throws.TypeOf()); Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), null), Throws.TypeOf()); Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), new Serializer()), Throws.Nothing); + Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), new Serializer(), null, new PsmApiClientOptions { IncludeDerivedProperties = true }), Throws.Nothing); } } @@ -375,12 +376,14 @@ public async Task VerifyMergeAsync() { var mergeUri = $"{BaseAddress}projects/{ProjectId}/branches/{BranchId}/merge"; string mergeBody = null; + var hasPreferHeader = false; this.mockHttp.Expect(HttpMethod.Post, mergeUri) .WithExactQueryString($"sourceCommitId={CommitId},{OtherCommitId}&description=the%20merge%20description") .With(request => { mergeBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + hasPreferHeader = request.Headers.Contains("Prefer"); return true; }) .Respond(HttpStatusCode.Created, JsonMediaType, ReadPayload("commit.json")); @@ -391,6 +394,31 @@ public async Task VerifyMergeAsync() { Assert.That(mergeCommit.Id, Is.EqualTo(CommitId)); Assert.That(mergeBody, Does.Contain(RootNamespaceId.ToString())); + Assert.That(mergeBody, Does.Not.Contain("\"qualifiedName\"")); + Assert.That(mergeBody, Does.Not.Contain("\"owner\"")); + Assert.That(mergeBody, Does.Not.Contain("\"membership\"")); + Assert.That(hasPreferHeader, Is.False); + } + + using var derivedHttpClient = this.mockHttp.ToHttpClient(); + derivedHttpClient.BaseAddress = BaseAddress; + var derivedClient = new PsmApiClient(derivedHttpClient, new DeSerializer(), new Serializer(), options: new PsmApiClientOptions { IncludeDerivedProperties = true }); + + this.mockHttp.Expect(HttpMethod.Post, mergeUri) + .WithExactQueryString($"sourceCommitId={CommitId}") + .WithHeaders("Prefer", "include-derived") + .With(request => + { + mergeBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + return true; + }) + .Respond(HttpStatusCode.Created, JsonMediaType, ReadPayload("commit.json")); + + mergeCommit = await derivedClient.MergeAsync(ProjectId, [CommitId], BranchId, [new Namespace { Id = RootNamespaceId }]); + + using (Assert.EnterMultipleScope()) + { + Assert.That(mergeCommit.Id, Is.EqualTo(CommitId)); Assert.That(mergeBody, Does.Contain("\"qualifiedName\"")); Assert.That(mergeBody, Does.Contain("\"owner\"")); Assert.That(mergeBody, Does.Contain("\"membership\"")); diff --git a/SySML2.NET.REST.Tests/SessionTestFixture.cs b/SySML2.NET.REST.Tests/SessionTestFixture.cs index 9f32150c7..f5bbb3507 100644 --- a/SySML2.NET.REST.Tests/SessionTestFixture.cs +++ b/SySML2.NET.REST.Tests/SessionTestFixture.cs @@ -129,8 +129,16 @@ public async Task VerifyOpen() Assert.That(this.assembler.Cache, Is.Empty); } + var derivedSession = new Session(this.httpClientFactory.Object, new DeSerializer(), new Serializer(), clientOptions: new PsmApiClientOptions { IncludeDerivedProperties = true }); + + this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects").WithHeaders("Prefer", "include-derived").Respond(JsonMediaType, "[]"); + + await derivedSession.Open(new Uri("http://localhost/api"), CancellationToken.None); + + Assert.That(derivedSession.Client, Is.Not.Null); + this.mockHttp.VerifyNoOutstandingExpectation(); - this.httpClientFactory.Verify(factory => factory.CreateClient(nameof(Session)), Times.Exactly(3)); + this.httpClientFactory.Verify(factory => factory.CreateClient(nameof(Session)), Times.Exactly(4)); } [Test] diff --git a/SySML2.NET.REST/PsmApiClient.cs b/SySML2.NET.REST/PsmApiClient.cs index eef325092..4bb6f49d4 100644 --- a/SySML2.NET.REST/PsmApiClient.cs +++ b/SySML2.NET.REST/PsmApiClient.cs @@ -43,6 +43,11 @@ public partial class PsmApiClient : IPsmApiClient /// private const string JsonMediaType = "application/json"; + /// + /// The RFC 7240 preference asking the server to include the derived properties in its responses + /// + private const string IncludeDerivedPreference = "include-derived"; + /// /// The pattern of one link-value of an RFC 8288 Link header, capturing its target and its relation type /// @@ -102,6 +107,11 @@ public partial class PsmApiClient : IPsmApiClient /// private readonly ILogger logger; + /// + /// The that tune the exchange with the server + /// + private readonly PsmApiClientOptions options; + /// /// Initializes a new instance of the class /// @@ -117,15 +127,19 @@ public partial class PsmApiClient : IPsmApiClient /// /// The used to set up logging, or null to disable logging /// + /// + /// The that tune the exchange with the server, or null to use the defaults + /// /// /// Thrown when , or is null /// - public PsmApiClient(HttpClient httpClient, IDeSerializer deSerializer, ISerializer serializer, ILoggerFactory loggerFactory = null) + public PsmApiClient(HttpClient httpClient, IDeSerializer deSerializer, ISerializer serializer, ILoggerFactory loggerFactory = null, PsmApiClientOptions options = null) { this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); this.deSerializer = deSerializer ?? throw new ArgumentNullException(nameof(deSerializer)); this.serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); this.logger = loggerFactory == null ? NullLogger.Instance : loggerFactory.CreateLogger(); + this.options = options ?? new PsmApiClientOptions(); } /// @@ -301,7 +315,7 @@ private async Task CreateContentAsync(IRequest requestBody, Cancell var stream = new MemoryStream(); - await this.serializer.SerializeRequestAsync(requestBody, SerializationModeKind.JSON, false, stream, WriterOptions, cancellationToken); + await this.serializer.SerializeRequestAsync(requestBody, SerializationModeKind.JSON, this.options.IncludeDerivedProperties, stream, WriterOptions, cancellationToken); return CreateContent(stream); } @@ -327,7 +341,7 @@ private async Task CreateContentAsync(IEnumerable requestBod var stream = new MemoryStream(); - await this.serializer.SerializeAsync(requestBody, SerializationModeKind.JSON, true, stream, WriterOptions, cancellationToken); + await this.serializer.SerializeAsync(requestBody, SerializationModeKind.JSON, this.options.IncludeDerivedProperties, stream, WriterOptions, cancellationToken); return CreateContent(stream); } @@ -677,6 +691,11 @@ private async Task SendAsync(HttpMethod method, string requ requestMessage.Content = content; requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(JsonMediaType)); + if (this.options.IncludeDerivedProperties) + { + requestMessage.Headers.Add("Prefer", IncludeDerivedPreference); + } + var response = await this.httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken); if (this.logger.IsEnabled(LogLevel.Debug)) diff --git a/SySML2.NET.REST/PsmApiClientOptions.cs b/SySML2.NET.REST/PsmApiClientOptions.cs new file mode 100644 index 000000000..6cfefbafb --- /dev/null +++ b/SySML2.NET.REST/PsmApiClientOptions.cs @@ -0,0 +1,22 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SySML2.NET.REST +{ + /// + /// The settings that tune how a exchanges payloads with the server + /// + public class PsmApiClientOptions + { + /// + /// Gets or sets a value indicating whether request bodies carry the derived properties and every request sends the Prefer: include-derived header + /// + public bool IncludeDerivedProperties { get; set; } + } +} diff --git a/SySML2.NET.REST/Session.cs b/SySML2.NET.REST/Session.cs index b633891b7..5e46877cf 100644 --- a/SySML2.NET.REST/Session.cs +++ b/SySML2.NET.REST/Session.cs @@ -62,6 +62,11 @@ public class Session : ISession /// private int generation; + /// + /// The handed to each + /// + private readonly PsmApiClientOptions clientOptions; + /// /// Initializes a new instance of the class /// @@ -80,16 +85,21 @@ public class Session : ISession /// /// The used to set up logging, or null to disable logging /// + /// + /// The handed to each , or null to use the defaults + /// /// /// Thrown when , , or is null /// - public Session(IHttpClientFactory httpClientFactory, IDeSerializer deSerializer, ISerializer serializer, IAssembler assembler, ILoggerFactory loggerFactory = null) + //public Session(IHttpClientFactory httpClientFactory, IDeSerializer deSerializer, ISerializer serializer, IAssembler assembler, ILoggerFactory loggerFactory = null) + public Session(IHttpClientFactory httpClientFactory, IDeSerializer deSerializer, ISerializer serializer, IAssembler assembler,ILoggerFactory loggerFactory = null, PsmApiClientOptions clientOptions = null) { this.httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); this.deSerializer = deSerializer ?? throw new ArgumentNullException(nameof(deSerializer)); this.serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); this.Assembler = assembler ?? throw new ArgumentNullException(nameof(assembler)); this.loggerFactory = loggerFactory; + this.clientOptions = clientOptions; } /// From 8de302f5d189cd4fd475e1e7010a64d0e5fdb39e Mon Sep 17 00:00:00 2001 From: Zeynep Delal Mutlu Date: Mon, 30 Nov 2026 16:01:07 +0100 Subject: [PATCH 3/4] pr check, the derived properties flag is seperated in terms of client request and server answer. --- .../Integration/LiveServerTestHost.cs | 2 +- .../PsmApiClientTestFixture.cs | 69 +++++++++++++++++-- SySML2.NET.REST.Tests/SessionTestFixture.cs | 19 +++-- SySML2.NET.REST/ISessionLifecycle.cs | 23 +++++++ SySML2.NET.REST/PsmApiClient.cs | 42 +++++++---- SySML2.NET.REST/PsmApiClientOptions.cs | 9 ++- SySML2.NET.REST/Session.cs | 39 +++++++---- SysML2.NET/PSM/PreferenceHeaders.cs | 32 +++++++++ 8 files changed, 195 insertions(+), 40 deletions(-) create mode 100644 SysML2.NET/PSM/PreferenceHeaders.cs diff --git a/SySML2.NET.REST.Tests/Integration/LiveServerTestHost.cs b/SySML2.NET.REST.Tests/Integration/LiveServerTestHost.cs index 8b5a8b257..ed4b9b7a8 100644 --- a/SySML2.NET.REST.Tests/Integration/LiveServerTestHost.cs +++ b/SySML2.NET.REST.Tests/Integration/LiveServerTestHost.cs @@ -91,7 +91,7 @@ public async Task OpenAsync() } } - this.Client = new PsmApiClient(this.httpClient, new DeSerializer(), new Serializer(), this.loggerFactory, new PsmApiClientOptions { IncludeDerivedProperties = true }); + this.Client = new PsmApiClient(this.httpClient, new DeSerializer(), new Serializer(), this.loggerFactory, new PsmApiClientOptions { SerializeDerivedProperties = true }); } } } diff --git a/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs b/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs index 068d02ace..4b1072346 100644 --- a/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs +++ b/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs @@ -21,6 +21,7 @@ namespace SySML2.NET.REST.Tests using RichardSzalay.MockHttp; + using SysML2.NET.Core.DTO.Kernel.Functions; using SysML2.NET.Core.DTO.Root.Namespaces; using SysML2.NET.PSM; using SysML2.NET.PSM.DTO; @@ -47,6 +48,10 @@ public class PsmApiClientTestFixture private static readonly Guid RootNamespaceId = Guid.Parse("864d5403-c87b-4679-9d3a-b09c7fde1dd9"); + private static readonly Guid FunctionId = Guid.Parse("761f87bf-e06e-55f7-8830-ebcc3f619e2d"); + + private static readonly KeyValuePair[] PreferenceAppliedHeader = [new(PreferenceHeaders.PreferenceApplied, PreferenceHeaders.IncludeDerived)]; + private MockHttpMessageHandler mockHttp; private PsmApiClient client; @@ -78,6 +83,14 @@ private static KeyValuePair[] CreateLinkHeader(string link) return [new KeyValuePair("Link", link)]; } + private PsmApiClient CreateClient(PsmApiClientOptions options) + { + var httpClient = this.mockHttp.ToHttpClient(); + httpClient.BaseAddress = BaseAddress; + + return new PsmApiClient(httpClient, new DeSerializer(), new Serializer(), options: options); + } + [Test] public void VerifyConstructor() { @@ -89,7 +102,7 @@ public void VerifyConstructor() Assert.That(() => new PsmApiClient(httpClient, null, new Serializer()), Throws.TypeOf()); Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), null), Throws.TypeOf()); Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), new Serializer()), Throws.Nothing); - Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), new Serializer(), null, new PsmApiClientOptions { IncludeDerivedProperties = true }), Throws.Nothing); + Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), new Serializer(), null, new PsmApiClientOptions { SerializeDerivedProperties = true, RequestDerivedProperties = true }), Throws.Nothing); } } @@ -236,8 +249,15 @@ public async Task VerifyGetRootsByProjectCommitAsync() { Assert.That(roots.Records, Has.Count.EqualTo(2)); Assert.That(roots.Records[0].Id, Is.EqualTo(RootNamespaceId)); + Assert.That(roots.Records[1], Is.TypeOf().With.Property(nameof(Function.qualifiedName)).Null); } + this.mockHttp.Expect(HttpMethod.Get, rootsUri).Respond(HttpStatusCode.OK, PreferenceAppliedHeader, JsonMediaType, ReadPayload("roots.json")); + + roots = await this.client.GetRootsByProjectCommitAsync(ProjectId, CommitId); + + Assert.That(roots.Records[1], Is.TypeOf().With.Property(nameof(Function.qualifiedName)).EqualTo("ControlFunctions::forAll")); + this.mockHttp.Expect(HttpMethod.Get, rootsUri).Respond(HttpStatusCode.NotFound, JsonMediaType, ErrorPayload); await Assert.ThatAsync(() => this.client.GetRootsByProjectCommitAsync(ProjectId, CommitId), @@ -276,19 +296,35 @@ public async Task VerifyGetRelationshipsByProjectCommitRelatedElementAsync() public async Task VerifyGetElementByProjectCommitIdAsync() { var elementUri = $"{BaseAddress}projects/{ProjectId}/commits/{CommitId}/elements/{RootNamespaceId}"; + var functionUri = $"{BaseAddress}projects/{ProjectId}/commits/{CommitId}/elements/{FunctionId}"; var roots = ReadPayload("roots.json"); + string functionElement; using (var rootsDocument = JsonDocument.Parse(roots)) { this.mockHttp.Expect(HttpMethod.Get, elementUri) .WithExactQueryString("excludeUsed=false") .Respond(JsonMediaType, rootsDocument.RootElement[0].GetRawText()); + + functionElement = rootsDocument.RootElement[1].GetRawText(); } var element = await this.client.GetElementByProjectCommitIdAsync(ProjectId, CommitId, RootNamespaceId, false); Assert.That(element, Is.TypeOf().With.Property(nameof(Namespace.Id)).EqualTo(RootNamespaceId)); + this.mockHttp.Expect(HttpMethod.Get, functionUri).Respond(JsonMediaType, functionElement); + + element = await this.client.GetElementByProjectCommitIdAsync(ProjectId, CommitId, FunctionId); + + Assert.That(element, Is.TypeOf().With.Property(nameof(Function.qualifiedName)).Null); + + this.mockHttp.Expect(HttpMethod.Get, functionUri).Respond(HttpStatusCode.OK, PreferenceAppliedHeader, JsonMediaType, functionElement); + + element = await this.client.GetElementByProjectCommitIdAsync(ProjectId, CommitId, FunctionId); + + Assert.That(element, Is.TypeOf().With.Property(nameof(Function.qualifiedName)).EqualTo("ControlFunctions::forAll")); + this.mockHttp.Expect(HttpMethod.Get, elementUri).Respond(JsonMediaType, roots); await Assert.ThatAsync(() => this.client.GetElementByProjectCommitIdAsync(ProjectId, CommitId, RootNamespaceId), Throws.TypeOf()); @@ -383,7 +419,7 @@ public async Task VerifyMergeAsync() .With(request => { mergeBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult(); - hasPreferHeader = request.Headers.Contains("Prefer"); + hasPreferHeader = request.Headers.Contains(PreferenceHeaders.Prefer); return true; }) .Respond(HttpStatusCode.Created, JsonMediaType, ReadPayload("commit.json")); @@ -400,21 +436,19 @@ public async Task VerifyMergeAsync() Assert.That(hasPreferHeader, Is.False); } - using var derivedHttpClient = this.mockHttp.ToHttpClient(); - derivedHttpClient.BaseAddress = BaseAddress; - var derivedClient = new PsmApiClient(derivedHttpClient, new DeSerializer(), new Serializer(), options: new PsmApiClientOptions { IncludeDerivedProperties = true }); + var serializingClient = this.CreateClient(new PsmApiClientOptions { SerializeDerivedProperties = true }); this.mockHttp.Expect(HttpMethod.Post, mergeUri) .WithExactQueryString($"sourceCommitId={CommitId}") - .WithHeaders("Prefer", "include-derived") .With(request => { mergeBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + hasPreferHeader = request.Headers.Contains(PreferenceHeaders.Prefer); return true; }) .Respond(HttpStatusCode.Created, JsonMediaType, ReadPayload("commit.json")); - mergeCommit = await derivedClient.MergeAsync(ProjectId, [CommitId], BranchId, [new Namespace { Id = RootNamespaceId }]); + mergeCommit = await serializingClient.MergeAsync(ProjectId, [CommitId], BranchId, [new Namespace { Id = RootNamespaceId }]); using (Assert.EnterMultipleScope()) { @@ -422,6 +456,27 @@ public async Task VerifyMergeAsync() Assert.That(mergeBody, Does.Contain("\"qualifiedName\"")); Assert.That(mergeBody, Does.Contain("\"owner\"")); Assert.That(mergeBody, Does.Contain("\"membership\"")); + Assert.That(hasPreferHeader, Is.False); + } + + var requestingClient = this.CreateClient(new PsmApiClientOptions { RequestDerivedProperties = true }); + + this.mockHttp.Expect(HttpMethod.Post, mergeUri) + .WithExactQueryString($"sourceCommitId={CommitId}") + .WithHeaders(PreferenceHeaders.Prefer, PreferenceHeaders.IncludeDerived) + .With(request => + { + mergeBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + return true; + }) + .Respond(HttpStatusCode.Created, JsonMediaType, ReadPayload("commit.json")); + + mergeCommit = await requestingClient.MergeAsync(ProjectId, [CommitId], BranchId, [new Namespace { Id = RootNamespaceId }]); + + using (Assert.EnterMultipleScope()) + { + Assert.That(mergeCommit.Id, Is.EqualTo(CommitId)); + Assert.That(mergeBody, Does.Not.Contain("\"qualifiedName\"")); } await Assert.ThatAsync(() => this.client.MergeAsync(ProjectId, null, BranchId), Throws.TypeOf()); diff --git a/SySML2.NET.REST.Tests/SessionTestFixture.cs b/SySML2.NET.REST.Tests/SessionTestFixture.cs index f5bbb3507..2ae169c93 100644 --- a/SySML2.NET.REST.Tests/SessionTestFixture.cs +++ b/SySML2.NET.REST.Tests/SessionTestFixture.cs @@ -26,6 +26,7 @@ namespace SySML2.NET.REST.Tests using RichardSzalay.MockHttp; using SysML2.NET.Dal; + using SysML2.NET.PSM; using SysML2.NET.REST.Exceptions; using SysML2.NET.Serializer.Json; @@ -129,16 +130,24 @@ public async Task VerifyOpen() Assert.That(this.assembler.Cache, Is.Empty); } - var derivedSession = new Session(this.httpClientFactory.Object, new DeSerializer(), new Serializer(), clientOptions: new PsmApiClientOptions { IncludeDerivedProperties = true }); + this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects") + .With(request => !request.Headers.Contains(PreferenceHeaders.Prefer)) + .Respond(JsonMediaType, "[]"); - this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects").WithHeaders("Prefer", "include-derived").Respond(JsonMediaType, "[]"); + await this.session.Open(new Uri("http://localhost/api"), null, CancellationToken.None); - await derivedSession.Open(new Uri("http://localhost/api"), CancellationToken.None); + Assert.That(this.session.Client, Is.Not.Null); + + this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects") + .WithHeaders(PreferenceHeaders.Prefer, PreferenceHeaders.IncludeDerived) + .Respond(JsonMediaType, "[]"); - Assert.That(derivedSession.Client, Is.Not.Null); + await this.session.Open(new Uri("http://localhost/api"), new PsmApiClientOptions { RequestDerivedProperties = true }, CancellationToken.None); + + Assert.That(this.session.Client, Is.Not.Null); this.mockHttp.VerifyNoOutstandingExpectation(); - this.httpClientFactory.Verify(factory => factory.CreateClient(nameof(Session)), Times.Exactly(4)); + this.httpClientFactory.Verify(factory => factory.CreateClient(nameof(Session)), Times.Exactly(5)); } [Test] diff --git a/SySML2.NET.REST/ISessionLifecycle.cs b/SySML2.NET.REST/ISessionLifecycle.cs index d0cf01f58..6c2a5897d 100644 --- a/SySML2.NET.REST/ISessionLifecycle.cs +++ b/SySML2.NET.REST/ISessionLifecycle.cs @@ -45,5 +45,28 @@ public interface ISessionLifecycle /// Thrown when is not absolute /// Task> Open(Uri baseAddress, CancellationToken cancellationToken); + + /// + /// Opens a connection to the server with the specified client options, replacing any open connection, and reads the first page of its projects + /// + /// + /// The absolute base address of the server + /// + /// + /// The of the connection, or null to use the defaults + /// + /// + /// The that cancels the operation + /// + /// + /// The first page of the projects of the server + /// + /// + /// Thrown when is null + /// + /// + /// Thrown when is not absolute + /// + Task> Open(Uri baseAddress, PsmApiClientOptions clientOptions, CancellationToken cancellationToken); } } diff --git a/SySML2.NET.REST/PsmApiClient.cs b/SySML2.NET.REST/PsmApiClient.cs index 4bb6f49d4..7267c4279 100644 --- a/SySML2.NET.REST/PsmApiClient.cs +++ b/SySML2.NET.REST/PsmApiClient.cs @@ -43,11 +43,6 @@ public partial class PsmApiClient : IPsmApiClient /// private const string JsonMediaType = "application/json"; - /// - /// The RFC 7240 preference asking the server to include the derived properties in its responses - /// - private const string IncludeDerivedPreference = "include-derived"; - /// /// The pattern of one link-value of an RFC 8288 Link header, capturing its target and its relation type /// @@ -87,6 +82,11 @@ public partial class PsmApiClient : IPsmApiClient /// private static readonly JsonWriterOptions WriterOptions = new(); + /// + /// The characters that end the token of an RFC 7240 preference, before its value or its parameters + /// + private static readonly char[] PreferenceTokenDelimiters = [';', '=']; + /// /// The whose addresses the server /// @@ -249,6 +249,24 @@ private static void ThrowIfNull(object value, string parameterName) } } + /// + /// Asserts whether the server confirmed, with the RFC 7240 Preference-Applied header, that the response carries the derived properties + /// + /// + /// The whose Preference-Applied header is read + /// + /// + /// true when the header lists the include-derived preference, otherwise false + /// + private static bool IsDerivedPreferenceApplied(HttpResponseMessage response) + { + return response.Headers.TryGetValues(PreferenceHeaders.PreferenceApplied, out var headerValues) + && headerValues + .SelectMany(headerValue => headerValue.Split(',')) + .Select(preference => preference.Split(PreferenceTokenDelimiters)[0].Trim()) + .Contains(PreferenceHeaders.IncludeDerived, StringComparer.OrdinalIgnoreCase); + } + /// /// Queries the page that the link with the specified relation type of the Link header points to /// @@ -315,13 +333,13 @@ private async Task CreateContentAsync(IRequest requestBody, Cancell var stream = new MemoryStream(); - await this.serializer.SerializeRequestAsync(requestBody, SerializationModeKind.JSON, this.options.IncludeDerivedProperties, stream, WriterOptions, cancellationToken); + await this.serializer.SerializeRequestAsync(requestBody, SerializationModeKind.JSON, this.options.SerializeDerivedProperties, stream, WriterOptions, cancellationToken); return CreateContent(stream); } /// - /// Creates the JSON body of a request from a sequence of data items, each written as a full Data including its derived properties + /// Creates the JSON body of a request from a sequence of data items, including their derived properties when is set /// /// /// The items to send, or null to send no body @@ -341,7 +359,7 @@ private async Task CreateContentAsync(IEnumerable requestBod var stream = new MemoryStream(); - await this.serializer.SerializeAsync(requestBody, SerializationModeKind.JSON, this.options.IncludeDerivedProperties, stream, WriterOptions, cancellationToken); + await this.serializer.SerializeAsync(requestBody, SerializationModeKind.JSON, this.options.SerializeDerivedProperties, stream, WriterOptions, cancellationToken); return CreateContent(stream); } @@ -575,7 +593,7 @@ private async Task ReadDataAsync(HttpResponseMessage response, Cancellatio { await using var stream = await ReadContentStreamAsync(response.Content, cancellationToken); - var data = await this.deSerializer.DeSerializeAsync(stream, SerializationModeKind.JSON, SerializationTargetKind.PSM, false, cancellationToken); + var data = await this.deSerializer.DeSerializeAsync(stream, SerializationModeKind.JSON, SerializationTargetKind.PSM, IsDerivedPreferenceApplied(response), cancellationToken); return data.Single(); } @@ -599,7 +617,7 @@ private async Task> ReadPagedDataAsync(HttpResponseMessage res { await using var stream = await ReadContentStreamAsync(response.Content, cancellationToken); - var data = await this.deSerializer.DeSerializeAsync(stream, SerializationModeKind.JSON, SerializationTargetKind.PSM, false, cancellationToken); + var data = await this.deSerializer.DeSerializeAsync(stream, SerializationModeKind.JSON, SerializationTargetKind.PSM, IsDerivedPreferenceApplied(response), cancellationToken); return CreatePagedResult(response, data.ToList()); } @@ -691,9 +709,9 @@ private async Task SendAsync(HttpMethod method, string requ requestMessage.Content = content; requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(JsonMediaType)); - if (this.options.IncludeDerivedProperties) + if (this.options.RequestDerivedProperties) { - requestMessage.Headers.Add("Prefer", IncludeDerivedPreference); + requestMessage.Headers.Add(PreferenceHeaders.Prefer, PreferenceHeaders.IncludeDerived); } var response = await this.httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken); diff --git a/SySML2.NET.REST/PsmApiClientOptions.cs b/SySML2.NET.REST/PsmApiClientOptions.cs index 6cfefbafb..4ec7320c0 100644 --- a/SySML2.NET.REST/PsmApiClientOptions.cs +++ b/SySML2.NET.REST/PsmApiClientOptions.cs @@ -15,8 +15,13 @@ namespace SySML2.NET.REST public class PsmApiClientOptions { /// - /// Gets or sets a value indicating whether request bodies carry the derived properties and every request sends the Prefer: include-derived header + /// Gets or sets a value indicating whether request bodies carry the derived properties of the data they send /// - public bool IncludeDerivedProperties { get; set; } + public bool SerializeDerivedProperties { get; set; } + + /// + /// Gets or sets a value indicating whether every request asks the server for the derived properties with the Prefer: include-derived header + /// + public bool RequestDerivedProperties { get; set; } } } diff --git a/SySML2.NET.REST/Session.cs b/SySML2.NET.REST/Session.cs index 5e46877cf..83b1fcf49 100644 --- a/SySML2.NET.REST/Session.cs +++ b/SySML2.NET.REST/Session.cs @@ -62,11 +62,6 @@ public class Session : ISession /// private int generation; - /// - /// The handed to each - /// - private readonly PsmApiClientOptions clientOptions; - /// /// Initializes a new instance of the class /// @@ -85,21 +80,16 @@ public class Session : ISession /// /// The used to set up logging, or null to disable logging /// - /// - /// The handed to each , or null to use the defaults - /// /// /// Thrown when , , or is null /// - //public Session(IHttpClientFactory httpClientFactory, IDeSerializer deSerializer, ISerializer serializer, IAssembler assembler, ILoggerFactory loggerFactory = null) - public Session(IHttpClientFactory httpClientFactory, IDeSerializer deSerializer, ISerializer serializer, IAssembler assembler,ILoggerFactory loggerFactory = null, PsmApiClientOptions clientOptions = null) + public Session(IHttpClientFactory httpClientFactory, IDeSerializer deSerializer, ISerializer serializer, IAssembler assembler, ILoggerFactory loggerFactory = null) { this.httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); this.deSerializer = deSerializer ?? throw new ArgumentNullException(nameof(deSerializer)); this.serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); this.Assembler = assembler ?? throw new ArgumentNullException(nameof(assembler)); this.loggerFactory = loggerFactory; - this.clientOptions = clientOptions; } /// @@ -213,7 +203,30 @@ public async Task LoadCommit(Guid projectId, Guid commitId, CancellationToken ca /// /// Thrown when is not absolute /// - public async Task> Open(Uri baseAddress, CancellationToken cancellationToken) + public Task> Open(Uri baseAddress, CancellationToken cancellationToken) => this.Open(baseAddress, null, cancellationToken); + + /// + /// Opens a connection to the server with the specified client options, replacing any open connection, and reads the first page of its projects + /// + /// + /// The absolute base address of the server + /// + /// + /// The of the connection, or null to use the defaults + /// + /// + /// The that cancels the operation + /// + /// + /// The first page of the projects of the server + /// + /// + /// Thrown when is null + /// + /// + /// Thrown when is not absolute + /// + public async Task> Open(Uri baseAddress, PsmApiClientOptions clientOptions, CancellationToken cancellationToken) { #if NET6_0_OR_GREATER ArgumentNullException.ThrowIfNull(baseAddress); @@ -236,7 +249,7 @@ public async Task> Open(Uri baseAddress, CancellationToken // a relative request URI drops the last path segment of a base address that does not end with a slash httpClient.BaseAddress = baseAddress.AbsoluteUri.EndsWith('/') ? baseAddress : new Uri($"{baseAddress.AbsoluteUri}/"); - var client = new PsmApiClient(httpClient, this.deSerializer, this.serializer, this.loggerFactory); + var client = new PsmApiClient(httpClient, this.deSerializer, this.serializer, this.loggerFactory, clientOptions); var projects = await client.GetProjectsAsync(cancellationToken: cancellationToken); diff --git a/SysML2.NET/PSM/PreferenceHeaders.cs b/SysML2.NET/PSM/PreferenceHeaders.cs new file mode 100644 index 000000000..3ed64b677 --- /dev/null +++ b/SysML2.NET/PSM/PreferenceHeaders.cs @@ -0,0 +1,32 @@ +// ------------------------------------------------------------------------------------------------ +// +// +// Copyright (C) 2022-2026 Starion Group S.A. +// SPDX-License-Identifier: Apache-2.0 +// +// +// ------------------------------------------------------------------------------------------------ + +namespace SysML2.NET.PSM +{ + /// + /// The RFC 7240 header names and preference tokens shared by every client and server of the REST/HTTP platform specific model + /// + public static class PreferenceHeaders + { + /// + /// The name of the request header that states the preferences of the client (RFC 7240, Section 2) + /// + public const string Prefer = "Prefer"; + + /// + /// The name of the response header that lists the preferences the server honoured (RFC 7240, Section 3) + /// + public const string PreferenceApplied = "Preference-Applied"; + + /// + /// The preference asking the server to include the derived properties of the data in its responses + /// + public const string IncludeDerived = "include-derived"; + } +} From ea674a2dda0436e4a48413ed02fa56e65b6c76f9 Mon Sep 17 00:00:00 2001 From: Zeynep Delal Mutlu Date: Tue, 1 Dec 2026 11:44:46 +0100 Subject: [PATCH 4/4] tiny PR check --- .../PsmApiClientTestFixture.cs | 71 +++++++++++++++++++ SySML2.NET.REST/PsmApiClient.cs | 4 +- 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs b/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs index 4b1072346..75d5d0e1c 100644 --- a/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs +++ b/SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs @@ -50,6 +50,8 @@ public class PsmApiClientTestFixture private static readonly Guid FunctionId = Guid.Parse("761f87bf-e06e-55f7-8830-ebcc3f619e2d"); + private static readonly Guid ChangeId = Guid.Parse("4b1c7d2e-9f3a-4e6b-8c5d-1a2b3c4d5e6f"); + private static readonly KeyValuePair[] PreferenceAppliedHeader = [new(PreferenceHeaders.PreferenceApplied, PreferenceHeaders.IncludeDerived)]; private MockHttpMessageHandler mockHttp; @@ -78,6 +80,13 @@ private static string ReadPayload(string fileName) return File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", fileName)); } + private static string CreateFunctionChangePayload() + { + using var rootsDocument = JsonDocument.Parse(ReadPayload("roots.json")); + + return $"{{\"@type\":\"DataVersion\",\"@id\":\"{ChangeId}\",\"identity\":{{\"@type\":\"DataIdentity\",\"@id\":\"{FunctionId}\"}},\"payload\":{rootsDocument.RootElement[1].GetRawText()}}}"; + } + private static KeyValuePair[] CreateLinkHeader(string link) { return [new KeyValuePair("Link", link)]; @@ -341,6 +350,68 @@ await Assert.ThatAsync(() => this.client.GetElementByProjectCommitIdAsync(Projec this.mockHttp.VerifyNoOutstandingExpectation(); } + [Test] + public async Task VerifyGetChangesByProjectCommitAsync() + { + var changesUri = $"{BaseAddress}projects/{ProjectId}/commits/{CommitId}/changes"; + var changes = $"[{CreateFunctionChangePayload()}]"; + + this.mockHttp.Expect(HttpMethod.Get, changesUri).Respond(JsonMediaType, changes); + + var result = await this.client.GetChangesByProjectCommitAsync(ProjectId, CommitId); + + using (Assert.EnterMultipleScope()) + { + Assert.That(result.Records, Has.Count.EqualTo(1)); + Assert.That(result.Records[0].Id, Is.EqualTo(ChangeId)); + Assert.That(result.Records[0].Payload, Is.TypeOf().With.Property(nameof(Function.qualifiedName)).Null); + } + + this.mockHttp.Expect(HttpMethod.Get, changesUri).Respond(HttpStatusCode.OK, PreferenceAppliedHeader, JsonMediaType, changes); + + result = await this.client.GetChangesByProjectCommitAsync(ProjectId, CommitId); + + Assert.That(result.Records[0].Payload, Is.TypeOf().With.Property(nameof(Function.qualifiedName)).EqualTo("ControlFunctions::forAll")); + + this.mockHttp.Expect(HttpMethod.Get, changesUri).Respond(HttpStatusCode.NotFound, JsonMediaType, ErrorPayload); + + await Assert.ThatAsync(() => this.client.GetChangesByProjectCommitAsync(ProjectId, CommitId), + Throws.TypeOf().With.Property(nameof(PsmApiException.StatusCode)).EqualTo(HttpStatusCode.NotFound)); + + this.mockHttp.VerifyNoOutstandingExpectation(); + } + + [Test] + public async Task VerifyGetChangeByProjectCommitIdAsync() + { + var changeUri = $"{BaseAddress}projects/{ProjectId}/commits/{CommitId}/changes/{ChangeId}"; + var change = CreateFunctionChangePayload(); + + this.mockHttp.Expect(HttpMethod.Get, changeUri).Respond(JsonMediaType, change); + + var result = await this.client.GetChangeByProjectCommitIdAsync(ProjectId, CommitId, ChangeId); + + using (Assert.EnterMultipleScope()) + { + Assert.That(result.Id, Is.EqualTo(ChangeId)); + Assert.That(result.Identity.Id, Is.EqualTo(FunctionId)); + Assert.That(result.Payload, Is.TypeOf().With.Property(nameof(Function.qualifiedName)).Null); + } + + this.mockHttp.Expect(HttpMethod.Get, changeUri).Respond(HttpStatusCode.OK, PreferenceAppliedHeader, JsonMediaType, change); + + result = await this.client.GetChangeByProjectCommitIdAsync(ProjectId, CommitId, ChangeId); + + Assert.That(result.Payload, Is.TypeOf().With.Property(nameof(Function.qualifiedName)).EqualTo("ControlFunctions::forAll")); + + this.mockHttp.Expect(HttpMethod.Get, changeUri).Respond(HttpStatusCode.NotFound, JsonMediaType, ErrorPayload); + + await Assert.ThatAsync(() => this.client.GetChangeByProjectCommitIdAsync(ProjectId, CommitId, ChangeId), + Throws.TypeOf().With.Property(nameof(PsmApiException.StatusCode)).EqualTo(HttpStatusCode.NotFound)); + + this.mockHttp.VerifyNoOutstandingExpectation(); + } + [Test] public async Task VerifyGetQueryResultsByProjectIdQueryPostAsync() { diff --git a/SySML2.NET.REST/PsmApiClient.cs b/SySML2.NET.REST/PsmApiClient.cs index 7267c4279..3da764200 100644 --- a/SySML2.NET.REST/PsmApiClient.cs +++ b/SySML2.NET.REST/PsmApiClient.cs @@ -544,7 +544,7 @@ private async Task ReadResponseAsync(HttpResponseMessage response, Cancell await using var stream = await ReadContentStreamAsync(response.Content, cancellationToken); - return await this.deSerializer.DeSerializeResponseAsync(stream, SerializationModeKind.JSON, false, cancellationToken); + return await this.deSerializer.DeSerializeResponseAsync(stream, SerializationModeKind.JSON, IsDerivedPreferenceApplied(response), cancellationToken); } /// @@ -566,7 +566,7 @@ private async Task> ReadPagedResponseAsync(HttpResponseMessage { await using var stream = await ReadContentStreamAsync(response.Content, cancellationToken); - var records = await this.deSerializer.DeSerializeResponsesAsync(stream, SerializationModeKind.JSON, false, cancellationToken); + var records = await this.deSerializer.DeSerializeResponsesAsync(stream, SerializationModeKind.JSON, IsDerivedPreferenceApplied(response), cancellationToken); return CreatePagedResult(response, records.ToList()); }