Files
Chronos/src/Chronos.App/Infrastructure/DiagnosticsBundle.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-23 12:45:18 +02:00

200 lines
9.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Model;
using Chronos.Core.Windows.Codecs;
using Chronos.Data;
using Chronos.Data.Sqlite;
namespace Chronos.App.Infrastructure;
/// <summary>
/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9, §22 Phase 8): an environment report, the codec
/// and encoder inventory, the settings, the latest failed jobs and the log files, zipped into a folder the user chose.
/// Everything passes through <see cref="SecretScrubber"/> (the saved server token, passwords and keys never leave the
/// PC) and no photo or archive file is ever included.
/// </summary>
public static class DiagnosticsBundle
{
/// <summary>Failed jobs included, newest first.</summary>
public const int FailedJobs = 50;
/// <summary>
/// Writes "Chronos diagnostics yyyy-MM-dd HHmm.zip" (" (2)", " (3)"… when that name is taken) into
/// <paramref name="folder"/> and returns its path; a bundle that fails half-way leaves no file behind. Call on the UI
/// thread: the settings are captured there; detection and writing run in the background.
/// </summary>
public static Task<string> CreateAsync(AppServices services, string folder, IEnumerable<string>? extraLines = null, CancellationToken ct = default)
{
var settings = services.Settings.ToJson();
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
return Task.Run(async () =>
{
var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : [];
var codecs = Codecs(services.Encoders);
var path = ExportNaming.Unique(folder, $"Chronos diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}", ".zip");
var temp = path + ".tmp";
try
{
await using (var file = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None))
using (var bundle = new DiagnosticsArchive(file))
{
bundle.AddText("environment.txt", report);
bundle.AddText("codecs.txt", codecs);
bundle.AddJson("settings.json", settings);
bundle.AddJobs("jobs-failed.json", failures);
bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct);
}
File.Move(temp, path);
return path;
}
finally
{
// Gone after a successful move; after a failure a half-written zip helps nobody.
if (File.Exists(temp)) File.Delete(temp);
}
}, ct);
}
/// <summary>Plain-text environment report.</summary>
public static string Report(AppEnvironment environment, IEnumerable<string>? extraLines = null)
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"Chronos {AppServices.VersionText}");
sb.Append(DiagnosticsArchive.SystemReport());
sb.AppendLine(CultureInfo.InvariantCulture, $"Data {environment.DataDirectory} (portable: {environment.IsPortable})");
if (extraLines is not null)
{
foreach (var line in extraLines) sb.AppendLine(line);
}
return sb.ToString();
}
private static string DatabaseLine(ChronosDatabase? database)
{
if (database is null) return "Index not open\n";
var line = string.Create(CultureInfo.InvariantCulture, $"Index schema {database.SchemaVersion}\n");
// The SQLite build's options (BRIEF §6.2) explain behaviour differences between Windows versions.
return database.Database is SqliteDatabase
? line + $"SQLite {SqliteDatabase.LibraryVersion}; compile options: {string.Join(' ', SqliteDatabase.CompileOptions)}\n"
: line;
}
/// <summary>Graphics adapter, video encoders, WIC decoders per format and missing Store extensions.</summary>
private static string Codecs(IEncoderInventory encoders)
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"Graphics adapter: {encoders.Adapter() ?? "none"}");
sb.AppendLine("Encoders:");
foreach (var e in encoders.Detect())
{
var size = e.MaxWidth > 0 ? string.Create(CultureInfo.InvariantCulture, $" max {e.MaxWidth}x{e.MaxHeight}") : string.Empty;
sb.AppendLine(CultureInfo.InvariantCulture, $" {e.Codec} · {e.DisplayName} ({(e.Hardware ? "hardware" : "software")}{(e.TenBit ? ", 10-bit" : string.Empty)}{size})");
}
try
{
var inventory = CodecInventory.Detect();
sb.AppendLine(CultureInfo.InvariantCulture, $"HEVC decoder: {inventory.HasHevcDecoder}; AV1 decoder: {inventory.HasAv1Decoder}");
sb.AppendLine("Image formats (WIC):");
foreach (var f in inventory.Formats)
{
var missing = f.MissingExtensions.Count == 0 ? string.Empty : "; missing " + string.Join(", ", f.MissingExtensions.Select(x => x.ProductName));
sb.AppendLine(CultureInfo.InvariantCulture, $" {f.Format}: {(f.IsNative ? "native" : f.Decoder is null ? "no decoder" : "preview only")}{(f.Decoder is { } d ? $" ({d.FriendlyName} {d.Version})" : string.Empty)}{missing}");
}
}
catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException or InvalidOperationException)
{
sb.AppendLine("WIC decoders could not be listed: " + ex.Message);
}
return sb.ToString();
}
}
/// <summary>
/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Chronos created
/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them.
/// </summary>
public static class CacheStore
{
public const string MarkerFile = ".chronos-cache";
/// <summary>The cache folder in effect.</summary>
public static string Folder(AppEnvironment environment, AppSettings settings) =>
string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
/// <summary>Creates the folder (if needed) and marks it as Chronos's.</summary>
public static void Prepare(string folder)
{
Directory.CreateDirectory(folder);
var marker = Path.Combine(folder, MarkerFile);
if (!File.Exists(marker)) File.WriteAllText(marker, "Chronos cache folder. Its contents can be deleted at any time.");
}
/// <summary>True when <paramref name="folder"/> is a Chronos cache folder (safe to empty).</summary>
public static bool IsOwned(string folder) => File.Exists(Path.Combine(folder, MarkerFile));
/// <summary>Total bytes of the files in the cache (0 when missing).</summary>
public static long Size(string folder)
{
if (!Directory.Exists(folder)) return 0;
long total = 0;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", options)) total += file.Length;
return total;
}
/// <summary>Deletes everything inside an owned cache folder except the marker; returns the bytes freed.</summary>
/// <exception cref="InvalidOperationException">The folder is not a Chronos cache folder.</exception>
public static long Clear(string folder)
{
if (!Directory.Exists(folder)) return 0;
if (!IsOwned(folder)) throw new InvalidOperationException("Not a Chronos cache folder: " + folder);
long freed = 0;
var root = new DirectoryInfo(folder);
foreach (var file in root.EnumerateFiles())
{
if (file.Name == MarkerFile) continue;
freed += TryDelete(file);
}
foreach (var directory in root.EnumerateDirectories())
{
if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) continue;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in directory.EnumerateFiles("*", options)) freed += TryDelete(file);
try
{
directory.Delete(recursive: true);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
return freed;
}
private static long TryDelete(FileInfo file)
{
try
{
var length = file.Length;
file.Delete();
return length;
}
catch (IOException)
{
return 0; // in use (a render spilling right now)
}
catch (UnauthorizedAccessException)
{
return 0;
}
}
}