-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeDump.cs
More file actions
16168 lines (13093 loc) · 581 KB
/
CodeDump.cs
File metadata and controls
16168 lines (13093 loc) · 581 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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\build\Build.cs
// ----------------------------------------
using System;
using System.IO;
using System.Linq;
using Nuke.Common;
// using Nuke.Common.CI;
// using Nuke.Common.Execution;
using Nuke.Common.IO;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tools.Coverlet;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.SonarScanner;
using Nuke.Common.Tools.Docker;
using Nuke.Common.Utilities.Collections;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.Docker.DockerTasks;
// ReSharper disable All
#pragma warning disable CS0618 // Type or member is obsolete
// dotnet tool install Nuke.GlobalTool --global
class Build : NukeBuild
{
public static int Main() => Execute<Build>(x => x.All);
[Parameter("Configuration to build - Default is 'Debug' (local) or 'Release' (server)")]
readonly Configuration Configuration = IsLocalBuild ? Configuration.Debug : Configuration.Release;
[Parameter("Solution file to build")]
readonly string SolutionFile;
[Solution] Solution Solution;
[Parameter("SonarQube server URL")]
readonly string SonarServerUrl = "http://localhost:9000";
[Parameter("SonarQube Docker image")]
readonly string SonarQubeDockerImage = "sonarqube:latest";
[Parameter("SonarQube Docker container name")]
readonly string SonarQubeContainerName = "sonarqube_container_bookfiesta";
[Parameter("Host path for SonarQube data")]
readonly AbsolutePath SonarQubeHostPath = RootDirectory / "tools" / "sonarqube" / "data";
[Parameter("Source directory containing .cs and .md files")]
readonly AbsolutePath SourceDirectory = RootDirectory / "src";
[Parameter("Output file path for concatenated files")]
readonly AbsolutePath CodeDumpOutputFile = RootDirectory / "CodeDump.cs";
// Default local admin credentials
readonly string SonarLogin = "admin";
readonly string SonarPassword = "admin";
// Use the solution name for both the SonarQube Project Name and Key
string SonarProjectName => Solution.Name;
string SonarProjectKey => Solution.Name.Replace(" ", "_").ToLower();
protected override void OnBuildInitialized()
{
if (string.IsNullOrEmpty(SolutionFile))
{
Console.WriteLine("Using default solution file.");
}
else
{
Console.WriteLine($"Using specified solution file: {SolutionFile}");
Solution = ProjectModelTasks.ParseSolution(SolutionFile);
}
}
Target Clean => _ => _
.Before(Restore)
.Executes(() =>
{
SourceDirectory.GlobDirectories("**/bin", "**/obj").ForEach(DeleteDirectory);
// EnsureCleanDirectory(OutputDirectory);
});
Target Restore => _ => _
.Executes(() =>
{
DotNetRestore(s => s
.SetProjectFile(Solution));
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() =>
{
DotNetBuild(s => s
.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.EnableNoRestore());
});
Target EnsureSonarQubeContainer => _ => _
.Executes(() =>
{
var isRunning = DockerPs(settings => settings
.SetQuiet(true)
.SetFilter($"name={SonarQubeContainerName}"))
.Any();
if (!isRunning)
{
SonarQubeHostPath.CreateDirectory();
DockerRun(settings => settings
.SetImage(SonarQubeDockerImage)
.SetName(SonarQubeContainerName)
.SetPublish("9000:9000"));
//.SetVolume($"{SonarQubeHostPath}:/opt/sonarqube/data")
//.SetDetach(true)
//.SetNetwork("host"));
System.Threading.Thread.Sleep(30000);
}
else
{
Console.WriteLine("SonarQube container is already running.");
}
});
Target SonarBegin => _ => _
.DependsOn(EnsureSonarQubeContainer)
.Before(Compile)
.Executes(() =>
{
SonarScannerTasks.SonarScannerBegin(s => s
.SetProjectKey(SonarProjectKey)
.SetName(SonarProjectName)
.SetServer(SonarServerUrl)
.SetLogin(SonarLogin)
.SetPassword(SonarPassword)
.SetFramework("net5.0"));
});
Target SonarEnd => _ => _
.After(Test)
.Executes(() =>
{
SonarScannerTasks.SonarScannerEnd(s => s
.SetLogin(SonarLogin)
.SetPassword(SonarPassword));
});
Target SonarAnalysis => _ => _
.DependsOn(SonarBegin, Test, SonarEnd)
.Executes(() =>
{
Console.WriteLine($"SonarQube analysis complete for project '{SonarProjectName}'.");
Console.WriteLine($"Project Key: {SonarProjectKey}");
Console.WriteLine($"Solution analyzed: {Solution.Path}");
Console.WriteLine($"You can view the results at {SonarServerUrl}");
Console.WriteLine("Default login credentials are admin/admin. Please change them after first login.");
});
Target Test => _ => _
.DependsOn(Compile)
.Executes(() =>
{
DotNetTest(s => s
.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.EnableNoRestore()
.EnableNoBuild()
.EnableCollectCoverage()
.SetCoverletOutputFormat(CoverletOutputFormat.opencover));
// .SetResultsDirectory(TestResultsDirectory));
});
Target CodeDump => _ => _
.Executes(() =>
{
var files = RootDirectory.GlobFiles("**/*.cs", "**/*.md")
.Where(file =>
!file.Name.Equals("GlobalSuppressions.cs", StringComparison.OrdinalIgnoreCase) &&
!file.Name.Equals("AssemblyInfo.cs", StringComparison.OrdinalIgnoreCase) &&
!file.Name.EndsWith(".g.cs", StringComparison.OrdinalIgnoreCase) &&
!file.Name.EndsWith("ApiClient.cs") &&
!file.Name.EndsWith("GlobalUsings.cs") &&
!file.Name.EndsWith("CodeDump.cs") &&
!file.Name.EndsWith("CODE_OF_CONDUCT") &&
!file.ToString().Contains("GlobalSuppressions.cs") &&
!file.ToString().Contains("Migrations") &&
!file.ToString().Contains(".UnitTests") &&
!file.ToString().Contains(".IntegrationTests")&&
!file.ToString().Contains(@"\bin\") && // Exclude bin folders
!file.ToString().Contains(@"\obj\"))
.ToList();
//files.AddRange(RootDirectory.GlobFiles("*.md"));
var totalFiles = files.Count;
var processedFiles = 0;
var csFiles = 0;
var mdFiles = 0;
var totalLines = 0;
Console.WriteLine($"Starting to process {totalFiles} files (.cs and .md)...");
using (var writer = new StreamWriter(CodeDumpOutputFile))
{
foreach (var file in files)
{
processedFiles++;
var fileName = file.Name;
var extension = Path.GetExtension(fileName).ToLower();
Console.WriteLine($"Processing: {fileName} ({processedFiles} of {totalFiles})");
writer.WriteLine($"// File: {file}");
writer.WriteLine("// ----------------------------------------");
var lines = File.ReadAllLines(file);
var contentStartIndex = FindContentStartIndex(lines);
totalLines += lines.Length - contentStartIndex;
for (int i = contentStartIndex; i < lines.Length; i++)
{
writer.WriteLine(lines[i]);
}
writer.WriteLine();
if (extension == ".cs")
csFiles++;
else if (extension == ".md")
mdFiles++;
}
}
Console.WriteLine($"All files have been concatenated into {CodeDumpOutputFile}");
Console.WriteLine($"Total files processed: {totalFiles}");
Console.WriteLine($"C# files: {csFiles}");
Console.WriteLine($"Markdown files: {mdFiles}");
Console.WriteLine($"Total lines: {totalLines}");
});
private int FindContentStartIndex(string[] lines)
{
for (var i = 0; i < lines.Length; i++)
{
if (!string.IsNullOrWhiteSpace(lines[i]) && !lines[i].TrimStart().StartsWith("//"))
{
return i;
}
}
return 0;
}
Target All => _ => _
.DependsOn(SonarAnalysis, CodeDump)
.Executes(() =>
{
Console.WriteLine("All tasks completed successfully.");
});
}
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\build\Configuration.cs
// ----------------------------------------
using System;
using System.ComponentModel;
using System.Linq;
using Nuke.Common.Tooling;
[TypeConverter(typeof(TypeConverter<Configuration>))]
public class Configuration : Enumeration
{
public static Configuration Debug = new Configuration { Value = nameof(Debug) };
public static Configuration Release = new Configuration { Value = nameof(Release) };
public static implicit operator string(Configuration configuration)
{
return configuration.Value;
}
}
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\src\Presentation.AppHost\HealthCheckAnnotation.cs
// ----------------------------------------
namespace Aspire.Hosting;
using Microsoft.Extensions.Diagnostics.HealthChecks;
/// <summary>
/// An annotation that associates a health check factory with a resource
/// </summary>
/// <param name="healthCheckFactory">A function that creates the health check</param>
public class HealthCheckAnnotation(Func<IResource, CancellationToken, Task<IHealthCheck?>> healthCheckFactory)
: IResourceAnnotation
{
public Func<IResource, CancellationToken, Task<IHealthCheck?>> HealthCheckFactory { get; } = healthCheckFactory;
public static HealthCheckAnnotation Create(Func<string, IHealthCheck> connectionStringFactory)
{
return new HealthCheckAnnotation(
async (resource, token) =>
{
if (resource is not IResourceWithConnectionString c)
{
return null;
}
if (await c.GetConnectionStringAsync(token) is not string cs)
{
return null;
}
return connectionStringFactory(cs);
});
}
}
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\src\Presentation.AppHost\HttpEndpointHealthCheckExtensions.cs
// ----------------------------------------
namespace Aspire.Hosting;
using HealthChecks.Uris;
using Microsoft.Extensions.Diagnostics.HealthChecks;
public static class HttpEndpointHealthCheckExtensions
{
/// <summary>
/// Adds a health check to the resource with HTTP endpoints.
/// </summary>
/// <typeparam name="T">The resource type.</typeparam>
/// <param name="builder">The resource builder.</param>
/// <param name="endpointName">
/// The optional name of the endpoint. If not specified, will be the first http or https
/// endpoint (based on scheme).
/// </param>
/// <param name="path">path to send the HTTP request to. This will be appended to the base URL of the resolved endpoint.</param>
/// <param name="configure">A callback to configure the options for this health check.</param>
public static IResourceBuilder<T> WithHealthCheck<T>(
this IResourceBuilder<T> builder,
string? endpointName = null,
string path = "health",
Action<UriHealthCheckOptions>? configure = null)
where T : IResourceWithEndpoints
{
return builder.WithAnnotation(
new HealthCheckAnnotation(
(resource, ct) =>
{
if (resource is not IResourceWithEndpoints resourceWithEndpoints)
{
return Task.FromResult<IHealthCheck?>(null);
}
var endpoint = endpointName is null
? resourceWithEndpoints.GetEndpoints().FirstOrDefault(e => e.Scheme is "http" or "https")
: resourceWithEndpoints.GetEndpoint(endpointName);
var url = endpoint?.Url;
if (url is null)
{
return Task.FromResult<IHealthCheck?>(null);
}
var options = new UriHealthCheckOptions();
options.AddUri(new Uri(new Uri(url), path));
configure?.Invoke(options);
var client = new HttpClient();
return Task.FromResult<IHealthCheck?>(new UriHealthCheck(options, () => client));
}));
}
}
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\src\Presentation.AppHost\Program.cs
// ----------------------------------------
var builder = DistributedApplication.CreateBuilder(args);
//var sqlPassword = builder.AddParameter("sql-password", secret: true);
var sql = builder.AddSqlServer(
"sql")
//port: 14329)
// password: sqlPassword)
.WithImageTag("latest")
//.WithDataVolume() // requires persistent password https://learn.microsoft.com/en-us/dotnet/aspire/fundamentals/persist-data-volumes
//.WithHealthCheck()
.AddDatabase("sqldata");
builder.AddProject<Projects.Presentation_Web_Server>("presentation-web-server")
.WaitFor(sql)
.WithReference(sql);
//TODO: add SEQ integration https://learn.microsoft.com/en-us/dotnet/aspire/logging/seq-integration?tabs=dotnet-cli
builder.Build().Run();
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\src\Presentation.AppHost\SqlResourceHealthCheckExtensions.cs
// ----------------------------------------
namespace Aspire.Hosting;
using HealthChecks.SqlServer;
public static class SqlResourceHealthCheckExtensions
{
/// <summary>
/// Adds a health check to the SQL Server resource.
/// </summary>
public static IResourceBuilder<SqlServerServerResource> WithHealthCheck(
this IResourceBuilder<SqlServerServerResource> builder)
{
return builder.WithSqlHealthCheck(cs => new SqlServerHealthCheckOptions { ConnectionString = cs });
}
/// <summary>
/// Adds a health check to the SQL Server database resource.
/// </summary>
public static IResourceBuilder<SqlServerDatabaseResource> WithHealthCheck(
this IResourceBuilder<SqlServerDatabaseResource> builder)
{
return builder.WithSqlHealthCheck(cs => new SqlServerHealthCheckOptions { ConnectionString = cs });
}
/// <summary>
/// Adds a health check to the SQL Server resource with a specific query.
/// </summary>
public static IResourceBuilder<SqlServerServerResource> WithHealthCheck(
this IResourceBuilder<SqlServerServerResource> builder,
string query)
{
return builder.WithSqlHealthCheck(
cs => new SqlServerHealthCheckOptions { ConnectionString = cs, CommandText = query });
}
/// <summary>
/// Adds a health check to the SQL Server database resource with a specific query.
/// </summary>
public static IResourceBuilder<SqlServerDatabaseResource> WithHealthCheck(
this IResourceBuilder<SqlServerDatabaseResource> builder,
string query)
{
return builder.WithSqlHealthCheck(
cs => new SqlServerHealthCheckOptions { ConnectionString = cs, CommandText = query });
}
private static IResourceBuilder<T> WithSqlHealthCheck<T>(
this IResourceBuilder<T> builder,
Func<string, SqlServerHealthCheckOptions> healthCheckOptionsFactory)
where T : IResource
{
return builder.WithAnnotation(
HealthCheckAnnotation.Create(cs => new SqlServerHealthCheck(healthCheckOptionsFactory(cs))));
}
}
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\src\Presentation.AppHost\WaitForDependenciesExtensions.cs
// ----------------------------------------
namespace Aspire.Hosting;
using System.Collections.Concurrent;
using System.Runtime.ExceptionServices;
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.Lifecycle;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using Polly;
using Polly.Retry;
public static class WaitForDependenciesExtensions
{
/// <summary>
/// Wait for a resource to be running before starting another resource.
/// </summary>
/// <typeparam name="T">The resource type.</typeparam>
/// <param name="builder">The resource builder.</param>
/// <param name="other">The resource to wait for.</param>
public static IResourceBuilder<T> WaitFor<T>(this IResourceBuilder<T> builder, IResourceBuilder<IResource> other)
where T : IResource
{
builder.ApplicationBuilder.AddWaitForDependencies();
return builder.WithAnnotation(new WaitOnAnnotation(other.Resource));
}
/// <summary>
/// Wait for a resource to run to completion before starting another resource.
/// </summary>
/// <typeparam name="T">The resource type.</typeparam>
/// <param name="builder">The resource builder.</param>
/// <param name="other">The resource to wait for.</param>
public static IResourceBuilder<T> WaitForCompletion<T>(this IResourceBuilder<T> builder, IResourceBuilder<IResource> other)
where T : IResource
{
builder.ApplicationBuilder.AddWaitForDependencies();
return builder.WithAnnotation(new WaitOnAnnotation(other.Resource) { WaitUntilCompleted = true });
}
/// <summary>
/// Adds a lifecycle hook that waits for all dependencies to be "running" before starting resources. If that resource
/// has a health check, it will be executed before the resource is considered "running".
/// </summary>
/// <param name="builder">The <see cref="IDistributedApplicationBuilder"/>.</param>
private static IDistributedApplicationBuilder AddWaitForDependencies(this IDistributedApplicationBuilder builder)
{
builder.Services.TryAddLifecycleHook<WaitForDependenciesRunningHook>();
return builder;
}
private class WaitOnAnnotation(IResource resource) : IResourceAnnotation
{
public IResource Resource { get; } = resource;
#pragma warning disable CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
public string[]? States { get; set; }
#pragma warning restore CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
public bool WaitUntilCompleted { get; set; }
}
private class WaitForDependenciesRunningHook(DistributedApplicationExecutionContext executionContext,
ResourceNotificationService resourceNotificationService) :
IDistributedApplicationLifecycleHook,
IAsyncDisposable
{
private readonly CancellationTokenSource _cts = new();
public Task BeforeStartAsync(DistributedApplicationModel appModel, CancellationToken cancellationToken = default)
{
// We don't need to execute any of this logic in publish mode
if (executionContext.IsPublishMode)
{
return Task.CompletedTask;
}
// The global list of resources being waited on
var waitingResources = new ConcurrentDictionary<IResource, ConcurrentDictionary<WaitOnAnnotation, TaskCompletionSource>>();
// For each resource, add an environment callback that waits for dependencies to be running
foreach (var r in appModel.Resources)
{
var resourcesToWaitOn = r.Annotations.OfType<WaitOnAnnotation>().ToLookup(a => a.Resource);
if (resourcesToWaitOn.Count == 0)
{
continue;
}
// Abuse the environment callback to wait for dependencies to be running
r.Annotations.Add(new EnvironmentCallbackAnnotation(async context =>
{
var dependencies = new List<Task>();
// Find connection strings and endpoint references and get the resource they point to
foreach (var group in resourcesToWaitOn)
{
var resource = group.Key;
// REVIEW: This logic does not handle cycles in the dependency graph (that would result in a deadlock)
// Don't wait for yourself
if (resource != r && resource is not null)
{
var pendingAnnotations = waitingResources.GetOrAdd(resource, _ => new());
foreach (var waitOn in group)
{
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
async Task Wait()
{
context.Logger?.LogInformation("Waiting for {Resource}.", waitOn.Resource.Name);
await tcs.Task;
context.Logger?.LogInformation("Waiting for {Resource} completed.", waitOn.Resource.Name);
}
pendingAnnotations[waitOn] = tcs;
dependencies.Add(Wait());
}
}
}
await resourceNotificationService.PublishUpdateAsync(r, s => s with
{
State = new("Waiting", KnownResourceStateStyles.Info)
});
await Task.WhenAll(dependencies).WaitAsync(context.CancellationToken);
}));
}
_ = Task.Run(async () =>
{
var stoppingToken = _cts.Token;
// These states are terminal but we need a better way to detect that
static bool IsKnownTerminalState(CustomResourceSnapshot snapshot) =>
snapshot.State == "FailedToStart" ||
snapshot.State == "Exited" ||
snapshot.ExitCode is not null;
// Watch for global resource state changes
await foreach (var resourceEvent in resourceNotificationService.WatchAsync(stoppingToken))
{
if (waitingResources.TryGetValue(resourceEvent.Resource, out var pendingAnnotations))
{
foreach (var (waitOn, tcs) in pendingAnnotations)
{
if (waitOn.States is string[] states && states.Contains(resourceEvent.Snapshot.State?.Text, StringComparer.Ordinal))
{
pendingAnnotations.TryRemove(waitOn, out _);
_ = DoTheHealthCheck(resourceEvent, tcs);
}
else if (waitOn.WaitUntilCompleted)
{
if (IsKnownTerminalState(resourceEvent.Snapshot))
{
pendingAnnotations.TryRemove(waitOn, out _);
_ = DoTheHealthCheck(resourceEvent, tcs);
}
}
else if (waitOn.States is null)
{
if (resourceEvent.Snapshot.State.Text == "Running")
{
pendingAnnotations.TryRemove(waitOn, out _);
_ = DoTheHealthCheck(resourceEvent, tcs);
}
else if (IsKnownTerminalState(resourceEvent.Snapshot))
{
pendingAnnotations.TryRemove(waitOn, out _);
tcs.TrySetException(new Exception($"Dependency {waitOn.Resource.Name} failed to start"));
}
}
}
}
}
},
cancellationToken);
return Task.CompletedTask;
}
private async Task DoTheHealthCheck(ResourceEvent resourceEvent, TaskCompletionSource tcs)
{
var resource = resourceEvent.Resource;
// REVIEW: Right now, every resource does an independent health check, we could instead cache
// the health check result and reuse it for all resources that depend on the same resource
#pragma warning disable CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
HealthCheckAnnotation? healthCheckAnnotation = null;
#pragma warning restore CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
// Find the relevant health check annotation. If the resource has a parent, walk up the tree
// until we find the health check annotation.
while (true)
{
// If we find a health check annotation, break out of the loop
if (resource.TryGetLastAnnotation(out healthCheckAnnotation))
{
break;
}
// If the resource has a parent, walk up the tree
if (resource is IResourceWithParent parent)
{
resource = parent.Parent;
}
else
{
break;
}
}
#pragma warning disable CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
Func<CancellationToken, ValueTask>? operation = null;
#pragma warning restore CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
if (healthCheckAnnotation?.HealthCheckFactory is { } factory)
{
#pragma warning disable CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
IHealthCheck? check;
#pragma warning restore CS8669 // The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
try
{
// TODO: Do need to pass a cancellation token here?
check = await factory(resource, default);
if (check is not null)
{
var context = new HealthCheckContext()
{
Registration = new HealthCheckRegistration("", check, HealthStatus.Unhealthy, [])
};
operation = async (cancellationToken) =>
{
var result = await check.CheckHealthAsync(context, cancellationToken);
if (result.Exception is not null)
{
ExceptionDispatchInfo.Throw(result.Exception);
}
if (result.Status != HealthStatus.Healthy)
{
throw new Exception("Health check failed");
}
};
}
}
catch (Exception ex)
{
tcs.TrySetException(ex);
return;
}
}
try
{
if (operation is not null)
{
var pipeline = CreateResiliencyPipeline();
await pipeline.ExecuteAsync(operation);
}
tcs.TrySetResult();
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
private static ResiliencePipeline CreateResiliencyPipeline()
{
var retryUntilCancelled = new RetryStrategyOptions()
{
ShouldHandle = new PredicateBuilder().Handle<Exception>(),
BackoffType = DelayBackoffType.Exponential,
MaxRetryAttempts = 5,
UseJitter = true,
MaxDelay = TimeSpan.FromSeconds(30)
};
return new ResiliencePipelineBuilder().AddRetry(retryUntilCancelled).Build();
}
public ValueTask DisposeAsync()
{
_cts.Cancel();
return default;
}
}
}
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\src\Presentation.ServiceDefaults\Extensions.cs
// ----------------------------------------
namespace Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
// Adds common .NET Aspire services: service discovery, resilience, health checks, and OpenTelemetry.
// This project should be referenced by each service project in your solution.
// To learn more about using this project, see https://aka.ms/dotnet/aspire/service-defaults
public static class Extensions
{
public static IHostApplicationBuilder AddServiceDefaults(this IHostApplicationBuilder builder)
{
//builder.ConfigureOpenTelemetry();
//builder.AddDefaultHealthChecks();
builder.Services.AddServiceDiscovery();
builder.Services.ConfigureHttpClientDefaults(
http =>
{
http.AddStandardResilienceHandler();
http.AddServiceDiscovery();
});
return builder;
}
public static IHostApplicationBuilder ConfigureOpenTelemetry(this IHostApplicationBuilder builder)
{
//builder.Logging.AddOpenTelemetry(logging =>
//{
// logging.IncludeFormattedMessage = true;
// logging.IncludeScopes = true;
//});
//builder.Services.AddOpenTelemetry()
// .WithMetrics(metrics =>
// {
// metrics.AddAspNetCoreInstrumentation()
// .AddHttpClientInstrumentation()
// .AddRuntimeInstrumentation();
// })
// .WithTracing(tracing =>
// {
// tracing.AddAspNetCoreInstrumentation()
// // Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
// //.AddGrpcClientInstrumentation()
// .AddHttpClientInstrumentation();
// });
//builder.AddOpenTelemetryExporters();
return builder;
}
public static IHostApplicationBuilder AddDefaultHealthChecks(this IHostApplicationBuilder builder)
{
builder.Services.AddHealthChecks()
// Add a default liveness check to ensure app is responsive
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
return builder;
}
public static WebApplication MapDefaultEndpoints(this WebApplication app)
{
// Adding health checks endpoints to applications in non-development environments has security implications.
// See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
if (app.Environment.IsDevelopment())
{
// All health checks must pass for app to be considered ready to accept traffic after starting
app.MapHealthChecks("/health");
// Only health checks tagged with the "live" tag must pass for app to be considered alive
app.MapHealthChecks("/alive", new HealthCheckOptions { Predicate = r => r.Tags.Contains("live") });
}
return app;
}
private static IHostApplicationBuilder AddOpenTelemetryExporters(this IHostApplicationBuilder builder)
{
//var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
//if (useOtlpExporter)
//{
// builder.Services.AddOpenTelemetry().UseOtlpExporter();
//}
// Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.AspNetCore package)
//if (!string.IsNullOrEmpty(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]))
//{
// builder.Services.AddOpenTelemetry()
// .UseAzureMonitor();
//}
return builder;
}
}
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\src\Presentation.Web.Client\Program.cs
// ----------------------------------------
#pragma warning disable SA1200 // Using directives should be placed correctly
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using MudBlazor;
using MudBlazor.Services;
using Polly;
#pragma warning restore SA1200 // Using directives should be placed correctly
var builder = WebAssemblyHostBuilder.CreateDefault(args);
var configuration = builder.Configuration.Build();
builder.Services.AddLocalization();
//builder.Services.AddScoped<IApiClient, ApiClient>();
builder.Services.AddHttpClient("backend-api")
.ConfigureHttpClient(c => c.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddPolicyHandler(Policy.TimeoutAsync<HttpResponseMessage>(TimeSpan.FromSeconds(30)));
builder.Services.AddScoped(sp => HttpClientFactory(sp, configuration));
builder.Services.AddMudServices(
config =>
{
config.SnackbarConfiguration.PositionClass = Defaults.Classes.Position.BottomRight;
config.SnackbarConfiguration.PreventDuplicates = false;
config.SnackbarConfiguration.NewestOnTop = true;
config.SnackbarConfiguration.ShowCloseIcon = true;
config.SnackbarConfiguration.VisibleStateDuration = 10000;
config.SnackbarConfiguration.HideTransitionDuration = 500;
config.SnackbarConfiguration.ShowTransitionDuration = 500;
config.SnackbarConfiguration.SnackbarVariant = Variant.Filled;
});
await builder.Build().RunAsync();
static HttpClient HttpClientFactory(IServiceProvider serviceProvider, IConfiguration configuration)
{
var httpClient = serviceProvider.GetRequiredService<IHttpClientFactory>().CreateClient("backend-api");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return httpClient;
}
// File: F:\projects\bit\bITdevKit.Examples.BookFiesta\src\Presentation.Web.Server\Program.cs
// ----------------------------------------
using BridgingIT.DevKit.Application.JobScheduling;
using BridgingIT.DevKit.Examples.BookFiesta.Modules.Inventory.Presentation;
using BridgingIT.DevKit.Examples.BookFiesta.Modules.Organization.Infrastructure;
using BridgingIT.DevKit.Infrastructure.EntityFramework;
using OpenTelemetry.Exporter;
#pragma warning disable SA1200 // Using directives should be placed correctly
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using Azure.Monitor.OpenTelemetry.Exporter;
using BridgingIT.DevKit.Application.Commands;
using BridgingIT.DevKit.Application.Messaging;
using BridgingIT.DevKit.Application.Queries;
using BridgingIT.DevKit.Application.Utilities;
using BridgingIT.DevKit.Common;
using BridgingIT.DevKit.Examples.BookFiesta.Modules.Catalog.Presentation;
using BridgingIT.DevKit.Examples.BookFiesta.Modules.Organization.Presentation;
using BridgingIT.DevKit.Examples.BookFiesta.Presentation.Web.Client.Pages;
using BridgingIT.DevKit.Examples.BookFiesta.Presentation.Web.Server;
using BridgingIT.DevKit.Examples.BookFiesta.Presentation.Web.Server.Components;
using BridgingIT.DevKit.Examples.BookFiesta.SharedKernel.Application;
using BridgingIT.DevKit.Presentation;
using BridgingIT.DevKit.Presentation.Web;
using BridgingIT.DevKit.Presentation.Web.JobScheduling;
using Hellang.Middleware.ProblemDetails;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using MudBlazor.Services;
using NSwag;
using NSwag.Generation.AspNetCore;
using NSwag.Generation.Processors.Security;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using Serilog;
#pragma warning restore SA1200 // Using directives should be placed correctly
// ===============================================================================================
// Create the webhost
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.Host.ConfigureAppConfiguration();
builder.Host.ConfigureLogging(builder.Configuration);
// ===============================================================================================
// Configure the modules
builder.Services.AddModules(builder.Configuration, builder.Environment)
.WithModule<OrganizationModule>()
.WithModule<InventoryModule>()
.WithModule<CatalogModule>()
.WithModuleContextAccessors()
.WithRequestModuleContextAccessors()
.WithModuleControllers(c => c.AddJsonOptions(ConfigureJsonOptions));
builder.Services.Configure<JsonOptions>(ConfigureJsonOptions); // configure json for minimal apis
// ===============================================================================================
// Configure the services
builder.Services.AddMediatR(); // or AddDomainEvents()?
builder.Services.AddMapping().WithMapster();
builder.Services.AddCommands()
.WithBehavior(typeof(ModuleScopeCommandBehavior<,>))
//.WithBehavior(typeof(ChaosExceptionCommandBehavior<,>))
.WithBehavior(typeof(RetryCommandBehavior<,>))
.WithBehavior(typeof(TimeoutCommandBehavior<,>))
.WithBehavior(typeof(TenantAwareCommandBehavior<,>));
builder.Services.AddQueries()
.WithBehavior(typeof(ModuleScopeQueryBehavior<,>))
//.WithBehavior(typeof(ChaosExceptionQueryBehavior<,>))
.WithBehavior(typeof(RetryQueryBehavior<,>))
.WithBehavior(typeof(TimeoutQueryBehavior<,>))
.WithBehavior(typeof(TenantAwareQueryBehavior<,>));