Skip to content

Commit cd75a91

Browse files
committed
Minor changes
1 parent c5382b1 commit cd75a91

10 files changed

Lines changed: 55 additions & 57 deletions

Apps/LogExporterApp/App.cs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ public Task InitializeAsync(IDnsServer dnsServer, string config)
123123
_config = AppConfig.Deserialize(config)
124124
?? throw new DnsClientException("Invalid application configuration.");
125125

126-
ConfigureStrategies();
126+
ConfigureExport();
127127

128128
// If no sinks exist, never enable logging.
129129
if (!_exportManager.HasStrategy())
@@ -161,16 +161,16 @@ public Task InsertLogAsync(DateTime timestamp, DnsDatagram request,
161161
{
162162
if (_enableLogging)
163163
{
164-
var entry = new LogEntry(timestamp, remoteEP, protocol, request, response, _config!.EnableEdnsLogging);
164+
LogEntry entry = new LogEntry(timestamp, remoteEP, protocol, request, response, _config!.EnableEdnsLogging);
165165

166166
if (!_channel.Writer.TryWrite(entry))
167167
{
168168
Interlocked.Increment(ref _droppedCount);
169169

170-
var now = DateTime.UtcNow;
170+
DateTime now = DateTime.UtcNow;
171171
if (now - _lastDropLog >= DropLogInterval)
172172
{
173-
var dropped = Interlocked.Exchange(ref _droppedCount, 0);
173+
long dropped = Interlocked.Exchange(ref _droppedCount, 0);
174174
_lastDropLog = now;
175175
_dnsServer?.WriteLog($"Log export queue full; dropped {dropped} entries over last {DropLogInterval.TotalSeconds:F0}s.");
176176
}
@@ -187,14 +187,14 @@ public Task InsertLogAsync(DateTime timestamp, DnsDatagram request,
187187
private async Task BackgroundWorkerAsync(CancellationToken token)
188188
{
189189
// ADR: Reuse this list buffer to avoid GC churn during high-volume logging.
190-
var batch = new List<LogEntry>(BULK_INSERT_COUNT);
190+
List<LogEntry> batch = new List<LogEntry>(BULK_INSERT_COUNT);
191191

192192
try
193193
{
194194
while (await _channel.Reader.WaitToReadAsync(token).ConfigureAwait(false))
195195
{
196196
while (batch.Count < BULK_INSERT_COUNT &&
197-
_channel.Reader.TryRead(out var entry))
197+
_channel.Reader.TryRead(out LogEntry? entry))
198198
{
199199
if (token.IsCancellationRequested)
200200
break;
@@ -204,7 +204,7 @@ private async Task BackgroundWorkerAsync(CancellationToken token)
204204

205205
if (batch.Count > 0)
206206
{
207-
await _exportManager.ImplementStrategyAsync(batch, token).ConfigureAwait(false);
207+
await _exportManager.UseStrategyAsync(batch, token).ConfigureAwait(false);
208208
batch.Clear(); // REUSE — do not reassign
209209
}
210210
}
@@ -220,7 +220,7 @@ private async Task BackgroundWorkerAsync(CancellationToken token)
220220
}
221221
}
222222

223-
private void ConfigureStrategies()
223+
private void ConfigureExport()
224224
{
225225
_exportManager.RemoveStrategy(typeof(ConsoleExportStrategy));
226226
if (_config!.ConsoleTarget != null && _config.ConsoleTarget.Enabled)
@@ -247,7 +247,7 @@ private async Task DrainRemainingLogs(List<LogEntry> batch, CancellationToken to
247247
{
248248
try
249249
{
250-
while (_channel!.Reader.TryRead(out var item))
250+
while (_channel!.Reader.TryRead(out LogEntry? item))
251251
{
252252
if (token.IsCancellationRequested)
253253
break;
@@ -256,14 +256,14 @@ private async Task DrainRemainingLogs(List<LogEntry> batch, CancellationToken to
256256

257257
if (batch.Count >= BULK_INSERT_COUNT)
258258
{
259-
await _exportManager.ImplementStrategyAsync(batch, token).ConfigureAwait(false);
259+
await _exportManager.UseStrategyAsync(batch, token).ConfigureAwait(false);
260260
batch.Clear(); // reuse instead of creating new list
261261
}
262262
}
263263

264264
if (batch.Count > 0 && !token.IsCancellationRequested)
265265
{
266-
await _exportManager.ImplementStrategyAsync(batch, token).ConfigureAwait(false);
266+
await _exportManager.UseStrategyAsync(batch, token).ConfigureAwait(false);
267267
batch.Clear();
268268
}
269269
}

Apps/LogExporterApp/AppConfig.cs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,36 +50,37 @@ public class AppConfig
5050

5151
/// <summary>
5252
/// Loads config and enforces DataAnnotations validation.
53-
///
53+
///<para>
5454
/// ADR: Validation is intentionally centralized here so that:
5555
/// - App receives only a fully valid configuration.
5656
/// - Errors surface early with domain-specific messages.
5757
/// - No runtime failures occur deep inside the logging pipeline.
5858
/// This ensures plugin initialization is deterministic and safe.
59+
/// </para>
5960
/// </summary>
6061
public static AppConfig Deserialize(string json)
6162
{
62-
var config = JsonSerializer.Deserialize<AppConfig>(json, DnsConfigSerializerOptions.Default)
63+
AppConfig config = JsonSerializer.Deserialize<AppConfig>(json, DnsConfigSerializerOptions.Default)
6364
?? throw new DnsClientException("Configuration could not be deserialized.");
6465

6566
ValidateObject(config);
6667

6768
// Validate enabled targets only — disabled ones may be incomplete by design.
68-
if (config.FileTarget?.Enabled == true)
69+
if (config.FileTarget?.Enabled is true)
6970
ValidateObject(config.FileTarget);
7071

71-
if (config.HttpTarget?.Enabled == true)
72+
if (config.HttpTarget?.Enabled is true)
7273
ValidateObject(config.HttpTarget);
7374

74-
if (config.SyslogTarget?.Enabled == true)
75+
if (config.SyslogTarget?.Enabled is true)
7576
ValidateObject(config.SyslogTarget);
7677

7778
return config;
7879
}
7980

8081
private static void ValidateObject(object instance)
8182
{
82-
var ctx = new ValidationContext(instance);
83+
ValidationContext ctx = new ValidationContext(instance);
8384
Validator.ValidateObject(instance, ctx, validateAllProperties: true);
8485
}
8586
}

Apps/LogExporterApp/DomainCache.cs

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -60,14 +60,14 @@ public DomainInfo GetOrAdd(string domainName)
6060
return DomainInfo.Empty;
6161

6262
// Fast path: try cache lookup with original name first (case-insensitive)
63-
if (_cache.TryGetValue(domainName, out var node))
63+
if (_cache.TryGetValue(domainName, out CacheNode? node))
6464
{
6565
node.Visited = true;
6666
return node.Domain;
6767
}
6868

6969
// Normalize only if needed, using string pool to reduce allocations
70-
var normalizedName = GetPooledNormalizedName(domainName);
70+
string normalizedName = GetPooledNormalizedName(domainName);
7171

7272
// Check cache again with normalized name (may differ from original)
7373
if (!ReferenceEquals(normalizedName, domainName) &&
@@ -77,7 +77,7 @@ public DomainInfo GetOrAdd(string domainName)
7777
return node.Domain;
7878
}
7979

80-
var domain = Parse(domainName);
80+
DomainInfo domain = Parse(domainName);
8181
AddToCache(normalizedName, domain);
8282
return domain;
8383
}
@@ -91,10 +91,10 @@ private string GetPooledNormalizedName(string name)
9191
if (!NeedsNormalization(name))
9292
return name;
9393

94-
var normalized = name.ToLowerInvariant().TrimEnd('.');
94+
string normalized = name.ToLowerInvariant().TrimEnd('.');
9595

9696
// Try to get from pool, or add if not present
97-
if (_stringPool.TryGetValue(normalized, out var pooled))
97+
if (_stringPool.TryGetValue(normalized, out string? pooled))
9898
return pooled;
9999

100100
// Limit pool size to prevent unbounded growth
@@ -125,13 +125,13 @@ private static bool NeedsNormalization(string name)
125125

126126
private static DomainInfo Parse(string name)
127127
{
128-
var parser = _parser.Value;
128+
DomainParser? parser = _parser.Value;
129129
if (parser == null)
130130
return DomainInfo.Empty;
131131

132132
try
133133
{
134-
var info = parser.Parse(name);
134+
Nager.PublicSuffix.DomainInfo? info = parser.Parse(name);
135135
if (info == null)
136136
return DomainInfo.Empty;
137137

@@ -159,7 +159,7 @@ private static DomainInfo Parse(string name)
159159
// - If it fails, we return null and logging continues without PSL data.
160160
try
161161
{
162-
var provider = new SimpleHttpRuleProvider();
162+
SimpleHttpRuleProvider provider = new SimpleHttpRuleProvider();
163163
provider.BuildAsync().GetAwaiter().GetResult();
164164
return new DomainParser(provider);
165165
}
@@ -179,7 +179,7 @@ private void AddToCache(string key, DomainInfo domain)
179179
while (_cache.Count >= MaxSize)
180180
Evict();
181181

182-
var newNode = new CacheNode(key, domain);
182+
CacheNode newNode = new CacheNode(key, domain);
183183
InsertAtHead(newNode);
184184
_cache[key] = newNode;
185185
}
@@ -195,23 +195,20 @@ private void InsertAtHead(CacheNode node)
195195

196196
_head = node;
197197

198-
if (_tail == null)
199-
_tail = node;
198+
_tail ??= node;
200199

201-
if (_hand == null)
202-
_hand = node;
200+
_hand ??= node;
203201
}
204202

205203
private void Evict()
206204
{
207-
if (_hand == null)
208-
_hand = _tail;
205+
_hand ??= _tail;
209206

210207
while (_hand != null)
211208
{
212209
if (!_hand.Visited)
213210
{
214-
var victim = _hand;
211+
CacheNode victim = _hand;
215212
_hand = _hand.Prev ?? _tail;
216213
RemoveNode(victim);
217214
_cache.TryRemove(victim.Key, out _);

Apps/LogExporterApp/LogEntry.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,14 +97,14 @@ public LogEntry(DateTime timestamp, IPEndPoint remoteEP, DnsTransportProtocol pr
9797
return;
9898
}
9999

100-
var ednsErrors = response.EDNS.Options.Where(o => o.Code == EDnsOptionCode.EXTENDED_DNS_ERROR).ToList();
100+
List<EDnsOption> ednsErrors = response.EDNS.Options.Where(o => o.Code == EDnsOptionCode.EXTENDED_DNS_ERROR).ToList();
101101
if (ednsErrors.Count == 0)
102102
{
103103
EDNS = EmptyEdns;
104104
return;
105105
}
106106

107-
var edns = new List<EDNSLog>(ednsErrors.Count);
107+
List<EDNSLog> edns = new List<EDNSLog>(ednsErrors.Count);
108108
foreach (EDnsOption extendedErrorLog in ednsErrors)
109109
{
110110
// ADR: EDNS extended error comes from network input and may not follow
@@ -113,7 +113,7 @@ public LogEntry(DateTime timestamp, IPEndPoint remoteEP, DnsTransportProtocol pr
113113
// allowing remote parties to crash the logging pipeline.
114114
// We now parse defensively and treat malformed data as a best-effort message.
115115

116-
var raw = extendedErrorLog.Data?.ToString();
116+
string? raw = extendedErrorLog.Data?.ToString();
117117
if (string.IsNullOrWhiteSpace(raw))
118118
continue;
119119

@@ -122,7 +122,7 @@ public LogEntry(DateTime timestamp, IPEndPoint remoteEP, DnsTransportProtocol pr
122122
string? errType = null;
123123
string? message = null;
124124

125-
var parts = raw.Split(':', 2, StringSplitOptions.TrimEntries);
125+
string[] parts = raw.Split(':', 2, StringSplitOptions.TrimEntries);
126126
if (parts.Length == 2)
127127
{
128128
errType = parts[0];

Apps/LogExporterApp/Strategy/ConsoleExportStrategy.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ public async Task ExportAsync(IReadOnlyList<LogEntry> logs, CancellationToken to
5555
if (_disposed || logs.Count == 0 || token.IsCancellationRequested)
5656
return;
5757

58-
using var ms = _memoryManager.GetStream("ConsoleExport-Batch");
58+
using RecyclableMemoryStream ms = _memoryManager.GetStream("ConsoleExport-Batch");
5959
NdjsonSerializer.WriteBatch(ms, logs);
6060

6161
ms.Position = 0;

Apps/LogExporterApp/Strategy/ExportManager.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ public void Dispose()
5050
// removed. Leaving them in the dictionary creates a misleading state
5151
// (“manager has strategies”) and allows accidental use-after-dispose.
5252
// Clearing ensures the manager becomes inert and conveys finality.
53-
foreach (var entry in _exportStrategies)
53+
foreach (KeyValuePair<Type, IExportStrategy> entry in _exportStrategies)
5454
entry.Value.Dispose();
5555

5656
_exportStrategies.Clear();
@@ -93,14 +93,14 @@ public bool HasStrategy()
9393
/// continues after shutdown. Strategies are responsible for honoring
9494
/// cancellation so shutdown stays bounded.
9595
/// </summary>
96-
public async Task ImplementStrategyAsync(IReadOnlyList<LogEntry> logs, CancellationToken token)
96+
public async Task UseStrategyAsync(IReadOnlyList<LogEntry> logs, CancellationToken token)
9797
{
9898
if (_disposed || logs == null || logs.Count == 0 || _exportStrategies.IsEmpty)
9999
return;
100100

101-
var tasks = new List<Task>(_exportStrategies.Count);
101+
List<Task> tasks = new List<Task>(_exportStrategies.Count);
102102

103-
foreach (var strategy in _exportStrategies.Values)
103+
foreach (IExportStrategy strategy in _exportStrategies.Values)
104104
tasks.Add(strategy.ExportAsync(logs, token));
105105

106106
await Task.WhenAll(tasks).ConfigureAwait(false);

Apps/LogExporterApp/Strategy/FileExportStrategy.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public async Task ExportAsync(IReadOnlyList<LogEntry> logs, CancellationToken to
8080
if (_disposed || logs.Count == 0 || token.IsCancellationRequested)
8181
return;
8282

83-
using var ms = _memoryManager.GetStream("FileExport-Batch");
83+
using RecyclableMemoryStream ms = _memoryManager.GetStream("FileExport-Batch");
8484
NdjsonSerializer.WriteBatch(ms, logs);
8585
ms.Position = 0;
8686

Apps/LogExporterApp/Strategy/HttpExportStrategy.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,15 @@ public sealed class HttpExportStrategy : IExportStrategy
4444

4545
public HttpExportStrategy(string endpoint, Dictionary<string, string?>? headers = null)
4646
{
47-
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri))
47+
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? uri))
4848
throw new ArgumentException("Invalid HTTP endpoint.", nameof(endpoint));
4949

5050
_endpoint = uri;
5151
_httpClient = new HttpClient();
5252

5353
if (headers != null)
5454
{
55-
foreach (var kv in headers)
55+
foreach (KeyValuePair<string, string?> kv in headers)
5656
{
5757
if (!_httpClient.DefaultRequestHeaders.TryAddWithoutValidation(kv.Key, kv.Value))
5858
throw new FormatException($"Failed to add HTTP header '{kv.Key}'.");
@@ -86,14 +86,14 @@ public async Task ExportAsync(IReadOnlyList<LogEntry> logs, CancellationToken to
8686
if (_disposed || logs.Count == 0 || token.IsCancellationRequested)
8787
return;
8888

89-
using var ms = _memoryManager.GetStream("HttpExport-Batch");
89+
using RecyclableMemoryStream ms = _memoryManager.GetStream("HttpExport-Batch");
9090

9191
// Use Stream overload explicitly to avoid ambiguity
9292
NdjsonSerializer.WriteBatch(ms, logs);
9393

9494
ms.Position = 0;
9595

96-
using var content = new StreamContent(ms);
96+
using StreamContent content = new StreamContent(ms);
9797
content.Headers.Add("Content-Type", "application/x-ndjson");
9898

9999
using HttpResponseMessage response = await _httpClient

Apps/LogExporterApp/Strategy/NdjsonSerializer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public static class NdjsonSerializer
1515
{
1616
public static void WriteBatch(Stream target, IReadOnlyList<LogEntry> logs)
1717
{
18-
using var writer = new Utf8JsonWriter(target, new JsonWriterOptions
18+
using Utf8JsonWriter writer = new Utf8JsonWriter(target, new JsonWriterOptions
1919
{
2020
Indented = false,
2121
SkipValidation = true,

0 commit comments

Comments
 (0)