-
Notifications
You must be signed in to change notification settings - Fork 856
VCST-4696: Platform Startup Extension Point #2985
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
OlegoO
wants to merge
4
commits into
dev
Choose a base branch
from
feat/VCST-4696
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
src/VirtoCommerce.Platform.Core/Modularity/IPlatformStartup.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| using Microsoft.AspNetCore.Builder; | ||
| using Microsoft.Extensions.Configuration; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Hosting; | ||
|
|
||
| namespace VirtoCommerce.Platform.Core.Modularity | ||
| { | ||
| /// <summary> | ||
| /// Allows modules to participate in early platform startup phases that occur | ||
| /// before or outside the standard <see cref="IModule.Initialize"/>/<see cref="IModule.PostInitialize"/> lifecycle. | ||
| /// <para> | ||
| /// Implementations must have a parameterless constructor (instantiated via <see cref="System.Activator.CreateInstance(System.Type)"/>). | ||
| /// </para> | ||
| /// <para> | ||
| /// Declare the implementation type in <c>module.manifest</c> using the <c><startupType></c> element. | ||
| /// </para> | ||
| /// </summary> | ||
| public interface IPlatformStartup | ||
| { | ||
| /// <summary> | ||
| /// Controls the order in which startup types are invoked within the same phase. | ||
| /// Lower values run first. Use <see cref="StartupPriority"/> constants for well-known values. | ||
| /// </summary> | ||
| int Priority => StartupPriority.Default; | ||
|
|
||
| /// <summary> | ||
| /// Determines when <see cref="Configure"/> is called in the middleware pipeline. | ||
| /// </summary> | ||
| PipelinePhase Phase => PipelinePhase.Initialization; | ||
|
|
||
| /// <summary> | ||
| /// Called during host building (Program.cs ConfigureAppConfiguration phase). | ||
| /// Use this to add configuration sources (e.g., Azure App Configuration). | ||
| /// </summary> | ||
| /// <param name="builder">The configuration builder to add sources to.</param> | ||
| /// <param name="hostEnvironment">The host environment (provides EnvironmentName, ContentRootPath, etc.).</param> | ||
| void ConfigureAppConfiguration(IConfigurationBuilder builder, IHostEnvironment hostEnvironment) { } | ||
|
|
||
| /// <summary> | ||
| /// Called during host building (Program.cs ConfigureServices phase). | ||
| /// Use this to register hosted services (e.g., Hangfire server). | ||
| /// </summary> | ||
| /// <param name="services">The host-level service collection.</param> | ||
| /// <param name="configuration">The fully-built host configuration.</param> | ||
| void ConfigureHostServices(IServiceCollection services, IConfiguration configuration) { } | ||
|
|
||
| /// <summary> | ||
| /// Called during Startup.ConfigureServices, after modules are loaded via AddModules(). | ||
| /// Use this to register application-level services. | ||
| /// </summary> | ||
| void ConfigureServices(IServiceCollection services, IConfiguration configuration) { } | ||
|
|
||
| /// <summary> | ||
| /// Called during Startup.Configure at the pipeline position determined by <see cref="Phase"/>. | ||
| /// Use this to add middleware or perform initialization. | ||
| /// </summary> | ||
| void Configure(IApplicationBuilder app, IConfiguration configuration) { } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
src/VirtoCommerce.Platform.Core/Modularity/PipelinePhase.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| namespace VirtoCommerce.Platform.Core.Modularity | ||
| { | ||
| /// <summary> | ||
| /// Determines when an <see cref="IPlatformStartup.Configure"/> method is invoked | ||
| /// within the Startup.Configure pipeline. | ||
| /// </summary> | ||
| public enum PipelinePhase | ||
| { | ||
| /// <summary> | ||
| /// Before routing and authentication middleware. | ||
| /// Use for configuration refresh middleware, custom request preprocessing, etc. | ||
| /// </summary> | ||
| EarlyMiddleware = 0, | ||
|
|
||
| /// <summary> | ||
| /// Within the ExecuteSynchronized block, after platform migrations | ||
| /// but before IModule.PostInitialize. | ||
| /// Use for infrastructure that requires the database to be ready (e.g., Hangfire). | ||
| /// </summary> | ||
| Initialization = 1, | ||
|
|
||
| /// <summary> | ||
| /// After endpoints are mapped and modules are post-initialized. | ||
| /// Use for middleware that needs to see all endpoints (e.g., Swagger). | ||
| /// </summary> | ||
| LateMiddleware = 2 | ||
| } | ||
| } |
21 changes: 21 additions & 0 deletions
21
src/VirtoCommerce.Platform.Core/Modularity/StartupPriority.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| namespace VirtoCommerce.Platform.Core.Modularity | ||
| { | ||
| /// <summary> | ||
| /// Well-known priority values for <see cref="IPlatformStartup"/> ordering. | ||
| /// Lower values execute first. | ||
| /// </summary> | ||
| public static class StartupPriority | ||
| { | ||
| /// <summary>Configuration sources should load first (e.g., Azure App Configuration).</summary> | ||
| public const int ConfigurationSource = -1000; | ||
|
|
||
| /// <summary>Infrastructure services like logging and caching (e.g., Serilog).</summary> | ||
| public const int Infrastructure = -500; | ||
|
|
||
| /// <summary>Default priority for module startup types.</summary> | ||
| public const int Default = 0; | ||
|
|
||
| /// <summary>Services that depend on other modules being registered (e.g., Swagger).</summary> | ||
| public const int Late = 500; | ||
| } | ||
| } |
124 changes: 124 additions & 0 deletions
124
src/VirtoCommerce.Platform.Modules/PlatformStartupDiscovery.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Reflection; | ||
| using System.Runtime.Loader; | ||
| using VirtoCommerce.Platform.Core.Modularity; | ||
|
|
||
| namespace VirtoCommerce.Platform.Modules | ||
| { | ||
| /// <summary> | ||
| /// Discovers and instantiates <see cref="IPlatformStartup"/> implementations from module assemblies. | ||
| /// Designed to run early in the platform lifecycle (Program.cs level) before DI is configured. | ||
| /// </summary> | ||
| public static class PlatformStartupDiscovery | ||
| { | ||
| /// <summary> | ||
| /// Scans module manifests in the discovery path for those declaring a startupType, | ||
| /// loads their assemblies from the probing path, and instantiates the startup types. | ||
| /// Returns an empty list if paths are missing or no startup types are found. | ||
| /// </summary> | ||
| /// <param name="discoveryPath">Path to scan for module.manifest files (e.g., "modules/").</param> | ||
| /// <param name="probingPath">Path where module assemblies are located (e.g., "app_data/modules/").</param> | ||
| /// <returns>List of discovered startup instances ordered by <see cref="IPlatformStartup.Priority"/>.</returns> | ||
| public static IReadOnlyList<IPlatformStartup> DiscoverStartups(string discoveryPath, string probingPath) | ||
| { | ||
| var startups = new List<IPlatformStartup>(); | ||
|
|
||
| if (string.IsNullOrEmpty(discoveryPath) || !Directory.Exists(discoveryPath)) | ||
| { | ||
| return startups; | ||
| } | ||
|
|
||
| if (string.IsNullOrEmpty(probingPath) || !Directory.Exists(probingPath)) | ||
| { | ||
| return startups; | ||
| } | ||
|
|
||
| // Register a permanent handler to resolve assemblies from the probing path. | ||
| // This is needed because startup assemblies are loaded into the default ALC | ||
| // before the full module loader (LoadContextAssemblyResolver) is configured, | ||
| // so their transitive dependencies won't be found otherwise. | ||
| // The handler must remain active because startup methods (ConfigureAppConfiguration, | ||
| // ConfigureHostServices, etc.) are invoked later during host building and may | ||
| // trigger assembly loads at that point. | ||
| var fullProbingPath = Path.GetFullPath(probingPath); | ||
| AssemblyLoadContext.Default.Resolving += (context, assemblyName) => | ||
| { | ||
| var candidatePath = Path.Combine(fullProbingPath, assemblyName.Name + ".dll"); | ||
| if (File.Exists(candidatePath)) | ||
| { | ||
| return context.LoadFromAssemblyPath(candidatePath); | ||
| } | ||
|
|
||
| return null; | ||
| }; | ||
|
|
||
| foreach (var manifestFile in Directory.EnumerateFiles(discoveryPath, "module.manifest", SearchOption.AllDirectories)) | ||
| { | ||
| // Exclude manifests from built modules artifacts | ||
| if (manifestFile.Contains("artifacts")) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| ModuleManifest manifest; | ||
| try | ||
| { | ||
| manifest = ManifestReader.Read(manifestFile); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| Console.Error.WriteLine($"Warning: Failed to read module manifest {manifestFile}: {ex.Message}"); | ||
| continue; | ||
| } | ||
|
|
||
| if (string.IsNullOrEmpty(manifest?.StartupType) || string.IsNullOrEmpty(manifest.AssemblyFile)) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| var assemblyPath = Path.GetFullPath(Path.Combine(probingPath, manifest.AssemblyFile)); | ||
| if (!File.Exists(assemblyPath)) | ||
| { | ||
| // Assembly not yet in probing path (first run). Skip gracefully. | ||
| continue; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath); | ||
| var startupType = assembly.GetType(manifest.StartupType); | ||
|
|
||
| if (startupType == null) | ||
| { | ||
| // Try partial match (same pattern as ModuleInitializer.TryResolveModuleTypeFromAssembly) | ||
| startupType = assembly.GetTypes() | ||
| .FirstOrDefault(t => typeof(IPlatformStartup).IsAssignableFrom(t) | ||
| && t.AssemblyQualifiedName?.StartsWith(manifest.StartupType) == true); | ||
| } | ||
|
|
||
| if (startupType != null | ||
| && typeof(IPlatformStartup).IsAssignableFrom(startupType) | ||
| && Activator.CreateInstance(startupType) is IPlatformStartup startup) | ||
| { | ||
| startups.Add(startup); | ||
| } | ||
| else | ||
| { | ||
| Console.Error.WriteLine( | ||
| $"Warning: Startup type '{manifest.StartupType}' in module '{manifest.Id}' does not implement IPlatformStartup or could not be instantiated."); | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| Console.Error.WriteLine( | ||
| $"Warning: Failed to load startup type '{manifest.StartupType}' from '{manifest.AssemblyFile}' (module '{manifest.Id}'): {ex.Message}"); | ||
| } | ||
| } | ||
|
|
||
| return startups.OrderBy(s => s.Priority).ToList(); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Artifacts path filter checks full path, not relative
Medium Severity
The
manifestFile.Contains("artifacts")check tests the entire absolute path, unlike the equivalent code inLocalStorageModuleCatalog.cswhich usesmanifestFile.Substring(_discoveryPath.Length).Contains("artifacts")to only check the relative portion after the discovery path. If the discovery path itself contains "artifacts" (common in CI/CD pipelines, e.g./build/artifacts/modules/), every manifest will be skipped and noIPlatformStartuptypes will be discovered.