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;
/// Administration (BRIEF ยง14.8): dashboard figures, server settings, log tail and downloads, audit log.
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.
if (LogFiles(options).FirstOrDefault(f => f.Name == name) is not { } file) return ApiErrors.NotFound(context, "log");
context.Response.Headers.CacheControl = "no-store";
return Results.File(file.FullName, "text/plain; charset=utf-8", file.Name, file.LastWriteTimeUtc, enableRangeProcessing: true);
});
}
private static async Task 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 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 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([.. page.Items.Select(Dto.Audit)], page.NextCursor, null), ProtocolJson.Default.PageAuditEntryDto);
}
/// The last lines lines (default 300) of the newest server log.
private static async Task 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);
}
/// Server log files, newest first.
private static List LogFiles(ServerOptions options) =>
Directory.Exists(options.LogPath)
? [.. new DirectoryInfo(options.LogPath).EnumerateFiles("*.log").OrderByDescending(f => f.LastWriteTimeUtc).ThenByDescending(f => f.Name)]
: [];
}