Skip to content

Commit 4068ba8

Browse files
EvangelinkCopilot
andauthored
Split CommonHost into focused partial files (#10548)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8ea243c0-fd25-4425-97ed-30fef1f98629
1 parent 6870877 commit 4068ba8

4 files changed

Lines changed: 360 additions & 319 deletions

File tree

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using Microsoft.Testing.Platform.Extensions;
5+
using Microsoft.Testing.Platform.Extensions.TestHost;
6+
using Microsoft.Testing.Platform.Helpers;
7+
using Microsoft.Testing.Platform.Logging;
8+
using Microsoft.Testing.Platform.Messages;
9+
using Microsoft.Testing.Platform.ServerMode;
10+
using Microsoft.Testing.Platform.Services;
11+
using Microsoft.Testing.Platform.Telemetry;
12+
13+
namespace Microsoft.Testing.Platform.Hosts;
14+
15+
internal abstract partial class CommonHost
16+
{
17+
protected static async Task DisposeServiceProviderAsync(ServiceProvider serviceProvider, Func<object, bool>? filter = null, List<object>? alreadyDisposed = null, bool isProcessShutdown = false)
18+
{
19+
alreadyDisposed ??= [];
20+
21+
// Close the message bus handshake before disposing anything at all. Consumers are routinely registered
22+
// as services in their own right, and several of them (the output device, the coverage accumulator) land
23+
// in Services *before* the bus does, so disabling inline when the loop happens to reach the bus would
24+
// already have disposed those consumers while their ConsumeAsync was still running.
25+
foreach (object service in serviceProvider.Services)
26+
{
27+
if (service is not BaseMessageBus messageBus || (filter is not null && !filter(messageBus)))
28+
{
29+
continue;
30+
}
31+
32+
await EnsureMessageBusDisabledAsync(messageBus, serviceProvider).ConfigureAwait(false);
33+
34+
// Disabling is bounded on an aborted run, so it can return with a consumer still inside
35+
// ConsumeAsync. Recording those as already disposed is what keeps every loop below off them:
36+
// disposing one now is precisely the race the handshake exists to prevent, so we leak it and let
37+
// the process exit reclaim it instead.
38+
foreach (IDataConsumer dataConsumer in messageBus.ConsumersStillRunning)
39+
{
40+
if (alreadyDisposed.Contains(dataConsumer))
41+
{
42+
continue;
43+
}
44+
45+
alreadyDisposed.Add(dataConsumer);
46+
await LogShutdownWarningAsync(
47+
serviceProvider,
48+
$"Not disposing data consumer '{dataConsumer.Uid}' because it is still consuming after the shutdown timeout elapsed.").ConfigureAwait(false);
49+
}
50+
}
51+
52+
foreach (object service in serviceProvider.Services)
53+
{
54+
// Logger is the most special service and we dispose it manually as last one, we want to be able to
55+
// collect logs till the end of the process.
56+
if (service is FileLoggerProvider)
57+
{
58+
continue;
59+
}
60+
61+
// The LoggerFactoryProxy owns the real ILoggerFactory and is disposed manually after the rest of
62+
// the services so that providers registered through it (including bridges to
63+
// Microsoft.Extensions.Logging) can flush at the very end of the process.
64+
if (service is LoggerFactoryProxy)
65+
{
66+
continue;
67+
}
68+
69+
// The ITestApplicationCancellationTokenSource contains the cancellation token and can be used by other services during the shutdown
70+
// we will collect manually in the correct moment.
71+
if (service is ITestApplicationCancellationTokenSource)
72+
{
73+
continue;
74+
}
75+
76+
if (filter is not null && !filter(service))
77+
{
78+
continue;
79+
}
80+
81+
// We need to ensure that we won't dispose special services till the shutdown
82+
#pragma warning disable CS0618 // Type or member is obsolete
83+
if (!isProcessShutdown &&
84+
service is ITelemetryCollector or
85+
ITestHostApplicationLifetime or
86+
IPushOnlyProtocol or
87+
IPlatformOpenTelemetryService or
88+
IOpenTelemetryProvider)
89+
{
90+
continue;
91+
}
92+
#pragma warning restore CS0618 // Type or member is obsolete
93+
94+
if (!alreadyDisposed.Contains(service))
95+
{
96+
await DisposeHelper.DisposeAsync(service).ConfigureAwait(false);
97+
alreadyDisposed.Add(service);
98+
}
99+
100+
if (service is BaseMessageBus busWithConsumers)
101+
{
102+
foreach (IDataConsumer dataConsumer in busWithConsumers.DataConsumerServices)
103+
{
104+
if (filter is not null && !filter(dataConsumer))
105+
{
106+
continue;
107+
}
108+
109+
// Consumers still inside ConsumeAsync were recorded as already disposed by the pre-pass
110+
// above, so this check is what spares them here.
111+
if (!alreadyDisposed.Contains(dataConsumer))
112+
{
113+
await DisposeHelper.DisposeAsync(dataConsumer).ConfigureAwait(false);
114+
alreadyDisposed.Add(dataConsumer);
115+
}
116+
}
117+
}
118+
}
119+
}
120+
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using Microsoft.Testing.Platform.Extensions.TestFramework;
5+
using Microsoft.Testing.Platform.Messages;
6+
using Microsoft.Testing.Platform.OutputDevice;
7+
using Microsoft.Testing.Platform.Services;
8+
using Microsoft.Testing.Platform.Telemetry;
9+
10+
namespace Microsoft.Testing.Platform.Hosts;
11+
12+
internal abstract partial class CommonHost
13+
{
14+
protected static async Task ExecuteRequestAsync(ProxyOutputDevice outputDevice, ITestSessionContext testSessionInfo,
15+
ServiceProvider serviceProvider, BaseMessageBus baseMessageBus, ITestFramework testFramework, TestHost.ClientInfo client)
16+
{
17+
// Reset the shared, application-scoped coverage accumulator at the start of every request here, in the
18+
// common host/request lifecycle, so it happens for all output modes (terminal, pipe, server, custom)
19+
// rather than only when the terminal device renders. Without this a prior session's coverage rows and
20+
// thresholds would be reprinted and its threshold-failure verdict could poison a later session.
21+
serviceProvider.GetRequiredService<TestCoverageResult>().Reset();
22+
23+
await DisplayBeforeSessionStartAsync(outputDevice, testSessionInfo).ConfigureAwait(false);
24+
CancellationToken cancellationToken = testSessionInfo.CancellationToken;
25+
try
26+
{
27+
try
28+
{
29+
IPlatformOpenTelemetryService? otelService = serviceProvider.GetPlatformOTelService();
30+
using (otelService?.StartActivity("OnTestSessionStarting"))
31+
{
32+
await NotifyTestSessionStartAsync(testSessionInfo, baseMessageBus, serviceProvider, otelService).ConfigureAwait(false);
33+
}
34+
35+
using (otelService?.StartActivity("TestFrameworkInvoker"))
36+
{
37+
await serviceProvider.GetTestFrameworkInvoker().ExecuteAsync(testFramework, client, cancellationToken).ConfigureAwait(false);
38+
}
39+
40+
using (otelService?.StartActivity("OnTestSessionEnding"))
41+
{
42+
await NotifyTestSessionEndAsync(testSessionInfo, baseMessageBus, serviceProvider, otelService).ConfigureAwait(false);
43+
}
44+
}
45+
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
46+
{
47+
// Do nothing we're canceled
48+
}
49+
50+
// We keep the display after session out of the OperationCanceledException catch because we want to notify the IPlatformOutputDevice
51+
// also in case of cancellation. Most likely it needs to notify users that the session was canceled.
52+
await DisplayAfterSessionEndRunAsync(outputDevice, testSessionInfo).ConfigureAwait(false);
53+
}
54+
finally
55+
{
56+
// The message bus shutdown handshake must complete before the services - and with them every
57+
// IDataConsumer - get disposed, otherwise a consumer can still be inside ConsumeAsync while it is
58+
// being disposed. NotifyTestSessionEndAsync does it on the happy path, but it is skipped whenever the
59+
// session is canceled or fails, so we close the handshake here for every outcome.
60+
await EnsureMessageBusDisabledAsync(baseMessageBus, serviceProvider).ConfigureAwait(false);
61+
}
62+
}
63+
64+
/// <summary>
65+
/// Disables the message bus, which stops accepting new payloads and awaits every consumer loop, so that no
66+
/// <see cref="Extensions.IDataConsumer.ConsumeAsync"/> can still be running once the consumers are disposed.
67+
/// </summary>
68+
/// <remarks>
69+
/// This is a best-effort safety net that runs on teardown paths, including the ones that are already unwinding
70+
/// because of a cancellation or a failure. Disabling is idempotent, so on the regular path this is a no-op and
71+
/// any consumer failure has already been surfaced by the real call. Failures here are logged and swallowed
72+
/// rather than replacing the exception that is being propagated; a consumer that survives the handshake is
73+
/// reported through <see cref="BaseMessageBus.ConsumersStillRunning"/> and left undisposed.
74+
/// </remarks>
75+
protected static async Task EnsureMessageBusDisabledAsync(BaseMessageBus baseMessageBus, IServiceProvider serviceProvider)
76+
{
77+
try
78+
{
79+
await baseMessageBus.DisableAsync().ConfigureAwait(false);
80+
}
81+
catch (Exception ex)
82+
{
83+
await LogShutdownWarningAsync(serviceProvider, $"Failed to disable the message bus during shutdown: {ex}").ConfigureAwait(false);
84+
}
85+
}
86+
}
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
3+
4+
using Microsoft.Testing.Platform.Extensions;
5+
using Microsoft.Testing.Platform.Extensions.TestHost;
6+
using Microsoft.Testing.Platform.Helpers;
7+
using Microsoft.Testing.Platform.Logging;
8+
using Microsoft.Testing.Platform.Messages;
9+
using Microsoft.Testing.Platform.OutputDevice;
10+
using Microsoft.Testing.Platform.Services;
11+
using Microsoft.Testing.Platform.Telemetry;
12+
13+
namespace Microsoft.Testing.Platform.Hosts;
14+
15+
internal abstract partial class CommonHost
16+
{
17+
private static async Task LogShutdownWarningAsync(IServiceProvider serviceProvider, string message)
18+
{
19+
try
20+
{
21+
if (serviceProvider.GetService<ILoggerFactory>()?.CreateLogger(nameof(CommonHost)) is { } logger)
22+
{
23+
await logger.LogWarningAsync(message).ConfigureAwait(false);
24+
}
25+
}
26+
catch (Exception)
27+
{
28+
// This runs on teardown paths that are often already unwinding, and the logging stack is itself
29+
// being torn down (a disposed LoggerFactoryProxy throws from CreateLogger, and providers can fail
30+
// from LogAsync). A failed warning must not replace the exception we were reporting, nor abort the
31+
// rest of the disposal.
32+
}
33+
}
34+
35+
private static async Task DisplayBeforeSessionStartAsync(ProxyOutputDevice outputDevice, ITestSessionContext sessionInfo)
36+
{
37+
// Display before session start
38+
await outputDevice.DisplayBeforeSessionStartAsync(sessionInfo.CancellationToken).ConfigureAwait(false);
39+
40+
if (outputDevice.OriginalOutputDevice is ITestSessionLifetimeHandler testSessionLifetimeHandler)
41+
{
42+
await testSessionLifetimeHandler.OnTestSessionStartingAsync(sessionInfo).ConfigureAwait(false);
43+
}
44+
}
45+
46+
private static async Task DisplayAfterSessionEndRunAsync(ProxyOutputDevice outputDevice, ITestSessionContext sessionInfo)
47+
{
48+
// Display after session end even when the session cancellation token is canceled.
49+
// We intentionally pass a non-cancelable token so final output/cleanup notifications are not skipped.
50+
await outputDevice.DisplayAfterSessionEndRunAsync(CancellationToken.None).ConfigureAwait(false);
51+
52+
// We want to ensure that the output service is the last one to run
53+
if (outputDevice.OriginalOutputDevice is ITestSessionLifetimeHandler testSessionLifetimeHandlerFinishing)
54+
{
55+
await testSessionLifetimeHandlerFinishing.OnTestSessionFinishingAsync(sessionInfo).ConfigureAwait(false);
56+
}
57+
}
58+
59+
private static async Task NotifyTestSessionStartAsync(ITestSessionContext testSessionContext, BaseMessageBus baseMessageBus, ServiceProvider serviceProvider, IPlatformOpenTelemetryService? otelService)
60+
{
61+
TestSessionLifetimeHandlersContainer? testSessionLifetimeHandlersContainer = serviceProvider.GetService<TestSessionLifetimeHandlersContainer>();
62+
if (testSessionLifetimeHandlersContainer is null)
63+
{
64+
return;
65+
}
66+
67+
foreach (ITestSessionLifetimeHandler testSessionLifetimeHandler in testSessionLifetimeHandlersContainer.TestSessionLifetimeHandlers)
68+
{
69+
using IPlatformActivity? activity = otelService?.StartActivity(testSessionLifetimeHandler.Uid, testSessionLifetimeHandler.ToOTelTags());
70+
await testSessionLifetimeHandler.OnTestSessionStartingAsync(testSessionContext).ConfigureAwait(false);
71+
}
72+
73+
// Drain messages generated by the session start notification before to start test execution.
74+
await baseMessageBus.DrainDataAsync().ConfigureAwait(false);
75+
}
76+
77+
private static async Task NotifyTestSessionEndAsync(ITestSessionContext testSessionContext, BaseMessageBus baseMessageBus, ServiceProvider serviceProvider, IPlatformOpenTelemetryService? otelService)
78+
{
79+
// Drain messages generated by the test session execution before to process the session end notification.
80+
await baseMessageBus.DrainDataAsync().ConfigureAwait(false);
81+
82+
TestSessionLifetimeHandlersContainer? testSessionLifetimeHandlersContainer = serviceProvider.GetService<TestSessionLifetimeHandlersContainer>();
83+
if (testSessionLifetimeHandlersContainer is null)
84+
{
85+
// Nothing else to notify. The bus is disabled by the caller's teardown safety net
86+
// (EnsureMessageBusDisabledAsync), which runs for every outcome of the session.
87+
return;
88+
}
89+
90+
IShutdownProgressReporter? shutdownProgressReporter = serviceProvider.GetService<IShutdownProgressReporter>();
91+
92+
// First, we call OnTestSessionFinishingAsync on all non-consumers.
93+
bool hasNonDataConsumers = false;
94+
foreach (ITestSessionLifetimeHandler testSessionLifetimeHandler in testSessionLifetimeHandlersContainer.TestSessionLifetimeHandlers)
95+
{
96+
if (testSessionLifetimeHandler is IDataConsumer)
97+
{
98+
// At first, we don't call this for data consumers.
99+
// We want to do this for potentially publishers-only handlers.
100+
// The order here matters, because one handler can produce a message that is consumed by another.
101+
// By making the consumers last, we reduce the likelihood of issues related to ordering.
102+
// One case where this is important is the dependency between Code Coverage's ITestSessionLifetimeHandler and TRX's ITestSessionLifetimeHandler.
103+
// We must run Code Coverage ITestSessionLifetimeHandler implementation first, as it will publish SessionFileArtifact.
104+
// The SessionFileArtifact is expected to be consumed by TRX's implementation of ITestSessionLifetimeHandler.
105+
// In that case, ITestSessionLifetimeHandler of CC is a producer-only handler which we will run first.
106+
// Then we will drain the message bus to ensure TRX handler have consumed the SessionFileArtifact.
107+
// Then we run TRX OnTestSessionFinishingAsync.
108+
continue;
109+
}
110+
111+
hasNonDataConsumers = true;
112+
113+
using (otelService?.StartActivity(testSessionLifetimeHandler.Uid, testSessionLifetimeHandler.ToOTelTags()))
114+
using (shutdownProgressReporter?.Track(testSessionLifetimeHandler.Uid, testSessionLifetimeHandler.DisplayName, nameof(ITestSessionLifetimeHandler.OnTestSessionFinishingAsync)))
115+
{
116+
await testSessionLifetimeHandler.OnTestSessionFinishingAsync(testSessionContext).ConfigureAwait(false);
117+
}
118+
}
119+
120+
if (hasNonDataConsumers)
121+
{
122+
// At this point, we called all non-consumer handlers.
123+
// Now, we want to make sure to drain the message bus before calling the consumer handlers.
124+
// Messages produced by non-consumer handlers could be consumed by consumer handlers.
125+
await baseMessageBus.DrainDataAsync().ConfigureAwait(false);
126+
}
127+
128+
foreach (ITestSessionLifetimeHandler testSessionLifetimeHandler in testSessionLifetimeHandlersContainer.TestSessionLifetimeHandlers)
129+
{
130+
if (testSessionLifetimeHandler is not IDataConsumer)
131+
{
132+
// We already called this for non-consumers.
133+
continue;
134+
}
135+
136+
using (otelService?.StartActivity(testSessionLifetimeHandler.Uid, testSessionLifetimeHandler.ToOTelTags()))
137+
using (shutdownProgressReporter?.Track(testSessionLifetimeHandler.Uid, testSessionLifetimeHandler.DisplayName, nameof(ITestSessionLifetimeHandler.OnTestSessionFinishingAsync)))
138+
{
139+
await testSessionLifetimeHandler.OnTestSessionFinishingAsync(testSessionContext).ConfigureAwait(false);
140+
}
141+
142+
// OnTestSessionFinishingAsync could produce information that needs to be handled by others.
143+
// While in many cases we already handled this by calling all non-consumers first, it's possible that
144+
// two consumers might depend on each other. In that case, we solely rely on registration order.
145+
// And we drain in between.
146+
await baseMessageBus.DrainDataAsync().ConfigureAwait(false);
147+
}
148+
149+
// We disable after the drain because it's possible that the drain will produce more messages
150+
await baseMessageBus.DrainDataAsync().ConfigureAwait(false);
151+
await baseMessageBus.DisableAsync().ConfigureAwait(false);
152+
}
153+
}

0 commit comments

Comments
 (0)