add posting of a heart beat

This commit is contained in:
2026-08-06 12:58:54 -05:00
parent 8af110873b
commit 3b54437269
7 changed files with 362 additions and 0 deletions
+44
View File
@@ -1,9 +1,28 @@
using Microsoft.AspNetCore.Http.HttpResults;
using SafelyYou;
using SafelyYou.Api;
using SafelyYou.Config;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddSingleton<KnownDevices>(_ =>
{
var deviceIds = File.ReadAllLines("/devices.csv").Skip(1).Select(id => new DeviceId(id)).ToHashSet();
return new KnownDevices(deviceIds);
});
builder.Services.AddSingleton<HeartBeatHistoryConfig>(_ =>
{
var millis = builder.Configuration.GetSection("HeartBeatHistory").GetValue<int>("WindowMillis");
return new HeartBeatHistoryConfig() { Window = TimeSpan.FromMilliseconds(millis) };
});
builder.Services.AddSingleton<HeartBeatHistories>();
var app = builder.Build();
// Configure the HTTP request pipeline.
@@ -14,6 +33,31 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection();
// heartbeat history
// upload stats
app.MapPost("/devices/{deviceId}/heartbeat", (string deviceId, HeartbeatRequest request,
KnownDevices knownDevices, HeartBeatHistories histories) =>
{
var device = new DeviceId(deviceId);
if (!knownDevices.Contains(device))
{
return Results.NotFound(new NotFoundResponse($"Device ID {deviceId} not found"));
}
var addResult = histories.Add(device, request.SentAt);
return addResult switch
{
DeviceHeartBeatHistory.AddResult.Added => Results.Ok(),
DeviceHeartBeatHistory.AddResult.OutOfSequence => Results.InternalServerError(
new ErrorResponse("Attempted to add a timestamp that was out of sequence or invalid.")),
_ => throw new ArgumentOutOfRangeException()
};
});
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"