using Titano.Core.Model; namespace Titano.Data.Repositories; /// Append-only record of who did what (BRIEF §5 AuditLog, §14.2). public sealed class AuditRepository { private const string Columns = "id, at, user_id, username, action, target_kind, target_id, details, remote_address"; private readonly DbAccess _db; internal AuditRepository(DbAccess db) => _db = db; public async Task AppendAsync(AuditEntry entry, CancellationToken cancellationToken = default) => await _db.ExecuteAsync($"INSERT INTO audit_log ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", [entry.Id, entry.At, entry.UserId, entry.Username, entry.Action, entry.TargetKind, entry.TargetId, entry.Details, entry.RemoteAddress], cancellationToken).ConfigureAwait(false); /// Entries newest first, optionally of one user. public Task> ListAsync(Guid? userId = null, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) => ListAsync(userId, action: null, limit, cursor, cancellationToken); /// Entries newest first, optionally of one user and one action (e.g. the sign-in log). public Task> ListAsync(Guid? userId, string? action, int limit = 100, string? cursor = null, CancellationToken cancellationToken = default) { var p = new SqlParameters(); var where = new List(); if (userId is { } user) where.Add($"user_id = {p.Add(user)}"); if (action is not null) where.Add($"action = {p.Add(action)}"); if (cursor is not null) { var (value, id) = Cursor.Decode("audit", cursor); where.Add(Cursor.After("at", "id", descending: true, value, id, p.Add)); } var take = Cursor.ClampLimit(limit); var sql = $"SELECT {Columns} FROM audit_log{(where.Count > 0 ? " WHERE " + string.Join(" AND ", where) : string.Empty)} " + $"ORDER BY at DESC, id DESC LIMIT {p.Add(take + 1)}"; return _db.RunAsync(async session => { var entries = await session.QueryListAsync(sql, p.ToArray(), Map, cancellationToken).ConfigureAwait(false); string? next = null; if (entries.Count > take) { entries.RemoveAt(take); next = Cursor.Encode("audit", entries[^1].At, entries[^1].Id); } return new Page(entries, next); }, cancellationToken); } private static AuditEntry Map(DbRow r) => new() { Id = r.GetGuid(0), At = r.GetDateTimeOffset(1), UserId = r.GetGuidOrNull(2), Username = r.GetStringOrNull(3), Action = r.GetString(4), TargetKind = r.GetStringOrNull(5), TargetId = r.GetStringOrNull(6), Details = r.GetStringOrNull(7), RemoteAddress = r.GetStringOrNull(8), }; }