Files
Chronos/src/Titano.App/Infrastructure/DiagnosticsBundle.cs
T
Claude 61d913baa9 fix(data): probe PRAGMA compile_options next to the SQLite version check
BRIEF §6.2 asks for the probe at startup. The options are read once per process
from an in-memory connection, logged with the library version and added to the
desktop diagnostics bundle; nothing depends on them (no FTS or JSON use).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 09:58:26 +00: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 Titano.App.Settings;
using Titano.Core.Diagnostics;
using Titano.Core.Export;
using Titano.Core.Model;
using Titano.Core.Windows.Codecs;
using Titano.Data;
using Titano.Data.Sqlite;
namespace Titano.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 "Titano 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, $"Titano 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, $"Titano {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(TitanoDatabase? 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 Titano 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 = ".titano-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 Titano's.</summary>
public static void Prepare(string folder)
{
Directory.CreateDirectory(folder);
var marker = Path.Combine(folder, MarkerFile);
if (!File.Exists(marker)) File.WriteAllText(marker, "Titano cache folder. Its contents can be deleted at any time.");
}
/// <summary>True when <paramref name="folder"/> is a Titano 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 Titano cache folder.</exception>
public static long Clear(string folder)
{
if (!Directory.Exists(folder)) return 0;
if (!IsOwned(folder)) throw new InvalidOperationException("Not a Titano 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;
}
}
}