-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathDefaultDocumentLoader.cs
More file actions
500 lines (423 loc) · 18.3 KB
/
DefaultDocumentLoader.cs
File metadata and controls
500 lines (423 loc) · 18.3 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using Microsoft.ClearScript.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.ClearScript
{
/// <summary>
/// Provides a default <c><see cref="DocumentLoader"></see></c> implementation.
/// </summary>
public class DefaultDocumentLoader : DocumentLoader, DocumentLoader.IStatistics
{
private static readonly IReadOnlyCollection<string> relativePrefixes = new List<string>
{
"." + Path.DirectorySeparatorChar,
"." + Path.AltDirectorySeparatorChar,
".." + Path.DirectorySeparatorChar,
".." + Path.AltDirectorySeparatorChar,
};
private static readonly Func<HttpClientHandler> defaultHttpClientHandlerFactory = static () => new HttpClientHandler();
private readonly List<Document> cache = new();
private long fileCheckCount;
private long webCheckCount;
private Func<HttpClientHandler> httpClientHandlerFactory;
// ReSharper disable EmptyConstructor
/// <summary>
/// Initializes a new <c><see cref="DefaultDocumentLoader"/></c> instance.
/// </summary>
public DefaultDocumentLoader()
{
// the help file builder (SHFB) insists on an empty constructor here
}
// ReSharper restore EmptyConstructor
internal Func<HttpClientHandler> HttpClientHandlerFactory
{
get => httpClientHandlerFactory ?? defaultHttpClientHandlerFactory;
set => httpClientHandlerFactory = value;
}
private Task<(Document, List<Uri>)> GetCachedDocumentOrCandidateUrisAsync(DocumentSettings settings, DocumentInfo? sourceInfo, Uri uri)
{
return GetCachedDocumentOrCandidateUrisWorkerAsync(settings, sourceInfo, uri.ToEnumerable());
}
private Task<(Document, List<Uri>)> GetCachedDocumentOrCandidateUrisAsync(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier)
{
return GetCachedDocumentOrCandidateUrisWorkerAsync(settings, sourceInfo, GetRawUris(settings, sourceInfo, specifier).Distinct());
}
private async Task<(Document, List<Uri>)> GetCachedDocumentOrCandidateUrisWorkerAsync(DocumentSettings settings, DocumentInfo? sourceInfo, IEnumerable<Uri> rawUris)
{
if (!string.IsNullOrWhiteSpace(settings.FileNameExtensions))
{
rawUris = rawUris.SelectMany(uri => ApplyExtensions(sourceInfo, uri, settings.FileNameExtensions));
}
var testUris = rawUris.ToList();
foreach (var testUri in testUris)
{
var flag = testUri.IsFile ? DocumentAccessFlags.EnableFileLoading : DocumentAccessFlags.EnableWebLoading;
if (settings.AccessFlags.HasAllFlags(flag))
{
var document = GetCachedDocument(testUri);
if (document is not null)
{
return (document, null);
}
}
}
var candidateUris = new List<Uri>();
foreach (var testUri in testUris)
{
if (await IsCandidateUriAsync(settings, testUri).ConfigureAwait(false))
{
candidateUris.Add(testUri);
}
}
return (null, candidateUris);
}
private static IEnumerable<Uri> GetRawUris(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier)
{
Uri baseUri;
Uri uri;
if (sourceInfo.HasValue && SpecifierMayBeRelative(settings, specifier))
{
baseUri = GetBaseUri(sourceInfo.Value);
if ((baseUri is not null) && Uri.TryCreate(baseUri, specifier, out uri))
{
yield return uri;
}
}
var searchPath = settings.SearchPath;
if (!string.IsNullOrWhiteSpace(searchPath))
{
foreach (var url in searchPath.SplitSearchPath())
{
if (Uri.TryCreate(url, UriKind.Absolute, out baseUri) && TryCombineSearchUri(baseUri, specifier, out uri))
{
yield return uri;
}
}
}
if (MiscHelpers.Try(out var path, static specifier => Path.Combine(Directory.GetCurrentDirectory(), specifier), specifier) && Uri.TryCreate(path, UriKind.Absolute, out uri))
{
yield return uri;
}
if (MiscHelpers.Try(out path, static specifier => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, specifier), specifier) && Uri.TryCreate(path, UriKind.Absolute, out uri))
{
yield return uri;
}
using (var process = Process.GetCurrentProcess())
{
var module = process.MainModule;
if ((module is not null) && Uri.TryCreate(module.FileName, UriKind.Absolute, out baseUri) && Uri.TryCreate(baseUri, specifier, out uri))
{
yield return uri;
}
}
}
private static IEnumerable<Uri> ApplyExtensions(DocumentInfo? sourceInfo, Uri uri, string extensions)
{
yield return uri;
var builder = new UriBuilder(uri);
var path = builder.Path;
if (!string.IsNullOrEmpty(Path.GetFileName(path)))
{
var existingExtension = Path.GetExtension(path);
var compatibleExtensions = GetCompatibleExtensions(sourceInfo, extensions).ToList();
if (!compatibleExtensions.Contains(existingExtension, StringComparer.OrdinalIgnoreCase))
{
foreach (var compatibleExtension in compatibleExtensions)
{
builder.Path = Path.ChangeExtension(path, existingExtension + compatibleExtension);
yield return builder.Uri;
}
}
}
}
private static IEnumerable<string> GetCompatibleExtensions(DocumentInfo? sourceInfo, string extensions)
{
string sourceExtension = null;
if (sourceInfo.HasValue)
{
sourceExtension = Path.GetExtension((sourceInfo.Value.Uri is not null) ? new UriBuilder(sourceInfo.Value.Uri).Path : sourceInfo.Value.Name);
if (!string.IsNullOrEmpty(sourceExtension))
{
yield return sourceExtension;
}
}
foreach (var extension in extensions.SplitSearchPath())
{
var tempExtension = extension.StartsWith(".", StringComparison.Ordinal) ? extension : "." + extension;
if (!tempExtension.Equals(sourceExtension, StringComparison.OrdinalIgnoreCase))
{
yield return tempExtension;
}
}
}
private static bool SpecifierMayBeRelative(DocumentSettings settings, string specifier)
{
return !settings.AccessFlags.HasAllFlags(DocumentAccessFlags.EnforceRelativePrefix) || relativePrefixes.Any(specifier.StartsWith);
}
private static Uri GetBaseUri(DocumentInfo sourceInfo)
{
var sourceUri = sourceInfo.Uri;
if ((sourceUri is null) && !Uri.TryCreate(sourceInfo.Name, UriKind.RelativeOrAbsolute, out sourceUri))
{
return null;
}
if (!sourceUri.IsAbsoluteUri)
{
return null;
}
return sourceUri;
}
private static bool TryCombineSearchUri(Uri searchUri, string specifier, out Uri uri)
{
var searchUrl = searchUri.AbsoluteUri;
if (!searchUrl.EndsWith("/", StringComparison.Ordinal))
{
searchUri = new Uri(searchUrl + "/");
}
return Uri.TryCreate(searchUri, specifier, out uri);
}
private async Task<bool> IsCandidateUriAsync(DocumentSettings settings, Uri uri)
{
return uri.IsFile ?
settings.AccessFlags.HasAllFlags(DocumentAccessFlags.EnableFileLoading) && await FileDocumentExistsAsync(uri.LocalPath).ConfigureAwait(false) :
settings.AccessFlags.HasAllFlags(DocumentAccessFlags.EnableWebLoading) && await WebDocumentExistsAsync(uri).ConfigureAwait(false);
}
private Task<bool> FileDocumentExistsAsync(string path)
{
Interlocked.Increment(ref fileCheckCount);
return Task.FromResult(File.Exists(path));
}
private async Task<bool> WebDocumentExistsAsync(Uri uri)
{
Interlocked.Increment(ref webCheckCount);
using (var client = new HttpClient(HttpClientHandlerFactory()))
{
using (var request = new HttpRequestMessage(HttpMethod.Head, uri))
{
try
{
using (var response = await client.SendAsync(request).ConfigureAwait(false))
{
return response.IsSuccessStatusCode;
}
}
catch (HttpRequestException)
{
return false;
}
}
}
}
private async Task<Document> LoadDocumentAsync(DocumentSettings settings, Uri uri, DocumentCategory category, DocumentContextCallback contextCallback)
{
if (uri.IsFile)
{
if (!settings.AccessFlags.HasAllFlags(DocumentAccessFlags.EnableFileLoading))
{
throw new UnauthorizedAccessException("The script engine is not configured for loading documents from the file system");
}
}
else
{
if (!settings.AccessFlags.HasAllFlags(DocumentAccessFlags.EnableWebLoading))
{
throw new UnauthorizedAccessException("The script engine is not configured for downloading documents from the Web");
}
}
var cachedDocument = GetCachedDocument(uri);
if (cachedDocument is not null)
{
return cachedDocument;
}
string contents;
if (uri.IsFile)
{
using (var reader = new StreamReader(uri.LocalPath))
{
contents = await reader.ReadToEndAsync().ConfigureAwait(false);
}
}
else
{
using (var client = new HttpClient(HttpClientHandlerFactory()))
{
contents = await client.GetStringAsync(uri).ConfigureAwait(false);
}
}
var documentInfo = new DocumentInfo(uri) { Category = category, ContextCallback = contextCallback };
if (!settings.AccessFlags.HasAllFlags(DocumentAccessFlags.UseAsyncLoadCallback))
{
var callback = settings.LoadCallback;
callback?.Invoke(ref documentInfo);
}
else
{
var callback = settings.AsyncLoadCallback;
if (callback is not null)
{
var documentInfoRef = ValueRef.Create(documentInfo);
await callback(documentInfoRef, new MemoryStream(Encoding.UTF8.GetBytes(contents), false)).ConfigureAwait(false);
documentInfo = documentInfoRef.Value;
}
}
var document = CacheDocument(new StringDocument(documentInfo, contents), false);
var expectedCategory = category ?? DocumentCategory.Script;
if (!settings.AccessFlags.HasAllFlags(DocumentAccessFlags.AllowCategoryMismatch) && (documentInfo.Category != expectedCategory))
{
throw new FileLoadException($"Document category mismatch: '{expectedCategory}' expected, '{documentInfo.Category}' loaded", uri.IsFile ? uri.LocalPath : uri.AbsoluteUri);
}
return document;
}
#region DocumentLoader overrides
/// <inheritdoc/>
public override uint MaxCacheSize { get; set; } = 1024;
/// <inheritdoc/>
public override async Task<Document> LoadDocumentAsync(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier, DocumentCategory category, DocumentContextCallback contextCallback)
{
MiscHelpers.VerifyNonNullArgument(settings, nameof(settings));
MiscHelpers.VerifyNonBlankArgument(specifier, nameof(specifier), "Invalid document specifier");
if ((settings.AccessFlags & DocumentAccessFlags.EnableAllLoading) == DocumentAccessFlags.None)
{
throw new UnauthorizedAccessException("The script engine is not configured for loading documents");
}
if (category is null)
{
category = sourceInfo.HasValue ? sourceInfo.Value.Category : DocumentCategory.Script;
}
(Document Document, List<Uri> CandidateUris) result;
if (Uri.TryCreate(specifier, UriKind.RelativeOrAbsolute, out var uri) && uri.IsAbsoluteUri)
{
result = await GetCachedDocumentOrCandidateUrisAsync(settings, sourceInfo, uri).ConfigureAwait(false);
}
else
{
result = await GetCachedDocumentOrCandidateUrisAsync(settings, sourceInfo, specifier).ConfigureAwait(false);
}
if (result.Document is not null)
{
return result.Document;
}
if (result.CandidateUris.Count < 1)
{
throw new FileNotFoundException(null, specifier);
}
if (result.CandidateUris.Count == 1)
{
return await LoadDocumentAsync(settings, result.CandidateUris[0], category, contextCallback).ConfigureAwait(false);
}
var exceptions = new List<Exception>(result.CandidateUris.Count);
foreach (var candidateUri in result.CandidateUris)
{
var task = LoadDocumentAsync(settings, candidateUri, category, contextCallback);
try
{
return await task.ConfigureAwait(false);
}
catch (Exception exception)
{
if ((task.Exception is not null) && task.Exception.InnerExceptions.Count == 1)
{
Debug.Assert(ReferenceEquals(task.Exception.InnerExceptions[0], exception));
exceptions.Add(exception);
}
else
{
exceptions.Add(task.Exception);
}
}
}
if (exceptions.Count < 1)
{
MiscHelpers.AssertUnreachable();
throw new FileNotFoundException(null, specifier);
}
if (exceptions.Count == 1)
{
MiscHelpers.AssertUnreachable();
throw new FileLoadException(exceptions[0].Message, specifier, exceptions[0]);
}
throw new AggregateException(exceptions).Flatten();
}
/// <inheritdoc/>
public override Document GetCachedDocument(Uri uri)
{
lock (cache)
{
for (var index = 0; index < cache.Count; index++)
{
var cachedDocument = cache[index];
if (cachedDocument.Info.Uri == uri)
{
cache.RemoveAt(index);
cache.Insert(0, cachedDocument);
return cachedDocument;
}
}
return null;
}
}
/// <inheritdoc/>
public override Document CacheDocument(Document document, bool replace)
{
MiscHelpers.VerifyNonNullArgument(document, nameof(document));
if ((document.Info.Uri is null) || !document.Info.Uri.IsAbsoluteUri)
{
throw new ArgumentException("The document must have an absolute URI", nameof(document));
}
lock (cache)
{
for (var index = 0; index < cache.Count;)
{
var cachedDocument = cache[index];
if (cachedDocument.Info.Uri != document.Info.Uri)
{
index++;
}
else
{
if (!replace)
{
Debug.Assert(cachedDocument.Contents.ReadToEnd().SequenceEqual(document.Contents.ReadToEnd()));
return cachedDocument;
}
cache.RemoveAt(index);
}
}
var maxCacheSize = Math.Max(16, Convert.ToInt32(Math.Min(MaxCacheSize, int.MaxValue)));
while (cache.Count >= maxCacheSize)
{
cache.RemoveAt(cache.Count - 1);
}
cache.Insert(0, document);
return document;
}
}
/// <inheritdoc/>
public override void DiscardCachedDocuments()
{
lock (cache)
{
cache.Clear();
}
}
#endregion
#region IStatistics implementation
long IStatistics.FileCheckCount => Interlocked.Read(ref fileCheckCount);
long IStatistics.WebCheckCount => Interlocked.Read(ref webCheckCount);
void IStatistics.ResetCheckCounts()
{
Interlocked.Exchange(ref fileCheckCount, 0);
Interlocked.Exchange(ref webCheckCount, 0);
}
#endregion
}
}