-
Notifications
You must be signed in to change notification settings - Fork 4
/
Program.cs
192 lines (166 loc) · 7.35 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
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Npgsql;
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using watchtower.Code;
using watchtower.Code.DiscordInteractions;
using watchtower.Code.ExtensionMethods;
using watchtower.Code.Tracking;
using watchtower.Models;
using watchtower.Services;
using watchtower.Services.Repositories.PSB;
namespace watchtower {
public class Program {
// Is set in main
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
private static IHost _Host;
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
private static void PrintD(string name, DateTime d) {
DateTimeOffset doo = new DateTimeOffset(d);
Console.WriteLine($"{name} => {d:u} ({d.Kind}) {doo:u} ({doo.Offset}) {doo.ToUnixTimeSeconds()} {d.GetDiscordFullTimestamp()}");
}
public static async Task Main(string[] args) {
Console.WriteLine($"Honu starting at {DateTime.UtcNow:u}");
// mitigation for https://github.com/advisories/GHSA-5crp-9r3c-p9vr
JsonConvert.DefaultSettings = () => new JsonSerializerSettings() {
MaxDepth = 128
};
bool hostBuilt = false;
CancellationTokenSource stopSource = new();
using TracerProvider? trace = Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("npgsql"))
.AddAspNetCoreInstrumentation(options => {
// only profile api calls
options.Filter = (c) => {
return c.Request.Path.StartsWithSegments("/api");
};
})
//.AddNpgsql()
.AddJaegerExporter(config => {
})
.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(HonuActivitySource.ActivitySourceName))
.AddSource(HonuActivitySource.ActivitySourceName)
.Build();
// Honu must be started in a background thread, as _Host.RunAsync will block until the whole server
// shuts down. If we were to await this Task, then it would be blocked until the server is done
// running, at which point then the command bus stuff would start
//
// That's not useful, because we want to be able to input commands while the server is running,
// not after the server is done running
_ = Task.Run(async () => {
ILogger<Program>? logger = null;
try {
Stopwatch timer = Stopwatch.StartNew();
_Host = CreateHostBuilder(args).Build();
logger = _Host.Services.GetService(typeof(ILogger<Program>)) as ILogger<Program>;
hostBuilt = true;
Console.WriteLine($"Took {timer.ElapsedMilliseconds}ms to build Honu");
timer.Stop();
} catch (Exception ex) {
if (logger != null) {
logger.LogError(ex, "fatal error starting Honu");
} else {
Console.WriteLine($"Fatal error starting Honu:\n{ex}");
}
}
try {
//await _Host.RunConsoleAsync();
await _Host.RunAsync(stopSource.Token);
} catch (Exception ex) {
if (logger != null) {
logger.LogError(ex, $"error while running honu");
} else {
Console.WriteLine($"error while running honu:\n{ex}");
}
}
});
for (int i = 0; i < 10; ++i) {
await Task.Delay(1000);
if (hostBuilt == true) {
break;
}
}
if (_Host == null) {
Console.Error.WriteLine($"FATAL> _Host was null after construction");
return;
}
ILogger<Program> logger = _Host.Services.GetRequiredService<ILogger<Program>>();
CommandBus? commands = _Host.Services.GetService(typeof(CommandBus)) as CommandBus;
if (commands == null) {
logger.LogError($"missing CommandBus");
Console.Error.WriteLine($"Missing ICommandBus");
}
// print both incase the logger is misconfigured or something
logger.LogInformation($"ran host");
Console.WriteLine($"Ran host");
string? line = "";
bool fastStop = false;
while (line != ".close") {
line = Console.ReadLine();
if (line == ".close" || line == ".closefast") {
if (line == ".closefast") {
fastStop = true;
}
break;
} else {
if (commands == null) {
logger.LogError($"Missing {nameof(CommandBus)} from host, cannot execute '{line}'");
Console.Error.WriteLine($"Missing {nameof(CommandBus)} from host, cannot execute '{line}'");
}
if (line != null && commands != null) {
await commands.Execute(line);
}
}
}
if (fastStop == true) {
logger.LogInformation($"stopping from 1'000ms");
Console.WriteLine($"stopping after 1'000ms");
CancellationTokenSource cts = new();
cts.CancelAfter(1000 * 1);
await _Host.StopAsync(cts.Token);
//stopSource.CancelAfter(1 * 1000);
} else {
Console.WriteLine($"stopping without a token");
//stopSource.Cancel();
await _Host.StopAsync();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) {
IHostBuilder? host = Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging => {
// i don't like any of the provided default loggers
logging.AddConsole(options => options.FormatterName = "HonuLogger")
.AddConsoleFormatter<HonuLogger, HonuFormatterOptions>(options => {
});
})
.ConfigureAppConfiguration(appConfig => {
appConfig.AddUserSecrets<Startup>();
}).ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup<Startup>();
});
return host;
}
}
}