-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
executable file
·164 lines (136 loc) · 4.77 KB
/
Program.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
using Microsoft.AspNetCore.HttpOverrides;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
builder.Host.ConfigureLogging(logging =>
{
logging.ClearProviders();
if (builder.Environment.IsProduction())
{
logging.AddFile("logs/{Date}.txt");
}
else
{
logging.AddConsole();
}
});
var app = builder.Build();
string script = System.IO.File.ReadAllText("get-commits.sh");
string scriptStatic = System.IO.File.ReadAllText("get-local-commits.sh");
var clients = new Dictionary<string, Client>();
Func<Task<UInt32>> intializeGeneratedReports = async () =>
{
UInt32 generatedReports = 0;
if (!File.Exists("generated-reports-number.txt")) return generatedReports;
var content = await File.ReadAllTextAsync("generated-reports-number.txt");
if (content == null) return generatedReports;
UInt32.TryParse(content, out generatedReports);
return generatedReports;
};
UInt32 generatedReports = await intializeGeneratedReports();
app.Logger.LogInformation($"Intialize local state with {generatedReports} generated reports");
System.AppDomain.CurrentDomain.ProcessExit += (object? sender, EventArgs e) =>
{
File.WriteAllText("generated-reports-number.txt", generatedReports.ToString());
app.Logger.LogInformation($"Stored {generatedReports} generated reports before exit");
};
app.MapGet("/status", async (context) =>
{
await context.Response.WriteAsJsonAsync(new
{
status = "OK",
date = DateTime.Now,
sessionId = context.Session.Id,
clients = clients.Count,
memory = System.GC.GetTotalMemory(true) / 1000,
generatedReports = generatedReports,
});
});
var clearClient = (string id) =>
{
var client = clients[id];
if (client == null)
{
app.Logger.LogWarning($"No client found for {id}");
return;
}
if (client.CommitsFile != null)
{
client.CommitsFile.Dispose();
app.Logger.LogInformation($"Deleted commits for {id}");
}
else
{
app.Logger.LogInformation($"No commits to delete for {id}");
}
clients.Remove(id);
};
app.MapGet("/see", async (context) =>
{
await context.Session.LoadAsync();
string id = context.Session.Id;
await context.SSEInitAsync();
app.Logger.LogInformation($"User {id} opened event stream");
await context.SSESendEventAsync(new SSEEvent("init") { Id = id, Retry = 10 });
clients.Add(id, new Client(context));
context.RequestAborted.Register(() =>
{
app.Logger.LogInformation($"User {id} closed event stream");
clearClient(id);
});
// Keep connection open and send periodic message while client doesnt cancel request
while (!context.RequestAborted.IsCancellationRequested)
{
await context.SSESendEventAsync(new SSEEvent("waiting-commits") { Id = id, Retry = 10 });
// ContinueWith allow to avoid error throwing
await Task.Delay(10_000, context.RequestAborted).ContinueWith(task => { });
}
});
app.MapGet("/script/{id}", async (HttpContext context, string id) =>
{
var userScript = script.Replace("{{ID}}", id);
await context.Response.WriteAsync(userScript);
});
app.MapGet("/script/static", async (HttpContext context) =>
{
await context.Response.WriteAsync(scriptStatic);
});
app.MapPost("/commits", async (context) =>
{
string id = context.Request.Headers["EventStreamId"];
if (string.IsNullOrEmpty(id)) { await Results.BadRequest().ExecuteAsync(context); return; }
var client = clients[id];
if (client == null) { await Results.Unauthorized().ExecuteAsync(context); return; }
var commitsFile = context.Request.Form.Files[0];
if (commitsFile == null) { await Results.BadRequest().ExecuteAsync(context); return; }
await client.Context.SSESendEventAsync(
new SSEEvent("commits-received") { Id = id, Retry = 10 }
);
// Copy received file to the client and reset stream position for reading
client.CommitsFile = new MemoryStream();
await commitsFile.CopyToAsync(client.CommitsFile);
client.CommitsFile.Position = 0;
app.Logger.LogInformation($"Commits received from {id}");
generatedReports += 1;
await client.Context.SSESendEventAsync(
new SSEEvent("commits-ready") { Id = id, Retry = 10 }
);
});
app.MapGet("/get-commits/{id}", async (HttpContext context, string id) =>
{
var client = clients[id];
if (client == null) { await Results.Unauthorized().ExecuteAsync(context); return; }
if (client.CommitsFile == null) { await Results.NotFound().ExecuteAsync(context); return; }
await Results.File(client.CommitsFile, "application/octet-stream").ExecuteAsync(context);
});
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseSession();
app.Run();