-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRazorComponentClientModuleCollection.cs
244 lines (207 loc) · 9.7 KB
/
RazorComponentClientModuleCollection.cs
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
using Microsoft.AspNetCore.Components.WebAssembly.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using Modulight.Modules.Client.RazorComponents.UI;
using Modulight.Modules.Hosting;
using System.Reflection;
namespace Modulight.Modules.Client.RazorComponents
{
/// <summary>
/// Specifies the contract for razor component module hosts.
/// </summary>
public interface IRazorComponentClientModuleCollection : IModuleCollection<IRazorComponentClientModule, RazorComponentClientModuleManifest>
{
/// <summary>
/// Load related assemblies for a given route.
/// </summary>
/// <param name="path">Route path.</param>
/// <param name="recurse">Load dependent assemblies recursely.</param>
/// <param name="throwOnError">Throw exceptions when error occurs instead of logs.</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<List<Assembly>> GetAssembliesForRouting(string path, bool recurse = false, bool throwOnError = false, CancellationToken cancellationToken = default);
/// <summary>
/// Validate modules.
/// Check if route roots conflict or assembly loading fails.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task Validate(CancellationToken cancellationToken = default);
/// <summary>
/// Load all <see cref="UIResource"/> defined in modules into DOM.
/// </summary>
/// <param name="moduleType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task LoadResources(Type? moduleType = null, CancellationToken cancellationToken = default);
}
/// <summary>
/// Extension methods for <see cref="IRazorComponentClientModuleCollection"/>.
/// </summary>
public static class RazorComponentClientModuleCollectionExtensions
{
/// <summary>
/// Load all <see cref="UIResource"/> defined in modules into DOM.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task LoadResources<T>(this IRazorComponentClientModuleCollection collection, CancellationToken cancellationToken = default) where T : IModule => collection.LoadResources(typeof(T), cancellationToken);
}
internal class RazorComponentClientModuleCollection : ModuleHostFilterCollection<IRazorComponentClientModule, RazorComponentClientModuleManifest>, IRazorComponentClientModuleCollection
{
public RazorComponentClientModuleCollection(IModuleHost host) : base(host)
{
Logger = host.Services.GetRequiredService<ILogger<RazorComponentClientModuleCollection>>();
}
public ILogger Logger { get; }
public async Task LoadResources(Type? moduleType = null, CancellationToken cancellationToken = default)
{
Logger.LogInformation($"Loading resources for {(moduleType is null ? "all" : moduleType.FullName)} modules.");
await using var scope = Host.Services.CreateAsyncScope();
var provider = scope.ServiceProvider;
var ui = provider.GetRequiredService<ModuleUILoader>();
var targetModules = DefinedModules;
if (moduleType is not null)
{
targetModules = targetModules.Where(x => x.IsModule(moduleType));
}
foreach (var module in targetModules)
{
var manifest = Host.GetManifest(module);
Logger.LogInformation($"Loading resources for {manifest.FullName}.");
var rcmanifest = GetManifest(module);
foreach (var resource in rcmanifest.Resources)
{
try
{
switch (resource.Type)
{
case UIResourceType.Script:
Logger.LogDebug($"Load script {resource.Path} of {manifest.FullName}.");
await ui.LoadScript(resource.Path, cancellationToken).ConfigureAwait(false);
break;
case UIResourceType.StyleSheet:
Logger.LogDebug($"Load stylesheet {resource.Path} of {manifest.FullName}.");
await ui.LoadStyleSheet(resource.Path, cancellationToken).ConfigureAwait(false);
break;
}
}
catch (JSException ex)
{
Logger.LogError(ex, $"Failed to load resource {resource.Path} of {manifest.FullName}");
}
}
}
Logger.LogInformation($"Loaded resources for {(moduleType is null ? "all" : moduleType.FullName)} modules.");
}
public async Task Validate(CancellationToken cancellationToken = default)
{
await using var scope = Host.Services.CreateAsyncScope();
var provider = scope.ServiceProvider;
HashSet<string> rootPaths = new();
foreach (var module in LoadedModules)
{
var pages = module.GetPageProvider(Host);
if (pages is not null)
{
if (pages.RootPath is not "")
{
if (rootPaths.Contains(pages.RootPath))
{
throw new ModulightException($"Same RootPath in modules: {pages.RootPath} @ {module.Manifest.Name}");
}
rootPaths.Add(pages.RootPath);
}
await GetAssembliesForRouting($"/{pages.RootPath}", throwOnError: true, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}
public async Task<List<Assembly>> GetAssembliesForRouting(string path, bool recurse = false, bool throwOnError = false, CancellationToken cancellationToken = default)
{
await using var scope = Host.Services.CreateAsyncScope();
var provider = scope.ServiceProvider;
var lazyLoader = provider.GetRequiredService<LazyAssemblyLoader>();
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
HashSet<string> processed = new();
List<Assembly> results = new();
Queue<string> toLoad = new();
foreach (var module in LoadedModules)
{
cancellationToken.ThrowIfCancellationRequested();
var name = module.GetType().GetAssemblyName();
if (processed.Add(name))
{
toLoad.Enqueue(name);
}
var pages = module.GetPageProvider(Host);
if (pages is null || pages is not null && pages.Contains(path))
{
foreach (var resource in GetManifest(module.GetType()).Resources.Where(x => x.Type is UIResourceType.Assembly))
{
cancellationToken.ThrowIfCancellationRequested();
if (processed.Add(resource.Path))
{
toLoad.Enqueue(resource.Path);
}
}
}
}
while (toLoad.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = toLoad.Dequeue();
Assembly? assembly;
assembly = loadedAssemblies.FirstOrDefault(x => x.GetName().Name == current);
if (assembly is null)
{
try
{
// Logger.LogInformation($"Loading assembly {current}");
assembly = Environment.OSVersion.Platform == PlatformID.Other
? (await lazyLoader.LoadAssembliesAsync(new[] { current + ".dll" }).ConfigureAwait(false)).FirstOrDefault()
: Assembly.Load(current);
}
catch (Exception ex)
{
if (throwOnError)
{
throw new ModulightException($"Failed to load assembly {current}", ex);
}
else
{
Logger.LogWarning($"Failed to load assembly {current}: {ex}");
}
}
}
if (assembly is null)
{
if (throwOnError)
{
throw new NullReferenceException($"Failed to load assembly {current}.");
}
Logger.LogError($"Failed to load assembly {current}.");
continue;
}
results.Add(assembly);
if (recurse)
{
foreach (var refe in assembly.GetReferencedAssemblies())
{
cancellationToken.ThrowIfCancellationRequested();
if (refe.Name is not null)
{
if (processed.Add(refe.Name))
{
toLoad.Enqueue(refe.Name);
}
}
}
}
}
return results;
}
}
}