Files
Chronos/src/Titano.Server/Api/AdminEndpoints.cs
T
Claude 9f03c07fdf fix(server): the current log downloads while the server keeps writing it
GET /api/v1/logs/files/{name} served the file with Results.File, which sets
Content-Length from the file's size and then copies it to its end. The current
log grows whenever the server logs, so a line written meanwhile made Kestrel
abort the response ("too many bytes written"); AdminTests failed on it once in
three full runs. The endpoint now sends the bytes the file held when it was
listed through FileResponses.Serve, a fixed-length, range-capable slice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-06 21:19:30 +00:00

114 lines
6.5 KiB
C#

using System.Text;
using Titano.Core.Model;
using Titano.Data;
using Titano.Protocol;
using Titano.Server.Configuration;
using Titano.Server.Jobs;
using Titano.Server.Security;
using Titano.Server.Storage;
namespace Titano.Server.Api;
/// <summary>Administration (BRIEF §14.8): dashboard figures, server settings, log tail and downloads, audit log.</summary>
public static class AdminEndpoints
{
private const int MaxTailLines = 2000;
private const int TailWindowBytes = 1 << 20;
public static void Map(RouteGroupBuilder api)
{
api.MapGet("/server/dashboard", DashboardAsync).Requires(Permissions.ManageArchive | Permissions.ManageUsers);
api.MapGet("/server/settings", (ServerSettingsStore store) => Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto))
.Requires(Permissions.ManageArchive);
api.MapPut("/server/settings", SaveSettingsAsync).Requires(Permissions.ManageArchive);
api.MapGet("/audit", AuditAsync).Requires(Permissions.ManageUsers | Permissions.ManageArchive);
var logs = api.MapGroup("/logs").Requires(Permissions.ManageArchive);
logs.MapGet("", TailAsync);
logs.MapGet("/files", (ServerOptions options) => Results.Json(LogFiles(options).Select(f => new LogFileDto(f.Name, f.Length, f.LastWriteTimeUtc)).ToList(),
ProtocolJson.Default.ListLogFileDto));
logs.MapGet("/files/{name}", (HttpContext context, string name, ServerOptions options) =>
{
// Only names of existing log files are served: the name never becomes part of a path. The current log keeps
// growing while it is sent, so the response holds the bytes it had when listed, as its Content-Length says.
if (LogFiles(options).FirstOrDefault(f => f.Name == name) is not { } file) return ApiErrors.NotFound(context, "log");
return FileResponses.Serve(context, file, 0, file.Length, "text/plain; charset=utf-8", "no-store", downloadName: file.Name)
?? ApiErrors.NotFound(context, "log");
});
}
private static async Task<IResult> DashboardAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, ServerOptions options, ServerState state,
JobEngineHost jobs, TimeProvider time)
{
var ct = context.RequestAborted;
var now = time.GetUtcNow();
var today = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
var users = await db.Users.ListAsync(ct);
var names = users.ToDictionary(u => u.Id, u => u.Username);
var counts = await db.Jobs.CountAsync(today, ct);
var running = await db.Jobs.ListAsync(JobState.Running, null, 10, null, ct);
var queued = await db.Jobs.ListAsync(JobState.Queued, null, 10, null, ct);
var nodes = await db.RenderNodes.ListAsync(ct);
var uploads = await db.Uploads.CommittedPerDayAsync(today.AddDays(-29), ct);
var activity = await db.Audit.ListAsync(null, null, 12, null, ct);
return Results.Json(new DashboardDto(
options.ServerName,
SystemEndpoints.Version,
(long)(now - state.StartedAt).TotalSeconds,
state.Database,
options.TlsMode.ToString().ToLowerInvariant(),
options.Discovery,
users.Count,
await ArchiveEndpoints.StatsAsync(db, archive, ct),
new JobCountsDto(counts.Queued, counts.Running, counts.Paused, counts.DoneSince, counts.FailedSince),
jobs.Workers,
[.. nodes.Select(n => Dto.Node(n, names.GetValueOrDefault(n.UserId, string.Empty)))],
[.. uploads.Select(u => new UploadDayDto(u.Day, u.Count, u.Bytes))],
[.. activity.Items.Select(Dto.Audit)],
[.. running.Items.Concat(queued.Items.OrderByDescending(j => j.Priority).ThenBy(j => j.Created)).Take(10).Select(Dto.Job)]),
ProtocolJson.Default.DashboardDto);
}
private static async Task<IResult> SaveSettingsAsync(HttpContext context, Caller caller, ServerSettingsDto request, ServerSettingsStore store, AuditLog audit)
{
switch (store.Save(request))
{
case ("setting_locked", var setting):
return ApiErrors.Conflict(context, "setting_locked", setting);
case (var code, var setting):
return ApiErrors.BadRequest(context, code, setting, setting);
}
await audit.WriteAsync(caller, context, "server_settings", "server", null, request.ServerName);
return Results.Json(store.Current(), ProtocolJson.Default.ServerSettingsDto);
}
private static async Task<IResult> AuditAsync(HttpContext context, TitanoDatabase db, Guid? user, string? action, string? cursor, int? limit)
{
var page = await db.Audit.ListAsync(user, string.IsNullOrWhiteSpace(action) ? null : action, limit ?? 100,
string.IsNullOrEmpty(cursor) ? null : cursor, context.RequestAborted);
return Results.Json(new Page<AuditEntryDto>([.. page.Items.Select(Dto.Audit)], page.NextCursor, null), ProtocolJson.Default.PageAuditEntryDto);
}
/// <summary>The last <c>lines</c> lines (default 300) of the newest server log.</summary>
private static async Task<IResult> TailAsync(HttpContext context, ServerOptions options, int? lines)
{
var take = Math.Clamp(lines ?? 300, 1, MaxTailLines);
if (LogFiles(options).FirstOrDefault() is not { } file) return Results.Json(new LogTailDto(string.Empty, []), ProtocolJson.Default.LogTailDto);
await using var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
var start = Math.Max(0, stream.Length - TailWindowBytes);
stream.Position = start;
using var reader = new StreamReader(stream, Encoding.UTF8);
var text = await reader.ReadToEndAsync(context.RequestAborted);
var all = text.Split('\n', StringSplitOptions.RemoveEmptyEntries);
// A window that starts mid-file begins with a partial line.
var complete = start > 0 && all.Length > 0 ? all[1..] : all;
return Results.Json(new LogTailDto(file.Name, [.. complete.TakeLast(take).Select(l => l.TrimEnd('\r'))]), ProtocolJson.Default.LogTailDto);
}
/// <summary>Server log files, newest first.</summary>
private static List<FileInfo> LogFiles(ServerOptions options) =>
Directory.Exists(options.LogPath)
? [.. new DirectoryInfo(options.LogPath).EnumerateFiles("*.log").OrderByDescending(f => f.LastWriteTimeUtc).ThenByDescending(f => f.Name)]
: [];
}