dotnet - add locking since the simulator seems to run a lot in parallel

change the port to match what the simulator uses by default

add serilog as part of debugging
This commit is contained in:
2026-08-06 15:54:07 -05:00
parent 9a1664bdbb
commit 459b90dcd7
6 changed files with 117 additions and 29 deletions
+8
View File
@@ -16,6 +16,7 @@ public sealed class KnownDevices
public sealed class DeviceHeartBeatHistory
{
private readonly Lock _lock = new();
public enum AddResult { Added, OutOfSequence }
@@ -25,6 +26,8 @@ public sealed class DeviceHeartBeatHistory
public AddResult Add(DateTimeOffset sentAt)
{
lock (_lock)
{
// Reject heartbeats that arrive before the latest registered time.
// Gaps are fine: uptime can be derived from first, last, and count.
@@ -44,19 +47,24 @@ public sealed class DeviceHeartBeatHistory
NumberOfHeartBeats++;
return AddResult.Added;
}
}
}
public sealed class HeartBeatHistories
{
private readonly ConcurrentDictionary<DeviceId, DeviceHeartBeatHistory> _histories = new();
private readonly Lock _lock = new ();
public DeviceHeartBeatHistory.AddResult Add(DeviceId deviceId, DateTimeOffset sentAt)
{
if (!_histories.TryGetValue(deviceId, out var history))
{
lock (_lock)
{
history = new();
_histories[deviceId] = history;
}
}
return history.Add(sentAt);
}
+76 -6
View File
@@ -1,15 +1,23 @@
using SafelyYou;
using SafelyYou.Api;
using Serilog;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
builder.Services.AddSerilog();
builder.Services.AddOpenApi();
builder.Services.AddSingleton<KnownDevices>(_ =>
{
var deviceIds = File.ReadAllLines("/devices.csv").Skip(1).Select(id => new DeviceId(id)).ToHashSet();
var deviceIds = File.ReadAllLines("./devices.csv").Skip(1).Select(id => new DeviceId(id)).ToHashSet();
Log.Logger.Information("@deviceIds", deviceIds);
return new KnownDevices(deviceIds);
});
@@ -17,6 +25,7 @@ builder.Services.AddSingleton<HeartBeatHistories>();
builder.Services.AddSingleton<UploadTimes>();
var app = builder.Build();
app.UseSerilogRequestLogging();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
@@ -24,12 +33,12 @@ if (app.Environment.IsDevelopment())
app.MapOpenApi();
}
app.UseHttpsRedirection();
//app.UseHttpsRedirection();
// heartbeat history
// upload stats
app.MapPost("/devices/{deviceId}/heartbeat", (string deviceId, HeartbeatRequest request,
app.MapPost("api/v1/devices/{deviceId}/heartbeat", (string deviceId, HeartbeatRequest request,
KnownDevices knownDevices, HeartBeatHistories histories) =>
{
var device = new DeviceId(deviceId);
@@ -49,7 +58,7 @@ app.MapPost("/devices/{deviceId}/heartbeat", (string deviceId, HeartbeatRequest
};
});
app.MapPost("/devices/{deviceId}/stats", (string deviceId, UploadStatsRequest request, KnownDevices knownDevices, UploadTimes uploadTimes) =>
app.MapPost("api/v1/devices/{deviceId}/stats", (string deviceId, UploadStatsRequest request, KnownDevices knownDevices, UploadTimes uploadTimes) =>
{
var device = new DeviceId(deviceId);
if (!knownDevices.Contains(device))
@@ -62,9 +71,10 @@ app.MapPost("/devices/{deviceId}/stats", (string deviceId, UploadStatsRequest re
return Results.NoContent();
// not sure where the 500 would go here beyond doing a try/catch
// note: sent_at isn't used here since the data is a short-cut of aggregation, so it's dropped.
});
app.MapGet("/devices/{deviceId}/stats", (string deviceId, KnownDevices knownDevices, HeartBeatHistories histories, UploadTimes uploadTimes) =>
app.MapGet("api/v1/devices/{deviceId}/stats", (string deviceId, KnownDevices knownDevices, HeartBeatHistories histories, UploadTimes uploadTimes) =>
{
var device = new DeviceId(deviceId);
if (!knownDevices.Contains(device))
@@ -73,7 +83,7 @@ app.MapGet("/devices/{deviceId}/stats", (string deviceId, KnownDevices knownDevi
}
var averageUploadTimeNanos = uploadTimes.AverageUploadTimeNanoseconds(device);
var timeSpanText = TimeSpan.FromTicks((long)(averageUploadTimeNanos / 100)).ToString(@"m\ms\s"); // loses accuracy on the Go nanos for this text conversion
var timeSpanText = FormatAsGoDuration(averageUploadTimeNanos);
var uptime = histories.Uptime(device);
return Results.Ok(new GetDeviceStatsResponse(timeSpanText, uptime));
@@ -84,3 +94,63 @@ app.MapGet("/devices/{deviceId}/stats", (string deviceId, KnownDevices knownDevi
app.Run();
// Matches Go's time.Duration.String() (e.g. "3m17.331667813s").
static string FormatAsGoDuration(System.Numerics.BigInteger nanos)
{
if (nanos <= 0) return "0s";
var u = (ulong)nanos;
Span<char> buf = stackalloc char[32];
var w = buf.Length;
// Fractional seconds from nanoseconds, omitting trailing zeros — same as Go fmtFrac(..., 9).
var frac = u % 1_000_000_000UL;
u /= 1_000_000_000UL;
buf[--w] = 's';
if (frac != 0)
{
var print = false;
for (var i = 0; i < 9; i++)
{
var digit = frac % 10;
frac /= 10;
if (digit != 0) print = true;
if (print) buf[--w] = (char)('0' + digit);
}
buf[--w] = '.';
}
var secs = u % 60;
u /= 60;
do
{
buf[--w] = (char)('0' + secs % 10);
secs /= 10;
} while (secs > 0);
if (u > 0)
{
buf[--w] = 'm';
var mins = u % 60;
u /= 60;
do
{
buf[--w] = (char)('0' + mins % 10);
mins /= 10;
} while (mins > 0);
if (u > 0)
{
buf[--w] = 'h';
do
{
buf[--w] = (char)('0' + u % 10);
u /= 10;
} while (u > 0);
}
}
return new string(buf[w..]);
}
@@ -5,7 +5,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5213",
"applicationUrl": "http://localhost:6733",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -14,7 +14,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7175;http://localhost:5213",
"applicationUrl": "https://localhost:7175;http://localhost:6734",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
+3
View File
@@ -8,6 +8,9 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.7" />
<PackageReference Include="Serilog" Version="4.4.0" />
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
</ItemGroup>
<ItemGroup>
+5 -2
View File
@@ -1,6 +1,9 @@
@SafelyYou_HostAddress = http://localhost:5213
@SafelyYou_HostAddress = http://localhost:6733/api
GET {{SafelyYou_HostAddress}}/weatherforecast/
POST {{SafelyYou_HostAddress}}/devices/38-4e-73-e0-33-59/heartbeat
Accept: application/json
{
"sent_at": "2026-08-06T16:51:22.861Z"
}
###
+4
View File
@@ -5,9 +5,12 @@ namespace SafelyYou;
public sealed class UploadTimes
{
private readonly Lock _lock = new();
private readonly ConcurrentDictionary<DeviceId, (BigInteger TotalUploadTime, int UploadCounts)> _uploadHistories = new();
public void Add(DeviceId deviceId, BigInteger uploadTimeNanos)
{
lock (_lock)
{
if (!_uploadHistories.TryGetValue(deviceId, out var history))
{
@@ -16,6 +19,7 @@ public sealed class UploadTimes
_uploadHistories[deviceId] = (history.TotalUploadTime + uploadTimeNanos, history.UploadCounts + 1);
}
}
public BigInteger AverageUploadTimeNanoseconds(DeviceId deviceId)
{