forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHotReloadFeature.cs
More file actions
65 lines (55 loc) · 2.17 KB
/
Copy pathHotReloadFeature.cs
File metadata and controls
65 lines (55 loc) · 2.17 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
using System;
using System.Threading.Tasks;
using ServiceStack.DataAnnotations;
namespace ServiceStack
{
/// <summary>
/// Back-end Service used by /js/hot-fileloader.js to detect file changes in /wwwroot and auto reload page.
/// </summary>
public class HotReloadFeature : IPlugin
{
public void Register(IAppHost appHost)
{
appHost.RegisterService(typeof(HotReloadFilesService));
}
}
[ExcludeMetadata]
[Route("/hotreload/files")]
public class HotReloadFiles : IReturn<HotReloadPageResponse>
{
public string Pattern { get; set; }
public string ETag { get; set; }
}
[DefaultRequest(typeof(HotReloadFiles))]
[Restrict(VisibilityTo = RequestAttributes.None)]
public class HotReloadFilesService : Service
{
public static TimeSpan LongPollDuration = TimeSpan.FromSeconds(60);
public static TimeSpan CheckDelay = TimeSpan.FromMilliseconds(50);
public async Task<HotReloadPageResponse> Any(HotReloadFiles request)
{
var pattern = request.Pattern ?? "*";
var startedAt = DateTime.UtcNow;
var maxLastModified = DateTime.MinValue;
var shouldReload = false;
while (DateTime.UtcNow - startedAt < LongPollDuration)
{
maxLastModified = DateTime.MinValue;
var files = VirtualFileSources.GetAllMatchingFiles(pattern);
foreach (var file in files)
{
file.Refresh();
if (file.LastModified > maxLastModified)
maxLastModified = file.LastModified;
}
if (string.IsNullOrEmpty(request.ETag))
return new HotReloadPageResponse { ETag = maxLastModified.Ticks.ToString() };
shouldReload = maxLastModified != DateTime.MinValue && maxLastModified.Ticks > long.Parse(request.ETag);
if (shouldReload)
break;
await Task.Delay(CheckDelay);
}
return new HotReloadPageResponse { Reload = shouldReload, ETag = maxLastModified.Ticks.ToString() };
}
}
}