Выполнениие лабораторной работы на 5, трек 2.
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public static class ApiErrors
|
||||
{
|
||||
public static int CodePoints(string value) => value.EnumerateRunes().Count();
|
||||
|
||||
// 401 с обязательным заголовком WWW-Authenticate (контракт: Basic для входа, Bearer для остального API).
|
||||
public static IResult Unauthorized(HttpContext context, string challenge, string message)
|
||||
{
|
||||
context.Response.Headers.WWWAuthenticate = challenge;
|
||||
return Error(context, 401, "unauthorized", message);
|
||||
}
|
||||
|
||||
public static IResult Error(
|
||||
HttpContext context,
|
||||
int statusCode,
|
||||
string code,
|
||||
string message)
|
||||
{
|
||||
var requestId = context.Items["request_id"]?.ToString() ?? context.TraceIdentifier;
|
||||
|
||||
// UseExceptionHandler очищает заголовки ответа, поэтому выставляем X-Request-Id заново.
|
||||
context.Response.Headers["X-Request-Id"] = requestId;
|
||||
|
||||
return Results.Json(
|
||||
new
|
||||
{
|
||||
error = new
|
||||
{
|
||||
code,
|
||||
message,
|
||||
request_id = requestId
|
||||
}
|
||||
},
|
||||
statusCode: statusCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Isopoh.Cryptography.Argon2;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public sealed class Argon2PasswordHasher : IPasswordHasher
|
||||
{
|
||||
// Минимум по рекомендации OWASP для Argon2id: m=19 MiB, t=2, p=1. Обоснование и выбор — в REPORT.md.
|
||||
private const int TimeCost = 2;
|
||||
private const int MemoryCostKiB = 19 * 1024;
|
||||
private const int Parallelism = 1;
|
||||
|
||||
// Каждое вычисление занимает ~19 MiB и ядро CPU: без лимита 100 параллельных входов = ~2 GiB памяти.
|
||||
private const int MaxConcurrency = 4;
|
||||
private static readonly TimeSpan SlotWaitTimeout = TimeSpan.FromSeconds(2);
|
||||
|
||||
private readonly SemaphoreSlim _slots = new(MaxConcurrency, MaxConcurrency);
|
||||
|
||||
// Хеш от случайного пароля, который никто не знает. Нужен только для выравнивания времени при неизвестном username.
|
||||
private readonly string _dummyHash;
|
||||
|
||||
public Argon2PasswordHasher()
|
||||
{
|
||||
_dummyHash = HashCore(Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)));
|
||||
}
|
||||
|
||||
public async Task<string> HashAsync(string password, CancellationToken ct)
|
||||
{
|
||||
await AcquireSlotAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Task.Run(() => HashCore(password), ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> VerifyAsync(string? hash, string password, CancellationToken ct)
|
||||
{
|
||||
await AcquireSlotAsync(ct);
|
||||
try
|
||||
{
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var ok = Argon2.Verify(hash ?? _dummyHash, password, secret: null, secureArrayCall: null);
|
||||
return hash is not null && ok;
|
||||
}, ct);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_slots.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AcquireSlotAsync(CancellationToken ct)
|
||||
{
|
||||
if (!await _slots.WaitAsync(SlotWaitTimeout, ct))
|
||||
{
|
||||
throw new PasswordHasherBusyException();
|
||||
}
|
||||
}
|
||||
|
||||
// HybridAddressing — это Argon2id. Соль генерируется библиотекой и входит в возвращаемую строку.
|
||||
private static string HashCore(string password) =>
|
||||
Argon2.Hash(password, TimeCost, MemoryCostKiB, Parallelism, Argon2Type.HybridAddressing);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Messenger.Api.Data;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public static class BearerAuth
|
||||
{
|
||||
public const string Scheme = "Bearer";
|
||||
public const string Challenge = "Bearer realm=\"messenger\"";
|
||||
public const string SessionIdClaim = "session_id";
|
||||
|
||||
// Ровно один заголовок Authorization вида "Bearer <token>"; иначе null (Basic и прочее здесь не принимаются).
|
||||
public static string? ExtractToken(HttpRequest request)
|
||||
{
|
||||
if (request.Headers.Authorization.Count != 1)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var value = request.Headers.Authorization[0];
|
||||
const string prefix = "Bearer ";
|
||||
if (value is null || !value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var token = value[prefix.Length..].Trim();
|
||||
return token.Length == 0 ? null : token;
|
||||
}
|
||||
|
||||
public static Guid GetUserId(this HttpContext context) =>
|
||||
Guid.Parse(context.User.FindFirstValue(ClaimTypes.NameIdentifier)!);
|
||||
|
||||
public static Guid GetSessionId(this HttpContext context) =>
|
||||
Guid.Parse(context.User.FindFirstValue(SessionIdClaim)!);
|
||||
}
|
||||
|
||||
// Стандартный обработчик аутентификации ASP.NET: превращает Bearer-токен в ClaimsPrincipal.
|
||||
// Срабатывает до выбора и выполнения эндпоинта (в том числе до разбора тела), поэтому 401 всегда раньше 400/404.
|
||||
public sealed class SessionAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
MessengerDbContext db)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var token = BearerAuth.ExtractToken(Request);
|
||||
if (token is null)
|
||||
{
|
||||
return AuthenticateResult.NoResult();
|
||||
}
|
||||
|
||||
var hash = SessionTokens.Hash(token);
|
||||
var now = Timestamps.UtcNowMilliseconds();
|
||||
|
||||
// Неизвестный, истёкший и отозванный токен неразличимы для клиента: во всех случаях это один 401.
|
||||
var session = await db.Sessions
|
||||
.AsNoTracking()
|
||||
.Where(s => s.TokenHash == hash && s.RevokedAt == null && s.ExpiresAt > now)
|
||||
.Select(s => new { s.Id, s.UserId })
|
||||
.FirstOrDefaultAsync(Context.RequestAborted);
|
||||
|
||||
if (session is null)
|
||||
{
|
||||
return AuthenticateResult.Fail("Недействительная сессия");
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity(
|
||||
[
|
||||
new Claim(ClaimTypes.NameIdentifier, session.UserId.ToString()),
|
||||
new Claim(BearerAuth.SessionIdClaim, session.Id.ToString())
|
||||
],
|
||||
BearerAuth.Scheme);
|
||||
|
||||
return AuthenticateResult.Success(
|
||||
new AuthenticationTicket(new ClaimsPrincipal(identity), BearerAuth.Scheme));
|
||||
}
|
||||
|
||||
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
await ApiErrors
|
||||
.Unauthorized(Context, BearerAuth.Challenge, "Требуется действительный Bearer-токен")
|
||||
.ExecuteAsync(Context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
// Непрозрачный для клиента cursor keyset-пагинации: (created_at, id) последнего элемента страницы.
|
||||
// Привязан к ресурсу (scope): cursor от другого списка или чата отклоняется как 400.
|
||||
public static class Cursors
|
||||
{
|
||||
public const string Chats = "chats";
|
||||
|
||||
public static string Messages(Guid chatId) => $"messages/{chatId:D}";
|
||||
|
||||
public static string Encode(string scope, DateTimeOffset createdAt, Guid id) =>
|
||||
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{scope}|{createdAt.UtcTicks}:{id:D}"));
|
||||
|
||||
// cursor == null — первая страница (успех, value == null). Любая ошибка формата или чужой scope — false.
|
||||
public static bool TryDecode(string? cursor, string scope, out (DateTimeOffset CreatedAt, Guid Id)? value)
|
||||
{
|
||||
value = null;
|
||||
if (cursor is null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (cursor.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var decoded = new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(Convert.FromBase64String(cursor));
|
||||
var scoped = decoded.Split('|', 2);
|
||||
if (scoped.Length != 2 || scoped[0] != scope)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var parts = scoped[1].Split(':', 2);
|
||||
if (parts.Length != 2 ||
|
||||
!long.TryParse(parts[0], out var ticks) ||
|
||||
ticks < DateTimeOffset.MinValue.UtcTicks || ticks > DateTimeOffset.MaxValue.UtcTicks ||
|
||||
!Guid.TryParse(parts[1], out var id))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
value = (new DateTimeOffset(ticks, TimeSpan.Zero), id);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or ArgumentException or DecoderFallbackException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
using System.Data.Common;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Npgsql;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public sealed class QueryCounter
|
||||
{
|
||||
public int Count;
|
||||
}
|
||||
|
||||
// Считает SQL-команды, выполненные EF Core в рамках текущего HTTP-запроса (для измерения «запросов к БД на запрос API»).
|
||||
// Включается только при DIAGNOSTIC_HEADERS=true. Команда ReserveMessageSlot (сырой NpgsqlCommand) не учитывается.
|
||||
public sealed class QueryCountingInterceptor(IHttpContextAccessor accessor) : DbCommandInterceptor
|
||||
{
|
||||
public const string ItemKey = "diagnostics.query_counter";
|
||||
|
||||
private void Count()
|
||||
{
|
||||
if (accessor.HttpContext?.Items[ItemKey] is QueryCounter counter)
|
||||
{
|
||||
Interlocked.Increment(ref counter.Count);
|
||||
}
|
||||
}
|
||||
|
||||
public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result)
|
||||
{
|
||||
Count();
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Count();
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
|
||||
{
|
||||
Count();
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Count();
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<object> result)
|
||||
{
|
||||
Count();
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<object> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Count();
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
}
|
||||
|
||||
public static class DependencyFailures
|
||||
{
|
||||
// Недоступность или перегрузка PostgreSQL (нет соединения, таймаут, исчерпан пул, остановка сервера) — это 503,
|
||||
// а не 500: ошибка ограничена, внутренние детали не раскрываются, запрос не принимается как доверенный.
|
||||
public static bool IsDatabaseUnavailable(Exception? error)
|
||||
{
|
||||
for (var e = error; e is not null; e = e.InnerException)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case PostgresException pg:
|
||||
// 08 — соединение, 53 — нехватка ресурсов, 57 — вмешательство оператора (shutdown и т.п.)
|
||||
if (pg.SqlState.StartsWith("08") || pg.SqlState.StartsWith("53") || pg.SqlState.StartsWith("57"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
break;
|
||||
case NpgsqlException:
|
||||
case TimeoutException:
|
||||
case System.Net.Sockets.SocketException:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public interface IPasswordHasher
|
||||
{
|
||||
/// <summary>PHC-строка Argon2id (соль и параметры внутри). Бросает <see cref="PasswordHasherBusyException"/>, если слот не освободился вовремя.</summary>
|
||||
Task<string> HashAsync(string password, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="hash"/> == null означает «пользователя нет»: проверка всё равно выполняется (против заглушки),
|
||||
/// чтобы время ответа не раскрывало существование username.
|
||||
/// </summary>
|
||||
Task<bool> VerifyAsync(string? hash, string password, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class PasswordHasherBusyException : Exception
|
||||
{
|
||||
public PasswordHasherBusyException() : base("Слишком много одновременных вычислений хеша пароля") { }
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public enum CacheStatus
|
||||
{
|
||||
Disabled, // кэш не настроен
|
||||
Hit,
|
||||
Miss,
|
||||
Bypass // кэш настроен, но недоступен: запрос обслужен напрямую из PostgreSQL
|
||||
}
|
||||
|
||||
// Кэш страниц истории. Источник истины — PostgreSQL; кэш лишь ускоряет чтение и никогда не обязателен.
|
||||
// Согласованность: версия истории чата (chats.history_version) входит в ключ, а версия читается из PostgreSQL
|
||||
// при каждом запросе (см. MessageEndpoints). Запись увеличивает версию в своей транзакции, поэтому
|
||||
// после подтверждённой записи ключ меняется, и устаревшая страница недостижима — явная инвалидация не нужна.
|
||||
// Старые ключи удаляются по TTL (CACHE_TTL_SECONDS) и вытесняются политикой maxmemory.
|
||||
public interface IMessageHistoryCache
|
||||
{
|
||||
Task<(string? Json, CacheStatus Status)> GetAsync(string key, CancellationToken ct);
|
||||
Task SetAsync(string key, string json, CancellationToken ct);
|
||||
}
|
||||
|
||||
public sealed class NullMessageHistoryCache : IMessageHistoryCache
|
||||
{
|
||||
public Task<(string? Json, CacheStatus Status)> GetAsync(string key, CancellationToken ct) =>
|
||||
Task.FromResult<(string?, CacheStatus)>((null, CacheStatus.Disabled));
|
||||
|
||||
public Task SetAsync(string key, string json, CancellationToken ct) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
public sealed class ValkeyMessageHistoryCache : IMessageHistoryCache, IDisposable
|
||||
{
|
||||
// После ошибки кэш пропускается на это время, чтобы каждый запрос не ждал таймаут недоступного сервера.
|
||||
private static readonly TimeSpan BypassWindow = TimeSpan.FromSeconds(5);
|
||||
|
||||
private readonly ConnectionMultiplexer _connection;
|
||||
private readonly TimeSpan _ttl;
|
||||
private readonly ILogger<ValkeyMessageHistoryCache> _logger;
|
||||
private long _bypassUntilTicks;
|
||||
|
||||
public ValkeyMessageHistoryCache(CacheSettings settings, ILogger<ValkeyMessageHistoryCache> logger)
|
||||
{
|
||||
var options = ConfigurationOptions.Parse(settings.Connection!);
|
||||
// Недоступный кэш не должен ронять ни старт, ни запросы: короткие таймауты, подключение в фоне.
|
||||
options.AbortOnConnectFail = false;
|
||||
options.ConnectTimeout = 500;
|
||||
options.SyncTimeout = 200;
|
||||
options.AsyncTimeout = 200;
|
||||
options.ConnectRetry = 1;
|
||||
_connection = ConnectionMultiplexer.Connect(options);
|
||||
_ttl = settings.Ttl;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<(string? Json, CacheStatus Status)> GetAsync(string key, CancellationToken ct)
|
||||
{
|
||||
if (IsBypassed())
|
||||
{
|
||||
return (null, CacheStatus.Bypass);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var value = await _connection.GetDatabase().StringGetAsync(key);
|
||||
return value.IsNull ? (null, CacheStatus.Miss) : ((string?)value, CacheStatus.Hit);
|
||||
}
|
||||
catch (Exception ex) when (ex is RedisException or TimeoutException)
|
||||
{
|
||||
StartBypass(ex);
|
||||
return (null, CacheStatus.Bypass);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SetAsync(string key, string json, CancellationToken ct)
|
||||
{
|
||||
if (IsBypassed())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _connection.GetDatabase().StringSetAsync(key, json, _ttl);
|
||||
}
|
||||
catch (Exception ex) when (ex is RedisException or TimeoutException)
|
||||
{
|
||||
StartBypass(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsBypassed() => Environment.TickCount64 < Interlocked.Read(ref _bypassUntilTicks);
|
||||
|
||||
private void StartBypass(Exception ex)
|
||||
{
|
||||
Interlocked.Exchange(ref _bypassUntilTicks, Environment.TickCount64 + (long)BypassWindow.TotalMilliseconds);
|
||||
_logger.LogWarning("Кэш недоступен ({Error}); чтение идёт напрямую из PostgreSQL ближайшие {Seconds} с",
|
||||
ex.GetType().Name, BypassWindow.TotalSeconds);
|
||||
}
|
||||
|
||||
public void Dispose() => _connection.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public static class SessionTokens
|
||||
{
|
||||
// 32 случайных байта = 256 бит энтропии (контракт: не менее 256). В base64url это 43 символа.
|
||||
public static string Generate() =>
|
||||
Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
|
||||
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
|
||||
// В БД хранится только SHA-256 токена. Быстрый хеш здесь уместен: токен случайный и длинный, подбирать нечего
|
||||
// (в отличие от пароля, который выбирает человек и который поэтому хешируется медленным Argon2id).
|
||||
public static byte[] Hash(string token) => SHA256.HashData(Encoding.UTF8.GetBytes(token));
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
// Все настройки читаются из IConfiguration (переменные окружения и, в тестах, UseSetting), а не напрямую из окружения:
|
||||
// так одно приложение можно поднять с разными настройками в одном процессе. Секреты передаются файлами (*_FILE).
|
||||
|
||||
public sealed record DatabaseSettings(string ConnectionString)
|
||||
{
|
||||
public static DatabaseSettings From(IConfiguration configuration)
|
||||
{
|
||||
var file = configuration["DATABASE_URL_FILE"]
|
||||
?? throw new InvalidOperationException("DATABASE_URL_FILE не задан");
|
||||
|
||||
var builder = new Npgsql.NpgsqlConnectionStringBuilder(File.ReadAllText(file).Trim())
|
||||
{
|
||||
Pooling = true,
|
||||
MinPoolSize = 1,
|
||||
// Ограниченный пул: больше MaxPoolSize соединений от одного экземпляра не открывается,
|
||||
// ожидающие запросы ждут не дольше Timeout и затем получают 503.
|
||||
MaxPoolSize = configuration.GetValue("DB_MAX_POOL_SIZE", 20),
|
||||
Timeout = configuration.GetValue("DB_CONNECT_TIMEOUT_SECONDS", 5),
|
||||
CommandTimeout = configuration.GetValue("DB_COMMAND_TIMEOUT_SECONDS", 5)
|
||||
};
|
||||
return new DatabaseSettings(builder.ConnectionString);
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record AuthSessionOptions(TimeSpan Ttl)
|
||||
{
|
||||
// SESSION_TTL_SECONDS: по умолчанию 3600; в тесте истечения допустимо 2. Неверное значение — ошибка старта, а не молчаливый дефолт.
|
||||
public static AuthSessionOptions From(IConfiguration configuration)
|
||||
{
|
||||
var raw = configuration["SESSION_TTL_SECONDS"];
|
||||
if (string.IsNullOrWhiteSpace(raw))
|
||||
{
|
||||
return new AuthSessionOptions(TimeSpan.FromSeconds(3600));
|
||||
}
|
||||
|
||||
if (!int.TryParse(raw, out var seconds) || seconds < 1)
|
||||
{
|
||||
throw new InvalidOperationException("SESSION_TTL_SECONDS должен быть положительным целым числом");
|
||||
}
|
||||
|
||||
return new AuthSessionOptions(TimeSpan.FromSeconds(seconds));
|
||||
}
|
||||
}
|
||||
|
||||
// Кэш необязателен: без CACHE_URL_FILE / CACHE_CONNECTION приложение работает только на PostgreSQL.
|
||||
public sealed record CacheSettings(string? Connection, TimeSpan Ttl)
|
||||
{
|
||||
public bool Enabled => !string.IsNullOrWhiteSpace(Connection);
|
||||
|
||||
public static CacheSettings From(IConfiguration configuration)
|
||||
{
|
||||
var connection = configuration["CACHE_CONNECTION"];
|
||||
var file = configuration["CACHE_URL_FILE"];
|
||||
if (!string.IsNullOrWhiteSpace(file) && File.Exists(file))
|
||||
{
|
||||
connection = File.ReadAllText(file).Trim();
|
||||
}
|
||||
|
||||
return new CacheSettings(connection, TimeSpan.FromSeconds(configuration.GetValue("CACHE_TTL_SECONDS", 300)));
|
||||
}
|
||||
}
|
||||
|
||||
// Диагностические заголовки X-Cache и X-Db-Queries для экспериментов; в обычной работе выключены.
|
||||
public sealed record DiagnosticsSettings(bool Headers)
|
||||
{
|
||||
public static DiagnosticsSettings From(IConfiguration configuration) =>
|
||||
new(configuration.GetValue("DIAGNOSTIC_HEADERS", false));
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public static class Timestamps
|
||||
{
|
||||
// Единая точность времени для хранения, сортировки, cursor и JSON-ответа: миллисекунды.
|
||||
// Клиент видит время с точностью до миллисекунды, поэтому порядок (created_at, id) должен
|
||||
// определяться теми же значениями, которые он видит.
|
||||
public static DateTimeOffset UtcNowMilliseconds()
|
||||
{
|
||||
var ticks = DateTimeOffset.UtcNow.UtcTicks;
|
||||
return new DateTimeOffset(ticks - ticks % TimeSpan.TicksPerMillisecond, TimeSpan.Zero);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
public sealed class UtcDateTimeOffsetJsonConverter : JsonConverter<DateTimeOffset>
|
||||
{
|
||||
public override DateTimeOffset Read(
|
||||
ref Utf8JsonReader reader,
|
||||
Type typeToConvert,
|
||||
JsonSerializerOptions options)
|
||||
{
|
||||
return DateTimeOffset.Parse(
|
||||
reader.GetString()!,
|
||||
CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind);
|
||||
}
|
||||
|
||||
public override void Write(
|
||||
Utf8JsonWriter writer,
|
||||
DateTimeOffset value,
|
||||
JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteStringValue(
|
||||
value.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user