Files
Chronos/src/Titano.App/Infrastructure/DiagnosticsBundle.cs
T
Claude ffbea7cb74 feat(app): library, jobs, settings, server, welcome and about screens
Local-mode composition root (SQLite index, one JobEngine fed by a single
handler registration list), keyset-paged library with thumbnail cache and
hover scrub, live job list with throttled updates and the shell job bar,
settings with live template validation and encoder self-test, server
connection with trust-on-first-use and DPAPI token, first-run welcome,
About with update check, and --capture screenshots with synthetic data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-02 12:26:58 +00:00

148 lines
6.8 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.IO.Compression;
using System.Runtime.InteropServices;
using System.Text;
namespace Titano.App.Infrastructure;
/// <summary>
/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9): the log files plus an environment report
/// (versions, OS, runtime, culture, folders), zipped into a folder the user chose. Settings and tokens are not included.
/// </summary>
public static class DiagnosticsBundle
{
/// <summary>Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" into <paramref name="folder"/> and returns its path.</summary>
public static Task<string> CreateAsync(AppEnvironment environment, string folder, IEnumerable<string>? extraLines = null, CancellationToken ct = default) =>
Task.Run(() =>
{
var path = Path.Combine(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}.zip");
var temp = path + ".tmp";
using (var zip = ZipFile.Open(temp, ZipArchiveMode.Create))
{
var report = zip.CreateEntry("environment.txt", CompressionLevel.Optimal);
using (var writer = new StreamWriter(report.Open(), new UTF8Encoding(false)))
{
writer.Write(Report(environment, extraLines));
}
if (Directory.Exists(environment.LogDirectory))
{
foreach (var log in Directory.EnumerateFiles(environment.LogDirectory, "*.log").OrderBy(f => f, StringComparer.Ordinal))
{
ct.ThrowIfCancellationRequested();
var entry = zip.CreateEntry("logs/" + Path.GetFileName(log), CompressionLevel.Optimal);
// The current log is open for writing: share the handle instead of copying the file.
using var source = new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var target = entry.Open();
source.CopyTo(target);
}
}
}
File.Move(temp, path, overwrite: true);
return path;
}, 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.AppendLine(CultureInfo.InvariantCulture, $"Created {DateTimeOffset.Now:O}");
sb.AppendLine(CultureInfo.InvariantCulture, $"OS {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Runtime {RuntimeInformation.FrameworkDescription} ({RuntimeInformation.ProcessArchitecture})");
sb.AppendLine(CultureInfo.InvariantCulture, $"Culture {CultureInfo.CurrentCulture.Name} / UI {CultureInfo.CurrentUICulture.Name}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Processors {Environment.ProcessorCount}");
sb.AppendLine(CultureInfo.InvariantCulture, $"Memory {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024 * 1024)} MB");
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();
}
}
/// <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;
}
}
}