From b13c9c5ccf775a072160c17d7b5de4421254fabf Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Sun, 15 Nov 2026 18:04:12 +0200 Subject: [PATCH] Updates the architecture diagrams and documents the PlantUML rendering workflow. --- README.md | 1 + .../1 system-context-diagram.puml | 5 +- .../architecture/1 system-context-diagram.svg | 2 +- .../architecture/2 container-diagram.puml | 25 +-- .../architecture/2 container-diagram.svg | 2 +- .../3.1 component-web-client-diagram.puml | 55 +++++-- .../3.1 component-web-client-diagram.svg | 2 +- .../3.2 component-api-server-diagram.puml | 97 ++++++++---- .../3.2 component-api-server-diagram.svg | 2 +- ...1 code-media-library-scanning-diagram.puml | 106 ++++++++----- ....1 code-media-library-scanning-diagram.svg | 2 +- .../4.2 code-book-reading-diagram.puml | 49 ++++-- .../4.2 code-book-reading-diagram.svg | 2 +- .../4.3 code-scheduler-diagram.puml | 145 ++++++++++++++++-- .../4.3 code-scheduler-diagram.svg | 2 +- docs/technical/architecture/README.md | 82 ++++++++++ src/Lumina.slnx | 1 + 17 files changed, 455 insertions(+), 125 deletions(-) create mode 100644 docs/technical/architecture/README.md diff --git a/README.md b/README.md index 6ea7de53..e0df7afa 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ For those with technical curiosities, here are some goodies to browse through: 5. [4.1 Code media library scanning diagram](./docs/technical/architecture/4.1%20code-media-library-scanning-diagram.svg) 6. [4.2 Code book reading diagram](./docs/technical/architecture/4.2%20code-book-reading-diagram.svg) 7. [4.3 Code scheduled jobs diagram](./docs/technical/architecture/4.3%20code-scheduler-diagram.svg) +- To regenerate the diagrams after editing a `.puml` file, follow the [diagram rendering instructions](./docs/technical/architecture/README.md). - Also for Software Architects, you might want to take a look at the Architecture Decision Log, where you may find important stories from the past of Lumina's development, like [this one](./docs/technical/architecture/architecture-knowledge-management/architecture-decision-log/architecture-decision-record-0001.md), and others like it. ## Telemetry and Observability diff --git a/docs/technical/architecture/1 system-context-diagram.puml b/docs/technical/architecture/1 system-context-diagram.puml index 7231e99d..19a2314d 100644 --- a/docs/technical/architecture/1 system-context-diagram.puml +++ b/docs/technical/architecture/1 system-context-diagram.puml @@ -1,4 +1,5 @@ @startuml Lumina System Context Diagram +!pragma layout elk !include LAYOUT_WITH_LEGEND() @@ -9,10 +10,10 @@ Person(admin, "Administrator", "A person who manages the media library system") System(lumina, "Lumina 1.1", "Allows users to organize, manage, stream and read their personal media content [detailed in '2 container-diagram.puml']") -System_Ext(metadataProvider, "Media Metadata Services", "External services that provide media information and metadata (TMDB, TVDB, GoodReads, MusicBrainz, etc)") +System_Ext(metadataProvider, "Media Metadata and Artwork Services", "External services that provide media information and artwork (MusicBrainz, Open Library, Cover Art Archive)") Rel(user, lumina, "Views, streams and reads media content") -Rel(admin, lumina, "Manages media library and system settings") +Rel(admin, lumina, "Manages media library, plugins, themes and system settings") Rel(lumina, metadataProvider, "Retrieves media metadata and artwork") caption [System Context] Lumina diff --git a/docs/technical/architecture/1 system-context-diagram.svg b/docs/technical/architecture/1 system-context-diagram.svg index 35fb094d..e8381dc1 100644 --- a/docs/technical/architecture/1 system-context-diagram.svg +++ b/docs/technical/architecture/1 system-context-diagram.svg @@ -1 +1 @@ -System Context diagram for Lumina Media Library ManagerHome User A person who wants to manageand stream their personalmedia collectionAdministrator A person who manages themedia library systemLumina 1.1 Allows users to organize,manage, stream and read theirpersonal media content[detailed in '2container-diagram.puml']Media Metadata Services External services that providemedia information andmetadata (TMDB, TVDB,GoodReads, MusicBrainz, etc)Views, streams and reads mediacontentManages media library and systemsettingsRetrieves media metadata andartworkLegend personsystemexternal personexternal system[System Context] LuminaThe system context diagram for the Lumina Media Library Manager - created with PlantUML \ No newline at end of file +System Context diagram for Lumina Media Library ManagerHome User A person who wants to manageand stream their personalmedia collectionAdministrator A person who manages themedia library systemLumina 1.1 Allows users to organize,manage, stream and read theirpersonal media content[detailed in '2container-diagram.puml']Media Metadata andArtwork Services External services that providemedia information and artwork(MusicBrainz, Open Library,Cover Art Archive)Views, streams and reads mediacontentManages media library, plugins,themes and system settingsRetrieves media metadata andartworkLegend personsystemexternal personexternal system[System Context] LuminaThe system context diagram for the Lumina Media Library Manager - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/2 container-diagram.puml b/docs/technical/architecture/2 container-diagram.puml index 93e4f19f..c00428f5 100644 --- a/docs/technical/architecture/2 container-diagram.puml +++ b/docs/technical/architecture/2 container-diagram.puml @@ -1,4 +1,5 @@ @startuml Lumina Container Diagram +!pragma layout elk !include LAYOUT_WITH_LEGEND() @@ -8,26 +9,26 @@ Person(user, "Home User", "A person who wants to manage and stream their persona Person(admin, "Administrator", "A person who manages the media library system") System_Boundary(c1, "Lumina 1.1") { - Container(webapp, "Web Application Client 2.1", "ASP.NET Core MVC", "Delivers server-rendered views with dynamic client-side functionality for media management, playback, and the scheduled jobs dashboard [detailed in '3.1 component-web-client-diagram.puml']") - - Container(api, "API Server 2.2", "ASP.NET Core", "Provides media management functionality via a REST API, processes media tasks, manages metadata synchronization, serves books for reading through format plugins, and runs the scheduled jobs that maintain the system [detailed in '3.2 component-api-server-diagram.puml']") - - ContainerDb(db, "Database", "SQLite", "Stores user data, media metadata, library configuration, scheduled jobs and their executions, automated jobs information, etc") - + Container(webapp, "Web Application Client 2.1", "ASP.NET Core + Razor", "Delivers server-rendered views with dynamic client-side functionality for media management, playback, reading, favorites, playlists, statistics, plugins, themes, and the scheduled jobs dashboard [detailed in '3.1 component-web-client-diagram.puml']") + + Container(api, "API Server 2.2", "ASP.NET Core", "Provides media library management, plugin metadata and artwork, music playback, book reading, themes, favorites, playlists, consumption statistics, and scheduled maintenance through a REST API [detailed in '3.2 component-api-server-diagram.puml']") + + ContainerDb(db, "Database", "SQLite", "Stores user data, media metadata, library configuration, favorites, playlists, media consumption, plugins, themes, scheduled jobs and their executions") + Container(filestore, "Media Store", "File System", "Stores the actual media files") - - Container(readCache, "Reading Cache", "File System", "Temporary directory in the API output, wiped at startup, where the reader plugins extract the contents of the books") + + Container(apiStorage, "API Local Storage", "File System", "API-private directories: the reading cache, the transcoding cache, the plugin store and the theme store") } -System_Ext(metadata, "Media Information Services", "External services like TMDB, TVDB, GoodReads, MusicBrainz, that provide media metadata") +System_Ext(metadata, "Media Metadata and Artwork Services", "External services like MusicBrainz, Open Library and Cover Art Archive, that provide media metadata and artwork") Rel(user, webapp, "Uses", "HTTPS") -Rel(admin, webapp, "Manages media library and system settings", "HTTPS") +Rel(admin, webapp, "Manages media library, plugins, themes and system settings", "HTTPS") Rel(webapp, api, "Makes API calls to", "JSON/HTTPS") Rel(api, db, "Reads from and writes to", "SQL") Rel(api, filestore, "Reads from and writes to") -Rel(api, readCache, "Reads from and writes to", "File system") -Rel(api, metadata, "Retrieves metadata from", "HTTPS") +Rel(api, apiStorage, "Reads from and writes to", "File system") +Rel(api, metadata, "Retrieves metadata and artwork from", "HTTPS") caption [Container] Lumina 1.1 diff --git a/docs/technical/architecture/2 container-diagram.svg b/docs/technical/architecture/2 container-diagram.svg index 57082e40..c00cfd93 100644 --- a/docs/technical/architecture/2 container-diagram.svg +++ b/docs/technical/architecture/2 container-diagram.svg @@ -1 +1 @@ -Container diagram for Lumina 1.1Lumina 1.1[system]Web Application Client2.1[ASP.NET Core MVC] Delivers server-rendered viewswith dynamic client-sidefunctionality for mediamanagement, playback, and thescheduled jobs dashboard[detailed in '3.1component-web-client-diagram.puml']API Server 2.2[ASP.NET Core] Provides media managementfunctionality via a REST API,processes media tasks,manages metadatasynchronization, serves booksfor reading through formatplugins, and runs the scheduledjobs that maintain the system[detailed in '3.2component-api-server-diagram.puml']Database[SQLite] Stores user data, mediametadata, library configuration,scheduled jobs and theirexecutions, automated jobsinformation, etcMedia Store[File System] Stores the actual media filesReading Cache[File System] Temporary directory in the APIoutput, wiped at startup, wherethe reader plugins extract thecontents of the booksHome User A person who wants to manageand stream their personalmedia collectionAdministrator A person who manages themedia library systemMedia InformationServices External services like TMDB,TVDB, GoodReads,MusicBrainz, that provide mediametadataUses[HTTPS]Manages media library and systemsettings[HTTPS]Makes API calls to[JSON/HTTPS]Reads from and writes to[SQL]Reads from and writes toReads from and writes to[File system]Retrieves metadata from[HTTPS]Legend personsystemcontainerexternal personexternal systemexternal container[Container] Lumina 1.1The container diagram for the Lumina 1.1 - created with PlantUML \ No newline at end of file +Container diagram for Lumina 1.1Lumina 1.1[system]Web Application Client2.1[ASP.NET Core + Razor] Delivers server-rendered viewswith dynamic client-sidefunctionality for mediamanagement, playback,reading, favorites, playlists,statistics, plugins, themes, andthe scheduled jobs dashboard[detailed in '3.1component-web-client-diagram.puml']API Server 2.2[ASP.NET Core] Provides media librarymanagement, plugin metadataand artwork, music playback,book reading, themes, favorites,playlists, consumption statistics,and scheduled maintenancethrough a REST API [detailed in'3.2component-api-server-diagram.puml']Database[SQLite] Stores user data, mediametadata, library configuration,favorites, playlists, mediaconsumption, plugins, themes,scheduled jobs and theirexecutionsMedia Store[File System] Stores the actual media filesAPI Local Storage[File System] API-private directories: thereading cache, the transcodingcache, the plugin store and thetheme storeHome User A person who wants to manageand stream their personalmedia collectionAdministrator A person who manages themedia library systemMedia Metadata andArtwork Services External services likeMusicBrainz, Open Library andCover Art Archive, that providemedia metadata and artworkUses[HTTPS]Manages media library, plugins,themes and system settings[HTTPS]Makes API calls to[JSON/HTTPS]Reads from and writes to[SQL]Reads from and writes toReads from and writes to[File system]Retrieves metadata and artworkfrom[HTTPS]Legend personsystemcontainerexternal personexternal systemexternal container[Container] Lumina 1.1The container diagram for the Lumina 1.1 - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/3.1 component-web-client-diagram.puml b/docs/technical/architecture/3.1 component-web-client-diagram.puml index ce28b718..12bc5d72 100644 --- a/docs/technical/architecture/3.1 component-web-client-diagram.puml +++ b/docs/technical/architecture/3.1 component-web-client-diagram.puml @@ -1,4 +1,5 @@ @startuml Lumina Web Application Components +!pragma layout elk !include LAYOUT_WITH_LEGEND() @@ -7,39 +8,61 @@ title Component diagram for Lumina Web Application Client 2.1 Container_Ext(api, "API Server 2.2", "Lumina.Presentation.Api", "Provides media management functionality via JSON/HTTPS API [detailed in '3.2 component-api-server-diagram.puml']") Container_Boundary(wb, "Web Application 2.1") { - Component(fileSystem, "File System Management", "ASP.NET MVC Controllers", "Handles file system operations including drives, directories, and files browsing") - - Component(library, "Library Management", "ASP.NET MVC Controllers", "Manages media libraries and their content (books, etc); the library edit page lets the owner enable or disable the reader plugins per library") - + Component(fileSystem, "File System Management", "FastEndpoints + Razor views", "Handles file system operations including drives, directories, files browsing, path operations and thumbnails") + + Component(library, "Library Management", "FastEndpoints + Razor views", "Manages media libraries and their content (books, music), their scan controls and their consumption statistics") + + Component(favorites, "Favorites", "FastEndpoints + Razor views", "Lists, adds and removes the favorites of the current user") + + Component(playlists, "Playlists", "FastEndpoints + Razor views", "Creates and edits playlists and their ordered entries") + Component(bookReader, "Book Reading", "FastEndpoints + JavaScript", "Serves the book reader view and proxies the reading manifest, section and resource endpoints to the API") - - Component(scheduler, "Scheduler", "FastEndpoints + JavaScript", "Serves the scheduled jobs dashboard, proxies the scheduled job endpoints to the API, and plots the executions of the scheduled job tasks over time") - - Component(admin, "Administration", "ASP.NET MVC Controllers", "Handles system administration and configuration") - - Component(users, "User Management", "ASP.NET MVC Controllers", "Handles authentication and user management") - - Component(clientJs, "Client-Side Logic", "JavaScript", "Handles dynamic page updates, persistent media playback, the book reader (table of contents, page navigation, font size), and the scheduled jobs dashboard (job type filters, execution graph, live hub updates)") - - Component(httpClient, "API HTTP Client", "C# TypedHttpClient", "Handles communication with the API server") + + Component(musicPlayback, "Music Playback", "FastEndpoints + JavaScript", "Serves the music player views and proxies track streams and normalized segments from the API without buffering them") + + Component(mediaConsumption, "Media Consumption", "FastEndpoints", "Proxies playback and reading progress, resume points and completion events to the API") + + Component(scheduler, "Scheduler", "FastEndpoints + JavaScript", "Serves the scheduled jobs dashboard, proxies the scheduled job and display preference endpoints to the API, and plots the executions of the scheduled job tasks over time") + + Component(admin, "Administration", "FastEndpoints + Razor views", "Manages roles, permissions, users, plugins and themes") + + Component(users, "User Management", "FastEndpoints + Razor views", "Handles authentication, registration, password recovery, the profile and user settings") + + Component(themes, "Theming", "Razor views + theme engine", "Renders the active theme, its layouts, navigation, audio player and file system browser, and serves theme assets") + + Component(clientJs, "Client-Side Logic", "JavaScript", "Handles dynamic page updates, persistent media playback, the book reader (table of contents, page navigation, font size), favorites and playlists, media library scan progress, and the scheduled jobs dashboard (job type filters, execution graph, live hub updates)") + + Component(httpClient, "API HTTP Client", "C# TypedHttpClient", "Handles buffered communication with the API server") + + Component(streamingClient, "Streaming API HTTP Client", "C# TypedHttpClient", "Streams track audio and segments from the API server without buffering them") } Rel(fileSystem, httpClient, "Uses") Rel(library, httpClient, "Uses") +Rel(favorites, httpClient, "Uses") +Rel(playlists, httpClient, "Uses") Rel(bookReader, httpClient, "Uses") +Rel(musicPlayback, streamingClient, "Uses") +Rel(mediaConsumption, httpClient, "Uses") Rel(scheduler, httpClient, "Uses") Rel(admin, httpClient, "Uses") Rel(users, httpClient, "Uses") +Rel(themes, httpClient, "Uses") Rel(httpClient, api, "Makes API calls to", "JSON/HTTPS") +Rel(streamingClient, api, "Streams track audio from", "JSON/HTTPS") Rel(clientJs, fileSystem, "Makes AJAX calls to") Rel(clientJs, library, "Makes AJAX calls to") +Rel(clientJs, favorites, "Makes AJAX calls to") +Rel(clientJs, playlists, "Makes AJAX calls to") Rel(clientJs, bookReader, "Makes AJAX calls to") +Rel(clientJs, musicPlayback, "Makes AJAX calls to") +Rel(clientJs, mediaConsumption, "Makes AJAX calls to") Rel(clientJs, scheduler, "Makes AJAX calls to") Rel(clientJs, admin, "Makes AJAX calls to") Rel(clientJs, users, "Makes AJAX calls to") -Rel(clientJs, api, "Receives scheduled jobs and execution updates from the scheduled jobs hub", "SignalR") +Rel(clientJs, api, "Receives media library scan progress and scheduled job updates from the SignalR hubs", "SignalR") caption [Component] Lumina - Web Application Client 2.1 (Lumina.Presentation.Web) footer The component diagram for the Lumina Web Application Client 2.1 - created with PlantUML -@enduml \ No newline at end of file +@enduml diff --git a/docs/technical/architecture/3.1 component-web-client-diagram.svg b/docs/technical/architecture/3.1 component-web-client-diagram.svg index 367a34a5..17fde618 100644 --- a/docs/technical/architecture/3.1 component-web-client-diagram.svg +++ b/docs/technical/architecture/3.1 component-web-client-diagram.svg @@ -1 +1 @@ -Component diagram for Lumina Web Application Client 2.1Web Application 2.1[container]File System Management[ASP.NET MVC Controllers] Handles file system operationsincluding drives, directories, andfiles browsingLibrary Management[ASP.NET MVC Controllers] Manages media libraries andtheir content (books, etc); thelibrary edit page lets the ownerenable or disable the readerplugins per libraryBook Reading[FastEndpoints + JavaScript] Serves the book reader viewand proxies the readingmanifest, section and resourceendpoints to the APIScheduler[FastEndpoints + JavaScript] Serves the scheduled jobsdashboard, proxies thescheduled job endpoints to theAPI, and plots the executions ofthe scheduled job tasks overtimeAdministration[ASP.NET MVC Controllers] Handles system administrationand configurationUser Management[ASP.NET MVC Controllers] Handles authentication anduser managementClient-Side Logic[JavaScript] Handles dynamic pageupdates, persistent mediaplayback, the book reader(table of contents, pagenavigation, font size), and thescheduled jobs dashboard (jobtype filters, execution graph, livehub updates)API HTTP Client[C# TypedHttpClient] Handles communication withthe API serverAPI Server 2.2[Lumina.Presentation.Api] Provides media managementfunctionality via JSON/HTTPSAPI [detailed in '3.2component-api-server-diagram.puml']UsesUsesUsesUsesUsesUsesMakes API calls to[JSON/HTTPS]Makes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toReceives scheduled jobs andexecution updates from thescheduled jobs hub[SignalR]Legend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Component] Lumina - Web Application Client 2.1 (Lumina.Presentation.Web)The component diagram for the Lumina Web Application Client 2.1 - created with PlantUML \ No newline at end of file +Component diagram for Lumina Web Application Client 2.1Web Application 2.1[container]File System Management[FastEndpoints + Razor views] Handles file system operationsincluding drives, directories,files browsing, path operationsand thumbnailsLibrary Management[FastEndpoints + Razor views] Manages media libraries andtheir content (books, music),their scan controls and theirconsumption statisticsFavorites[FastEndpoints + Razor views] Lists, adds and removes thefavorites of the current userPlaylists[FastEndpoints + Razor views] Creates and edits playlists andtheir ordered entriesBook Reading[FastEndpoints + JavaScript] Serves the book reader viewand proxies the readingmanifest, section and resourceendpoints to the APIMusic Playback[FastEndpoints + JavaScript] Serves the music player viewsand proxies track streams andnormalized segments from theAPI without buffering themMedia Consumption[FastEndpoints] Proxies playback and readingprogress, resume points andcompletion events to the APIScheduler[FastEndpoints + JavaScript] Serves the scheduled jobsdashboard, proxies thescheduled job and displaypreference endpoints to theAPI, and plots the executions ofthe scheduled job tasks overtimeAdministration[FastEndpoints + Razor views] Manages roles, permissions,users, plugins and themesUser Management[FastEndpoints + Razor views] Handles authentication,registration, password recovery,the profile and user settingsTheming[Razor views + theme engine] Renders the active theme, itslayouts, navigation, audioplayer and file system browser,and serves theme assetsClient-Side Logic[JavaScript] Handles dynamic pageupdates, persistent mediaplayback, the book reader(table of contents, pagenavigation, font size), favoritesand playlists, media library scanprogress, and the scheduledjobs dashboard (job type filters,execution graph, live hubupdates)API HTTP Client[C# TypedHttpClient] Handles bufferedcommunication with the APIserverStreaming API HTTPClient[C# TypedHttpClient] Streams track audio andsegments from the API serverwithout buffering themAPI Server 2.2[Lumina.Presentation.Api] Provides media managementfunctionality via JSON/HTTPSAPI [detailed in '3.2component-api-server-diagram.puml']UsesUsesUsesUsesUsesUsesUsesUsesUsesUsesUsesMakes API calls to[JSON/HTTPS]Streams track audio from[JSON/HTTPS]Makes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toReceives media library scanprogress and scheduled jobupdates from the SignalR hubs[SignalR]Legend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Component] Lumina - Web Application Client 2.1 (Lumina.Presentation.Web)The component diagram for the Lumina Web Application Client 2.1 - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/3.2 component-api-server-diagram.puml b/docs/technical/architecture/3.2 component-api-server-diagram.puml index 9b01eccf..d0cb4292 100644 --- a/docs/technical/architecture/3.2 component-api-server-diagram.puml +++ b/docs/technical/architecture/3.2 component-api-server-diagram.puml @@ -1,4 +1,5 @@ @startuml Lumina API Server Components +!pragma layout elk !include LAYOUT_WITH_LEGEND() @@ -7,50 +8,94 @@ title Component diagram for Lumina API Server 2.2 Container_Ext(webapp, "Web Application Client 2.1", "Lumina.Presentation.Web", "Provides the user interface [detailed in '3.1 component-web-client-diagram.puml']") Container_Boundary(api, "API Server 2.2") { - Component(endpoints, "API Endpoints", "FastEndpoints", "Provides REST API endpoints for media management and streaming") - - Component(mediaManagement, "Media Library Management", "Domain Services", "Handles media libraries operations and metadata management") - - Component(userManagement, "User Management", "Domain Services", "Handles user authentication and authorization") - - Component(fileSystem, "File System Management", "Domain Services", "Manages file system operations and media access") - - Component(backgroundServices, "Background Services 3.2.1", ".NET Worker Services", "Handles media scanning, metadata synchronization and other maintenance tasks [detailed in '4.1 code-media-library-scanning-diagram.puml']") - + Component(endpoints, "API Endpoints", "FastEndpoints", "Provides REST API endpoints for libraries, media items, playback, reading, favorites, playlists, statistics, plugins, themes, scheduling, users, administration and maintenance") + + Component(mediaManagement, "Media Library Management", "Application + Domain services", "Handles media libraries and their books and music, and owns the lifecycle and queueing of their scans") + + Component(mediaConsumption, "Media Consumption", "Application + Domain services", "Tracks playback and reading progress, resume points and per-user consumption statistics") + + Component(favorites, "Favorites", "Application + Domain services", "Tracks the favorite library items of each user") + + Component(playlists, "Playlists", "Application + Domain services", "Creates playlists and orders their entries") + + Component(fileSystem, "File System Management", "Application + Domain services", "Manages drives, directories, files, paths and thumbnails") + + Component(userManagement, "User Management", "Application + Domain services", "Handles authentication, roles, permissions and user settings") + + Component(backgroundServices, "Media Library Scanning 3.2.1", ".NET Worker Services", "Executes the queued media library scans, owns their metadata and artwork enrichment, and publishes their progress notifications [detailed in '4.1 code-media-library-scanning-diagram.puml']") + Component(bookReading, "Book Reading 3.2.2", "Application + Infrastructure services", "Resolves the reader plugin of a book, checks its per-library enablement, extracts the book into the reading cache on first access, sanitizes every section, and serves the reading manifest, sections and resources [detailed in '4.2 code-book-reading-diagram.puml']") - + Component(readerPlugins, "Book Reader Plugins", "Lumina.Plugins.Epub, Lumina.Plugins.Pdf", "Decode a book format into a normalized reading document (spine, table of contents, sections, resources), loaded into the host by the plugin loader [detailed in '4.2 code-book-reading-diagram.puml']") - - Component(scheduledJobs, "Scheduled Jobs 3.2.3", "Application + Infrastructure services", "Lets administrators schedule the one off or recurring execution of maintenance tasks (media library scans, temporary files cleanup); a background scheduler runs the tasks on their schedules and the scheduled jobs hub broadcasts the jobs and their executions [detailed in '4.3 code-scheduler-diagram.puml']") - - Component(repositories, "Repositories", "EF Core", "Provides data access abstraction for domain entities") + + Component(musicPlayback, "Music Playback", "Application + Infrastructure services", "Decides how a track is delivered, normalizes audio with ffmpeg, caches it as segments and serves the track stream and segment endpoints") + + Component(plugins, "Plugin Hosting", "Plugin loader + Application services", "Loads metadata, artwork and book reader plugins, installs them, stores their settings and applies the per-library provider configurations; the hosted metadata and artwork providers call the external services") + + Component(themes, "Themes", "Application + Infrastructure services", "Installs, repairs and serves theme packs and their assets") + + Component(scheduledJobs, "Scheduled Jobs 3.2.3", "Application + Infrastructure services", "Lets administrators schedule the one off or recurring execution of maintenance tasks (media library scans, temporary files cleanup, theme repair, execution history cleanup, technical data cleanup), stores the display preferences of the scheduler page, and broadcasts the jobs and their executions; a background scheduler runs the tasks on their schedules [detailed in '4.3 code-scheduler-diagram.puml']") + + Component(repositories, "Repositories", "EF Core + Dapper", "Provides data access for the domain entities and the consumption statistics") } -ContainerDb(db, "Database", "SQLite", "Stores user data, media metadata, and system configuration") +ContainerDb_Ext(db, "Database", "SQLite", "Stores user data, media metadata, library configuration, favorites, playlists, media consumption, plugins, themes, scheduled jobs and their executions") -Container(readCache, "Reading Cache", "File System", "Temporary directory in the API output, wiped at startup, where the reader plugins extract the contents of the books") +Container_Ext(filestore, "Media Store", "File System", "Stores the actual media files") -System_Ext(metadataServices, "External Metadata Services", "Provides media information (TMDB, TVDB, GoodReads, MusicBrainz, etc)") +Container_Ext(readCache, "Reading Cache", "File System", "Temporary directory in the API output, wiped at startup, where the reader plugins extract the contents of the books") + +Container_Ext(transcodingCache, "Transcoding Cache", "File System", "Normalized audio cache. By default a private directory under the system temporary directory, scoped to the API account; a configured relative TranscodingSettings:CacheDirectory resolves under the API base directory. It must never overlap the media root: it must neither sit inside it nor contain it.") + +Container_Ext(pluginStore, "Plugin Store", "File System", "Plugin assemblies and their dependencies, installed into this directory on upload and loaded from it when the API starts") + +Container_Ext(themeStore, "Theme Store", "File System", "Installed and bundled theme packs served by the API") + +System_Ext(metadataServices, "Media Metadata and Artwork Services", "Provides media information and artwork (MusicBrainz, Open Library, Cover Art Archive)") Rel(webapp, endpoints, "Makes API calls to", "JSON/HTTPS") Rel(endpoints, mediaManagement, "Uses") -Rel(endpoints, userManagement, "Uses") +Rel(endpoints, mediaConsumption, "Uses") +Rel(endpoints, favorites, "Uses") +Rel(endpoints, playlists, "Uses") Rel(endpoints, fileSystem, "Uses") +Rel(endpoints, userManagement, "Uses") Rel(endpoints, bookReading, "Uses") +Rel(endpoints, musicPlayback, "Uses") +Rel(endpoints, plugins, "Uses") +Rel(endpoints, themes, "Uses") Rel(endpoints, scheduledJobs, "Uses") Rel(mediaManagement, repositories, "Uses") +Rel(mediaManagement, filestore, "Reads from and writes to") +Rel(mediaManagement, plugins, "Configures the metadata and artwork providers") +Rel(mediaConsumption, repositories, "Uses") +Rel(favorites, repositories, "Uses") +Rel(playlists, repositories, "Uses") Rel(userManagement, repositories, "Uses") -Rel(fileSystem, repositories, "Uses") -Rel(backgroundServices, mediaManagement, "Uses") -Rel(scheduledJobs, repositories, "Uses") -Rel(repositories, db, "Reads from and writes to", "SQL") -Rel(mediaManagement, metadataServices, "Retrieves metadata from", "HTTPS") -Rel(bookReading, readerPlugins, "Resolves and invokes") Rel(bookReading, repositories, "Reads the per-library reader enablement") +Rel(bookReading, readerPlugins, "Resolves and invokes") Rel(bookReading, readCache, "Extracts into and serves from", "File system") Rel(readerPlugins, readCache, "Extracts into", "File system") -Rel(scheduledJobs, backgroundServices, "Queues the media library scans of its ScanMediaLibraries task") +Rel(musicPlayback, repositories, "Reads the track locations") +Rel(musicPlayback, filestore, "Reads the source tracks") +Rel(musicPlayback, transcodingCache, "Reads from and writes to", "File system") +Rel(plugins, readerPlugins, "Loads and registers") +Rel(plugins, repositories, "Stores plugin settings and provider configurations") +Rel(plugins, pluginStore, "Installs into and loads plugin assemblies from", "File system") +Rel(plugins, metadataServices, "Retrieves metadata and artwork from", "HTTPS") +Rel(themes, repositories, "Reads and updates the current theme") +Rel(themes, themeStore, "Reads and writes theme packs", "File system") +Rel(backgroundServices, mediaManagement, "Prepares the scan job graph") +Rel(backgroundServices, fileSystem, "Reads and writes media files") +Rel(backgroundServices, plugins, "Uses the enabled metadata and artwork providers") +Rel(backgroundServices, repositories, "Reads and writes the scan staging data") +Rel(mediaManagement, backgroundServices, "Queues and cancels scans") +Rel(fileSystem, filestore, "Browses") +Rel(scheduledJobs, repositories, "Uses") +Rel(scheduledJobs, mediaManagement, "Queues the media library scans of its ScanMediaLibraries task") +Rel(scheduledJobs, themes, "Repairs the installed themes of its RepairThemes task") Rel(scheduledJobs, readCache, "Empties with its CleanTemporaryFiles task", "File system") +Rel(repositories, db, "Reads from and writes to", "SQL") caption [Component] Lumina - API Server 2.2 (Lumina.Presentation.Api) diff --git a/docs/technical/architecture/3.2 component-api-server-diagram.svg b/docs/technical/architecture/3.2 component-api-server-diagram.svg index 8d389fae..18c9a293 100644 --- a/docs/technical/architecture/3.2 component-api-server-diagram.svg +++ b/docs/technical/architecture/3.2 component-api-server-diagram.svg @@ -1 +1 @@ -Component diagram for Lumina API Server 2.2API Server 2.2[container]API Endpoints[FastEndpoints] Provides REST API endpointsfor media management andstreamingMedia LibraryManagement[Domain Services] Handles media librariesoperations and metadatamanagementUser Management[Domain Services] Handles user authenticationand authorizationFile System Management[Domain Services] Manages file system operationsand media accessBackground Services3.2.1[.NET Worker Services] Handles media scanning,metadata synchronization andother maintenance tasks[detailed in '4.1code-media-library-scanning-diagram.puml']Book Reading 3.2.2[Application + Infrastructure services] Resolves the reader plugin of abook, checks its per-libraryenablement, extracts the bookinto the reading cache on firstaccess, sanitizes every section,and serves the readingmanifest, sections andresources [detailed in '4.2code-book-reading-diagram.puml']Book Reader Plugins[Lumina.Plugins.Epub,Lumina.Plugins.Pdf] Decode a book format into anormalized reading document(spine, table of contents,sections, resources), loadedinto the host by the pluginloader [detailed in '4.2code-book-reading-diagram.puml']Scheduled Jobs 3.2.3[Application + Infrastructure services] Lets administrators schedulethe one off or recurringexecution of maintenance tasks(media library scans, temporaryfiles cleanup); a backgroundscheduler runs the tasks ontheir schedules and thescheduled jobs hub broadcaststhe jobs and their executions[detailed in '4.3code-scheduler-diagram.puml']Repositories[EF Core] Provides data accessabstraction for domain entitiesWeb Application Client2.1[Lumina.Presentation.Web] Provides the user interface[detailed in '3.1component-web-client-diagram.puml']Database[SQLite] Stores user data, mediametadata, and systemconfigurationReading Cache[File System] Temporary directory in the APIoutput, wiped at startup, wherethe reader plugins extract thecontents of the booksExternal MetadataServices Provides media information(TMDB, TVDB, GoodReads,MusicBrainz, etc)Makes API calls to[JSON/HTTPS]UsesUsesUsesUsesUsesUsesUsesUsesUsesUsesReads from and writes to[SQL]Retrieves metadata from[HTTPS]Resolves and invokesReads the per-library readerenablementExtracts into and serves from[File system]Extracts into[File system]Queues the media library scans ofits ScanMediaLibraries taskEmpties with itsCleanTemporaryFiles task[File system]Legend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Component] Lumina - API Server 2.2 (Lumina.Presentation.Api)The component diagram for the Lumina API Server 2.2 - created with PlantUML \ No newline at end of file +Component diagram for Lumina API Server 2.2API Server 2.2[container]API Endpoints[FastEndpoints] Provides REST API endpointsfor libraries, media items,playback, reading, favorites,playlists, statistics, plugins,themes, scheduling, users,administration and maintenanceMedia LibraryManagement[Application + Domain services] Handles media libraries andtheir books and music, andowns the lifecycle and queueingof their scansMedia Consumption[Application + Domain services] Tracks playback and readingprogress, resume points andper-user consumption statisticsFavorites[Application + Domain services] Tracks the favorite library itemsof each userPlaylists[Application + Domain services] Creates playlists and orderstheir entriesFile System Management[Application + Domain services] Manages drives, directories,files, paths and thumbnailsUser Management[Application + Domain services] Handles authentication, roles,permissions and user settingsMedia Library Scanning3.2.1[.NET Worker Services] Executes the queued medialibrary scans, owns theirmetadata and artworkenrichment, and publishes theirprogress notifications [detailedin '4.1code-media-library-scanning-diagram.puml']Book Reading 3.2.2[Application + Infrastructure services] Resolves the reader plugin of abook, checks its per-libraryenablement, extracts the bookinto the reading cache on firstaccess, sanitizes every section,and serves the readingmanifest, sections andresources [detailed in '4.2code-book-reading-diagram.puml']Book Reader Plugins[Lumina.Plugins.Epub,Lumina.Plugins.Pdf] Decode a book format into anormalized reading document(spine, table of contents,sections, resources), loadedinto the host by the pluginloader [detailed in '4.2code-book-reading-diagram.puml']Music Playback[Application + Infrastructure services] Decides how a track isdelivered, normalizes audio withffmpeg, caches it as segmentsand serves the track stream andsegment endpointsPlugin Hosting[Plugin loader + Application services] Loads metadata, artwork andbook reader plugins, installsthem, stores their settings andapplies the per-library providerconfigurations; the hostedmetadata and artwork providerscall the external servicesThemes[Application + Infrastructure services] Installs, repairs and servestheme packs and their assetsScheduled Jobs 3.2.3[Application + Infrastructure services] Lets administrators schedulethe one off or recurringexecution of maintenance tasks(media library scans, temporaryfiles cleanup, theme repair,execution history cleanup,technical data cleanup), storesthe display preferences of thescheduler page, and broadcaststhe jobs and their executions; abackground scheduler runs thetasks on their schedules[detailed in '4.3code-scheduler-diagram.puml']Repositories[EF Core + Dapper] Provides data access for thedomain entities and theconsumption statisticsWeb Application Client2.1[Lumina.Presentation.Web] Provides the user interface[detailed in '3.1component-web-client-diagram.puml']Database[SQLite] Stores user data, mediametadata, library configuration,favorites, playlists, mediaconsumption, plugins, themes,scheduled jobs and theirexecutionsMedia Store[File System] Stores the actual media filesReading Cache[File System] Temporary directory in the APIoutput, wiped at startup, wherethe reader plugins extract thecontents of the booksTranscoding Cache[File System] Normalized audio cache. Bydefault a private directory underthe system temporary directory,scoped to the API account; aconfigured relativeTranscodingSettings:CacheDirectoryresolves under the API basedirectory. It must never overlapthe media root: it must neithersit inside it nor contain it.Plugin Store[File System] Plugin assemblies and theirdependencies, installed into thisdirectory on upload and loadedfrom it when the API startsTheme Store[File System] Installed and bundled themepacks served by the APIMedia Metadata andArtwork Services Provides media information andartwork (MusicBrainz, OpenLibrary, Cover Art Archive)Makes API calls to[JSON/HTTPS]UsesUsesUsesUsesUsesUsesUsesUsesUsesUsesUsesUsesReads from and writes toConfigures the metadata andartwork providersUsesUsesUsesUsesReads the per-library readerenablementResolves and invokesExtracts into and serves from[File system]Extracts into[File system]Reads the track locationsReads the source tracksReads from and writes to[File system]Loads and registersStores plugin settings andprovider configurationsInstalls into and loads pluginassemblies from[File system]Retrieves metadata and artworkfrom[HTTPS]Reads and updates the currentthemeReads and writes theme packs[File system]Prepares the scan job graphReads and writes media filesUses the enabled metadata andartwork providersReads and writes the scan stagingdataQueues and cancels scansBrowsesUsesQueues the media library scans ofits ScanMediaLibraries taskRepairs the installed themes of itsRepairThemes taskEmpties with itsCleanTemporaryFiles task[File system]Reads from and writes to[SQL]Legend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Component] Lumina - API Server 2.2 (Lumina.Presentation.Api)The component diagram for the Lumina API Server 2.2 - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/4.1 code-media-library-scanning-diagram.puml b/docs/technical/architecture/4.1 code-media-library-scanning-diagram.puml index e9318281..9909556b 100644 --- a/docs/technical/architecture/4.1 code-media-library-scanning-diagram.puml +++ b/docs/technical/architecture/4.1 code-media-library-scanning-diagram.puml @@ -1,8 +1,9 @@ @startuml Media Library Scanning System Code +!pragma layout elk !include LAYOUT_WITH_LEGEND() -title Code diagram for Background Services 3.2.1 +title Code diagram for Media Library Scanning 3.2.1 skinparam class { BackgroundColor White @@ -23,6 +24,9 @@ interface IMediaLibraryScanJob { + ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task } +interface IMediaLibraryScanDiscoveryJob { +} + abstract class MediaLibraryScanJob { # parentsPayloadsExecuted: int + {abstract} ExecuteAsync(id: Guid, input: TInput, token: CancellationToken): Task @@ -148,16 +152,16 @@ class MediaLibraryScanJobFactory { } interface IMediaLibraryScannerFactory { - + CreateLibraryScanner(libraryType: LibraryType): IMediaTypeScanner + + CreateLibraryScanner(libraryType: LibraryType): Result } class MediaLibraryScannerFactory { - + CreateLibraryScanner(libraryType: LibraryType): IMediaTypeScanner + + CreateLibraryScanner(libraryType: LibraryType): Result } interface IMediaTypeScanner { + SupportedLibraryType: LibraryType - + CreateScanJobsForLibrary(libraryId: LibraryId): IEnumerable + + CreateScanJobsForLibrary(libraryId: LibraryId): IMediaLibraryScanDiscoveryJob } interface IBookLibraryTypeScanner { @@ -169,13 +173,13 @@ interface IMusicLibraryTypeScanner { class BookLibraryTypeScanner { - _mediaScanJobFactory: IMediaLibraryScanJobFactory + SupportedLibraryType: LibraryType - + CreateScanJobsForLibrary(libraryId: LibraryId): IEnumerable + + CreateScanJobsForLibrary(libraryId: LibraryId): IMediaLibraryScanDiscoveryJob } class MusicLibraryTypeScanner { - _mediaScanJobFactory: IMediaLibraryScanJobFactory + SupportedLibraryType: LibraryType - + CreateScanJobsForLibrary(libraryId: LibraryId): IEnumerable + + CreateScanJobsForLibrary(libraryId: LibraryId): IMediaLibraryScanDiscoveryJob } ' ============================== MEDIA TYPE STRATEGIES ============================== @@ -183,7 +187,8 @@ class MusicLibraryTypeScanner { interface IMediaLibraryScanItemMaterializer { + SupportedLibraryType: LibraryType + ResetEnrichmentStateForChangedPathsAsync(unitOfWork: IUnitOfWork, libraryId: Guid, paths: IReadOnlyCollection, token: CancellationToken): Task> - + MaterializeItemsAsync(unitOfWork: IUnitOfWork, libraryId: Guid, scanId: Guid, paths: IReadOnlyList, token: CancellationToken): Task> + + MaterializeItemsAsync(unitOfWork: IUnitOfWork, libraryId: Guid, scanId: Guid, paths: IReadOnlySet, token: CancellationToken): Task> + + ClearStagedDataAsync(unitOfWork: IUnitOfWork, libraryId: Guid, scanId: Guid, token: CancellationToken): Task> + ResetMetadataStatusForLibraryAsync(unitOfWork: IUnitOfWork, libraryId: Guid, token: CancellationToken): Task> + ResetArtworkStatusForLibraryAsync(unitOfWork: IUnitOfWork, libraryId: Guid, token: CancellationToken): Task> } @@ -263,6 +268,7 @@ class LibraryScan { + UserId: UserId + Status: LibraryScanJobStatus + {static} Create(libraryId: LibraryId, userId: UserId, pastScans: List): Result + + {static} Create(id: ScanId, libraryId: LibraryId, userId: UserId, status: LibraryScanJobStatus, pastScans: List): Result + QueueScan(): Result + StartScan(): Result + FinishScan(): Result @@ -276,56 +282,62 @@ note right of LibraryScan end note interface IMediaLibraryScanningService { - + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, token: CancellationToken): Task> + + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, token: CancellationToken): Task> + CancelScan(scan: LibraryScan): Result } class MediaLibraryScanningService { - - _mediaLibrariesScanQueue: IMediaLibrariesScanQueue - _mediaLibraryScannerFactory: IMediaLibraryScannerFactory - _mediaLibrariesScanCancellationTracker: IMediaLibrariesScanCancellationTracker - _mediaLibrariesScanProgressTracker: IMediaLibrariesScanProgressTracker - _domainEventPublisher: IDomainEventPublisher - + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, token: CancellationToken): Task> + + StartScanAsync(scan: LibraryScan, libraryType: LibraryType, token: CancellationToken): Task> + CancelScan(scan: LibraryScan): Result } note top of MediaLibraryScanningService - Central service that starts a scan by building its job graph, - registering it in the cancellation and progress trackers and - enqueueing the root jobs, and that cancels a running scan. + Central service that resolves the scanner of the library type, + builds the scan job graph, registers the scan in the cancellation + and progress trackers, and publishes the scan started events. + It returns the file system discovery job, which is the root of + the graph and whose execution completes the entire scan. end note ' ============================== QUEUE AND PROCESSING ============================== interface IMediaLibrariesScanQueue { - + Writer: ChannelWriter - + Reader: ChannelReader + + Writer: ChannelWriter + + Reader: ChannelReader } class MediaLibrariesScanQueue { - - _channel: Channel - + Writer: ChannelWriter - + Reader: ChannelReader + - _channel: Channel + + Writer: ChannelWriter + + Reader: ChannelReader } note bottom of MediaLibrariesScanQueue - In-memory queue that receives only the root scan jobs of a - scan. Children are triggered directly by their parents, and - are never placed on this queue. + In-memory queue of scan composite ids. The scan processor + prepares and executes one scan at a time, so the scans run + consecutively, in the order in which they were queued. The + jobs of a scan are never placed on this queue. end note -class MediaLibraryScanJobProcessorJob { - - _mediaScanQueue: IMediaLibrariesScanQueue +class MediaLibraryScanProcessorJob { + - _mediaLibrariesScanQueue: IMediaLibrariesScanQueue - _mediaLibrariesScanCancellationTracker: IMediaLibrariesScanCancellationTracker + - _serviceScopeFactory: IServiceScopeFactory + - _logger: ILogger # ExecuteAsync(token: CancellationToken): Task + - ProcessScanAsync(compositeId: MediaLibraryScanCompositeId, token: CancellationToken): Task + - ReportScanFailureAsync(compositeId: MediaLibraryScanCompositeId, libraryId: LibraryId, exception: Exception, token: CancellationToken): Task } -note top of MediaLibraryScanJobProcessorJob - Background service that launches the payload execution of the - root scan jobs that arrive on the in-memory queue, firing them - in a fire-and-forget manner without awaiting their long running - payload execution (see ADR-0001, ADR-0009). +note top of MediaLibraryScanProcessorJob + Background service that consumes the queued scan ids one at a + time, reads the pending scan, prepares its job graph through the + scanning service and executes the discovery job. A failing scan + is reported and does not stop the scans queued behind it. end note ' ============================== TRACKERS ============================== @@ -342,6 +354,7 @@ class MediaLibrariesScanCancellationTracker { } interface IMediaLibrariesScanProgressTracker { + + InitializeQueuedScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId): Result + InitializeScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, totalJobs: int): Result + UpdateScanProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId): Result + UpdateScanJobProgress(libraryId: LibraryId, compositeKey: MediaLibraryScanCompositeId, progress: MediaLibraryScanJobProgress): Result @@ -382,6 +395,12 @@ class LibraryScanQueuedDomainEventHandler { + HandleAsync(domainEvent: LibraryScanQueuedDomainEvent, token: CancellationToken): ValueTask } +note right of LibraryScanQueuedDomainEventHandler + Registers the scan for cancellation, reports it as queued, + and writes its composite id to the scan queue. The scan + processor prepares and executes the job graph later. +end note + class LibraryScanStartedDomainEventHandler { + HandleAsync(domainEvent: LibraryScanStartedDomainEvent, token: CancellationToken): ValueTask } @@ -410,8 +429,9 @@ class LibraryScanJobProgressChangedDomainEventHandler { IMediaLibraryScanJob <|.. MediaLibraryScanJob : implements -IMediaLibraryScanJob <|-- IBooksFileSystemDiscoveryJob -IMediaLibraryScanJob <|-- IMusicFileSystemDiscoveryJob +IMediaLibraryScanJob <|-- IMediaLibraryScanDiscoveryJob +IMediaLibraryScanDiscoveryJob <|-- IBooksFileSystemDiscoveryJob +IMediaLibraryScanDiscoveryJob <|-- IMusicFileSystemDiscoveryJob IMediaLibraryScanJob <|-- IMusicMetadataExtractionJob IMediaLibraryScanJob <|-- IMediaLibraryScanDiffJob IMediaLibraryScanJob <|-- IMediaLibraryScanHashJob @@ -442,12 +462,12 @@ IMediaLibraryScanResultsSaveJob <|.. MediaLibraryScanResultsSaveJob : implements ' ============================== JOB TRIGGER CHAIN ============================== -BooksFileSystemDiscoveryJob ..> MediaLibraryScanDiffJob : triggers -MusicFileSystemDiscoveryJob ..> MediaLibraryScanDiffJob : triggers +BooksFileSystemDiscoveryJob ..> MediaLibraryScanDiffJob : triggers (books) +MusicFileSystemDiscoveryJob ..> MediaLibraryScanDiffJob : triggers (music) MediaLibraryScanDiffJob ..> MediaLibraryScanHashJob : triggers -MediaLibraryScanHashJob ..> MediaLibraryScanResultsSaveJob : triggers -MediaLibraryScanHashJob ..> MusicMetadataExtractionJob : triggers -MusicMetadataExtractionJob ..> MediaLibraryScanResultsSaveJob : triggers +MediaLibraryScanHashJob ..> MediaLibraryScanResultsSaveJob : triggers (books) +MediaLibraryScanHashJob ..> MusicMetadataExtractionJob : triggers (music) +MusicMetadataExtractionJob ..> MediaLibraryScanResultsSaveJob : triggers (music) MediaLibraryScanResultsSaveJob ..> MediaLibraryScanProviderConfigurationInvalidationJob : triggers MediaLibraryScanProviderConfigurationInvalidationJob ..> MediaLibraryScanMetadataEnrichmentJob : triggers MediaLibraryScanMetadataEnrichmentJob ..> MediaLibraryScanArtworkEnrichmentJob : triggers @@ -507,7 +527,6 @@ MediaLibraryScanJobFactory ..> IMediaLibraryScanJob : creates IMediaLibraryScanningService <|.. MediaLibraryScanningService : implements MediaLibraryScanningService --> IMediaLibraryScannerFactory : uses -MediaLibraryScanningService --> IMediaLibrariesScanQueue : writes root jobs to MediaLibraryScanningService --> IMediaLibrariesScanCancellationTracker : registers scan MediaLibraryScanningService --> IMediaLibrariesScanProgressTracker : initializes progress MediaLibraryScanningService ..> LibraryScan : starts and cancels @@ -516,9 +535,10 @@ MediaLibraryScanningService ..> LibraryScan : starts and cancels IMediaLibrariesScanQueue <|.. MediaLibrariesScanQueue : implements -MediaLibraryScanJobProcessorJob --> IMediaLibrariesScanQueue : reads from -MediaLibraryScanJobProcessorJob --> IMediaLibrariesScanCancellationTracker : links scan token -MediaLibraryScanJobProcessorJob ..> IMediaLibraryScanJob : triggers root job +MediaLibraryScanProcessorJob --> IMediaLibrariesScanQueue : reads queued scans from +MediaLibraryScanProcessorJob --> IMediaLibrariesScanCancellationTracker : links the scan token +MediaLibraryScanProcessorJob --> IMediaLibraryScanningService : prepares the job graph +MediaLibraryScanProcessorJob ..> IMediaLibraryScanDiscoveryJob : executes the discovery job ' ============================== TRACKER RELATIONSHIPS ============================== @@ -534,7 +554,9 @@ DebouncedMediaLibraryScanProgressNotifier --> IMediaLibrariesScanProgressTracker ' ============================== DOMAIN EVENT RELATIONSHIPS ============================== -LibraryScanQueuedDomainEventHandler --> IMediaLibraryScanningService : starts scan +LibraryScanQueuedDomainEventHandler --> IMediaLibrariesScanQueue : writes the scan to +LibraryScanQueuedDomainEventHandler --> IMediaLibrariesScanCancellationTracker : registers the scan +LibraryScanQueuedDomainEventHandler --> IMediaLibrariesScanProgressTracker : reports the queued scan LibraryScanCancelledDomainEventHandler --> IMediaLibraryScanningService : cancels scan LibraryScanFinishedDomainEventHandler --> IMediaLibrariesScanCancellationTracker : removes scan @@ -554,7 +576,7 @@ LibraryScanProgressChangedDomainEventHandler --> IMediaLibraryScanProgressNotifi LibraryScanJobProgressChangedDomainEventHandler --> IMediaLibrariesScanProgressTracker : updates job progress LibraryScanJobProgressChangedDomainEventHandler --> IMediaLibraryScanProgressNotifier : notifies update -caption [Code] Lumina - Background Services 3.2.1 +caption [Code] Lumina - Media Library Scanning 3.2.1 -footer The code diagram for the Background Services 3.2.1 - created with PlantUML +footer The code diagram for the Media Library Scanning 3.2.1 - created with PlantUML @enduml diff --git a/docs/technical/architecture/4.1 code-media-library-scanning-diagram.svg b/docs/technical/architecture/4.1 code-media-library-scanning-diagram.svg index 84b81ed4..367a981c 100644 --- a/docs/technical/architecture/4.1 code-media-library-scanning-diagram.svg +++ b/docs/technical/architecture/4.1 code-media-library-scanning-diagram.svg @@ -1 +1 @@ -Code diagram for Background Services 3.2.1IMediaLibraryScanJobScanId: ScanIdUserId: UserIdLibraryId: LibraryIdChildren:List<IMediaLibraryScanJob>Parents:List<IMediaLibraryScanJob>Status: LibraryScanJobStatusAddChild(job:IMediaLibraryScanJob)AddParent(job:IMediaLibraryScanJob)ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanJobparentsPayloadsExecuted: intExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskAbstract base class for all medialibrary scan jobs.Jobs form a directed acyclicgraph: every job executes itspayload only once all of its parentshave completed, andthen triggers its children. Each jobcreates its own DIscope throughIServiceScopeFactory (seeADR-0001).IBooksFileSystemDiscoveryJobIMusicFileSystemDiscoveryJobIMusicMetadataExtractionJobIMediaLibraryScanDiffJobIMediaLibraryScanHashJobIMediaLibraryScanProviderConfigurationInvalidationJobIMediaLibraryScanMetadataEnrichmentJobIMediaLibraryScanArtworkEnrichmentJobIMediaLibraryScanResultsSaveJobBooksFileSystemDiscoveryJobSTAGING_BATCH_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMusicFileSystemDiscoveryJobSTAGING_BATCH_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMusicMetadataExtractionJobEXTRACTION_BATCH_SIZE:int = 1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanDiffJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanHashJobHASHING_PAGE_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanProviderConfigurationInvalidationJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanMetadataEnrichmentJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanArtworkEnrichmentJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanResultsSaveJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskDiscovers the files of every librarycontent location, writesthem in bounded batches to thestaging results table and, whenthe library opts in, comparesdirectory scan fingerprints toskip unchanged directories (seeADR-0004, ADR-0005,ADR-0007).Marks the staging results againstthe media library scansnapshot of the previous scan witha single database-sidediff (see ADR-0004).Computes the content hashes ofthe files that changed sincethe previous scan, in boundedpages (see ADR-0004).Persists the results of the currentscan and swaps the scansnapshot in a single transaction,then triggers the providerconfiguration invalidation job.ScanFailurePublisherPublishAsync(serviceScopeFactory:IServiceScopeFactory, libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,exception: Exception, token:CancellationToken): TaskHelper used by every scan job topublish theLibraryScanFailedDomainEvent,so that a failed scanreleases its processing resources(see ADR-0009).IMediaLibraryScanJobFactoryCreateJob<TJob>(libraryId:LibraryId): TJobMediaLibraryScanJobFactoryCreateJob<TJob>(libraryId:LibraryId): TJobIMediaLibraryScannerFactoryCreateLibraryScanner(libraryType:LibraryType):IMediaTypeScannerMediaLibraryScannerFactoryCreateLibraryScanner(libraryType:LibraryType):IMediaTypeScannerIMediaTypeScannerSupportedLibraryType:LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId):IEnumerable<IMediaLibraryScanJob>IBookLibraryTypeScannerIMusicLibraryTypeScannerBookLibraryTypeScanner_mediaScanJobFactory:IMediaLibraryScanJobFactorySupportedLibraryType:LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId):IEnumerable<IMediaLibraryScanJob>MusicLibraryTypeScanner_mediaScanJobFactory:IMediaLibraryScanJobFactorySupportedLibraryType:LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId):IEnumerable<IMediaLibraryScanJob>IMediaLibraryScanItemMaterializerSupportedLibraryType:LibraryTypeResetEnrichmentStateForChangedPathsAsync(unitOfWork:IUnitOfWork, libraryId: Guid,paths:IReadOnlyCollection<string>,token: CancellationToken):Task<Result<Updated>>MaterializeItemsAsync(unitOfWork:IUnitOfWork, libraryId: Guid,scanId: Guid, paths:IReadOnlyList<string>, token:CancellationToken):Task<Result<Success>>ResetMetadataStatusForLibraryAsync(unitOfWork:IUnitOfWork, libraryId: Guid,token: CancellationToken):Task<Result<Updated>>ResetArtworkStatusForLibraryAsync(unitOfWork:IUnitOfWork, libraryId: Guid,token: CancellationToken):Task<Result<Updated>>IMediaLibraryScanMetadataEnricherSupportedLibraryType:LibraryTypeEnrichAsync(libraryId: LibraryId,scanId: ScanId, userId: UserId,token: CancellationToken):TaskIMediaLibraryScanArtworkEnricherSupportedLibraryType:LibraryTypeEnrichAsync(libraryId: LibraryId,scanId: ScanId, userId: UserId,token: CancellationToken):TaskBooksMediaLibraryScanItemMaterializerMusicMediaLibraryScanItemMaterializerBooksMediaLibraryScanMetadataEnricherENRICHMENT_PAGE_SIZE:int = 1000MusicMediaLibraryScanMetadataEnricherENRICHMENT_PAGE_SIZE:int = 200BooksMediaLibraryScanArtworkEnricherENRICHMENT_PAGE_SIZE:int = 1000MusicMediaLibraryScanArtworkEnricherENRICHMENT_PAGE_SIZE:int = 200Builds the books scan job graph:file system discovery,scan diff, hashing, scan resultssave, provider configurationinvalidation, metadata enrichmentand artwork enrichment.ILibraryPathTemplateServiceGetDefaultTemplate(libraryType:LibraryType):LibraryPathTemplateResolveTemplate(libraryType:LibraryType, providedParts:IReadOnlyList<LibraryPathPart>):Result<LibraryPathTemplate>Validate(libraryType:LibraryType, template:LibraryPathTemplate):Result<Success>Parse(libraryType: LibraryType,template: LibraryPathTemplate,relativePath: string,pathSeparator: char):Result<Optional<ParsedLibraryPath>>LibraryPathTemplateServiceILibraryPathPartCatalogSupportedLibraryType:LibraryTypeGetPartDefinitions():IReadOnlyList<LibraryPathPartDefinition>GetDefaultTemplate():LibraryPathTemplateMusicLibraryPathPartCatalogBookLibraryPathPartCatalogValidates media library pathtemplates and derives itemmetadata from paths, using thecatalog of each library type.LibraryScan_pastScans: List<LibraryScan>LibraryId: LibraryIdUserId: UserIdStatus: LibraryScanJobStatusCreate(libraryId: LibraryId,userId: UserId, pastScans:List<LibraryScan>):Result<LibraryScan>QueueScan(): Result<Success>StartScan(): Result<Success>FinishScan(): Result<Success>CancelScan():Result<Success>FailScan(): Result<Success>Aggregate root of the library scan,which drives the scanlifecycle through its domainevents.IMediaLibraryScanningServiceStartScanAsync(scan:LibraryScan, libraryType:LibraryType, token:CancellationToken):Task<Result<Success>>CancelScan(scan:LibraryScan): Result<Success>MediaLibraryScanningService_mediaLibrariesScanQueue:IMediaLibrariesScanQueue_mediaLibraryScannerFactory:IMediaLibraryScannerFactory_mediaLibrariesScanCancellationTracker:IMediaLibrariesScanCancellationTracker_mediaLibrariesScanProgressTracker:IMediaLibrariesScanProgressTracker_domainEventPublisher:IDomainEventPublisherStartScanAsync(scan:LibraryScan, libraryType:LibraryType, token:CancellationToken):Task<Result<Success>>CancelScan(scan:LibraryScan): Result<Success>Central service that starts a scanby building its job graph,registering it in the cancellationand progress trackers andenqueueing the root jobs, and thatcancels a running scan.IMediaLibrariesScanQueueWriter:ChannelWriter<IMediaLibraryScanJob>Reader:ChannelReader<IMediaLibraryScanJob>MediaLibrariesScanQueue_channel:Channel<IMediaLibraryScanJob>Writer:ChannelWriter<IMediaLibraryScanJob>Reader:ChannelReader<IMediaLibraryScanJob>In-memory queue that receivesonly the root scan jobs of ascan. Children are triggereddirectly by their parents, andare never placed on this queue.MediaLibraryScanJobProcessorJob_mediaScanQueue:IMediaLibrariesScanQueue_mediaLibrariesScanCancellationTracker:IMediaLibrariesScanCancellationTrackerExecuteAsync(token:CancellationToken): TaskBackground service that launchesthe payload execution of theroot scan jobs that arrive on thein-memory queue, firing themin a fire-and-forget manner withoutawaiting their long runningpayload execution (seeADR-0001, ADR-0009).IMediaLibrariesScanCancellationTrackerGetTokenForScan(compositeKey:MediaLibraryScanCompositeId):CancellationTokenRegisterScan(compositeKey:MediaLibraryScanCompositeId)RemoveScan(compositeKey:MediaLibraryScanCompositeId)CancelScan(compositeKey:MediaLibraryScanCompositeId)MediaLibrariesScanCancellationTracker_runningScans:ConcurrentDictionary<MediaLibraryScanCompositeId,CancellationTokenSource>IMediaLibrariesScanProgressTrackerInitializeScanProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,totalJobs: int): Result<Created>UpdateScanProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId):Result<Updated>UpdateScanJobProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,progress:MediaLibraryScanJobProgress):Result<Updated>GetScanProgress(compositeKey:MediaLibraryScanCompositeId):Result<MediaLibraryScanProgress>RemoveScanProgress(compositeKey:MediaLibraryScanCompositeId):Result<MediaLibraryScanProgress>MediaLibrariesScanProgressTracker_scanProgresses:ConcurrentDictionary<MediaLibraryScanCompositeId,MediaLibraryScanProgress>IMediaLibraryScanProgressNotifierSendLibraryProgressUpdateEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskSendLibraryScanFinishedEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskSendLibraryScanFailedEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskDebouncedMediaLibraryScanProgressNotifier_hubContext:IHubContext<MediaLibraryScanProgressHub>_mediaLibrariesScanProgressTracker:IMediaLibrariesScanProgressTracker_debouncers:ConcurrentDictionary<MediaLibraryScanCompositeId,DebounceDispatcher>MediaLibraryScanProgressHubSubscribeToScan(scanId:Guid): TaskSignalR hub that groupsconnections per scan, so thatsubscribed clients receivereal-time progress updates.LibraryScanQueuedDomainEventHandlerHandleAsync(domainEvent:LibraryScanQueuedDomainEvent,token: CancellationToken):ValueTaskLibraryScanStartedDomainEventHandlerHandleAsync(domainEvent:LibraryScanStartedDomainEvent,token: CancellationToken):ValueTaskLibraryScanFinishedDomainEventHandlerHandleAsync(domainEvent:LibraryScanFinishedDomainEvent,token: CancellationToken):ValueTaskLibraryScanFailedDomainEventHandlerHandleAsync(domainEvent:LibraryScanFailedDomainEvent,token: CancellationToken):ValueTaskLibraryScanCancelledDomainEventHandlerHandleAsync(domainEvent:LibraryScanCancelledDomainEvent,token: CancellationToken):ValueTaskLibraryScanProgressChangedDomainEventHandlerHandleAsync(domainEvent:LibraryScanProgressChangedDomainEvent,token: CancellationToken):ValueTaskLibraryScanJobProgressChangedDomainEventHandlerHandleAsync(domainEvent:LibraryScanJobProgressChangedDomainEvent,token: CancellationToken):ValueTaskimplementsinheritsinheritsinheritsinheritsinheritsinheritsinheritsinheritsinheritsimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementstriggerstriggerstriggerstriggerstriggerstriggerstriggerstriggerstriggerspublishes failure on unhandledexceptionimplementsimplementsimplementsimplementscreatesusescreatescreatescreatescreatescreatescreatescreatesusescreatescreatescreatescreatescreatescreatescreatescreatesdelegates todelegates todelegates todelegates toimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementsusesderives metadata from pathscreatesimplementsuseswrites root jobs toregisters scaninitializes progressstarts and cancelsimplementsreads fromlinks scan tokentriggers root jobimplementsimplementsimplementsnotifies SignalR clientsreads progressstarts scancancels scanremoves scanupdates progressnotifies finishremoves scanremoves progressnotifies failureremoves scanremoves progressupdates progressnotifies updateupdates job progressnotifies updateLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Background Services 3.2.1The code diagram for the Background Services 3.2.1 - created with PlantUML \ No newline at end of file +Code diagram for Media Library Scanning 3.2.1IMediaLibraryScanJobScanId: ScanIdUserId: UserIdLibraryId: LibraryIdChildren:List<IMediaLibraryScanJob>Parents:List<IMediaLibraryScanJob>Status: LibraryScanJobStatusAddChild(job:IMediaLibraryScanJob)AddParent(job:IMediaLibraryScanJob)ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskIMediaLibraryScanDiscoveryJobMediaLibraryScanJobparentsPayloadsExecuted: intExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskAbstract base class for all medialibrary scan jobs.Jobs form a directed acyclicgraph: every job executes itspayload only once all of its parentshave completed, andthen triggers its children. Each jobcreates its own DIscope throughIServiceScopeFactory (seeADR-0001).IBooksFileSystemDiscoveryJobIMusicFileSystemDiscoveryJobIMusicMetadataExtractionJobIMediaLibraryScanDiffJobIMediaLibraryScanHashJobIMediaLibraryScanProviderConfigurationInvalidationJobIMediaLibraryScanMetadataEnrichmentJobIMediaLibraryScanArtworkEnrichmentJobIMediaLibraryScanResultsSaveJobBooksFileSystemDiscoveryJobSTAGING_BATCH_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMusicFileSystemDiscoveryJobSTAGING_BATCH_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMusicMetadataExtractionJobEXTRACTION_BATCH_SIZE:int = 1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanDiffJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanHashJobHASHING_PAGE_SIZE: int =1000ExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanProviderConfigurationInvalidationJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanMetadataEnrichmentJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanArtworkEnrichmentJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskMediaLibraryScanResultsSaveJobExecuteAsync<TInput>(id:Guid, input: TInput, token:CancellationToken): TaskDiscovers the files of every librarycontent location, writesthem in bounded batches to thestaging results table and, whenthe library opts in, comparesdirectory scan fingerprints toskip unchanged directories (seeADR-0004, ADR-0005,ADR-0007).Marks the staging results againstthe media library scansnapshot of the previous scan witha single database-sidediff (see ADR-0004).Computes the content hashes ofthe files that changed sincethe previous scan, in boundedpages (see ADR-0004).Persists the results of the currentscan and swaps the scansnapshot in a single transaction,then triggers the providerconfiguration invalidation job.ScanFailurePublisherPublishAsync(serviceScopeFactory:IServiceScopeFactory, libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,exception: Exception, token:CancellationToken): TaskHelper used by every scan job topublish theLibraryScanFailedDomainEvent,so that a failed scanreleases its processing resources(see ADR-0009).IMediaLibraryScanJobFactoryCreateJob<TJob>(libraryId:LibraryId): TJobMediaLibraryScanJobFactoryCreateJob<TJob>(libraryId:LibraryId): TJobIMediaLibraryScannerFactoryCreateLibraryScanner(libraryType:LibraryType):Result<IMediaTypeScanner>MediaLibraryScannerFactoryCreateLibraryScanner(libraryType:LibraryType):Result<IMediaTypeScanner>IMediaTypeScannerSupportedLibraryType:LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId):IMediaLibraryScanDiscoveryJobIBookLibraryTypeScannerIMusicLibraryTypeScannerBookLibraryTypeScanner_mediaScanJobFactory:IMediaLibraryScanJobFactorySupportedLibraryType:LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId):IMediaLibraryScanDiscoveryJobMusicLibraryTypeScanner_mediaScanJobFactory:IMediaLibraryScanJobFactorySupportedLibraryType:LibraryTypeCreateScanJobsForLibrary(libraryId:LibraryId):IMediaLibraryScanDiscoveryJobIMediaLibraryScanItemMaterializerSupportedLibraryType:LibraryTypeResetEnrichmentStateForChangedPathsAsync(unitOfWork:IUnitOfWork, libraryId: Guid,paths:IReadOnlyCollection<string>,token: CancellationToken):Task<Result<Updated>>MaterializeItemsAsync(unitOfWork:IUnitOfWork, libraryId: Guid,scanId: Guid, paths:IReadOnlySet<string>, token:CancellationToken):Task<Result<Success>>ClearStagedDataAsync(unitOfWork:IUnitOfWork, libraryId: Guid,scanId: Guid, token:CancellationToken):Task<Result<Deleted>>ResetMetadataStatusForLibraryAsync(unitOfWork:IUnitOfWork, libraryId: Guid,token: CancellationToken):Task<Result<Updated>>ResetArtworkStatusForLibraryAsync(unitOfWork:IUnitOfWork, libraryId: Guid,token: CancellationToken):Task<Result<Updated>>IMediaLibraryScanMetadataEnricherSupportedLibraryType:LibraryTypeEnrichAsync(libraryId: LibraryId,scanId: ScanId, userId: UserId,token: CancellationToken):TaskIMediaLibraryScanArtworkEnricherSupportedLibraryType:LibraryTypeEnrichAsync(libraryId: LibraryId,scanId: ScanId, userId: UserId,token: CancellationToken):TaskBooksMediaLibraryScanItemMaterializerMusicMediaLibraryScanItemMaterializerBooksMediaLibraryScanMetadataEnricherENRICHMENT_PAGE_SIZE:int = 1000MusicMediaLibraryScanMetadataEnricherENRICHMENT_PAGE_SIZE:int = 200BooksMediaLibraryScanArtworkEnricherENRICHMENT_PAGE_SIZE:int = 1000MusicMediaLibraryScanArtworkEnricherENRICHMENT_PAGE_SIZE:int = 200Builds the books scan job graph:file system discovery,scan diff, hashing, scan resultssave, provider configurationinvalidation, metadata enrichmentand artwork enrichment.ILibraryPathTemplateServiceGetDefaultTemplate(libraryType:LibraryType):LibraryPathTemplateResolveTemplate(libraryType:LibraryType, providedParts:IReadOnlyList<LibraryPathPart>):Result<LibraryPathTemplate>Validate(libraryType:LibraryType, template:LibraryPathTemplate):Result<Success>Parse(libraryType: LibraryType,template: LibraryPathTemplate,relativePath: string,pathSeparator: char):Result<Optional<ParsedLibraryPath>>LibraryPathTemplateServiceILibraryPathPartCatalogSupportedLibraryType:LibraryTypeGetPartDefinitions():IReadOnlyList<LibraryPathPartDefinition>GetDefaultTemplate():LibraryPathTemplateMusicLibraryPathPartCatalogBookLibraryPathPartCatalogValidates media library pathtemplates and derives itemmetadata from paths, using thecatalog of each library type.LibraryScan_pastScans: List<LibraryScan>LibraryId: LibraryIdUserId: UserIdStatus: LibraryScanJobStatusCreate(libraryId: LibraryId,userId: UserId, pastScans:List<LibraryScan>):Result<LibraryScan>Create(id: ScanId, libraryId:LibraryId, userId: UserId, status:LibraryScanJobStatus,pastScans: List<LibraryScan>):Result<LibraryScan>QueueScan(): Result<Success>StartScan(): Result<Success>FinishScan(): Result<Success>CancelScan():Result<Success>FailScan(): Result<Success>Aggregate root of the library scan,which drives the scanlifecycle through its domainevents.IMediaLibraryScanningServiceStartScanAsync(scan:LibraryScan, libraryType:LibraryType, token:CancellationToken):Task<Result<IMediaLibraryScanDiscoveryJob>>CancelScan(scan:LibraryScan): Result<Success>MediaLibraryScanningService_mediaLibraryScannerFactory:IMediaLibraryScannerFactory_mediaLibrariesScanCancellationTracker:IMediaLibrariesScanCancellationTracker_mediaLibrariesScanProgressTracker:IMediaLibrariesScanProgressTracker_domainEventPublisher:IDomainEventPublisherStartScanAsync(scan:LibraryScan, libraryType:LibraryType, token:CancellationToken):Task<Result<IMediaLibraryScanDiscoveryJob>>CancelScan(scan:LibraryScan): Result<Success>Central service that resolves thescanner of the library type,builds the scan job graph,registers the scan in thecancellationand progress trackers, andpublishes the scan started events.It returns the file system discoveryjob, which is the root ofthe graph and whose executioncompletes the entire scan.IMediaLibrariesScanQueueWriter:ChannelWriter<MediaLibraryScanCompositeId>Reader:ChannelReader<MediaLibraryScanCompositeId>MediaLibrariesScanQueue_channel:Channel<MediaLibraryScanCompositeId>Writer:ChannelWriter<MediaLibraryScanCompositeId>Reader:ChannelReader<MediaLibraryScanCompositeId>In-memory queue of scancomposite ids. The scanprocessorprepares and executes one scanat a time, so the scans runconsecutively, in the order inwhich they were queued. Thejobs of a scan are never placed onthis queue.MediaLibraryScanProcessorJob_mediaLibrariesScanQueue:IMediaLibrariesScanQueue_mediaLibrariesScanCancellationTracker:IMediaLibrariesScanCancellationTracker_serviceScopeFactory:IServiceScopeFactory_logger:ILogger<MediaLibraryScanProcessorJob>ExecuteAsync(token:CancellationToken): TaskProcessScanAsync(compositeId:MediaLibraryScanCompositeId,token: CancellationToken):TaskReportScanFailureAsync(compositeId:MediaLibraryScanCompositeId,libraryId: LibraryId, exception:Exception, token:CancellationToken): TaskBackground service thatconsumes the queued scan idsone at atime, reads the pending scan,prepares its job graph through thescanning service and executes thediscovery job. A failing scanis reported and does not stop thescans queued behind it.IMediaLibrariesScanCancellationTrackerGetTokenForScan(compositeKey:MediaLibraryScanCompositeId):CancellationTokenRegisterScan(compositeKey:MediaLibraryScanCompositeId)RemoveScan(compositeKey:MediaLibraryScanCompositeId)CancelScan(compositeKey:MediaLibraryScanCompositeId)MediaLibrariesScanCancellationTracker_runningScans:ConcurrentDictionary<MediaLibraryScanCompositeId,CancellationTokenSource>IMediaLibrariesScanProgressTrackerInitializeQueuedScanProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId):Result<Created>InitializeScanProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,totalJobs: int): Result<Created>UpdateScanProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId):Result<Updated>UpdateScanJobProgress(libraryId:LibraryId, compositeKey:MediaLibraryScanCompositeId,progress:MediaLibraryScanJobProgress):Result<Updated>GetScanProgress(compositeKey:MediaLibraryScanCompositeId):Result<MediaLibraryScanProgress>RemoveScanProgress(compositeKey:MediaLibraryScanCompositeId):Result<MediaLibraryScanProgress>MediaLibrariesScanProgressTracker_scanProgresses:ConcurrentDictionary<MediaLibraryScanCompositeId,MediaLibraryScanProgress>IMediaLibraryScanProgressNotifierSendLibraryProgressUpdateEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskSendLibraryScanFinishedEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskSendLibraryScanFailedEventAsync(compositeKey:MediaLibraryScanCompositeId,token: CancellationToken):TaskDebouncedMediaLibraryScanProgressNotifier_hubContext:IHubContext<MediaLibraryScanProgressHub>_mediaLibrariesScanProgressTracker:IMediaLibrariesScanProgressTracker_debouncers:ConcurrentDictionary<MediaLibraryScanCompositeId,DebounceDispatcher>MediaLibraryScanProgressHubSubscribeToScan(scanId:Guid): TaskSignalR hub that groupsconnections per scan, so thatsubscribed clients receivereal-time progress updates.LibraryScanQueuedDomainEventHandlerHandleAsync(domainEvent:LibraryScanQueuedDomainEvent,token: CancellationToken):ValueTaskRegisters the scan forcancellation, reports it as queued,and writes its composite id to thescan queue. The scanprocessor prepares and executesthe job graph later.LibraryScanStartedDomainEventHandlerHandleAsync(domainEvent:LibraryScanStartedDomainEvent,token: CancellationToken):ValueTaskLibraryScanFinishedDomainEventHandlerHandleAsync(domainEvent:LibraryScanFinishedDomainEvent,token: CancellationToken):ValueTaskLibraryScanFailedDomainEventHandlerHandleAsync(domainEvent:LibraryScanFailedDomainEvent,token: CancellationToken):ValueTaskLibraryScanCancelledDomainEventHandlerHandleAsync(domainEvent:LibraryScanCancelledDomainEvent,token: CancellationToken):ValueTaskLibraryScanProgressChangedDomainEventHandlerHandleAsync(domainEvent:LibraryScanProgressChangedDomainEvent,token: CancellationToken):ValueTaskLibraryScanJobProgressChangedDomainEventHandlerHandleAsync(domainEvent:LibraryScanJobProgressChangedDomainEvent,token: CancellationToken):ValueTaskimplementsinheritsinheritsinheritsinheritsinheritsinheritsinheritsinheritsinheritsimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementstriggers (books)triggers (music)triggerstriggers (books)triggers (music)triggers (music)triggerstriggerstriggerspublishes failure on unhandledexceptionimplementsimplementsimplementsimplementscreatesusescreatescreatescreatescreatescreatescreatescreatesusescreatescreatescreatescreatescreatescreatescreatescreatesdelegates todelegates todelegates todelegates toimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementsimplementsusesderives metadata from pathscreatesimplementsusesregisters scaninitializes progressstarts and cancelsimplementsreads queued scans fromlinks the scan tokenprepares the job graphexecutes the discovery jobimplementsimplementsimplementsnotifies SignalR clientsreads progresswrites the scan toregisters the scanreports the queued scancancels scanremoves scanupdates progressnotifies finishremoves scanremoves progressnotifies failureremoves scanremoves progressupdates progressnotifies updateupdates job progressnotifies updateLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Media Library Scanning 3.2.1The code diagram for the Media Library Scanning 3.2.1 - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/4.2 code-book-reading-diagram.puml b/docs/technical/architecture/4.2 code-book-reading-diagram.puml index 04df1260..10c39bc6 100644 --- a/docs/technical/architecture/4.2 code-book-reading-diagram.puml +++ b/docs/technical/architecture/4.2 code-book-reading-diagram.puml @@ -1,4 +1,5 @@ @startuml Book Reading and Book Reader Plugins Code +!pragma layout elk !include LAYOUT_WITH_LEGEND() @@ -35,8 +36,13 @@ interface IBookReaderEnablementCache { class BookReadingService { - _extractions: ConcurrentDictionary - _bookExtractionLocks: ConcurrentDictionary - - _pluginIdsByReaderKey: IReadOnlyDictionary + - _pluginIdsByReaderKey: IReadOnlyDictionary? + - _serviceProvider: IServiceProvider + - _pluginManager: IPluginManager - _enablementCache: IBookReaderEnablementCache + - _serviceScopeFactory: IServiceScopeFactory + - _logger: ILogger + - _readerMapSync: object + GetManifestAsync(...): Task> + GetSectionAsync(...): Task> + GetResourceAsync(...): Task> @@ -119,14 +125,19 @@ class LibraryBookReaderConfigurationRepository class GetLibraryBookReadersQueryHandler { - _unitOfWork: IUnitOfWork + - _authorizationService: IAuthorizationService + - _currentUserService: ICurrentUserService - _bookReaderRegistry: IBookReaderRegistry + - _validator: IValidator + HandleAsync(query: GetLibraryBookReadersQuery, token: CancellationToken): Task>> } class GetLibraryTypeBookReadersQueryHandler { - _unitOfWork: IUnitOfWork + - _currentUserService: ICurrentUserService - _providerConfigurationStore: IMediaLibraryProviderConfigurationStore - _bookReaderRegistry: IBookReaderRegistry + - _validator: IValidator + HandleAsync(query: GetLibraryTypeBookReadersQuery, token: CancellationToken): Task>> } @@ -138,20 +149,28 @@ end note class MediaLibraryProviderConfigurationStore { - _unitOfWork: IUnitOfWork + - _pluginManager: IPluginManager + - _serviceProvider: IServiceProvider - _enablementCache: IBookReaderEnablementCache + + GetConfigurationsAsync(libraryId: Guid, token: CancellationToken): Task>> + + EnsureProviderConfigurationsAsync(libraryId: Guid, libraryType: LibraryType, token: CancellationToken): Task> + + RemoveProviderConfigurationsForLibraryAsync(libraryId: Guid, token: CancellationToken): Task> + + RemoveProviderConfigurationsAsync(pluginId: Guid, token: CancellationToken): Task> + ConfigureProvidersAsync(libraryId: Guid, libraryType: LibraryType, metadataProviders: IReadOnlyList?, artworkProviders: IReadOnlyList?, bookReaders: IReadOnlyList?, shouldReconcileOmittedKinds: bool, token: CancellationToken): Task> + GetSupportedBookReaderPluginIds(libraryType: LibraryType): IReadOnlyList } note right of MediaLibraryProviderConfigurationStore - Called by the add and update library commands. Applies the - chosen metadata providers, artwork providers and book readers - of a media library by upserting their configuration rows in - the same save as the library. When shouldReconcileOmittedKinds - is set, the kinds without explicit choices are reconciled with - the library type first. Book reader changes invalidate the - enablement cache of the library so that a disabled reader - stops being served immediately. + Stores the metadata provider, artwork provider and book reader + configuration of each media library. EnsureProviderConfigurationsAsync + only adds the configurations that are missing, while + ConfigureProvidersAsync reconciles them with the plugins supporting + the library type and sets the enabled state and order chosen when + the library is added or updated. Calling them when the library or + a plugin is added or removed keeps the persisted rows in sync with + the loaded plugins. Book reader changes invalidate the enablement + cache of the library so that a disabled reader stops being served + immediately. end note ' ============================== BOOK READER PLUGINS ============================== @@ -208,12 +227,20 @@ end note class EpubPlugin { + Id: Guid + Name: string = EPUB Reader + + Author: string = Lumina + + Version: Version + + Description: string + + GetSettingsSchema(): IReadOnlyList + RegisterServices(services: IServiceCollection) } class PdfPlugin { + Id: Guid + Name: string = PDF Reader + + Author: string = Lumina + + Version: Version + + Description: string + + GetSettingsSchema(): IReadOnlyList + RegisterServices(services: IServiceCollection) } @@ -248,8 +275,8 @@ ILibraryBookReaderConfigurationRepository --> LibraryBookReaderConfigurationEnti ' ============================== BOOK READER PLUGIN RELATIONSHIPS ============================== -EpubReader <|.. IBookReader : implements -PdfReader <|.. IBookReader : implements +IBookReader <|.. EpubReader : implements +IBookReader <|.. PdfReader : implements EpubReader ..> EpubDocumentParser : parses PdfReader ..> PdfDocumentParser : parses and renders pages diff --git a/docs/technical/architecture/4.2 code-book-reading-diagram.svg b/docs/technical/architecture/4.2 code-book-reading-diagram.svg index 71f770f4..519dc869 100644 --- a/docs/technical/architecture/4.2 code-book-reading-diagram.svg +++ b/docs/technical/architecture/4.2 code-book-reading-diagram.svg @@ -1 +1 @@ -Code diagram for Book Reading 3.2.2 and Book Reader PluginsIBookReadingServiceGetManifestAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingManifestResponse>>GetSectionAsync(bookId: Guid,libraryId: Guid, path: string,libraryType: LibraryType,locationRef: string,shouldRenderPdfAsImages:bool, shouldPreserveStyles:bool, token:CancellationToken):Task<Result<ReadingSectionDto>>GetResourceAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,resourceKey: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,token: CancellationToken):Task<Result<ReadingAvailabilityResponse>>IBookReaderRegistryGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>IBookReaderEnablementCacheGet(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)BookReadingService_extractions:ConcurrentDictionary<ReadingCacheKey,BookExtractionEntry>_bookExtractionLocks:ConcurrentDictionary<ReadingCacheKey,SemaphoreSlim>_pluginIdsByReaderKey:IReadOnlyDictionary<ReaderKey,Guid>_enablementCache:IBookReaderEnablementCacheGetManifestAsync(...):Task<Result<ReadingManifestResponse>>GetSectionAsync(...):Task<Result<ReadingSectionDto>>GetResourceAsync(...):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(...):Task<Result<ReadingAvailabilityResponse>>Serves the manifest, sections andresources of a book:resolves the reader of the bookformat, checks theper-library enablement through thecache, reuses the alreadyextracted document while thefingerprint of the book file isunchanged, extracts eachrendering preference (text or pageimages) into its own directoryunder the reading cache, andproduces on-demand resources(for example a PDF page render)once per resource file.BookReaderRegistry_pluginManager:IPluginManager_serviceProvider:IServiceProviderGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>Reads the supported extensionslive from the book readersregistered by the loaded plugins,so that a plugin updatethat changes its formats neverleaves stale configurations.BookReaderEnablementCache_enablements:ConcurrentDictionary<(GuidLibraryId, Guid PluginId), bool>Get(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)ReadingCachePathsDIRECTORY_NAME: string =reading-cacheGetRootDirectory(): stringThe reading cache is a temporarydirectory in the API output,wiped at startup, under whichevery book keeps one directoryper rendering preference (text andimages).ReadingContentSanitizerRESOURCE_ATTRIBUTE:string = data-lumina-resourceSanitize(html: string,shouldPreserveStyles: bool):stringSanitizes every reading sectionwith an explicit allowlist ofinert markup, regardless of whatthe reader plugin produced;whether the style attributesurvives is the per-user choice.LibraryBookReaderConfigurationEntityId: GuidLibraryId: GuidPluginId: GuidIsEnabled: boolILibraryBookReaderConfigurationRepositoryGetByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>>>GetByLibraryAndPluginIdAsync(libraryId:Guid, pluginId: Guid, token:CancellationToken):Task<Result<LibraryBookReaderConfigurationEntity?>>UpsertAsync(configuration:LibraryBookReaderConfigurationEntity,token: CancellationToken):Task<Result<Updated>>DeleteByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByPluginIdAsync(pluginId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByLibraryIdAndPluginIdsAsync(libraryId:Guid, pluginIds:IEnumerable<Guid>, token:CancellationToken):Task<Result<Deleted>>LibraryBookReaderConfigurationRepositoryGetLibraryBookReadersQueryHandler_unitOfWork: IUnitOfWork_bookReaderRegistry:IBookReaderRegistryHandleAsync(query:GetLibraryBookReadersQuery,token: CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderResponse>>>GetLibraryTypeBookReadersQueryHandler_unitOfWork: IUnitOfWork_providerConfigurationStore:IMediaLibraryProviderConfigurationStore_bookReaderRegistry:IBookReaderRegistryHandleAsync(query:GetLibraryTypeBookReadersQuery,token: CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderResponse>>>Lists the book readers thatsupport a library type, disabled,so that they can be chosen beforea library is created orbefore a change of its type issaved.MediaLibraryProviderConfigurationStore_unitOfWork: IUnitOfWork_enablementCache:IBookReaderEnablementCacheConfigureProvidersAsync(libraryId:Guid, libraryType: LibraryType,metadataProviders:IReadOnlyList<LibraryProviderSelectionDto>?,artworkProviders:IReadOnlyList<LibraryProviderSelectionDto>?,bookReaders:IReadOnlyList<LibraryProviderSelectionDto>?,shouldReconcileOmittedKinds:bool, token:CancellationToken):Task<Result<Success>>GetSupportedBookReaderPluginIds(libraryType:LibraryType):IReadOnlyList<Guid>Called by the add and updatelibrary commands. Applies thechosen metadata providers,artwork providers and bookreadersof a media library by upsertingtheir configuration rows inthe same save as the library.WhenshouldReconcileOmittedKindsis set, the kinds without explicitchoices are reconciled withthe library type first. Book readerchanges invalidate theenablement cache of the library sothat a disabled readerstops being served immediately.IBookReaderSupportedExtensions:IReadOnlyList<string>SupportedLibraryTypes:IReadOnlyList<LibraryType>OpenAsync(path: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<ReadingDocumentDto>GetResourceAsync(path: string,workingDirectory: string,resourceKey: string, token:CancellationToken):Task<byte[]>Contract of a reader plugin,implemented inLumina.Plugins.Contracts.The plugins are host-trusted: theyreceive the absolute path of thebook and a working directory toextract into, while the hostsanitizes and contained-checkseverything they produce beforeserving it to the client.EpubReaderReads .epub books of the EBookand Book library types.EPUB is a ZIP archive, decodedentry by entry with boundedsizes and archive-containedpaths.EpubDocumentParserParse(epubPath: string,workingDirectory: string, token:CancellationToken):ReadingDocumentDtoPdfReaderReads .pdf books of the EBookand Book library types.Each page is a reading section;the table of contents comesfrom the PDF bookmarks.PdfDocumentParserParse(pdfPath: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):ReadingDocumentDtoRenderResource(pdfPath:string, resourceKey: string,token: CancellationToken):byte[]Extracts the text layer of thepages with PdfPig, and rendersthe pages as images withPDFtoImage on demand when therender-as-images user setting isenabled; file size, page countand rendered page area arebounded.EpubPluginId: GuidName: string = EPUB ReaderRegisterServices(services:IServiceCollection)PdfPluginId: GuidName: string = PDF ReaderRegisterServices(services:IServiceCollection)implementsimplementsimplementsimplementsfinds the plugin of the book formatchecks the per-library enablementfills the cache on a missopens and produces resourcessanitizes section contentextracts into and serves fromreads the supported extensions ofloaded pluginsreads configurationsreads supported extensionsreads the supported readersreads supported extensionsupserts the configurationsinvalidates the library entriespersistsimplementsimplementsparsesparses and renders pagesregisters as a keyed IBookReaderregisters as a keyed IBookReaderLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Book Reading 3.2.2 and Book Reader PluginsThe code diagram for the Book Reading 3.2.2 and the Book Reader Plugins - created with PlantUML \ No newline at end of file +Code diagram for Book Reading 3.2.2 and Book Reader PluginsIBookReadingServiceGetManifestAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingManifestResponse>>GetSectionAsync(bookId: Guid,libraryId: Guid, path: string,libraryType: LibraryType,locationRef: string,shouldRenderPdfAsImages:bool, shouldPreserveStyles:bool, token:CancellationToken):Task<Result<ReadingSectionDto>>GetResourceAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,resourceKey: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(bookId:Guid, libraryId: Guid, path:string, libraryType: LibraryType,token: CancellationToken):Task<Result<ReadingAvailabilityResponse>>IBookReaderRegistryGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>IBookReaderEnablementCacheGet(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)BookReadingService_extractions:ConcurrentDictionary<ReadingCacheKey,BookExtractionEntry>_bookExtractionLocks:ConcurrentDictionary<ReadingCacheKey,SemaphoreSlim>_pluginIdsByReaderKey:IReadOnlyDictionary<ReaderKey,Guid>?_serviceProvider:IServiceProvider_pluginManager:IPluginManager_enablementCache:IBookReaderEnablementCache_serviceScopeFactory:IServiceScopeFactory_logger:ILogger<BookReadingService>_readerMapSync: objectGetManifestAsync(...):Task<Result<ReadingManifestResponse>>GetSectionAsync(...):Task<Result<ReadingSectionDto>>GetResourceAsync(...):Task<Result<ReadingResourceDataDto>>GetAvailabilityAsync(...):Task<Result<ReadingAvailabilityResponse>>Serves the manifest, sections andresources of a book:resolves the reader of the bookformat, checks theper-library enablement through thecache, reuses the alreadyextracted document while thefingerprint of the book file isunchanged, extracts eachrendering preference (text or pageimages) into its own directoryunder the reading cache, andproduces on-demand resources(for example a PDF page render)once per resource file.BookReaderRegistry_pluginManager:IPluginManager_serviceProvider:IServiceProviderGetSupportedExtensionsByPluginId():IReadOnlyDictionary<Guid,IReadOnlyList<string>>Reads the supported extensionslive from the book readersregistered by the loaded plugins,so that a plugin updatethat changes its formats neverleaves stale configurations.BookReaderEnablementCache_enablements:ConcurrentDictionary<(GuidLibraryId, Guid PluginId), bool>Get(libraryId: Guid, pluginId:Guid): bool?Set(libraryId: Guid, pluginId:Guid, isEnabled: bool)Invalidate(libraryId: Guid,pluginId: Guid)InvalidateLibrary(libraryId: Guid)InvalidatePlugin(pluginId: Guid)ReadingCachePathsDIRECTORY_NAME: string =reading-cacheGetRootDirectory(): stringThe reading cache is a temporarydirectory in the API output,wiped at startup, under whichevery book keeps one directoryper rendering preference (text andimages).ReadingContentSanitizerRESOURCE_ATTRIBUTE:string = data-lumina-resourceSanitize(html: string,shouldPreserveStyles: bool):stringSanitizes every reading sectionwith an explicit allowlist ofinert markup, regardless of whatthe reader plugin produced;whether the style attributesurvives is the per-user choice.LibraryBookReaderConfigurationEntityId: GuidLibraryId: GuidPluginId: GuidIsEnabled: boolILibraryBookReaderConfigurationRepositoryGetByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderConfigurationEntity>>>GetByLibraryAndPluginIdAsync(libraryId:Guid, pluginId: Guid, token:CancellationToken):Task<Result<LibraryBookReaderConfigurationEntity?>>UpsertAsync(configuration:LibraryBookReaderConfigurationEntity,token: CancellationToken):Task<Result<Updated>>DeleteByLibraryIdAsync(libraryId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByPluginIdAsync(pluginId:Guid, token:CancellationToken):Task<Result<Deleted>>DeleteByLibraryIdAndPluginIdsAsync(libraryId:Guid, pluginIds:IEnumerable<Guid>, token:CancellationToken):Task<Result<Deleted>>LibraryBookReaderConfigurationRepositoryGetLibraryBookReadersQueryHandler_unitOfWork: IUnitOfWork_authorizationService:IAuthorizationService_currentUserService:ICurrentUserService_bookReaderRegistry:IBookReaderRegistry_validator:IValidator<GetLibraryBookReadersQuery>HandleAsync(query:GetLibraryBookReadersQuery,token: CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderResponse>>>GetLibraryTypeBookReadersQueryHandler_unitOfWork: IUnitOfWork_currentUserService:ICurrentUserService_providerConfigurationStore:IMediaLibraryProviderConfigurationStore_bookReaderRegistry:IBookReaderRegistry_validator:IValidator<GetLibraryTypeBookReadersQuery>HandleAsync(query:GetLibraryTypeBookReadersQuery,token: CancellationToken):Task<Result<IReadOnlyList<LibraryBookReaderResponse>>>Lists the book readers thatsupport a library type, disabled,so that they can be chosen beforea library is created orbefore a change of its type issaved.MediaLibraryProviderConfigurationStore_unitOfWork: IUnitOfWork_pluginManager:IPluginManager_serviceProvider:IServiceProvider_enablementCache:IBookReaderEnablementCacheGetConfigurationsAsync(libraryId:Guid, token:CancellationToken):Task<Result<IReadOnlyList<LibraryMetadataProviderConfigurationEntity>>>EnsureProviderConfigurationsAsync(libraryId:Guid, libraryType: LibraryType,token: CancellationToken):Task<Result<Success>>RemoveProviderConfigurationsForLibraryAsync(libraryId:Guid, token:CancellationToken):Task<Result<Deleted>>RemoveProviderConfigurationsAsync(pluginId:Guid, token:CancellationToken):Task<Result<Deleted>>ConfigureProvidersAsync(libraryId:Guid, libraryType: LibraryType,metadataProviders:IReadOnlyList<LibraryProviderSelectionDto>?,artworkProviders:IReadOnlyList<LibraryProviderSelectionDto>?,bookReaders:IReadOnlyList<LibraryProviderSelectionDto>?,shouldReconcileOmittedKinds:bool, token:CancellationToken):Task<Result<Success>>GetSupportedBookReaderPluginIds(libraryType:LibraryType):IReadOnlyList<Guid>Stores the metadata provider,artwork provider and book readerconfiguration of each medialibrary.EnsureProviderConfigurationsAsynconly adds the configurations thatare missing, whileConfigureProvidersAsyncreconciles them with the pluginssupportingthe library type and sets theenabled state and order chosenwhenthe library is added or updated.Calling them when the library ora plugin is added or removedkeeps the persisted rows in syncwiththe loaded plugins. Book readerchanges invalidate theenablementcache of the library so that adisabled reader stops beingservedimmediately.IBookReaderSupportedExtensions:IReadOnlyList<string>SupportedLibraryTypes:IReadOnlyList<LibraryType>OpenAsync(path: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):Task<ReadingDocumentDto>GetResourceAsync(path: string,workingDirectory: string,resourceKey: string, token:CancellationToken):Task<byte[]>Contract of a reader plugin,implemented inLumina.Plugins.Contracts.The plugins are host-trusted: theyreceive the absolute path of thebook and a working directory toextract into, while the hostsanitizes and contained-checkseverything they produce beforeserving it to the client.EpubReaderReads .epub books of the EBookand Book library types.EPUB is a ZIP archive, decodedentry by entry with boundedsizes and archive-containedpaths.EpubDocumentParserParse(epubPath: string,workingDirectory: string, token:CancellationToken):ReadingDocumentDtoPdfReaderReads .pdf books of the EBookand Book library types.Each page is a reading section;the table of contents comesfrom the PDF bookmarks.PdfDocumentParserParse(pdfPath: string,workingDirectory: string,shouldRenderPdfAsImages:bool, token:CancellationToken):ReadingDocumentDtoRenderResource(pdfPath:string, resourceKey: string,token: CancellationToken):byte[]Extracts the text layer of thepages with PdfPig, and rendersthe pages as images withPDFtoImage on demand when therender-as-images user setting isenabled; file size, page countand rendered page area arebounded.EpubPluginId: GuidName: string = EPUB ReaderAuthor: string = LuminaVersion: VersionDescription: stringGetSettingsSchema():IReadOnlyList<PluginSettingDescriptorDto>RegisterServices(services:IServiceCollection)PdfPluginId: GuidName: string = PDF ReaderAuthor: string = LuminaVersion: VersionDescription: stringGetSettingsSchema():IReadOnlyList<PluginSettingDescriptorDto>RegisterServices(services:IServiceCollection)implementsimplementsimplementsimplementsfinds the plugin of the book formatchecks the per-library enablementfills the cache on a missopens and produces resourcessanitizes section contentextracts into and serves fromreads the supported extensions ofloaded pluginsreads configurationsreads supported extensionsreads the supported readersreads supported extensionsupserts the configurationsinvalidates the library entriespersistsimplementsimplementsparsesparses and renders pagesregisters as a keyed IBookReaderregisters as a keyed IBookReaderLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Book Reading 3.2.2 and Book Reader PluginsThe code diagram for the Book Reading 3.2.2 and the Book Reader Plugins - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/4.3 code-scheduler-diagram.puml b/docs/technical/architecture/4.3 code-scheduler-diagram.puml index 0f31d592..34ad47de 100644 --- a/docs/technical/architecture/4.3 code-scheduler-diagram.puml +++ b/docs/technical/architecture/4.3 code-scheduler-diagram.puml @@ -1,4 +1,5 @@ @startuml Scheduled Jobs Code +!pragma layout elk !include LAYOUT_WITH_LEGEND() @@ -21,6 +22,7 @@ class ScheduledJob { + LastStartedOnUtc: Optional + LastCompletedOnUtc: Optional + {static} Create(name: string, taskType: ScheduledTaskType, schedule: Schedule, ownerUserId: UserId): Result + + {static} Create(id: ScheduledJobId, name: string, taskType: ScheduledTaskType, schedule: Schedule, ownerUserId: UserId, status: ScheduledJobStatus, lastStartedOnUtc: Optional, lastCompletedOnUtc: Optional): Result + Add(): Result + StartCycle(): Result + StopCycle(): Result @@ -56,6 +58,10 @@ class DailySchedule { + {static} Create(hour: int, minute: int): Result } +class OnceAtStartupSchedule { + + {static} Create(): Result +} + class ScheduledJobId { + Value: Guid + {static} CreateUnique(): ScheduledJobId @@ -73,6 +79,7 @@ class ScheduledJobExecutionStartedDomainEvent { } class ScheduledJobExecutionCompletedDomainEvent { + RunId: Guid + + TaskType: ScheduledTaskType + IsCycleRun: bool + CompletedOnUtc: DateTime } @@ -96,8 +103,9 @@ interface IScheduledJobNotifier { interface IScheduledJobRepository { + GetByIdAsync(id: Guid, token: CancellationToken): Task> - + GetAllAsync(token: CancellationToken): Task>> + + GetByIdWithoutTrackingAsync(id: Guid, token: CancellationToken): Task> + GetActiveOrRunningAsync(token: CancellationToken): Task>> + + GetAllAsync(token: CancellationToken): Task>> + InsertAsync(entity: ScheduledJobEntity, token: CancellationToken): Task> + UpdateAsync(entity: ScheduledJobEntity, token: CancellationToken): Task> + DeleteByIdAsync(id: Guid, token: CancellationToken): Task> @@ -110,6 +118,12 @@ interface IScheduledJobExecutionRepository { + InsertAsync(entity: ScheduledJobExecutionEntity, token: CancellationToken): Task> + UpdateAsync(entity: ScheduledJobExecutionEntity, token: CancellationToken): Task> + DeleteByScheduledJobIdAsync(scheduledJobId: Guid, token: CancellationToken): Task> + + DeleteOlderThanAsync(cutoffUtc: DateTime, token: CancellationToken): Task> +} + +interface ISchedulerDisplayPreferencesRepository { + + GetByUserIdAsync(userId: Guid, token: CancellationToken): Task> + + UpsertAsync(preferences: SchedulerDisplayPreferencesEntity, token: CancellationToken): Task> } ' ============================== APPLICATION HANDLERS ============================== @@ -142,6 +156,14 @@ class GetScheduledJobHistoryQueryHandler { + HandleAsync(query: GetScheduledJobHistoryQuery, token: CancellationToken): Task>> } +class UpdateSchedulerDisplayPreferencesCommandHandler { + + HandleAsync(command: UpdateSchedulerDisplayPreferencesCommand, token: CancellationToken): Task> +} + +class GetSchedulerDisplayPreferencesQueryHandler { + + HandleAsync(query: GetSchedulerDisplayPreferencesQuery, token: CancellationToken): Task> +} + ' ============================== DOMAIN EVENT HANDLERS ============================== class ScheduledJobAddedDomainEventHandler { @@ -178,8 +200,8 @@ class ScheduledJobRemovedDomainEventHandler { note bottom of ScheduledJobExecutionStartedDomainEventHandler Updates the scheduled job to Running, inserts the open execution - history row, and notifies the SignalR clients about the started - execution. + history row with whether its cycle was active, and notifies the + SignalR clients about the started execution. end note note bottom of ScheduledJobExecutionCompletedDomainEventHandler @@ -193,28 +215,55 @@ end note class ScheduledJobSchedulerJob { - _serviceScopeFactory: IServiceScopeFactory - _runtimeRegistry: IScheduledJobRuntimeRegistry - - _logger: ILogger + - _logger: ILogger + - _cycleTickerFactory: Func + StartCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + StopCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + RunOnceAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + ExecuteAsync(stoppingToken: CancellationToken): Task + - SynchronizeBundledThemesIfNeededAsync(token: CancellationToken): Task + - EnsureTechnicalDataCleanupScheduledJobAsync(token: CancellationToken): Task - ResumeActiveCyclesAsync(token: CancellationToken): Task - - RunCycleWorkerAsync(scheduledJobId: ScheduledJobId, runImmediately: bool, stoppingToken: CancellationToken): Task + - RunCycleWorkerAsync(scheduledJobId: ScheduledJobId, shouldRunImmediately: bool, stoppingToken: CancellationToken): Task + - RunOnceWorkerAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task - RunScheduledJobAsync(scheduledJobId: ScheduledJobId, isCycleRun: bool, token: CancellationToken): Task - ExecuteScheduledJobRunAsync(scheduledJobId: ScheduledJobId, isCycleRun: bool, token: CancellationToken): Task + - CompleteExecutionAsync(scheduledJob: ScheduledJob, unitOfWork: IUnitOfWork, domainEventPublisher: IDomainEventPublisher, isCycleRun: bool, token: CancellationToken): Task + - ReconcileInterruptedRunAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + - GetScheduleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + - CalculateDelayAsync(schedule: Schedule): Task } note right of ScheduledJobSchedulerJob Background service (registered as IScheduledJobScheduler and hosted) - that resumes the active execution cycles at startup, runs each cycle - worker on its schedule through PeriodicTimer, guards each execution - against overlapping runs, and publishes the started and completed - domain events of every run through the EventualConsistencyMiddleware. + that resumes the active execution cycles at startup, synchronizes + the bundled themes when no RepairThemes job exists, seeds the + technical data cleanup job, runs each cycle worker through an + IScheduledJobCycleTicker, guards each execution against overlapping + runs, and publishes the started and completed domain events of + every run through IDomainEventPublisher. +end note + +interface IScheduledJobCycleTicker { + + Period: TimeSpan {set} + + WaitForNextTickAsync(token: CancellationToken): ValueTask +} + +class PeriodicScheduledJobCycleTicker { + - _periodicTimer: PeriodicTimer +} + +note bottom of IScheduledJobCycleTicker + Cancellable periodic ticker that drives the cadence of an + execution cycle. It is separated from PeriodicTimer so that + the cycle worker can be tested with a stubbed ticker. end note interface IScheduledJobRuntimeRegistry { + TryStartCycle(scheduledJobId: ScheduledJobId, cycleCancellationTokenSource: CancellationTokenSource): bool + + HasActiveCycle(scheduledJobId: ScheduledJobId): bool + StopCycle(scheduledJobId: ScheduledJobId) + + EndCycle(scheduledJobId: ScheduledJobId, cycleCancellationTokenSource: CancellationTokenSource) + TryAcquireRunSlot(scheduledJobId: ScheduledJobId): bool + ReleaseRunSlot(scheduledJobId: ScheduledJobId) } @@ -240,6 +289,12 @@ class ScheduledTaskExecutorFactory { + CreateExecutor(taskType: ScheduledTaskType): IScheduledTaskExecutor } +note right of ScheduledTaskExecutorFactory + Creates the executor of a scheduled job from its task type: + ScanMediaLibraries, CleanTemporaryFiles, RepairThemes, + CleanScheduledJobExecutionHistory or TechnicalDataCleanup. +end note + interface IScheduledTaskExecutor { + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task> } @@ -267,6 +322,41 @@ note right of TemporaryFilesCleanupTaskExecutor cannot be resolved safely inside the application base directory. end note +class RepairThemesTaskExecutor { + - _themeService: IThemeService + - _unitOfWork: IUnitOfWork + - _logger: ILogger + + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task> +} + +note right of RepairThemesTaskExecutor + Executes the RepairThemes task: reinstalls the files of the bundled + themes whose installed files are missing, through the theme service. +end note + +class CleanScheduledJobExecutionHistoryTaskExecutor { + - _dateTimeProvider: IDateTimeProvider + - _unitOfWork: IUnitOfWork + - _logger: ILogger + + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task> +} + +note right of CleanScheduledJobExecutionHistoryTaskExecutor + Executes the CleanScheduledJobExecutionHistory task: removes the + execution history rows that are older than one month. +end note + +class TechnicalDataCleanupTaskExecutor { + - _unitOfWork: IUnitOfWork + - _logger: ILogger + + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task> +} + +note right of TechnicalDataCleanupTaskExecutor + Executes the TechnicalDataCleanup task: marks the media library scans + that were interrupted by a previous shutdown as failed. +end note + ' ============================== INFRASTRUCTURE - NOTIFICATIONS ============================== class ScheduledJobNotifier { @@ -299,6 +389,7 @@ interface IScheduledJobsClient { interface IUnitOfWork { + ScheduledJobRepository: IScheduledJobRepository + ScheduledJobExecutionRepository: IScheduledJobExecutionRepository + + SchedulerDisplayPreferencesRepository: ISchedulerDisplayPreferencesRepository + SaveChangesAsync(token: CancellationToken): Task } @@ -306,6 +397,8 @@ class ScheduledJobRepository class ScheduledJobExecutionRepository +class SchedulerDisplayPreferencesRepository + ' ============================== STORAGE MODEL ============================== class ScheduledJobEntity { @@ -329,6 +422,15 @@ class ScheduledJobExecutionEntity { + IsCycleRun: bool + StartedOnUtc: DateTime + CompletedOnUtc: DateTime? + + WasCycleActive: bool +} + +class SchedulerDisplayPreferencesEntity { + + Id: Guid + + UserId: Guid + + JobTypeFilter: ScheduledTaskType? + + DisplayTimeSpan: int + + DisplayTimeUnit: SchedulerDisplayTimeUnit } note bottom of ScheduledJobEntity @@ -340,12 +442,21 @@ end note note bottom of ScheduledJobExecutionEntity Stored in the ScheduledJobExecutions table, indexed by the started time and the scheduled job id for fast history queries and cleanup. + WasCycleActive records whether the execution belonged to an active + cycle, so an interrupted cycle is resumed after a restart. +end note + +note bottom of SchedulerDisplayPreferencesEntity + Stored in the SchedulerDisplayPreferences table, one row per user, + and used by the scheduler page for its job type filter and its + display time span and unit. end note ' ============================== AGGREGATE AND VALUE OBJECT RELATIONSHIPS ============================== Schedule <|-- IntervalSchedule : inherits Schedule <|-- DailySchedule : inherits +Schedule <|-- OnceAtStartupSchedule : inherits ScheduledJob *-- Schedule : has one ScheduledJob o-- ScheduledJobId : identified by @@ -365,6 +476,7 @@ IScheduledJobScheduler <|.. ScheduledJobSchedulerJob : implements IScheduledJobNotifier <|.. ScheduledJobNotifier : implements IScheduledJobRepository <|.. ScheduledJobRepository : implements IScheduledJobExecutionRepository <|.. ScheduledJobExecutionRepository : implements +ISchedulerDisplayPreferencesRepository <|.. SchedulerDisplayPreferencesRepository : implements ' ============================== COMMAND AND QUERY HANDLER RELATIONSHIPS ============================== @@ -386,6 +498,9 @@ RemoveScheduledJobCommandHandler --> IScheduledJobScheduler : stops the running GetScheduledJobsQueryHandler --> IScheduledJobRepository : reads all GetScheduledJobHistoryQueryHandler --> IScheduledJobExecutionRepository : reads by time range +UpdateSchedulerDisplayPreferencesCommandHandler --> IUnitOfWork : upserts the preferences +GetSchedulerDisplayPreferencesQueryHandler --> IUnitOfWork : reads the preferences + ' ============================== DOMAIN EVENT HANDLER RELATIONSHIPS ============================== ScheduledJobAddedDomainEventHandler --> IScheduledJobNotifier : notifies @@ -408,10 +523,12 @@ ScheduledJobExecutionStoppedDomainEventHandler --> IScheduledJobNotifier : notif ScheduledJobSchedulerJob --> IScheduledJobRuntimeRegistry : tracks cycles and run slots ScheduledJobSchedulerJob --> IScheduledJobRepository : loads jobs and schedules +ScheduledJobSchedulerJob --> IScheduledJobCycleTicker : ticks each execution cycle ScheduledJobSchedulerJob ..> ScheduledJobExecutionStartedDomainEvent : publishes ScheduledJobSchedulerJob ..> ScheduledJobExecutionCompletedDomainEvent : publishes ScheduledJobSchedulerJob ..> ScheduledJob : marks the execution started and completed +IScheduledJobCycleTicker <|.. PeriodicScheduledJobCycleTicker : implements IScheduledJobRuntimeRegistry <|.. ScheduledJobRuntimeRegistry : implements ScheduledJobSchedulerJob --> IScheduledTaskExecutorFactory : creates the task executor @@ -419,11 +536,20 @@ IScheduledTaskExecutorFactory <|.. ScheduledTaskExecutorFactory : implements ScheduledTaskExecutorFactory ..> MediaLibraryScanTaskExecutor : creates for ScanMediaLibraries ScheduledTaskExecutorFactory ..> TemporaryFilesCleanupTaskExecutor : creates for CleanTemporaryFiles +ScheduledTaskExecutorFactory ..> RepairThemesTaskExecutor : creates for RepairThemes +ScheduledTaskExecutorFactory ..> CleanScheduledJobExecutionHistoryTaskExecutor : creates for CleanScheduledJobExecutionHistory +ScheduledTaskExecutorFactory ..> TechnicalDataCleanupTaskExecutor : creates for TechnicalDataCleanup IScheduledTaskExecutor <|.. MediaLibraryScanTaskExecutor : implements IScheduledTaskExecutor <|.. TemporaryFilesCleanupTaskExecutor : implements +IScheduledTaskExecutor <|.. RepairThemesTaskExecutor : implements +IScheduledTaskExecutor <|.. CleanScheduledJobExecutionHistoryTaskExecutor : implements +IScheduledTaskExecutor <|.. TechnicalDataCleanupTaskExecutor : implements MediaLibraryScanTaskExecutor --> IUnitOfWork : queues the library scans of the owner +RepairThemesTaskExecutor --> IUnitOfWork : repairs the themes from the bundled archives +CleanScheduledJobExecutionHistoryTaskExecutor --> IUnitOfWork : deletes the old executions +TechnicalDataCleanupTaskExecutor --> IUnitOfWork : fails the interrupted scans ' ============================== NOTIFICATION RELATIONSHIPS ============================== @@ -435,6 +561,7 @@ ScheduledJobsHub --> IScheduledJobsClient : typed client contract ScheduledJobRepository --> ScheduledJobEntity : persists ScheduledJobExecutionRepository --> ScheduledJobExecutionEntity : persists +SchedulerDisplayPreferencesRepository --> SchedulerDisplayPreferencesEntity : persists caption [Code] Lumina - Scheduled Jobs 3.2.3 diff --git a/docs/technical/architecture/4.3 code-scheduler-diagram.svg b/docs/technical/architecture/4.3 code-scheduler-diagram.svg index 65824eac..39f60f00 100644 --- a/docs/technical/architecture/4.3 code-scheduler-diagram.svg +++ b/docs/technical/architecture/4.3 code-scheduler-diagram.svg @@ -1 +1 @@ -Code diagram for Scheduled Jobs 3.2.3ScheduledJob_currentExecutionRunId:Optional<Guid>Name: stringTaskType: ScheduledTaskTypeSchedule: ScheduleStatus: ScheduledJobStatusOwnerUserId: UserIdLastStartedOnUtc:Optional<DateTime>LastCompletedOnUtc:Optional<DateTime>Create(name: string, taskType:ScheduledTaskType, schedule:Schedule, ownerUserId:UserId): Result<ScheduledJob>Add(): Result<Success>StartCycle(): Result<Success>StopCycle(): Result<Success>Fire(): Result<Success>Remove(): Result<Success>MarkExecutionStarted(isCycleRun:bool): Result<Success>MarkExecutionCompleted(isCycleRun:bool): Result<Success>Aggregate root of the schedulingbounded context. Drives thelife cycle of a scheduled job and ofeach execution of its taskthrough domain events. Theprivate _currentExecutionRunIdtracksthe run of the task currentlyexecuting, so that only the workerthat marked the run as started cancomplete it.ScheduleScheduleType: ScheduleTypeGetDelayUntilNextExecution(utcNow:DateTime, timeZone:TimeZoneInfo): TimeSpanIntervalScheduleIntervalMinutes: intCreate(intervalMinutes: int):Result<IntervalSchedule>DailyScheduleHour: intMinute: intCreate(hour: int, minute: int):Result<DailySchedule>ScheduledJobIdValue: GuidCreateUnique():ScheduledJobIdCreate(value: Guid):ScheduledJobIdScheduledJobAddedDomainEventScheduledJobCycleStartedDomainEventScheduledJobCycleStoppedDomainEventScheduledJobExecutionStartedDomainEventRunId: GuidTaskType: ScheduledTaskTypeIsCycleRun: boolStartedOnUtc: DateTimeScheduledJobExecutionCompletedDomainEventRunId: GuidIsCycleRun: boolCompletedOnUtc: DateTimeScheduledJobExecutionStoppedDomainEventScheduledJobFiredDomainEventScheduledJobRemovedDomainEventIScheduledJobSchedulerStartCycleAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskStopCycleAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskRunOnceAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskIScheduledJobNotifierSendScheduledJobsAsync(scheduledJobs:IReadOnlyList<ScheduledJobResponse>,token: CancellationToken):TaskSendScheduledJobExecutionStartedAsync(execution:ScheduledJobExecutionResponse,token: CancellationToken):TaskSendScheduledJobExecutionCompletedAsync(execution:ScheduledJobExecutionResponse,token: CancellationToken):TaskIScheduledJobRepositoryGetByIdAsync(id: Guid, token:CancellationToken):Task<Result<ScheduledJobEntity?>>GetAllAsync(token:CancellationToken):Task<Result<IEnumerable<ScheduledJobEntity>>>GetActiveOrRunningAsync(token:CancellationToken):Task<Result<IEnumerable<ScheduledJobEntity>>>InsertAsync(entity:ScheduledJobEntity, token:CancellationToken):Task<Result<Created>>UpdateAsync(entity:ScheduledJobEntity, token:CancellationToken):Task<Result<Updated>>DeleteByIdAsync(id: Guid,token: CancellationToken):Task<Result<Deleted>>IScheduledJobExecutionRepositoryGetByIdAsync(id: Guid, token:CancellationToken):Task<Result<ScheduledJobExecutionEntity?>>GetOpenByScheduledJobIdAsync(scheduledJobId:Guid, token:CancellationToken):Task<Result<ScheduledJobExecutionEntity?>>GetByTimeRangeAsync(fromUtc:DateTime, toUtc: DateTime,token: CancellationToken):Task<Result<IEnumerable<ScheduledJobExecutionEntity>>>InsertAsync(entity:ScheduledJobExecutionEntity,token: CancellationToken):Task<Result<Created>>UpdateAsync(entity:ScheduledJobExecutionEntity,token: CancellationToken):Task<Result<Updated>>DeleteByScheduledJobIdAsync(scheduledJobId:Guid, token:CancellationToken):Task<Result<Success>>AddScheduledJobCommandHandlerHandleAsync(command:AddScheduledJobCommand,token: CancellationToken):Task<Result<ScheduledJobResponse>>StartScheduledJobCommandHandlerHandleAsync(command:StartScheduledJobCommand,token: CancellationToken):Task<Result<ScheduledJobResponse>>StopScheduledJobCommandHandlerHandleAsync(command:StopScheduledJobCommand,token: CancellationToken):Task<Result<ScheduledJobResponse>>FireScheduledJobCommandHandlerHandleAsync(command:FireScheduledJobCommand,token: CancellationToken):Task<Result<ScheduledJobResponse>>RemoveScheduledJobCommandHandlerHandleAsync(command:RemoveScheduledJobCommand,token: CancellationToken):Task<Result<Success>>GetScheduledJobsQueryHandlerHandleAsync(query:GetScheduledJobsQuery,token: CancellationToken):Task<Result<IEnumerable<ScheduledJobResponse>>>GetScheduledJobHistoryQueryHandlerHandleAsync(query:GetScheduledJobHistoryQuery,token: CancellationToken):Task<Result<IEnumerable<ScheduledJobExecutionResponse>>>ScheduledJobAddedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobAddedDomainEvent,token: CancellationToken):ValueTaskScheduledJobCycleStartedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobCycleStartedDomainEvent,token: CancellationToken):ValueTaskScheduledJobCycleStoppedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobCycleStoppedDomainEvent,token: CancellationToken):ValueTaskScheduledJobExecutionStartedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobExecutionStartedDomainEvent,token: CancellationToken):ValueTaskScheduledJobExecutionCompletedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobExecutionCompletedDomainEvent,token: CancellationToken):ValueTaskScheduledJobExecutionStoppedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobExecutionStoppedDomainEvent,token: CancellationToken):ValueTaskScheduledJobFiredDomainEventHandlerHandleAsync(domainEvent:ScheduledJobFiredDomainEvent,token: CancellationToken):ValueTaskScheduledJobRemovedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobRemovedDomainEvent,token: CancellationToken):ValueTaskUpdates the scheduled job toRunning, inserts the openexecutionhistory row, and notifies theSignalR clients about the startedexecution.Returns the scheduled job toActive after a cycle run, orcompletesit after a one time execution,closes the execution history row,and notifies the SignalR clientsabout the completed execution.ScheduledJobSchedulerJob_serviceScopeFactory:IServiceScopeFactory_runtimeRegistry:IScheduledJobRuntimeRegistry_logger: ILoggerStartCycleAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskStopCycleAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskRunOnceAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskExecuteAsync(stoppingToken:CancellationToken): TaskResumeActiveCyclesAsync(token:CancellationToken): TaskRunCycleWorkerAsync(scheduledJobId:ScheduledJobId,runImmediately: bool,stoppingToken:CancellationToken): TaskRunScheduledJobAsync(scheduledJobId:ScheduledJobId, isCycleRun:bool, token:CancellationToken): TaskExecuteScheduledJobRunAsync(scheduledJobId:ScheduledJobId, isCycleRun:bool, token:CancellationToken): TaskBackground service (registered asIScheduledJobScheduler andhosted)that resumes the active executioncycles at startup, runs each cycleworker on its schedule throughPeriodicTimer, guards eachexecutionagainst overlapping runs, andpublishes the started andcompleteddomain events of every runthrough theEventualConsistencyMiddleware.IScheduledJobRuntimeRegistryTryStartCycle(scheduledJobId:ScheduledJobId,cycleCancellationTokenSource:CancellationTokenSource): boolStopCycle(scheduledJobId:ScheduledJobId)TryAcquireRunSlot(scheduledJobId:ScheduledJobId): boolReleaseRunSlot(scheduledJobId:ScheduledJobId)ScheduledJobRuntimeRegistry_runtimeStates:ConcurrentDictionary<ScheduledJobId,ScheduledJobRuntimeState>Holds the live runtime state of thescheduled jobs in memory: onecancellation token source perexecution cycle and one run slotperscheduled job, so no twoexecutions of the same taskoverlap.IScheduledTaskExecutorFactoryCreateExecutor(taskType:ScheduledTaskType):IScheduledTaskExecutorScheduledTaskExecutorFactory_serviceProvider:IServiceProviderCreateExecutor(taskType:ScheduledTaskType):IScheduledTaskExecutorIScheduledTaskExecutorExecutePayloadAsync(scheduledJob:ScheduledJob, token:CancellationToken):Task<Result<Success>>MediaLibraryScanTaskExecutor_unitOfWork: IUnitOfWork_domainEventPublisher:IDomainEventPublisherExecutePayloadAsync(scheduledJob:ScheduledJob, token:CancellationToken):Task<Result<Success>>Executes the ScanMediaLibrariestask on behalf of the owner of thescheduled job: queues a medialibrary scan for every enabled andunlocked library that is not alreadybeing scanned, and lets themedia library scanning subsystemprocess them.TemporaryFilesCleanupTaskExecutorExecutePayloadAsync(scheduledJob:ScheduledJob, token:CancellationToken):Task<Result<Success>>Executes theCleanTemporaryFiles task:empties the temporary readingcache directory of the application,failing closed when the directorycannot be resolved safely insidethe application base directory.ScheduledJobNotifier_hubContext:IHubContext<ScheduledJobsHub,IScheduledJobsClient>SendScheduledJobsAsync(scheduledJobs:IReadOnlyList<ScheduledJobResponse>,token: CancellationToken):TaskSendScheduledJobExecutionStartedAsync(execution:ScheduledJobExecutionResponse,token: CancellationToken):TaskSendScheduledJobExecutionCompletedAsync(execution:ScheduledJobExecutionResponse,token: CancellationToken):TaskScheduledJobsHub_serviceScopeFactory:IServiceScopeFactoryOnConnectedAsync(): TaskSignalR hub that broadcasts thestate of the scheduled jobs and oftheir executions to the connectedadministrator clients. Everyconnection must belong to anadministrator account, and isabortedotherwise.IScheduledJobsClientReceiveScheduledJobsAsync(scheduledJobs:IReadOnlyList<ScheduledJobResponse>):TaskScheduledJobExecutionStartedAsync(execution:ScheduledJobExecutionResponse):TaskScheduledJobExecutionCompletedAsync(execution:ScheduledJobExecutionResponse):TaskIUnitOfWorkScheduledJobRepository:IScheduledJobRepositoryScheduledJobExecutionRepository:IScheduledJobExecutionRepositorySaveChangesAsync(token:CancellationToken): TaskScheduledJobRepositoryScheduledJobExecutionRepositoryScheduledJobEntityId: GuidName: stringTaskType: ScheduledTaskTypeScheduleType: ScheduleTypeIntervalMinutes: int?Hour: int?Minute: int?Status: ScheduledJobStatusOwnerUserId: GuidLastStartedOnUtc: DateTime?LastCompletedOnUtc:DateTime?ScheduledJobExecutionEntityId: GuidScheduledJobId: GuidTaskType: ScheduledTaskTypeIsCycleRun: boolStartedOnUtc: DateTimeCompletedOnUtc: DateTime?Stored in the ScheduledJobstable, whose enums are persistedasstrings and which is indexed bystatus so the scheduler canquicklyfind the active and running cyclesat startup.Stored in theScheduledJobExecutions table,indexed by the startedtime and the scheduled job id forfast history queries and cleanup.inheritsinheritshas oneidentified byraisesraisesraisesraisesraisesraisesraisesraisesimplementsimplementsimplementsimplementsimplementsinsertscreatescreatesupdates statusstarts the cycleupdates statusstops the cyclestops the running cyclereads the jobfires the task oncedeletes the jobdeletes the executionsstops the running cyclereads allreads by time rangenotifiesstarts the cyclenotifiesnotifiesfires the task oncenotifiesupdates to Runninginserts the executionnotifies the started executionrestores or completescloses the executionnotifies the completed executioncloses the open executionnotifiestracks cycles and run slotsloads jobs and schedulespublishespublishesmarks the execution started andcompletedimplementscreates the task executorimplementscreates for ScanMediaLibrariescreates for CleanTemporaryFilesimplementsimplementsqueues the library scans of the ownerbroadcasts to SignalR clientstyped client contractpersistspersistsLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Scheduled Jobs 3.2.3The code diagram for the Scheduled Jobs 3.2.3 - created with PlantUML \ No newline at end of file +Code diagram for Scheduled Jobs 3.2.3ScheduledJob_currentExecutionRunId:Optional<Guid>Name: stringTaskType: ScheduledTaskTypeSchedule: ScheduleStatus: ScheduledJobStatusOwnerUserId: UserIdLastStartedOnUtc:Optional<DateTime>LastCompletedOnUtc:Optional<DateTime>Create(name: string, taskType:ScheduledTaskType, schedule:Schedule, ownerUserId:UserId): Result<ScheduledJob>Create(id: ScheduledJobId,name: string, taskType:ScheduledTaskType, schedule:Schedule, ownerUserId: UserId,status: ScheduledJobStatus,lastStartedOnUtc:Optional<DateTime>,lastCompletedOnUtc:Optional<DateTime>):Result<ScheduledJob>Add(): Result<Success>StartCycle(): Result<Success>StopCycle(): Result<Success>Fire(): Result<Success>Remove(): Result<Success>MarkExecutionStarted(isCycleRun:bool): Result<Success>MarkExecutionCompleted(isCycleRun:bool): Result<Success>Aggregate root of the schedulingbounded context. Drives thelife cycle of a scheduled job and ofeach execution of its taskthrough domain events. Theprivate _currentExecutionRunIdtracksthe run of the task currentlyexecuting, so that only the workerthat marked the run as started cancomplete it.ScheduleScheduleType: ScheduleTypeGetDelayUntilNextExecution(utcNow:DateTime, timeZone:TimeZoneInfo): TimeSpanIntervalScheduleIntervalMinutes: intCreate(intervalMinutes: int):Result<IntervalSchedule>DailyScheduleHour: intMinute: intCreate(hour: int, minute: int):Result<DailySchedule>OnceAtStartupScheduleCreate():Result<OnceAtStartupSchedule>ScheduledJobIdValue: GuidCreateUnique():ScheduledJobIdCreate(value: Guid):ScheduledJobIdScheduledJobAddedDomainEventScheduledJobCycleStartedDomainEventScheduledJobCycleStoppedDomainEventScheduledJobExecutionStartedDomainEventRunId: GuidTaskType: ScheduledTaskTypeIsCycleRun: boolStartedOnUtc: DateTimeScheduledJobExecutionCompletedDomainEventRunId: GuidTaskType: ScheduledTaskTypeIsCycleRun: boolCompletedOnUtc: DateTimeScheduledJobExecutionStoppedDomainEventScheduledJobFiredDomainEventScheduledJobRemovedDomainEventIScheduledJobSchedulerStartCycleAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskStopCycleAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskRunOnceAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskIScheduledJobNotifierSendScheduledJobsAsync(scheduledJobs:IReadOnlyList<ScheduledJobResponse>,token: CancellationToken):TaskSendScheduledJobExecutionStartedAsync(execution:ScheduledJobExecutionResponse,token: CancellationToken):TaskSendScheduledJobExecutionCompletedAsync(execution:ScheduledJobExecutionResponse,token: CancellationToken):TaskIScheduledJobRepositoryGetByIdAsync(id: Guid, token:CancellationToken):Task<Result<ScheduledJobEntity?>>GetByIdWithoutTrackingAsync(id:Guid, token:CancellationToken):Task<Result<ScheduledJobEntity?>>GetActiveOrRunningAsync(token:CancellationToken):Task<Result<IEnumerable<ScheduledJobEntity>>>GetAllAsync(token:CancellationToken):Task<Result<IEnumerable<ScheduledJobEntity>>>InsertAsync(entity:ScheduledJobEntity, token:CancellationToken):Task<Result<Created>>UpdateAsync(entity:ScheduledJobEntity, token:CancellationToken):Task<Result<Updated>>DeleteByIdAsync(id: Guid,token: CancellationToken):Task<Result<Deleted>>IScheduledJobExecutionRepositoryGetByIdAsync(id: Guid, token:CancellationToken):Task<Result<ScheduledJobExecutionEntity?>>GetOpenByScheduledJobIdAsync(scheduledJobId:Guid, token:CancellationToken):Task<Result<ScheduledJobExecutionEntity?>>GetByTimeRangeAsync(fromUtc:DateTime, toUtc: DateTime,token: CancellationToken):Task<Result<IEnumerable<ScheduledJobExecutionEntity>>>InsertAsync(entity:ScheduledJobExecutionEntity,token: CancellationToken):Task<Result<Created>>UpdateAsync(entity:ScheduledJobExecutionEntity,token: CancellationToken):Task<Result<Updated>>DeleteByScheduledJobIdAsync(scheduledJobId:Guid, token:CancellationToken):Task<Result<Success>>DeleteOlderThanAsync(cutoffUtc:DateTime, token:CancellationToken):Task<Result<Success>>ISchedulerDisplayPreferencesRepositoryGetByUserIdAsync(userId:Guid, token:CancellationToken):Task<Result<SchedulerDisplayPreferencesEntity?>>UpsertAsync(preferences:SchedulerDisplayPreferencesEntity,token: CancellationToken):Task<Result<Updated>>AddScheduledJobCommandHandlerHandleAsync(command:AddScheduledJobCommand,token: CancellationToken):Task<Result<ScheduledJobResponse>>StartScheduledJobCommandHandlerHandleAsync(command:StartScheduledJobCommand,token: CancellationToken):Task<Result<ScheduledJobResponse>>StopScheduledJobCommandHandlerHandleAsync(command:StopScheduledJobCommand,token: CancellationToken):Task<Result<ScheduledJobResponse>>FireScheduledJobCommandHandlerHandleAsync(command:FireScheduledJobCommand,token: CancellationToken):Task<Result<ScheduledJobResponse>>RemoveScheduledJobCommandHandlerHandleAsync(command:RemoveScheduledJobCommand,token: CancellationToken):Task<Result<Success>>GetScheduledJobsQueryHandlerHandleAsync(query:GetScheduledJobsQuery,token: CancellationToken):Task<Result<IEnumerable<ScheduledJobResponse>>>GetScheduledJobHistoryQueryHandlerHandleAsync(query:GetScheduledJobHistoryQuery,token: CancellationToken):Task<Result<IEnumerable<ScheduledJobExecutionResponse>>>UpdateSchedulerDisplayPreferencesCommandHandlerHandleAsync(command:UpdateSchedulerDisplayPreferencesCommand,token: CancellationToken):Task<Result<Updated>>GetSchedulerDisplayPreferencesQueryHandlerHandleAsync(query:GetSchedulerDisplayPreferencesQuery,token: CancellationToken):Task<Result<SchedulerDisplayPreferencesResponse>>ScheduledJobAddedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobAddedDomainEvent,token: CancellationToken):ValueTaskScheduledJobCycleStartedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobCycleStartedDomainEvent,token: CancellationToken):ValueTaskScheduledJobCycleStoppedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobCycleStoppedDomainEvent,token: CancellationToken):ValueTaskScheduledJobExecutionStartedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobExecutionStartedDomainEvent,token: CancellationToken):ValueTaskScheduledJobExecutionCompletedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobExecutionCompletedDomainEvent,token: CancellationToken):ValueTaskScheduledJobExecutionStoppedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobExecutionStoppedDomainEvent,token: CancellationToken):ValueTaskScheduledJobFiredDomainEventHandlerHandleAsync(domainEvent:ScheduledJobFiredDomainEvent,token: CancellationToken):ValueTaskScheduledJobRemovedDomainEventHandlerHandleAsync(domainEvent:ScheduledJobRemovedDomainEvent,token: CancellationToken):ValueTaskUpdates the scheduled job toRunning, inserts the openexecutionhistory row with whether its cyclewas active, and notifies theSignalR clients about the startedexecution.Returns the scheduled job toActive after a cycle run, orcompletesit after a one time execution,closes the execution history row,and notifies the SignalR clientsabout the completed execution.ScheduledJobSchedulerJob_serviceScopeFactory:IServiceScopeFactory_runtimeRegistry:IScheduledJobRuntimeRegistry_logger:ILogger<ScheduledJobSchedulerJob>_cycleTickerFactory:Func<TimeSpan,IScheduledJobCycleTicker>StartCycleAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskStopCycleAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskRunOnceAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskExecuteAsync(stoppingToken:CancellationToken): TaskSynchronizeBundledThemesIfNeededAsync(token:CancellationToken): TaskEnsureTechnicalDataCleanupScheduledJobAsync(token:CancellationToken): TaskResumeActiveCyclesAsync(token:CancellationToken): TaskRunCycleWorkerAsync(scheduledJobId:ScheduledJobId,shouldRunImmediately: bool,stoppingToken:CancellationToken): TaskRunOnceWorkerAsync(scheduledJobId:ScheduledJobId, token:CancellationToken): TaskRunScheduledJobAsync(scheduledJobId:ScheduledJobId, isCycleRun:bool, token:CancellationToken): TaskExecuteScheduledJobRunAsync(scheduledJobId:ScheduledJobId, isCycleRun:bool, token:CancellationToken): TaskCompleteExecutionAsync(scheduledJob:ScheduledJob, unitOfWork:IUnitOfWork,domainEventPublisher:IDomainEventPublisher,isCycleRun: bool, token:CancellationToken): TaskReconcileInterruptedRunAsync(scheduledJobId:ScheduledJobId, token:CancellationToken):Task<ScheduledJobStatus>GetScheduleAsync(scheduledJobId:ScheduledJobId, token:CancellationToken):Task<Schedule?>CalculateDelayAsync(schedule:Schedule): Task<TimeSpan>Background service (registered asIScheduledJobScheduler andhosted)that resumes the active executioncycles at startup, synchronizesthe bundled themes when noRepairThemes job exists, seedsthetechnical data cleanup job, runseach cycle worker through anIScheduledJobCycleTicker,guards each execution againstoverlappingruns, and publishes the startedand completed domain events ofevery run throughIDomainEventPublisher.IScheduledJobCycleTickerPeriod: TimeSpan {set}WaitForNextTickAsync(token:CancellationToken):ValueTask<bool>PeriodicScheduledJobCycleTicker_periodicTimer: PeriodicTimerCancellable periodic ticker thatdrives the cadence of anexecution cycle. It is separatedfrom PeriodicTimer so thatthe cycle worker can be testedwith a stubbed ticker.IScheduledJobRuntimeRegistryTryStartCycle(scheduledJobId:ScheduledJobId,cycleCancellationTokenSource:CancellationTokenSource): boolHasActiveCycle(scheduledJobId:ScheduledJobId): boolStopCycle(scheduledJobId:ScheduledJobId)EndCycle(scheduledJobId:ScheduledJobId,cycleCancellationTokenSource:CancellationTokenSource)TryAcquireRunSlot(scheduledJobId:ScheduledJobId): boolReleaseRunSlot(scheduledJobId:ScheduledJobId)ScheduledJobRuntimeRegistry_runtimeStates:ConcurrentDictionary<ScheduledJobId,ScheduledJobRuntimeState>Holds the live runtime state of thescheduled jobs in memory: onecancellation token source perexecution cycle and one run slotperscheduled job, so no twoexecutions of the same taskoverlap.IScheduledTaskExecutorFactoryCreateExecutor(taskType:ScheduledTaskType):IScheduledTaskExecutorScheduledTaskExecutorFactory_serviceProvider:IServiceProviderCreateExecutor(taskType:ScheduledTaskType):IScheduledTaskExecutorCreates the executor of ascheduled job from its task type:ScanMediaLibraries,CleanTemporaryFiles,RepairThemes,CleanScheduledJobExecutionHistoryor TechnicalDataCleanup.IScheduledTaskExecutorExecutePayloadAsync(scheduledJob:ScheduledJob, token:CancellationToken):Task<Result<Success>>MediaLibraryScanTaskExecutor_unitOfWork: IUnitOfWork_domainEventPublisher:IDomainEventPublisherExecutePayloadAsync(scheduledJob:ScheduledJob, token:CancellationToken):Task<Result<Success>>Executes the ScanMediaLibrariestask on behalf of the owner of thescheduled job: queues a medialibrary scan for every enabled andunlocked library that is not alreadybeing scanned, and lets themedia library scanning subsystemprocess them.TemporaryFilesCleanupTaskExecutorExecutePayloadAsync(scheduledJob:ScheduledJob, token:CancellationToken):Task<Result<Success>>Executes theCleanTemporaryFiles task:empties the temporary readingcache directory of the application,failing closed when the directorycannot be resolved safely insidethe application base directory.RepairThemesTaskExecutor_themeService: IThemeService_unitOfWork: IUnitOfWork_logger:ILogger<RepairThemesTaskExecutor>ExecutePayloadAsync(scheduledJob:ScheduledJob, token:CancellationToken):Task<Result<Success>>Executes the RepairThemes task:reinstalls the files of the bundledthemes whose installed files aremissing, through the themeservice.CleanScheduledJobExecutionHistoryTaskExecutor_dateTimeProvider:IDateTimeProvider_unitOfWork: IUnitOfWork_logger:ILogger<CleanScheduledJobExecutionHistoryTaskExecutor>ExecutePayloadAsync(scheduledJob:ScheduledJob, token:CancellationToken):Task<Result<Success>>Executes theCleanScheduledJobExecutionHistorytask: removes theexecution history rows that areolder than one month.TechnicalDataCleanupTaskExecutor_unitOfWork: IUnitOfWork_logger:ILogger<TechnicalDataCleanupTaskExecutor>ExecutePayloadAsync(scheduledJob:ScheduledJob, token:CancellationToken):Task<Result<Success>>Executes theTechnicalDataCleanup task:marks the media library scansthat were interrupted by aprevious shutdown as failed.ScheduledJobNotifier_hubContext:IHubContext<ScheduledJobsHub,IScheduledJobsClient>SendScheduledJobsAsync(scheduledJobs:IReadOnlyList<ScheduledJobResponse>,token: CancellationToken):TaskSendScheduledJobExecutionStartedAsync(execution:ScheduledJobExecutionResponse,token: CancellationToken):TaskSendScheduledJobExecutionCompletedAsync(execution:ScheduledJobExecutionResponse,token: CancellationToken):TaskScheduledJobsHub_serviceScopeFactory:IServiceScopeFactoryOnConnectedAsync(): TaskSignalR hub that broadcasts thestate of the scheduled jobs and oftheir executions to the connectedadministrator clients. Everyconnection must belong to anadministrator account, and isabortedotherwise.IScheduledJobsClientReceiveScheduledJobsAsync(scheduledJobs:IReadOnlyList<ScheduledJobResponse>):TaskScheduledJobExecutionStartedAsync(execution:ScheduledJobExecutionResponse):TaskScheduledJobExecutionCompletedAsync(execution:ScheduledJobExecutionResponse):TaskIUnitOfWorkScheduledJobRepository:IScheduledJobRepositoryScheduledJobExecutionRepository:IScheduledJobExecutionRepositorySchedulerDisplayPreferencesRepository:ISchedulerDisplayPreferencesRepositorySaveChangesAsync(token:CancellationToken): TaskScheduledJobRepositoryScheduledJobExecutionRepositorySchedulerDisplayPreferencesRepositoryScheduledJobEntityId: GuidName: stringTaskType: ScheduledTaskTypeScheduleType: ScheduleTypeIntervalMinutes: int?Hour: int?Minute: int?Status: ScheduledJobStatusOwnerUserId: GuidLastStartedOnUtc: DateTime?LastCompletedOnUtc:DateTime?ScheduledJobExecutionEntityId: GuidScheduledJobId: GuidTaskType: ScheduledTaskTypeIsCycleRun: boolStartedOnUtc: DateTimeCompletedOnUtc: DateTime?WasCycleActive: boolSchedulerDisplayPreferencesEntityId: GuidUserId: GuidJobTypeFilter:ScheduledTaskType?DisplayTimeSpan: intDisplayTimeUnit:SchedulerDisplayTimeUnitStored in the ScheduledJobstable, whose enums are persistedasstrings and which is indexed bystatus so the scheduler canquicklyfind the active and running cyclesat startup.Stored in theScheduledJobExecutions table,indexed by the startedtime and the scheduled job id forfast history queries and cleanup.WasCycleActive records whetherthe execution belonged to anactivecycle, so an interrupted cycle isresumed after a restart.Stored in theSchedulerDisplayPreferencestable, one row per user,and used by the scheduler pagefor its job type filter and itsdisplay time span and unit.inheritsinheritsinheritshas oneidentified byraisesraisesraisesraisesraisesraisesraisesraisesimplementsimplementsimplementsimplementsimplementsinsertscreatescreatesupdates statusstarts the cycleupdates statusstops the cyclestops the running cyclereads the jobfires the task oncedeletes the jobdeletes the executionsstops the running cyclereads allreads by time rangeupserts the preferencesreads the preferencesnotifiesstarts the cyclenotifiesnotifiesfires the task oncenotifiesupdates to Runninginserts the executionnotifies the started executionrestores or completescloses the executionnotifies the completed executioncloses the open executionnotifiestracks cycles and run slotsloads jobs and schedulesticks each execution cyclepublishespublishesmarks the execution started andcompletedimplementsimplementscreates the task executorimplementscreates for ScanMediaLibrariescreates for CleanTemporaryFilescreates for RepairThemescreates forCleanScheduledJobExecutionHistorycreates for TechnicalDataCleanupimplementsimplementsimplementsimplementsimplementsqueues the library scans of the ownerrepairs the themes from the bundledarchivesdeletes the old executionsfails the interrupted scansimplementsbroadcasts to SignalR clientstyped client contractpersistspersistspersistsLegend personsystemcontainercomponentexternal personexternal systemexternal containerexternal component[Code] Lumina - Scheduled Jobs 3.2.3The code diagram for the Scheduled Jobs 3.2.3 - created with PlantUML \ No newline at end of file diff --git a/docs/technical/architecture/README.md b/docs/technical/architecture/README.md new file mode 100644 index 00000000..34fcdbf6 --- /dev/null +++ b/docs/technical/architecture/README.md @@ -0,0 +1,82 @@ +# Architecture Diagrams + +This folder contains the C4 architecture diagrams of Lumina. Every diagram is maintained as a PlantUML source file (`.puml`) and rendered to a committed SVG (`.svg`) with the same base name. + +## Layout + +Every diagram starts with: + +```plantuml +!pragma layout elk +``` + +This selects the Eclipse Layout Kernel (ELK) instead of Graphviz. ELK is bundled with PlantUML since version 1.2024.6, so neither Graphviz nor a separate ELK installation is required. It draws connectors as straight orthogonal segments instead of Bezier curves. + +## Rendering + +Prerequisites: +- Java 17 or newer. +- PlantUML 1.2026.7, the version recorded in the metadata of the committed SVG files. + +Download the pinned PlantUML jar once. + +PowerShell: + +```powershell +Invoke-WebRequest -Uri "https://repo1.maven.org/maven2/net/sourceforge/plantuml/plantuml/1.2026.7/plantuml-1.2026.7.jar" -OutFile "$env:TEMP\plantuml-1.2026.7.jar" +``` + +Bash: + +```bash +curl -L -o /tmp/plantuml-1.2026.7.jar "https://repo1.maven.org/maven2/net/sourceforge/plantuml/plantuml/1.2026.7/plantuml-1.2026.7.jar" +``` + +From this folder, render every `.puml` file to an `.svg` file next to it. + +PowerShell: + +```powershell +cd docs/technical/architecture +java -jar "$env:TEMP\plantuml-1.2026.7.jar" --charset UTF-8 --format svg --ignore-startuml-filename . +``` + +Bash: + +```bash +cd docs/technical/architecture +java -jar /tmp/plantuml-1.2026.7.jar --charset UTF-8 --format svg --ignore-startuml-filename . +``` + +The options are required for reproducible output: +- `--charset UTF-8` reads the source as UTF-8. +- `--format svg` writes the vector SVG files that are committed. +- `--ignore-startuml-filename` names each output file after its `.puml` source. Without it, PlantUML uses the `@startuml` title as the file name. +- The input `.` renders every diagram in the current folder and writes each SVG beside its source. + +Do not add `--output-dir` when rendering this folder. PlantUML resolves a relative output directory against each source file, so `--output-dir .` creates a nested copy of the folder. Running from the folder without that option writes the SVG files in place. + +Commit the regenerated `.svg` files together with the `.puml` change. Never edit an SVG by hand. + +## Verifying the output + +The `.puml` file is the source of truth. The committed SVG carries the PlantUML version marker and rendering hints, but no readable `@startuml` source and no `` block. After rendering, check that: +- the SVG contains ``, +- its base name matches its `.puml` source, +- the diagram connectors are straight orthogonal segments, not curved paths. + +The only reliable way to tell whether a committed SVG is current is to start from a clean working tree, re-render it from its `.puml` with the pinned command, and then check the generated SVGs for changes. From the architecture folder where the render command runs: + +```bash +git diff --exit-code -- '*.svg' +``` + +If you run the check from the repository root instead, use the full path: + +```bash +git diff --exit-code -- 'docs/technical/architecture/*.svg' +``` + +A non-zero exit code means the render changed one or more SVG files, so the committed ones were stale. Review the diff, commit the regenerated SVGs together with the `.puml` change, and re-run the check. + +If a future PlantUML release is adopted, update the version in this document and in the download commands, then re-render every diagram in the same change. Mixing PlantUML versions produces noisy SVG diffs and different layouts. diff --git a/src/Lumina.slnx b/src/Lumina.slnx index fa3ab402..25841efb 100644 --- a/src/Lumina.slnx +++ b/src/Lumina.slnx @@ -88,6 +88,7 @@ +