Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/engine-de-statification.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ flowchart TD
### Problems (all in the engine)

- **God class** — `FalloutBuild` is ~456 LOC across 5 partials with 4 responsibilities: inheritable base class (`FalloutBuild.cs`), process-global state + static ctor (`FalloutBuild.Statics.cs:16-30`), output formatting (`FalloutBuild.Output.cs`), extension host (`FalloutBuild.Events.cs`). The partials hide the size, not the coupling.
- **Static state leaks across runs** — `BuildManager.cs:20,41,69` (handlers accumulate), `Logging.cs:20,214` (`LevelSwitch` + `InMemorySink.Instance` carry log events over), `ValueInjectionUtility.cs:13` (`s_valueCache` persists), `NuGetToolPathResolver.cs:14-17` (set per-run at `BuildManager.cs:53-56`, never reset).
- **Static state leaks across runs** — `BuildManager.cs:20,41,69` (handlers accumulate), `Logging.cs:20` (`LevelSwitch` carries over) and `Logging.cs:214` (`InMemorySink.Instance` carried log events over; now per-run on `BuildContext.LogSink`, FT-6), `ValueInjectionUtility.cs:13` (`s_valueCache` persists), `NuGetToolPathResolver.cs:14-17` (set per-run at `BuildManager.cs:53-56`, never reset).
- **Test/prod path divergence** — production reads the static `ParameterService.Instance` (`ParameterService.Statics.cs:11-13`), but `ParameterServiceTest.cs:14-22` constructs a *fresh* `ParameterService(funcs)`. Tests exercise a different object than production.
- **No DIP seams** — `BuildManager.cs:39-41` pokes `Console` directly; `BuildExecutor.cs:81` writes the filesystem directly; output goes through static `Host.Error()`.

Expand Down
30 changes: 26 additions & 4 deletions src/Fallout.Build/Execution/BuildContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@ namespace Fallout.Build.Execution;
/// <remarks>
/// <para>
/// <see cref="Current"/> is stored in an <see cref="AsyncLocal{T}"/>, so concurrent runs each see their own context.
/// The context owns the cancellation handlers, the event subscriptions and the <see cref="ParameterService"/>.
/// The context owns the cancellation handlers, the event subscriptions, the <see cref="ParameterService"/>
/// and the in-memory log sink.
/// Serilog's <c>Log.Logger</c> is still process-wide, so two runs at the same time can send events
/// to each other's sink. The sink itself is not shared.
/// </para>
/// <para>
/// On dispose, the context also resets some process-wide state: the in-memory log sink, the value-injection cache
/// On dispose, the context also resets some process-wide state: the value-injection cache
/// and the NuGet and npm tool path resolvers. That state is shared, so concurrent runs in one process can still
/// affect each other through it.
/// </para>
Expand Down Expand Up @@ -48,9 +51,17 @@ internal sealed class BuildContext : IDisposable
/// </summary>
public ParameterService Parameters { get; } = ParameterService.CreateDefault();

/// <summary>
/// The in-memory log sink for this run. FT-6 / <see href="https://github.com/Fallout-build/Fallout/issues/311">#311</see>:
/// <c>Logging.ConfigureInMemory</c> wires Serilog to this instance at the top of the run and
/// <c>WriteErrorsAndWarnings</c> reads it back at the end, both inside the scope — so a run's
/// warnings and errors are discarded with it rather than resurfacing in the next build.
/// </summary>
public Logging.InMemorySink LogSink { get; } = new();

private BuildContext()
{
onCancelKeyPress = (_, _) => cancellationHandlers.ForEach(x => x());
onCancelKeyPress = (_, _) => RunCancellationHandlers();
onToolOptionsCreated = (options, _) => VerbosityMapping.Apply((ToolOptions)options);
Console.CancelKeyPress += onCancelKeyPress;
ToolOptions.Created += onToolOptionsCreated;
Expand All @@ -59,13 +70,25 @@ private BuildContext()
/// <summary>Creates the ambient context for a build run and installs it as <see cref="Current"/>.</summary>
public static BuildContext Activate() => currentInstance.Value = new BuildContext();

/// <summary>
/// Runs the cancellation handlers with this context as <see cref="Current"/>. <c>Console.CancelKeyPress</c>
/// fires on a thread that does not carry the run's <see cref="AsyncLocal{T}"/>, and the handlers
/// (for example the build summary) read run state such as <see cref="LogSink"/> through it.
/// </summary>
internal void RunCancellationHandlers()
{
currentInstance.Value = this;
cancellationHandlers.ForEach(x => x());
}

public void RegisterCancellationHandler(Action handler) => cancellationHandlers.AddFirst(handler);

public void UnregisterCancellationHandler(Action handler) => cancellationHandlers.Remove(handler);

public void Dispose()
{
// These subscriptions belong to this instance, so removing them never affects another context.
// The per-run services (Parameters, LogSink) are dropped with the context, so they need no reset.
Console.CancelKeyPress -= onCancelKeyPress;
ToolOptions.Created -= onToolOptionsCreated;

Expand All @@ -76,7 +99,6 @@ public void Dispose()
return;
}

Logging.InMemorySink.Instance.Clear();
ValueInjectionUtility.ClearCache();
NuGetToolPathResolver.Reset();
NpmToolPathResolver.Reset();
Expand Down
6 changes: 6 additions & 0 deletions src/Fallout.Build/Host.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,19 @@ protected internal virtual void WriteErrorsAndWarnings()
// TODO: move to Logging
using (WriteBlock("Errors & Warnings"))
{
// The logger we replace owns the run's file sinks. Setting Log.Logger does not dispose it.
// Without this, `build.log` stays open and the next run in the same process cannot reset it.
var replaced = Log.Logger as IDisposable;

Log.Logger = new LoggerConfiguration()
.WriteTo.Console(
outputTemplate: Logging.ErrorsAndWarningsOutputTemplate,
theme: (ConsoleTheme)Theme,
applyThemeToRedirectedOutput: true)
.CreateLogger();

replaced?.Dispose();

var nonEmptyLogEvents = Logging.InMemorySink.Instance.LogEvents.Where(x => !x.MessageTemplate.Text.IsNullOrEmpty());
nonEmptyLogEvents.ForEach(Log.Write);
}
Expand Down
21 changes: 18 additions & 3 deletions src/Fallout.Build/Logging.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Fallout.Build.Execution;
using Fallout.Common.CI;
using Fallout.Common.Execution.Theming;
using Fallout.Common.IO;
Expand Down Expand Up @@ -242,11 +243,21 @@ public static IDisposable SetTarget(string name)

public class InMemorySink : ILogEventSink, IDisposable
{
public static InMemorySink Instance { get; } = new();
// FT-6 (#311): the active sink is the per-run one on BuildContext, so one build's warnings and
// errors cannot resurface in the next build in the same process. The fallback covers logging
// outside a run — process-wide, but with no run for its events to bleed into.
private static readonly Lazy<InMemorySink> ambientInstance = new(() => new InMemorySink());

/// <summary>
/// The sink of the running build, or a shared fallback sink outside a run. The result changes
/// between runs, so do not cache it across a run boundary. A sink fetched before
/// <c>BuildManager.Execute</c> starts is the fallback, not the run's sink.
/// </summary>
public static InMemorySink Instance => BuildContext.Current?.LogSink ?? ambientInstance.Value;

private readonly List<LogEvent> logEvents;

private InMemorySink()
internal InMemorySink()
{
logEvents = new List<LogEvent>();
}
Expand All @@ -259,7 +270,11 @@ public void Emit(LogEvent logEvent)
logEvents.Add(logEvent);
}

/// <summary>Drops accumulated events so a subsequent build in the same process starts clean. FT-1 / #306.</summary>
/// <summary>
/// Drops accumulated events. Since FT-6 / #311 a run's sink is discarded with its
/// <see cref="BuildContext"/>, so this is no longer needed to keep runs from bleeding into each
/// other — it stays for explicit resets (and for <see cref="Dispose"/>).
/// </summary>
public void Clear()
{
logEvents.Clear();
Expand Down
65 changes: 49 additions & 16 deletions tests/Fallout.Build.Specs/BuildContextSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ namespace Fallout.Common.Specs.Execution;

/// <summary>
/// Covers <see cref="BuildContext"/> (FT-2 / #307) — the per-run ambient scope that owns the
/// process-global state a build touches. <see cref="BuildContext.Current"/> is <c>AsyncLocal</c>, so
/// each case resolves its own context, but the singletons the teardown resets (in-memory sink,
/// value-injection cache, resolver config) remain process-wide — assertions that touch them key on a
/// sentinel rather than on the singleton being empty.
/// process-global state a build touches, plus the services that have since moved onto it (the
/// parameter service, FT-4 / #309; the in-memory log sink, FT-6 / #311).
/// <see cref="BuildContext.Current"/> is <c>AsyncLocal</c>, so each case resolves its own context, but
/// the singletons the teardown still resets (value-injection cache, resolver config) remain
/// process-wide — assertions that touch those key on a sentinel rather than on the singleton being empty.
/// </summary>
[Collection(ProcessGlobalStateCollection.Name)]
public class BuildContextSpecs
Expand Down Expand Up @@ -104,6 +105,39 @@ public void Parameter_service_state_does_not_leak_into_the_next_run()
ParameterService.Instance.ArgumentsFromCommitMessageService.Should().BeNull();
}

[Fact]
public void Log_sink_facade_resolves_the_current_contexts_sink()
{
using var context = BuildContext.Activate();

// FT-6 (#311): same seam as the parameter service — the static sink is a pointer at the run.
Logging.InMemorySink.Instance.Should().BeSameAs(context.LogSink);
}

[Fact]
public void Log_sink_facade_falls_back_to_an_ambient_sink_outside_a_run()
{
BuildContext.Current.Should().BeNull();

// Logging outside a run (a CLI command, a spec) has to land somewhere rather than throw.
Logging.InMemorySink.Instance.Should().NotBeNull();
Logging.InMemorySink.Instance.Should().BeSameAs(Logging.InMemorySink.Instance);
}

[Fact]
public void Each_run_gets_its_own_log_sink()
{
Logging.InMemorySink first;
Logging.InMemorySink second;

using (var context = BuildContext.Activate())
first = context.LogSink;
using (var context = BuildContext.Activate())
second = context.LogSink;

second.Should().NotBeSameAs(first);
}

[Fact]
public void Disposing_a_superseded_context_leaves_the_newer_one_current()
{
Expand All @@ -119,20 +153,17 @@ public void Disposing_a_superseded_context_leaves_the_newer_one_current()
[Fact]
public void Disposing_a_superseded_context_leaves_the_shared_state_intact()
{
var sink = Logging.InMemorySink.Instance;
var sentinel = $"build-context-superseded-{Guid.NewGuid()}";

var first = BuildContext.Activate();
using var second = BuildContext.Activate();
NuGetToolPathResolver.EmbeddedPackagesDirectory = sentinel;
sink.Emit(CreateLogEvent(sentinel));

// `second` is the live run and this state belongs to it. The teardown resets are process-wide,
// `second` is the live run and this config belongs to it. The teardown resets are process-wide,
// so a superseded scope disposing out of order must skip them entirely — clearing Current is
// not the only thing the identity guard protects.
first.Dispose();

sink.LogEvents.Should().Contain(x => x.MessageTemplate.Text == sentinel);
NuGetToolPathResolver.EmbeddedPackagesDirectory.Should().Be(sentinel);
}

Expand Down Expand Up @@ -186,20 +217,22 @@ public void Cancellation_handler_facade_is_a_no_op_without_an_active_context()
}

[Fact]
public void Dispose_runs_the_per_run_teardown()
public void Log_events_do_not_carry_into_the_next_run()
{
var sink = Logging.InMemorySink.Instance;
var sentinel = $"build-context-teardown-{Guid.NewGuid()}";
var sentinel = $"build-context-log-{Guid.NewGuid()}";

using (BuildContext.Activate())
{
sink.Emit(CreateLogEvent(sentinel));
Logging.InMemorySink.Instance.Emit(CreateLogEvent(sentinel));
}

// Leaving the scope disposes the context, whose teardown clears the shared in-memory sink so a
// subsequent run in the same process starts clean. Assert on the sentinel specifically so a
// build emitting on another flow can't make this flaky.
sink.LogEvents.Should().NotContain(x => x.MessageTemplate.Text == sentinel);
// FT-6 (#311): the sink belonged to the run that just ended and went out of scope with it, so
// the next run starts on an empty one. Nothing clears a shared sink — there is no shared sink.
// Assert on the sentinel specifically so a build emitting on another flow can't make it flaky.
using (BuildContext.Activate())
{
Logging.InMemorySink.Instance.LogEvents.Should().NotContain(x => x.MessageTemplate.Text == sentinel);
}
}

private static LogEvent CreateLogEvent(string message) =>
Expand Down
Loading
Loading