forked from datalust/seqcli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppContainer.cs
More file actions
204 lines (169 loc) · 6.76 KB
/
AppContainer.cs
File metadata and controls
204 lines (169 loc) · 6.76 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
// Copyright © Datalust Pty Ltd and Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Seq.Apps;
using Seq.Apps.LogEvents;
using SeqCli.Mapping;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Compact.Reader;
// ReSharper disable IdentifierTypo, StringLiteralTypo, SuspiciousTypeConversion.Global
namespace SeqCli.Apps.Hosting;
partial class AppContainer : IAppHost, IDisposable
{
readonly SeqApp _seqApp;
readonly AppLoader _loader;
static readonly Regex HexDigits = HexDigitsRegex();
readonly JsonSerializer _serializer = JsonSerializer.Create(new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.None,
Culture = CultureInfo.InvariantCulture
});
public AppContainer(
ILogger logger,
string packageBinaryPath,
App app,
Host host,
string? seqAppTypeName = null)
{
if (packageBinaryPath == null) throw new ArgumentNullException(nameof(packageBinaryPath));
Logger = logger ?? throw new ArgumentNullException(nameof(logger));
App = app ?? throw new ArgumentNullException(nameof(app));
Host = host ?? throw new ArgumentNullException(nameof(host));
_loader = new AppLoader(packageBinaryPath);
if (!_loader.TryLoadSeqAppType(seqAppTypeName, out var seqAppType))
throw new ArgumentException($"The Seq app type `{seqAppTypeName}` could not be loaded.");
_seqApp = AppActivator.CreateInstance(seqAppType, App.Title, App.Settings);
_seqApp.Attach(this);
}
public App App { get; }
public ILogger Logger { get; }
public Host Host { get; }
public string StoragePath => App.StoragePath;
public void Dispose()
{
(_seqApp as IDisposable)?.Dispose();
_loader.Dispose();
}
public async Task SendAsync(string clef)
{
if (clef == null) throw new ArgumentNullException(nameof(clef));
if (_seqApp is ISubscribeToJsonAsync jled)
{
// Shorter, cheaper path for the "modern" interface
try
{
await jled.OnAsync(clef);
}
catch (Exception ex)
{
ReadSerilogEvent(clef, out var eventId, out _);
Logger.Error(ex, "The event {EventId} could not be sent to {AppInstanceTitle}.", eventId, App.Title);
}
}
else
{
await SendTypedEventAsync(clef);
}
}
async Task SendTypedEventAsync(string clef)
{
var serilogEvent = ReadSerilogEvent(clef, out var eventId, out var eventType);
try
{
if (_seqApp is ISubscribeTo<LogEventData> led)
{
led.On(EventFormat.FromRaw(eventId, eventType, serilogEvent));
}
else if (_seqApp is ISubscribeToAsync<LogEventData> leda)
{
await leda.OnAsync(EventFormat.FromRaw(eventId, eventType, serilogEvent));
}
else if (_seqApp is ISubscribeTo<LogEvent> sled)
{
sled.On(new Event<LogEvent>(eventId, eventType, serilogEvent.Timestamp.UtcDateTime, serilogEvent));
}
else if (_seqApp is ISubscribeToAsync<LogEvent> sleda)
{
await sleda.OnAsync(new Event<LogEvent>(eventId, eventType, serilogEvent.Timestamp.UtcDateTime, serilogEvent));
}
else
{
throw new SeqAppException("The app doesn't support any recognized subscriber interfaces.");
}
}
catch (Exception ex)
{
Logger.Error(ex, "The event {EventId} could not be sent to {AppInstanceTitle}.", eventId, App.Title);
}
}
LogEvent ReadSerilogEvent(string clef, out string eventId, out uint eventType)
{
var jvalue = new JsonTextReader(new StringReader(clef));
if (!(_serializer.Deserialize<JToken>(jvalue) is JObject jobject))
throw new InvalidDataException($"The line is not a JSON object: `{clef.Trim()}`.");
if (jobject.TryGetValue("@l", out var levelToken))
{
jobject.Remove("@l");
jobject.Add("@l", new JValue(LevelMapping.ToSerilogLevel(levelToken.Value<string>()!).ToString()));
}
SanitizeTraceIdentifiers(jobject);
var raw = LogEventReader.ReadFromJObject(jobject);
eventId = "event-0";
if (raw.Properties.TryGetValue("@seqid", out var id) &&
id is ScalarValue {Value: string sid})
eventId = sid;
eventType = 0u;
if (raw.Properties.TryGetValue("@i", out var et) &&
et is ScalarValue {Value: string set} && uint.TryParse(set, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var uet))
eventType = uet;
return raw;
}
internal static void SanitizeTraceIdentifiers(JObject jobject)
{
// Serilog.Formatting.Compact.Reader constructs LogEvents which use the System.Diagnostics ActivityTraceId
// and ActivitySpanId types; these throw when constructed with invalid inputs.
if (jobject.TryGetValue("@tr", out var traceIdToken) && !IsValidHexIdentifier(traceIdToken, 32))
jobject.Remove("@tr");
if (jobject.TryGetValue("@sp", out var spanIdToken) && !IsValidHexIdentifier(spanIdToken, 16))
jobject.Remove("@sp");
if (jobject.TryGetValue("@ps", out var parentSpanIdToken) && !IsValidHexIdentifier(parentSpanIdToken, 16))
jobject.Remove("@ps");
}
static bool IsValidHexIdentifier(JToken? value, int requiredChars)
{
if (value?.Value<string>() is not { } id)
return false;
return id.Length == requiredChars && HexDigits.IsMatch(id);
}
public void StartPublishing(TextWriter inputWriter)
{
if (_seqApp is IPublishJson pjson)
pjson.Start(inputWriter);
}
public void StopPublishing()
{
if (_seqApp is IPublishJson pjson)
pjson.Stop();
}
// Technically,
[GeneratedRegex("^[0-9a-f]*$")]
private static partial Regex HexDigitsRegex();
}