Files
Anubis/src/Anubis/Db/DbValues.cs
T
Alby96andClaude Opus 5.5 6e365673b8
ci / test (postgres) (push) Successful in 6m25s
ci / test (sqlite) (push) Successful in 4m1s
ci / test (postgres) (pull_request) Failing after 6m4s
ci / image (push) Canceled after 0s
ci / test (sqlite) (pull_request) Successful in 4m34s
ci / image (pull_request) Skipped
Collect diagnostics for the analysis of a long run and package a Windows trial release (refs #95 #55)
The 48-hour soak run at home kept being cut short by the host, never by Anubis.
The user will instead run a release for as long as they like and paste back a
report, so the bot now records what that report needs (ADR 0013).

- Every 5 minutes and at each start, a process sample goes to diagnostic_samples:
  memory, GC, threads, handles, CPU, exceptions, database size, log warnings and
  errors, and outbound HTTP calls by destination with duration buckets, read from
  the System.Net.Http meter without any new package.
- Every scheduled job run goes to job_runs. Both tables keep 30 days.
- The Markdown report (at most 60 KB, redacted, user folders masked) adds
  findings, the soak checks, starts and silences, jobs, calls, grouped log
  warnings and errors, and resources over time with their slopes. It comes from
  "anubis diagnostics", GET /api/diagnostica.md and a button in Diario e sistema.
- New {long} column token: SQLite STRICT tables reject BIGINT.
- "tasks release-win" builds the trial zip with a start script, a script that
  writes the report, and Italian instructions. Version 0.7.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:57:03 +01:00

104 lines
4.9 KiB
C#

using System.Globalization;
using Anubis.Platform;
namespace Anubis.Db;
/// <summary>A JSON document column (SPEC 5.4: generic JSON, no engine-specific operators). Stored as written.</summary>
public readonly record struct DbJson(string Text);
/// <summary>
/// The in-house column types of SPEC 5.4, the same on both engines (ADR 0007):
/// <list type="bullet">
/// <item>money, quantities and prices: <see cref="decimal"/>, <c>NUMERIC(38,18)</c> on PostgreSQL and canonical text on SQLite, rounded to 18 decimals before writing (trap 19);</item>
/// <item>moments: <see cref="DateTimeOffset"/> in UTC, microsecond precision, ISO text on SQLite; a <see cref="DateTime"/> without time zone is refused;</item>
/// <item>identifiers: <see cref="Guid"/> (UUIDv7), <c>UUID</c> on PostgreSQL and lowercase text on SQLite.</item>
/// </list>
/// </summary>
public static class DbValues
{
/// <summary>NUMERIC(38,18) keeps 20 digits before the decimal point.</summary>
public static readonly decimal MaxMagnitude = 99_999_999_999_999_999_999m;
public const int Scale = 18;
private const string TimestampFormat = "yyyy-MM-dd'T'HH:mm:ss.ffffff'Z'";
/// <summary>Rounds to 18 decimals (half away from zero, as PostgreSQL does) and refuses values the column cannot hold.</summary>
public static decimal Money(decimal value)
{
if (Math.Abs(value) > MaxMagnitude)
{
throw new OverflowException($"Value {value.ToString(CultureInfo.InvariantCulture)} exceeds NUMERIC(38,18).");
}
return Normalize(Math.Round(value, Scale, MidpointRounding.AwayFromZero));
}
/// <summary>Removes trailing zeros so the same number always has the same text: 1.500 becomes 1.5.</summary>
public static decimal Normalize(decimal value) => value / 1.000000000000000000000000000000000m;
public static string MoneyText(decimal value) => Money(value).ToString(CultureInfo.InvariantCulture);
public static decimal ParseMoney(string text) => Normalize(decimal.Parse(text, NumberStyles.Number, CultureInfo.InvariantCulture));
/// <summary>UTC, truncated to microseconds (the precision of PostgreSQL TIMESTAMPTZ).</summary>
public static DateTimeOffset Moment(DateTimeOffset value)
{
var utc = value.ToUniversalTime();
return new DateTimeOffset(utc.UtcTicks - (utc.UtcTicks % 10), TimeSpan.Zero);
}
public static string MomentText(DateTimeOffset value) => Moment(value).ToString(TimestampFormat, CultureInfo.InvariantCulture);
public static DateTimeOffset ParseMoment(string text)
{
if (!text.EndsWith('Z'))
{
throw new FormatException("A stored moment has no time zone: " + text);
}
return DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
}
/// <summary>Converts a .NET value to what the engine's driver should receive.</summary>
public static object ToProvider(object? value, DbEngine engine) => value switch
{
null => DBNull.Value,
decimal d => engine == DbEngine.Sqlite ? MoneyText(d) : Money(d),
DateTimeOffset t => engine == DbEngine.Sqlite ? MomentText(t) : Moment(t),
DateTime dt => dt.Kind == DateTimeKind.Utc
? ToProvider(new DateTimeOffset(dt), engine)
: throw new ArgumentException("Moments must carry a time zone: use DateTimeOffset or a UTC DateTime."),
Guid g => engine == DbEngine.Sqlite ? g.ToString("D") : g,
bool b => engine == DbEngine.Sqlite ? (b ? 1L : 0L) : b,
DbJson j => j.Text,
int i => (long)i,
_ => value,
};
/// <summary>The column type behind each token of the migration files.</summary>
public static string ColumnType(string token, DbEngine engine) => (token, engine) switch
{
("money", DbEngine.Postgres) => "NUMERIC(38,18)",
("money", DbEngine.Sqlite) => "TEXT",
("uuid", DbEngine.Postgres) => "UUID",
("uuid", DbEngine.Sqlite) => "TEXT",
("timestamp", DbEngine.Postgres) => "TIMESTAMPTZ",
("timestamp", DbEngine.Sqlite) => "TEXT",
("json", DbEngine.Postgres) => "JSON",
("json", DbEngine.Sqlite) => "TEXT",
("bool", DbEngine.Postgres) => "BOOLEAN",
("bool", DbEngine.Sqlite) => "INTEGER",
("bytes", DbEngine.Postgres) => "BYTEA",
("bytes", DbEngine.Sqlite) => "BLOB",
// A whole number beyond 2^31 (bytes of memory, counters of a long run): SQLite's INTEGER is already 64 bits.
("long", DbEngine.Postgres) => "BIGINT",
("long", DbEngine.Sqlite) => "INTEGER",
("float", DbEngine.Postgres) => "DOUBLE PRECISION",
("float", DbEngine.Sqlite) => "REAL",
("strict", DbEngine.Postgres) => "",
("strict", DbEngine.Sqlite) => " STRICT",
_ => throw new InvalidOperationException($"Unknown column type token '{token}'."),
};
}