-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03-code-sketch.html
More file actions
447 lines (399 loc) · 20 KB
/
Copy path03-code-sketch.html
File metadata and controls
447 lines (399 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>03 · Code Sketch — Multi-Tenant Platform</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Fraunces:opsz,wght@9..144,500;9..144,600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" />
<link rel="stylesheet" href="../assets/styles.css" />
</head>
<body>
<div class="layout">
<aside class="sidebar">
<a href="../index.html" class="brand">
<span class="brand-mark">MTP</span>
<span class="brand-text">Multi-Tenant Platform</span>
</a>
<nav>
<div class="nav-group">
<h4>Foundations</h4>
<ul>
<li><a href="../index.html"><span class="nav-num">00</span>Overview</a></li>
<li><a href="01-findings.html"><span class="nav-num">01</span>Findings</a></li>
<li><a href="02-architecture.html"><span class="nav-num">02</span>Architecture</a></li>
<li><a href="10-tenancy-model.html"><span class="nav-num">10</span>Tenancy Model</a></li>
</ul>
</div>
<div class="nav-group">
<h4>Validation</h4>
<ul>
<li><a href="03-code-sketch.html" class="active"><span class="nav-num">03</span>Code Sketch</a></li>
<li><a href="04-ui-rule-config.html"><span class="nav-num">04</span>UI Rule Config</a></li>
<li><a href="05-result-pattern.html"><span class="nav-num">05</span>Result Pattern</a></li>
<li><a href="06-reconciliation.html"><span class="nav-num">06</span>Reconciliation</a></li>
</ul>
</div>
<div class="nav-group">
<h4>Tenant Surface</h4>
<ul>
<li><a href="07-ui-schema.html"><span class="nav-num">07</span>UI Schema</a></li>
<li><a href="08-i18n-l10n.html"><span class="nav-num">08</span>i18n / l10n</a></li>
<li><a href="09-extension-fields.html"><span class="nav-num">09</span>Extension Fields</a></li>
</ul>
</div>
<div class="nav-group">
<h4>Frontend</h4>
<ul>
<li><a href="../mockups/classic.html"><span class="nav-num">UI1</span>AppShell — Classic</a></li>
<li><a href="../mockups/zoho.html"><span class="nav-num">UI2</span>AppShell — 2-Stage</a></li>
<li><a href="../mockups/exam-setup.html"><span class="nav-num">UI3</span>AppShell — Exam Setup</a></li>
<li><a href="../mockups/ux-showcase-1.html"><span class="nav-num">UI4</span>AppShell — UX Showcase</a></li>
<li><a href="../mockups/ux-showcase-2.html"><span class="nav-num">UI5</span>AppShell — UX Showcase 2</a></li>
<li><a href="../mockups/ux-showcase-3.html"><span class="nav-num">UI6</span>AppShell — UX Showcase 3</a></li>
<li><a href="../mockups/ux-showcase-4.html"><span class="nav-num">UI8</span>AppShell — UX Showcase 4</a></li>
<li><a href="../mockups/ux-catalog.html"><span class="nav-num">UI7</span>UX Pattern Catalog</a></li>
<li><a href="../mockups/notes.html"><span class="nav-num">UIN</span>AppShell Notes</a></li>
</ul>
</div>
<div class="nav-group">
<h4>Decisions</h4>
<ul>
<li><a href="../adr/0001-hybrid-validation-strategy.html"><span class="nav-num">ADR-1</span>Hybrid Validation</a></li>
<li><a href="../adr/0002-database-per-client.html"><span class="nav-num">ADR-2</span>DB-per-Client</a></li>
<li><a href="../adr/0003-frontend-stack.html"><span class="nav-num">ADR-3</span>Frontend Stack</a></li>
<li><a href="../adr/0004-authorization-permission-model.html"><span class="nav-num">ADR-4</span>Authz & Permissions</a></li>
<li><a href="../adr/0005-repo-topology.html"><span class="nav-num">ADR-5</span>Repo Topology</a></li>
<li><a href="../adr/0006-no-module-federation.html"><span class="nav-num">ADR-6</span>No Module Federation</a></li>
<li><a href="../adr/0007-ui-stack-radix-cssmodules.html"><span class="nav-num">ADR-7</span>UI Stack — Radix</a></li>
<li><a href="../adr/0008-mtp-web-folder-structure.html"><span class="nav-num">ADR-8</span>mtp-web Folder Structure</a></li>
<li><a href="../adr/0009-hr-payroll-three-aggregates.html"><span class="nav-num">ADR-9</span>HR-Payroll — 3 Aggregates, 1 Module</a></li>
</ul>
</div>
<div class="nav-group">
<h4>GNUMS — Conventions</h4>
<ul>
<li><a href="../gnums/module-catalog.html"><span class="nav-num">MOD</span>Module Catalog</a></li>
<li><a href="../gnums/all-modules-inventory.html"><span class="nav-num">REF</span>Procedure Inventory</a></li>
<li><a href="../gnums/org-hierarchy.html"><span class="nav-num">ORG</span>Org Hierarchy</a></li>
<li><a href="../gnums/hierarchy-comparison.html"><span class="nav-num">CMP</span>Hierarchy Comparison</a></li>
</ul>
</div>
<div class="nav-group">
<h4>GNUMS — Modules</h4>
<ul>
<li><a href="../gnums/methodology.html"><span class="nav-num">HOW</span>Study Methodology</a></li>
<li><a href="../gnums/accounting/scope.html"><span class="nav-num">ACC</span>Accounting — Scope</a></li>
<li><a href="../gnums/staff/scope.html"><span class="nav-num">STF</span>Staff — Scope</a></li>
<li><a href="../gnums/hr-payroll/scope.html"><span class="nav-num">HRP</span>HR-Payroll — Scope</a></li>
<li><a href="../gnums/exam/scope.html"><span class="nav-num">EXM</span>Exam — Scope</a></li>
<li><a href="../gnums/exam/strategy.html"><span class="nav-num">PLAY</span>Exam — Strategy</a></li>
<li><a href="../gnums/student/scope.html"><span class="nav-num">STU</span>Student — Scope</a></li>
<li><a href="../gnums/student/strategy.html"><span class="nav-num">SPL</span>Student — Strategy</a></li>
<li><a href="../gnums/student/cluster-01-core-identity.html"><span class="nav-num">SC1</span>Student / Core Identity</a></li>
<li><a href="../gnums/student/cluster-02-subordinate-entities.html"><span class="nav-num">SC2</span>Student / Subordinate Entities</a></li>
<li><a href="../gnums/student/cluster-03-master-config.html"><span class="nav-num">SC3</span>Student / Master & Config</a></li>
<li><a href="../gnums/student/cluster-04-certificate-workflow.html"><span class="nav-num">SC4</span>Student / Certificate Workflow</a></li>
<li><a href="../gnums/student/cluster-05-bvm-activities.html"><span class="nav-num">SC5</span>Student / NCC NSS Yoga</a></li>
<li><a href="../gnums/student/cluster-06-mentoring.html"><span class="nav-num">SC6</span>Student / Mentoring</a></li>
</ul>
</div>
</nav>
</aside>
<main>
<span class="eyebrow">03 · Code</span>
<h1>Code sketch: Strategy + FluentValidation + Rule Engine</h1>
<p class="lede">
A concrete sketch for a loan-application feature, in plain ASP.NET Core service-layer style.
Controllers call application services directly. FluentValidation runs at the model-binding
layer. No MediatR, no CQRS.
</p>
<h2>1. Request and result DTOs</h2>
<pre><code class="language-csharp">namespace App.Features.LoanApplication;
public sealed class SubmitLoanApplicationRequest
{
public Guid CustomerId { get; init; }
public decimal Amount { get; init; }
public int TermMonths { get; init; }
public string Purpose { get; init; } = "";
public Dictionary<string, object?> ExtendedFields { get; init; } = new();
// Codes of Confirmable issues the user has reviewed and accepted.
// Server still evaluates all rules; this only changes whether matching
// confirmable issues count as blocking.
public IReadOnlySet<string>? AcknowledgedIssueCodes { get; init; }
}
public sealed record SubmitLoanApplicationResponse(
Guid LoanApplicationId,
IReadOnlyList<ValidationIssue> Advisories);
</code></pre>
<h2>2. Shape validator — tenant-agnostic</h2>
<pre><code class="language-csharp">namespace App.Features.LoanApplication.Validation;
public sealed class SubmitLoanApplicationShapeValidator
: AbstractValidator<SubmitLoanApplicationRequest>
{
public SubmitLoanApplicationShapeValidator()
{
RuleFor(x => x.CustomerId).NotEmpty();
RuleFor(x => x.Amount).GreaterThan(0).LessThan(100_000_000);
RuleFor(x => x.TermMonths).InclusiveBetween(1, 600);
RuleFor(x => x.Purpose).NotEmpty().MaximumLength(500);
}
}
</code></pre>
<p>One validator. No tenant branching. Catches the 80% of malformed requests cheaply.</p>
<h2>3. Wire FluentValidation as ASP.NET Core auto-validation</h2>
<pre><code class="language-csharp">// Program.cs
builder.Services
.AddControllers()
.AddFluentValidation(); // legacy package, or use FluentValidation.AspNetCore.AddFluentValidationAutoValidation()
builder.Services
.AddValidatorsFromAssemblyContaining<SubmitLoanApplicationShapeValidator>();
builder.Services
.AddFluentValidationAutoValidation()
.AddFluentValidationClientsideAdapters();
</code></pre>
<p>
When model binding completes, FluentValidation runs automatically. Failures populate
<code>ModelState</code>; ASP.NET Core's automatic 400 response shapes them as
<code>ProblemDetails</code>. No code in the controller.
</p>
<h2>4. Feature flow strategy contract</h2>
<pre><code class="language-csharp">namespace App.Features.LoanApplication.Flows;
public interface IFeatureFlow<TInput, TResult>
{
string FeatureKey { get; }
Task<Result<TResult>> ExecuteAsync(TInput input, CancellationToken ct);
}
public interface ILoanApplicationFlow
: IFeatureFlow<SubmitLoanApplicationRequest, Guid> { }
public enum IssueKind
{
Advisory, // surface, never blocks
Confirmable, // blocks until user acknowledges
Blocking // hard fail, no override
}
public sealed record ValidationIssue(
IssueKind Kind,
string Code,
string Message,
string? Field = null,
string? Source = null);
public sealed class Result<T>
{
public bool IsSuccess { get; init; }
public T? Value { get; init; }
public IReadOnlyList<ValidationIssue> Issues { get; init; } = Array.Empty<ValidationIssue>();
public bool HasBlocking => Issues.Any(i => i.Kind == IssueKind.Blocking);
public bool RequiresAck => Issues.Any(i => i.Kind == IssueKind.Confirmable);
public static Result<T> Ok(T value, params ValidationIssue[] advisories) =>
new() { IsSuccess = true, Value = value, Issues = advisories };
public static Result<T> Fail(params ValidationIssue[] issues) =>
new() { IsSuccess = false, Issues = issues };
}
</code></pre>
<h2>5. Flow resolver</h2>
<pre><code class="language-csharp">public interface IFeatureFlowResolver
{
TFlow Resolve<TFlow>(string featureKey) where TFlow : class;
}
public sealed class FeatureFlowResolver(
IFlowBindingCache bindings,
IServiceProvider sp) : IFeatureFlowResolver
{
public TFlow Resolve<TFlow>(string featureKey) where TFlow : class
{
// Binding cache reads from the current client's DbContext.
// Client identity is implicit via the per-request connection (see page 10).
var binding = bindings.Get(featureKey)
?? bindings.GetDefault(featureKey)
?? throw new InvalidOperationException(
$"No flow bound for feature '{featureKey}'");
return sp.GetKeyedService<TFlow>(binding.StrategyKey)
?? throw new InvalidOperationException(
$"Flow strategy '{binding.StrategyKey}' not registered");
}
}
</code></pre>
<h2>6. Concrete strategies</h2>
<pre><code class="language-csharp">public sealed class DefaultLoanApplicationFlow(
ILoanRepository repo,
IRuleEvaluator rules,
IFlowBindingCache bindings) : ILoanApplicationFlow
{
public string FeatureKey => "loan-application";
public async Task<Result<Guid>> ExecuteAsync(
SubmitLoanApplicationRequest input, CancellationToken ct)
{
var binding = bindings.Get(FeatureKey)!;
var issues = (await rules.EvaluateAsync(
binding.FlowVersionId, "Submit", input, ct)).Issues;
var ack = input.AcknowledgedIssueCodes ?? new HashSet<string>();
var blocking = issues.Where(i => i.Kind == IssueKind.Blocking).ToList();
var unack = issues.Where(i => i.Kind == IssueKind.Confirmable
&& !ack.Contains(i.Code)).ToList();
if (blocking.Count > 0 || unack.Count > 0)
return Result<Guid>.Fail([..blocking, ..unack]);
var advisories = issues.Where(i => i.Kind == IssueKind.Advisory).ToArray();
var application = LoanApplication.Create(
input.CustomerId, input.Amount, input.TermMonths,
input.Purpose, input.ExtendedFields);
await repo.AddAsync(application, ct);
return Result<Guid>.Ok(application.Id, advisories);
}
}
public sealed class ClientA_LoanApplicationFlow(
ILoanRepository repo,
ICreditBureauClient bureau,
IRuleEvaluator rules,
IFlowBindingCache bindings) : ILoanApplicationFlow
{
public string FeatureKey => "loan-application";
public async Task<Result<Guid>> ExecuteAsync(
SubmitLoanApplicationRequest input, CancellationToken ct)
{
var binding = bindings.Get(FeatureKey)!;
var issues = (await rules.EvaluateAsync(
binding.FlowVersionId, "Submit", input, ct)).Issues.ToList();
var score = await bureau.GetScoreAsync(input.CustomerId, ct);
if (score < 650)
issues.Add(new ValidationIssue(
IssueKind.Blocking,
"ClientA.CreditScore",
"Score below client minimum",
Field: "CreditScore"));
var ack = input.AcknowledgedIssueCodes ?? new HashSet<string>();
var blocking = issues.Where(i => i.Kind == IssueKind.Blocking).ToList();
var unack = issues.Where(i => i.Kind == IssueKind.Confirmable
&& !ack.Contains(i.Code)).ToList();
if (blocking.Count > 0 || unack.Count > 0)
return Result<Guid>.Fail([..blocking, ..unack]);
var advisories = issues.Where(i => i.Kind == IssueKind.Advisory).ToArray();
var application = LoanApplication.Create(
input.CustomerId, input.Amount, input.TermMonths,
input.Purpose, input.ExtendedFields);
application.RequireDualApproval();
await repo.AddAsync(application, ct);
return Result<Guid>.Ok(application.Id, advisories);
}
}
</code></pre>
<h2>7. DI registration</h2>
<pre><code class="language-csharp">public static class FeatureFlowRegistration
{
public static IServiceCollection AddFeatureFlows(this IServiceCollection s)
{
s.AddKeyedScoped<ILoanApplicationFlow, DefaultLoanApplicationFlow>("default");
s.AddKeyedScoped<ILoanApplicationFlow, ClientA_LoanApplicationFlow>("client-a-v2");
s.AddScoped<IFeatureFlowResolver, FeatureFlowResolver>();
s.AddSingleton<IFlowBindingCache, FlowBindingCache>();
s.AddScoped<IRuleEvaluator, JsonRuleEvaluator>();
return s;
}
}
</code></pre>
<p>
<code>StrategyKey</code> in the <code>FEATURE_FLOW_VERSION</code> table matches the DI key
(<code>"default"</code>, <code>"tenant-a-v2"</code>). Add a strategy = add a class + register
a key + insert a row.
</p>
<h2>8. Application service</h2>
<pre><code class="language-csharp">public interface ILoanApplicationService
{
Task<Result<Guid>> SubmitAsync(
SubmitLoanApplicationRequest request, CancellationToken ct);
}
public sealed class LoanApplicationService(IFeatureFlowResolver resolver)
: ILoanApplicationService
{
public Task<Result<Guid>> SubmitAsync(
SubmitLoanApplicationRequest request, CancellationToken ct)
{
var flow = resolver.Resolve<ILoanApplicationFlow>("loan-application");
return flow.ExecuteAsync(request, ct);
}
}
</code></pre>
<h2>9. Controller</h2>
<pre><code class="language-csharp">[ApiController]
[Route("api/loan-applications")]
public sealed class LoanApplicationsController(ILoanApplicationService service)
: ControllerBase
{
[HttpPost]
public async Task<IActionResult> Submit(
SubmitLoanApplicationRequest request, CancellationToken ct)
{
// FluentValidation already ran in the model-binding pipeline.
var result = await service.SubmitAsync(request, ct);
if (!result.IsSuccess)
{
// Confirmable-only failures = 409 so the client can show an ack modal.
if (!result.HasBlocking && result.RequiresAck)
return Conflict(new { requiresAcknowledgement = true, issues = Format(result.Issues) });
return UnprocessableEntity(new { issues = Format(result.Issues) });
}
return CreatedAtAction(nameof(GetById),
new { id = result.Value },
new SubmitLoanApplicationResponse(result.Value, result.Issues));
}
private static IEnumerable<object> Format(IReadOnlyList<ValidationIssue> issues) =>
issues.Select(i => new
{
kind = i.Kind.ToString(),
code = i.Code,
message = i.Message,
field = i.Field
});
[HttpGet("{id:guid}")]
public IActionResult GetById(Guid id) => Ok(new { id });
}
</code></pre>
<h2>10. Rule engine surface</h2>
<pre><code class="language-csharp">public interface IRuleEvaluator
{
Task<RuleEvaluationResult> EvaluateAsync<T>(
Guid flowVersionId,
string ruleSetName,
T target,
CancellationToken ct);
}
public sealed class RuleEvaluationResult
{
public IReadOnlyList<ValidationIssue> Issues { get; init; } = Array.Empty<ValidationIssue>();
}
</code></pre>
<p>
Implementation uses persisted rule rows plus a small expression interpreter. Details in the
<a href="04-ui-rule-config.html">next section</a>.
</p>
<h2>11. Test strategy</h2>
<table>
<thead><tr><th>Layer</th><th>Test type</th><th>Tool</th></tr></thead>
<tbody>
<tr><td>Shape validators</td><td>Unit</td><td><code>validator.TestValidate(request)</code></td></tr>
<tr><td>Strategy classes</td><td>Unit, mock repos/clients</td><td>xUnit + NSubstitute</td></tr>
<tr><td>Rule evaluator</td><td>Unit, fixture-driven JSON rules</td><td>xUnit</td></tr>
<tr><td>Resolver</td><td>Unit, in-memory binding cache</td><td>xUnit</td></tr>
<tr><td>End-to-end per tenant</td><td>Integration</td><td><code>WebApplicationFactory</code> + Testcontainers</td></tr>
</tbody>
</table>
<div class="doc-footer">
<a href="02-architecture.html">
<span class="label">← Previous</span>
<span class="title">02 · Architecture</span>
</a>
<a href="04-ui-rule-config.html" class="next">
<span class="label">Next</span>
<span class="title">04 · UI Rule Config →</span>
</a>
</div>
</main>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
<script>mermaid.initialize({ startOnLoad: true, theme: 'default' });</script>
</body>
</html>