Skip to content

Commit f43c80d

Browse files
committed
feat(WP-1.2): SF0005, SF0014, SF0010 code fix and text correlation
- SF0005 (warning): an event created in an aggregate's Decide that no When of the aggregate accepts. - SF0014 (error): routing.Command<T>().To(...) for a command owned in the compilation (the target aggregate's Decide, also from a referenced module, or an ICommandHandler in source). - SF0010 code fix adds [JsonSerializable(typeof(T))] to the module's JSON context (RS1038 suppressed: code fixes are IDE-only, ADR-027). - Process managers: CorrelateBy may return a string, parsed into the id with TryParse (GEN-13). - Tests GEN-13, 28, 35, 36; guide docs/v3.0.0/guides/reading-generated-code.md.
1 parent bfa4398 commit f43c80d

19 files changed

Lines changed: 510 additions & 7 deletions

‎Directory.Packages.props‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
</ItemGroup>
1818
<ItemGroup Label="Generator (Roslyn 4.14 loads in every .NET 10 SDK compiler)">
1919
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" />
20+
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.14.0" />
2021
<PackageVersion Include="Microsoft.CodeAnalysis.Analyzers" Version="3.11.0" />
2122
</ItemGroup>
2223
<ItemGroup Label="Testing toolkit and tests">
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# Reading generated code
2+
3+
SourceFlow.Net v3 finds and wires domain types at **compile time**. The `SourceFlow.Generators` source generator ships inside the `SourceFlow.Net` package (ADR-004). It writes ordinary C# that you can read, step through in the debugger and review in pull requests. Nothing in command dispatch, event application or registration uses reflection (GAP-16).
4+
5+
This page shows where the generated files are and what each one contains.
6+
7+
## Where to find the files
8+
9+
Every project in this repository sets `EmitCompilerGeneratedFiles=true` (root `Directory.Build.props`), so generated files land on disk:
10+
11+
```text
12+
obj/<Configuration>/net10.0/generated/
13+
SourceFlow.Generators/SourceFlow.Generators.SourceFlowGenerator/ ← SourceFlow output
14+
System.Text.Json.SourceGeneration/…/ ← your module's JsonSerializerContext
15+
```
16+
17+
In your own application, set the same property in the project file:
18+
19+
```xml
20+
<PropertyGroup>
21+
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
22+
</PropertyGroup>
23+
```
24+
25+
In Visual Studio and Rider, the files also appear under **Dependencies → Analyzers → SourceFlow.Generators**. *Go to definition* on a generated member opens them too.
26+
27+
Each file is named `<Namespace>.<Type>.<Kind>.g.cs`, for example `Bank.Accounts.BankAccount.Aggregate.g.cs`. Each one starts with `// <auto-generated/>`. Don't edit them: they're rebuilt on every compilation.
28+
29+
## What is generated
30+
31+
| You write | Kind | Generated |
32+
|-----------|------|-----------|
33+
| `[StronglyTypedId] partial record struct AccountId(Guid Value)` | `Id` | `New()` (UUIDv7), `Parse`/`TryParse`, `ToString` (`"D"`), `ToStreamSegment()` (`"N"`), formatting, a JSON converter |
34+
| `[Aggregate("bank-account")] partial record BankAccount : IAggregate<…>` | `Aggregate` | `IAggregateRuntime`: `AggregateName`, `DecidedCommands`, `TargetingCommands`, a `Decide` switch over command types, `TargetOf` (the `[AggregateId]` member), and an `Evolve` switch over the `When` methods |
35+
| `[Projection("account-summary")] partial class … : IDocumentProjection<TDoc, TKey>` | `Projection` | `HandledEvents`, `TryGetKey`, `FormatKey`, and an `Apply` switch over the `When` methods |
36+
| `[ProcessManager("money-transfer")] partial record … : IProcessManager<…>` | `ProcessManager` | `HandledMessages`, a `TryCorrelate` switch over `CorrelateBy`, and a `React` switch |
37+
| `[SourceFlowModule(typeof(MyJsonContext))] partial class MyModule` | `Module` | `Register`: every message type (sorted by name, with its kind), aggregate, projection, process manager and handler in the assembly, plus your JSON context |
38+
39+
### Example: an aggregate
40+
41+
From the Bank sample (`samples/Bank/Bank.Accounts/BankAccount.cs`):
42+
43+
```csharp
44+
static Decision IAggregateRuntime<BankAccount, AccountId>.Decide(BankAccount state, ICommand command, in DecisionContext context)
45+
{
46+
return command switch
47+
{
48+
CloseAccount c => state.Decide(c, context),
49+
Deposit c => state.Decide(c, context),
50+
OpenAccount c => state.Decide(c, context),
51+
Withdraw c => state.Decide(c, context),
52+
_ => throw new UnhandledMessageException(command.GetType()),
53+
};
54+
}
55+
56+
public BankAccount Evolve(IEvent @event)
57+
{
58+
return @event switch
59+
{
60+
AccountClosed e => When(e),
61+
AccountOpened e => When(e),
62+
MoneyDeposited e => When(e),
63+
MoneyWithdrawn e => When(e),
64+
_ => this, // tolerant evolve: unknown events leave the state unchanged
65+
};
66+
}
67+
```
68+
69+
A few things to notice:
70+
71+
- **Dispatch is a `switch`, not reflection.** A command without a `Decide` isn't in the switch. Analyzer SF0006 warns about it at build time, and startup rejects it.
72+
- **`Evolve` ignores events it doesn't know.** Analyzer SF0005 warns when your `Decide` produces an event that has no `When`, because that event would never change the state.
73+
- **Lists are sorted.** Sorting makes the output deterministic, so review diffs stay small.
74+
75+
### Example: process manager correlation
76+
77+
`CorrelateBy` can return the id type itself, or a `string` that is parsed into the id. If the string doesn't parse, the message isn't correlated:
78+
79+
```csharp
80+
case global::Bank.Transfers.TransferRequested m: id = CorrelateBy(m); return true;
81+
case global::Text.CaseOpened m: return global::Text.CaseId.TryParse(CorrelateBy(m), out id);
82+
```
83+
84+
## Analyzers that guard the generated code
85+
86+
Some diagnostics come from the same package (doc 03 §9):
87+
88+
| Id | Severity | Meaning |
89+
|----|----------|---------|
90+
| SF0001 / SF0002 | Error | A message has no `[MessageType]`, or a name and version are declared twice |
91+
| SF0003 | Error | The command's target id member is missing or ambiguous (use `[AggregateId]`) |
92+
| SF0004 / SF0007 / SF0009 | Error / Error / Warning | Purity: `When` with side effects, an async `Decide`, or a non-deterministic API in a pure method |
93+
| SF0005 | Warning | `Decide` produces an event that has no `When` |
94+
| SF0006 | Warning | A command has no `Decide` or handler |
95+
| SF0008 | Error | An aggregate or process manager has the wrong shape (it must be a `sealed partial record` with `init` properties) |
96+
| SF0010 | Error | A message or state type is missing from the module's `JsonSerializerContext`. **Code fix:** *Add `[JsonSerializable(typeof(T))]`* |
97+
| SF0014 | Error | A command is handled locally and also routed with `routing.Command<T>().To(…)` (ADR-007) |
98+
99+
## Reviewing changes
100+
101+
Generated output is reproducible: the same sources always produce the same files. In this repository, the Bank sample's output is also kept as an approved snapshot (GEN-39). To see what a domain change does to the generated code, build and diff the `obj/…/generated` folder, or let the snapshot test show the change.
102+
103+
The generator is incremental. An edit that doesn't touch a SourceFlow type (`[Aggregate]`, `[Projection]`, `[ProcessManager]`, `[MessageType]`, `[StronglyTypedId]` or a module) produces no new generator work (GEN-38).

‎docs/v3.0.0/implementation/STATUS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Updated in the PR that completes a work package (CONTRIBUTING.md). Status values
1010
| WP-0.4 | Quality harness | 1 | done | |
1111
| WP-0.5 | Design baseline | 0.5 | done | |
1212
| WP-1.1 | Core contracts and SPIs (`SourceFlow.Net`) | 1.5 | done | Contracts in namespace SourceFlow; UT-ABS-01..18 |
13-
| WP-1.2 | `SourceFlow.Generators` (generators + analyzers) | 4 | in progress | Generator (ids, aggregates, PMs, projections, module) + SF0001-0004, SF0006-0010 done; SF0005 (event without When) and SF0014 (constant-route analysis) pending |
13+
| WP-1.2 | `SourceFlow.Generators` (generators + analyzers) | 4 | done | Generator (ids, aggregates, PMs incl. text `CorrelateBy`, projections, session projections, module); analyzers SF0001–SF0010 and SF0014 (routing `Command<T>().To(…)` for a locally owned command), SF0010 code fix (adds `[JsonSerializable]`); GEN-01..42 (GEN-13, 28, 35, 36 added). Guide: `docs/v3.0.0/guides/reading-generated-code.md`. SF0015/16/18 come with WP-1.13 |
1414
| WP-1.3 | Messaging core | 2 | done | Envelope, CloudEvents, UUIDv5/v7, registry, serializer, upcasters; UT-MSG-01..28 |
1515
| WP-1.4 | Storage SPI + in-memory store | 2.5 | done | Storage SPI, InMemoryStore, SCK (49 cases) green |
1616
| WP-1.5 | Runtime model and routing | 1.5 | done | RoutingBuilder/RoutingTable (RT-R1, RT-R5), options + validators; UT-RT |
@@ -22,7 +22,7 @@ Updated in the PR that completes a work package (CONTRIBUTING.md). Status values
2222
| WP-1.11 | `SourceFlow.Testing` | 2.5 | done | SourceFlowTestHost, AggregateSpec, ProcessManagerSpec, ProjectionSpec, approvals; UT-TST |
2323
| WP-1.12 | Schema catalog | 2 | todo | |
2424
| WP-1.13 | SFQL front end (pipeline + SQL syntax) + in-memory interpreter + domain queries | 5.5 | in progress | Done: request guard, lexer, both parsers into one AST (UT-QL-01..13, 61..65, 69..77); catalog from the runtime model (Q-B1), binder with per-version renames, typing, output naming, G-6 tie-break, G-10/G-11/G-12 (SFQ0201–0206; UT-QL-21..33, 79, 88); policy: permissions, PII keys, cost guard, join and offset rules, limits (SFQ0301, 0401, 0402, 0405, 0406, 0409, 0501; UT-QL-34..39, 80, 89); in-memory interpreter (SQL three-valued logic, hash joins, grouping, subqueries, aggregate as-of folds, schema rows) and `IQueryService` (typed parameters SFQ0202/0203, PII redaction, tenancy, keyset continuation tokens SFQ0601, `at_least` consistency waits SFQ0602, plan cache, `IQueryEngine` SPI for provider compilers; UT-QL-41..60). PostgreSQL compiler: WP-2.8. Next: the typed builder and `[DomainQuery]` |
25-
| WP-1.14 | Bank sample (ported v2 E2E domain) | 1.5 | in progress | Bank.Contracts/Accounts/Transfers/Notifications + E2E-01..07, 11, 13, 14, 17..20 green; Bank.Api waits for WP-4.2 |
25+
| WP-1.14 | Bank sample (ported v2 E2E domain) | 1.5 | done | Bank.Contracts/Accounts/Transfers/Notifications + E2E-01..07, 11, 13, 14, 17..20 green; Bank.Api host (commands, demo query endpoints), Studio demo console, docker-compose demo and ghcr.io images (`v3-images` workflow) |
2626
| WP-1.R | Retire v2 core | 0.5 | todo | |
2727
| WP-2.1 | PostgreSQL schema and migrator | 1.5 | done | V001 schema (ADR-028: json payload columns, tenant columns), PostgreSqlSchemaMigrator (advisory lock, checksummed schema_history, db script), UsePostgreSql with AutoMigrate (Development only by default); SCK-M01..M06. V002 (RLS) and V003 (partitioned events) come with WP-2.6 and WP-4.5 |
2828
| WP-2.2 | PostgreSQL append and stream read | 2 | done | Write-behind session (one NpgsqlBatch, append first; ES-R1/ES-R2), CTE append for all ExpectedVersion kinds, conflict and closed-stream diagnosis, single-statement stream read; SCK-01..19 green. Commit is batch + COMMIT (two round trips; folding COMMIT in is WP-2.10) |

‎src/Core/SourceFlow.Generators/AnalyzerReleases.Unshipped.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ SF0001 | SourceFlow.Messages | Error | Message type has no [MessageType]
66
SF0002 | SourceFlow.Messages | Error | Duplicate message type name and version
77
SF0003 | SourceFlow.Commands | Error | Command target id is missing or ambiguous
88
SF0004 | SourceFlow.Purity | Error | When method has side effects
9+
SF0005 | SourceFlow.Shape | Warning | Event produced by Decide has no When
910
SF0006 | SourceFlow.Commands | Warning | Command has no Decide or handler
1011
SF0007 | SourceFlow.Purity | Error | Decide must be synchronous
1112
SF0008 | SourceFlow.Shape | Error | Aggregate or process manager shape
1213
SF0009 | SourceFlow.Purity | Warning | Non-deterministic API in a pure method
1314
SF0010 | SourceFlow.Serialization | Error | Type missing from the module's JSON context
15+
SF0014 | SourceFlow.Commands | Error | Command is both owned and routed

‎src/Core/SourceFlow.Generators/CompilationInventory.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System.Collections.Concurrent;
22
using System.Collections.Generic;
3+
using System.Collections.Immutable;
34
using System.Linq;
45
using Microsoft.CodeAnalysis;
56
using Microsoft.CodeAnalysis.Diagnostics;
@@ -121,7 +122,11 @@ private void ReportJsonContexts(CompilationAnalysisContext context)
121122
{
122123
if (!listed.Contains(required) && required.Locations.Any(l => l.IsInSource))
123124
{
124-
context.ReportDiagnostic(Diagnostic.Create(Diagnostics.MissingJsonType, required.Locations.First(l => l.IsInSource), required.Name, jsonContext.Name));
125+
// The code fix reads the context and the type from the properties.
126+
var properties = ImmutableDictionary<string, string?>.Empty
127+
.Add(JsonContextCodeFix.ContextKey, SymbolExtensions.MetadataName(jsonContext))
128+
.Add(JsonContextCodeFix.TypeKey, required.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
129+
context.ReportDiagnostic(Diagnostic.Create(Diagnostics.MissingJsonType, required.Locations.First(l => l.IsInSource), properties, required.Name, jsonContext.Name));
125130
}
126131
}
127132
}

‎src/Core/SourceFlow.Generators/Diagnostics.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,16 @@ internal static class Diagnostics
2727
"'When' in '{0}' must be pure: {1}",
2828
"SourceFlow.Purity", DiagnosticSeverity.Error, isEnabledByDefault: true, helpLinkUri: HelpBase);
2929

30+
public static readonly DiagnosticDescriptor EventWithoutWhen = new(
31+
"SF0005", "Event produced by Decide has no When",
32+
"'{0}' produces '{1}' in Decide but has no 'When({1})'; the state ignores it",
33+
"SourceFlow.Shape", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: HelpBase);
34+
35+
public static readonly DiagnosticDescriptor OwnedAndRouted = new(
36+
"SF0014", "Command is both owned and routed",
37+
"Command '{0}' is handled in this service by '{1}' and also routed to an endpoint; a command is owned or routed, never both (ADR-007)",
38+
"SourceFlow.Commands", DiagnosticSeverity.Error, isEnabledByDefault: true, helpLinkUri: HelpBase);
39+
3040
public static readonly DiagnosticDescriptor NoOwner = new(
3141
"SF0006", "Command has no Decide or handler",
3242
"Command '{0}' targets '{1}' but has no Decide method and no ICommandHandler in this compilation; add one or route it (startup fails otherwise)",

‎src/Core/SourceFlow.Generators/Emitters.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,11 @@ public static string ProcessManager(ProcessManagerModel model)
176176
w.Line($"case {m} m: id = CorrelateBy(m); return true;");
177177
}
178178

179+
foreach (string m in model.TextCorrelatedMessages)
180+
{
181+
w.Line($"case {m} m: return {model.IdType}.TryParse(CorrelateBy(m), out id);");
182+
}
183+
179184
w.Line("default: id = default; return false;");
180185
w.Close();
181186
w.Close();

‎src/Core/SourceFlow.Generators/Infrastructure.cs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,27 @@ public static bool Implements(this ITypeSymbol symbol, string metadataName)
168168
return symbol.FindInterface(metadataName) is not null || MetadataName(symbol) == metadataName;
169169
}
170170

171+
public static bool InheritsOrIs(this ITypeSymbol type, ITypeSymbol target)
172+
{
173+
for (ITypeSymbol? current = type; current is not null; current = current.BaseType)
174+
{
175+
if (SymbolEqualityComparer.Default.Equals(current, target))
176+
{
177+
return true;
178+
}
179+
}
180+
181+
foreach (INamedTypeSymbol contract in type.AllInterfaces)
182+
{
183+
if (SymbolEqualityComparer.Default.Equals(contract, target))
184+
{
185+
return true;
186+
}
187+
}
188+
189+
return false;
190+
}
191+
171192
public static AttributeData? FindAttribute(this ISymbol symbol, string metadataName)
172193
{
173194
foreach (AttributeData attribute in symbol.GetAttributes())
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
using System.Collections.Immutable;
2+
using System.Linq;
3+
using System.Threading;
4+
using System.Threading.Tasks;
5+
using Microsoft.CodeAnalysis;
6+
using Microsoft.CodeAnalysis.CodeActions;
7+
using Microsoft.CodeAnalysis.CodeFixes;
8+
using Microsoft.CodeAnalysis.CSharp;
9+
using Microsoft.CodeAnalysis.CSharp.Syntax;
10+
11+
namespace SourceFlow.Generators
12+
{
13+
/// <summary>SF0010 code fix: adds <c>[JsonSerializable(typeof(T))]</c> to the module's JSON context (DC-1, GEN-35).</summary>
14+
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(JsonContextCodeFix))]
15+
public sealed class JsonContextCodeFix : CodeFixProvider
16+
{
17+
internal const string ContextKey = "context";
18+
internal const string TypeKey = "type";
19+
20+
/// <inheritdoc />
21+
public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(Diagnostics.MissingJsonType.Id);
22+
23+
/// <inheritdoc />
24+
public override FixAllProvider GetFixAllProvider()
25+
{
26+
return WellKnownFixAllProviders.BatchFixer;
27+
}
28+
29+
/// <inheritdoc />
30+
public override Task RegisterCodeFixesAsync(CodeFixContext context)
31+
{
32+
foreach (Diagnostic diagnostic in context.Diagnostics)
33+
{
34+
if (!diagnostic.Properties.TryGetValue(ContextKey, out string? contextName) || contextName is null
35+
|| !diagnostic.Properties.TryGetValue(TypeKey, out string? typeName) || typeName is null)
36+
{
37+
continue;
38+
}
39+
40+
string title = $"Add [JsonSerializable(typeof({typeName.Replace("global::", string.Empty)}))] to {contextName.Split('.').Last()}";
41+
context.RegisterCodeFix(
42+
CodeAction.Create(title, ct => AddAsync(context.Document.Project, contextName, typeName, ct), equivalenceKey: "SF0010:" + typeName),
43+
diagnostic);
44+
}
45+
46+
return Task.CompletedTask;
47+
}
48+
49+
private static async Task<Solution> AddAsync(Project project, string contextName, string typeName, CancellationToken cancellationToken)
50+
{
51+
Solution solution = project.Solution;
52+
Compilation? compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
53+
INamedTypeSymbol? jsonContext = compilation?.GetTypeByMetadataName(contextName);
54+
SyntaxReference? reference = jsonContext?.DeclaringSyntaxReferences.FirstOrDefault();
55+
if (reference is null || solution.GetDocument(reference.SyntaxTree) is not { } document)
56+
{
57+
return solution;
58+
}
59+
60+
SyntaxNode node = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
61+
if (node is not TypeDeclarationSyntax declaration)
62+
{
63+
return solution;
64+
}
65+
66+
AttributeListSyntax attribute = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(
67+
SyntaxFactory.Attribute(
68+
SyntaxFactory.ParseName("System.Text.Json.Serialization.JsonSerializable"),
69+
SyntaxFactory.AttributeArgumentList(SyntaxFactory.SingletonSeparatedList(
70+
SyntaxFactory.AttributeArgument(SyntaxFactory.TypeOfExpression(SyntaxFactory.ParseTypeName(typeName))))))))
71+
.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed);
72+
73+
SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false) ?? node.SyntaxTree.GetRoot(cancellationToken);
74+
TypeDeclarationSyntax updated = declaration.WithAttributeLists(declaration.AttributeLists.Add(attribute));
75+
return solution.WithDocumentSyntaxRoot(document.Id, root.ReplaceNode(declaration, updated));
76+
}
77+
}
78+
}

0 commit comments

Comments
 (0)