using System.IO; using System.Net.Http; using System.Reflection; using Titano.App.About; using Titano.App.Jobs; using Titano.App.Library; using Titano.App.Server; using Titano.App.Settings; using Titano.Core.Archiving; using Titano.Core.Diagnostics; using Titano.Core.Imaging.Decoders; using Titano.Core.Model; using Titano.Core.Windows.Wic; using Titano.Data; using Titano.Data.Archiving; using Titano.Data.Jobs; namespace Titano.App.Infrastructure; /// /// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the /// archive engine (WIC first, then managed decoders), the one of this PC with the handlers of /// , thumbnails, the server session, the encoder inventory and the update check. /// Started after the window shows, stopped when the app exits. The last archive is reopened at start and rescanned /// every (BRIEF §7: polling, no file-system watchers). /// public sealed class AppServices : IAsyncDisposable { public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10); private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) }); private readonly CancellationTokenSource _stopping = new(); private readonly Dictionary _scans = []; private Task _polling = Task.CompletedTask; public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs) { Environment = environment; Settings = settings; SaveSettingsAction = saveSettings; Dialogs = dialogs; ArchiveSetup = new EngineArchiveSetup(this); Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector()); Encoders = new MediaFoundationInventory(); CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct); } public AppEnvironment Environment { get; } public AppSettings Settings { get; } public IAppDialogs Dialogs { get; } private Action SaveSettingsAction { get; } /// First-run and Library archive actions. public IArchiveSetup ArchiveSetup { get; set; } /// The archive engine; null until the index is open. public ArchiveService? Archives { get; private set; } public ServerSession Server { get; set; } public IEncoderInventory Encoders { get; set; } /// Latest public release (GitHub Releases API of the releases repository, BRIEF §18). public Func> CheckForUpdateAsync { get; set; } /// The index; null until succeeded. public TitanoDatabase? Database { get; private set; } public JobEngine? Engine { get; private set; } public IJobQueue? Jobs { get; private set; } public ThumbnailService? Thumbnails { get; private set; } /// Why the index could not be opened; null when it is open. public Exception? OpenError { get; private set; } /// Node id of this PC's workers. public string WorkerId { get; init; } = System.Environment.MachineName; /// "0.1.0" (informational version). public static string VersionText { get; } = typeof(AppServices).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; /// The job handlers of this PC's engine — the single registration list; a kind without a handler stays /// queued (it is never claimed here). public static IReadOnlyList CreateJobHandlers(AppServices services) => services.Archives?.CreateJobHandlers() ?? []; /// Queues a scan of unless one is already waiting or running. public async Task QueueScanAsync(Archive archive, bool full, CancellationToken ct = default) { if (Engine is null || Database is null) return; Guid previous; lock (_scans) { _scans.TryGetValue(archive.Id, out previous); } if (previous != Guid.Empty && await Database.Jobs.GetAsync(previous, ct) is { State: JobState.Queued or JobState.Running }) return; var job = await Engine.EnqueueAsync(ArchiveJobs.Scan(archive, full), cancellationToken: ct); lock (_scans) { _scans[archive.Id] = job.Id; } } public void SaveSettings() => SaveSettingsAction(); /// Opens (or creates) the index at , migrates it and starts the job engine. public async Task OpenAsync(string databasePath, CancellationToken ct = default) { try { Database = await Task.Run(() => TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(databasePath), ct), ct); Log.Info("app", $"Index open (schema {Database.SchemaVersion}) at {databasePath}"); } catch (Exception ex) when (ex is DatabaseException or System.IO.IOException or UnauthorizedAccessException or DllNotFoundException) { OpenError = ex; Log.Error("app", "The index could not be opened", ex); return; } await StartJobsAsync(Database, startEngine: true, ct); Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems); if (Settings.LastArchivePath is { Length: > 0 } root) _polling = PollAsync(root, _stopping.Token); } /// Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped. public async Task AttachAsync(TitanoDatabase database, bool startEngine = true, CancellationToken ct = default) { Database = database; await StartJobsAsync(database, startEngine, ct); Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems); } public async ValueTask DisposeAsync() { await _stopping.CancelAsync(); await _polling; _stopping.Dispose(); (Jobs as IDisposable)?.Dispose(); if (Engine is not null) await Engine.DisposeAsync(); Thumbnails?.Dispose(); Server.Dispose(); if (Database is not null) await Database.DisposeAsync(); } /// Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically. private async Task PollAsync(string root, CancellationToken ct) { try { if (Archives is null) return; var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct); using var timer = new PeriodicTimer(ScanInterval); do { if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct); } while (await timer.WaitForNextTickAsync(ct)); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException) { Log.Warning("archive", $"The archive at {root} could not be opened", ex); } } private async Task StartJobsAsync(TitanoDatabase database, bool startEngine, CancellationToken ct) { Archives = new ArchiveService(database, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(new WicDecoderProvider()) }); var handlers = CreateJobHandlers(this); var kinds = handlers.Select(h => h.Kind).Distinct().ToArray(); Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds }); // With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job. var started = startEngine && handlers.Count > 0; if (started) await Engine.StartAsync(ct); Jobs = new EngineJobQueue(database, Engine, started); Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued"); } }