From ab8ab513970f05ba506330b7d58decd8071e7c96 Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 3 Sep 2026 12:52:08 -0700 Subject: [PATCH] Documents the scheduling module --- README.md | 1 + .../api/scheduling/Api.Scheduling.md | 246 ++++++++++ .../architecture/2 container-diagram.puml | 6 +- .../architecture/2 container-diagram.svg | 2 +- .../3.1 component-web-client-diagram.puml | 7 +- .../3.1 component-web-client-diagram.svg | 2 +- .../3.2 component-api-server-diagram.puml | 6 + .../3.2 component-api-server-diagram.svg | 2 +- .../4.3 code-scheduler-diagram.puml | 442 ++++++++++++++++++ .../4.3 code-scheduler-diagram.svg | 1 + .../requests/scheduling/AddScheduledJob.http | 12 + .../requests/scheduling/FireScheduledJob.http | 2 + .../scheduling/GetScheduledJobHistory.http | 2 + .../requests/scheduling/GetScheduledJobs.http | 2 + .../scheduling/RemoveScheduledJob.http | 2 + .../scheduling/StartScheduledJob.http | 2 + .../requests/scheduling/StopScheduledJob.http | 2 + src/Lumina.sln | 2 + 18 files changed, 734 insertions(+), 7 deletions(-) create mode 100644 docs/technical/api/scheduling/Api.Scheduling.md create mode 100644 docs/technical/architecture/4.3 code-scheduler-diagram.puml create mode 100644 docs/technical/architecture/4.3 code-scheduler-diagram.svg create mode 100644 docs/technical/requests/scheduling/AddScheduledJob.http create mode 100644 docs/technical/requests/scheduling/FireScheduledJob.http create mode 100644 docs/technical/requests/scheduling/GetScheduledJobHistory.http create mode 100644 docs/technical/requests/scheduling/GetScheduledJobs.http create mode 100644 docs/technical/requests/scheduling/RemoveScheduledJob.http create mode 100644 docs/technical/requests/scheduling/StartScheduledJob.http create mode 100644 docs/technical/requests/scheduling/StopScheduledJob.http diff --git a/README.md b/README.md index 35eeace9..f7754981 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ For those with technical curiosities, here are some goodies to browse through: 4. [3.2 Component API Server diagram](./docs/technical/architecture/3.2%20component-api-server-diagram.svg) 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) - 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/api/scheduling/Api.Scheduling.md b/docs/technical/api/scheduling/Api.Scheduling.md new file mode 100644 index 00000000..a93ec99e --- /dev/null +++ b/docs/technical/api/scheduling/Api.Scheduling.md @@ -0,0 +1,246 @@ +# Lumina API + +- [Lumina API](#lumina-api) + - [Scheduled Jobs](#scheduled-jobs) + - [Add Scheduled Job](#add-scheduled-job) + - [Add Scheduled Job Request](#add-scheduled-job-request) + - [Add Scheduled Job Response](#add-scheduled-job-response) + - [Get Scheduled Jobs](#get-scheduled-jobs) + - [Get Scheduled Jobs Request](#get-scheduled-jobs-request) + - [Get Scheduled Jobs Response](#get-scheduled-jobs-response) + - [Get Scheduled Job History](#get-scheduled-job-history) + - [Get Scheduled Job History Request](#get-scheduled-job-history-request) + - [Get Scheduled Job History Response](#get-scheduled-job-history-response) + - [Remove Scheduled Job](#remove-scheduled-job) + - [Remove Scheduled Job Request](#remove-scheduled-job-request) + - [Remove Scheduled Job Response](#remove-scheduled-job-response) + - [Start Scheduled Job](#start-scheduled-job) + - [Start Scheduled Job Request](#start-scheduled-job-request) + - [Start Scheduled Job Response](#start-scheduled-job-response) + - [Stop Scheduled Job](#stop-scheduled-job) + - [Stop Scheduled Job Request](#stop-scheduled-job-request) + - [Stop Scheduled Job Response](#stop-scheduled-job-response) + - [Fire Scheduled Job](#fire-scheduled-job) + - [Fire Scheduled Job Request](#fire-scheduled-job-request) + - [Fire Scheduled Job Response](#fire-scheduled-job-response) + +## Scheduled Jobs + +### Add Scheduled Job + +#### Add Scheduled Job Request + +```js +POST api/v1/scheduled-jobs +``` + +```json +{ + "name": "Rescan media libraries", + "taskType": "ScanMediaLibraries", + "scheduleType": "DailyAtHourAndMinute", + "intervalMinutes": null, + "hour": 3, + "minute": 0 +} +``` + +#### Add Scheduled Job Response + +```js +200 Ok +``` + +```json +{ + "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d", + "name": "Rescan media libraries", + "taskType": "ScanMediaLibraries", + "scheduleType": "DailyAtHourAndMinute", + "intervalMinutes": null, + "hour": 3, + "minute": 0, + "status": "Added", + "lastStartedOnUtc": null, + "lastCompletedOnUtc": null +} +``` + +### Get Scheduled Jobs + +#### Get Scheduled Jobs Request + +```js +GET api/v1/scheduled-jobs +``` + +#### Get Scheduled Jobs Response + +```js +200 Ok +``` + +```json +[ + { + "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d", + "name": "Rescan media libraries", + "taskType": "ScanMediaLibraries", + "scheduleType": "DailyAtHourAndMinute", + "intervalMinutes": null, + "hour": 3, + "minute": 0, + "status": "Active", + "lastStartedOnUtc": "2026-09-02T03:00:00.0000000Z", + "lastCompletedOnUtc": "2026-09-02T03:00:42.0000000Z" + }, + { + "id": "8c3f7b2e-1a4d-4f9c-b8e6-7d2a5f1c9e4b", + "name": "Clean temporary files", + "taskType": "CleanTemporaryFiles", + "scheduleType": "WithIntervalInMinutes", + "intervalMinutes": 60, + "hour": null, + "minute": null, + "status": "Added", + "lastStartedOnUtc": null, + "lastCompletedOnUtc": null + } +] +``` + +### Get Scheduled Job History + +#### Get Scheduled Job History Request + +```js +GET api/v1/scheduled-jobs/history?from=2026-09-02T00:00:00.0000000Z&to=2026-09-03T00:00:00.0000000Z +``` + +#### Get Scheduled Job History Response + +```js +200 Ok +``` + +```json +[ + { + "id": "e5a1c9d4-6b7f-4a2e-9d3c-8f4b1a6c2d5e", + "scheduledJobId": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d", + "taskType": "ScanMediaLibraries", + "isCycleRun": true, + "startedOnUtc": "2026-09-02T03:00:00.0000000Z", + "completedOnUtc": "2026-09-02T03:00:42.0000000Z" + }, + { + "id": "7f2d4e8a-3c5b-4f1a-9b6e-2a8c4d7e1f3b", + "scheduledJobId": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d", + "taskType": "ScanMediaLibraries", + "isCycleRun": false, + "startedOnUtc": "2026-09-02T08:15:00.0000000Z", + "completedOnUtc": "2026-09-02T08:15:55.0000000Z" + } +] +``` + +### Remove Scheduled Job + +#### Remove Scheduled Job Request + +```js +DELETE api/v1/scheduled-jobs/{scheduledJobId} +``` + +#### Remove Scheduled Job Response + +```js +200 Ok +``` + +### Start Scheduled Job + +#### Start Scheduled Job Request + +```js +PUT api/v1/scheduled-jobs/{scheduledJobId}/start +``` + +#### Start Scheduled Job Response + +```js +200 Ok +``` + +```json +{ + "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d", + "name": "Rescan media libraries", + "taskType": "ScanMediaLibraries", + "scheduleType": "DailyAtHourAndMinute", + "intervalMinutes": null, + "hour": 3, + "minute": 0, + "status": "Active", + "lastStartedOnUtc": null, + "lastCompletedOnUtc": null +} +``` + +### Stop Scheduled Job + +#### Stop Scheduled Job Request + +```js +PUT api/v1/scheduled-jobs/{scheduledJobId}/stop +``` + +#### Stop Scheduled Job Response + +```js +200 Ok +``` + +```json +{ + "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d", + "name": "Rescan media libraries", + "taskType": "ScanMediaLibraries", + "scheduleType": "DailyAtHourAndMinute", + "intervalMinutes": null, + "hour": 3, + "minute": 0, + "status": "Added", + "lastStartedOnUtc": "2026-09-02T03:00:00.0000000Z", + "lastCompletedOnUtc": "2026-09-02T03:00:42.0000000Z" +} +``` + +### Fire Scheduled Job + +#### Fire Scheduled Job Request + +```js +PUT api/v1/scheduled-jobs/{scheduledJobId}/fire +``` + +#### Fire Scheduled Job Response + +```js +200 Ok +``` + +```json +{ + "id": "d0b8e2a4-3f9c-4b6d-8e7a-1c5f2a9b4e6d", + "name": "Rescan media libraries", + "taskType": "ScanMediaLibraries", + "scheduleType": "DailyAtHourAndMinute", + "intervalMinutes": null, + "hour": 3, + "minute": 0, + "status": "Active", + "lastStartedOnUtc": null, + "lastCompletedOnUtc": null +} +``` diff --git a/docs/technical/architecture/2 container-diagram.puml b/docs/technical/architecture/2 container-diagram.puml index b39ac302..93e4f19f 100644 --- a/docs/technical/architecture/2 container-diagram.puml +++ b/docs/technical/architecture/2 container-diagram.puml @@ -8,11 +8,11 @@ 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 and playback [detailed in '3.1 component-web-client-diagram.puml']") + 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, and serves books for reading through format plugins [detailed in '3.2 component-api-server-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, automated jobs information, etc") + ContainerDb(db, "Database", "SQLite", "Stores user data, media metadata, library configuration, scheduled jobs and their executions, automated jobs information, etc") Container(filestore, "Media Store", "File System", "Stores the actual media files") diff --git a/docs/technical/architecture/2 container-diagram.svg b/docs/technical/architecture/2 container-diagram.svg index 00c22baa..57082e40 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 and playback[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, and servesbooks for reading throughformat plugins [detailed in '3.2component-api-server-diagram.puml']Database[SQLite] Stores user data, mediametadata, library configuration,automated jobs information, 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 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 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 4c047f64..ce28b718 100644 --- a/docs/technical/architecture/3.1 component-web-client-diagram.puml +++ b/docs/technical/architecture/3.1 component-web-client-diagram.puml @@ -13,11 +13,13 @@ Container_Boundary(wb, "Web Application 2.1") { 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, and the book reader (table of contents, page navigation, font size)") + 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") } @@ -25,14 +27,17 @@ Container_Boundary(wb, "Web Application 2.1") { Rel(fileSystem, httpClient, "Uses") Rel(library, httpClient, "Uses") Rel(bookReader, httpClient, "Uses") +Rel(scheduler, httpClient, "Uses") Rel(admin, httpClient, "Uses") Rel(users, httpClient, "Uses") Rel(httpClient, api, "Makes API calls to", "JSON/HTTPS") Rel(clientJs, fileSystem, "Makes AJAX calls to") Rel(clientJs, library, "Makes AJAX calls to") Rel(clientJs, bookReader, "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") caption [Component] Lumina - Web Application Client 2.1 (Lumina.Presentation.Web) 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 1a888bea..367a34a5 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 APIAdministration[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, and the book reader(table of contents, pagenavigation, font size)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']UsesUsesUsesUsesUsesMakes API calls to[JSON/HTTPS]Makes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toMakes AJAX calls toLegend 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[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 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 c1edde0a..9b01eccf 100644 --- a/docs/technical/architecture/3.2 component-api-server-diagram.puml +++ b/docs/technical/architecture/3.2 component-api-server-diagram.puml @@ -21,6 +21,8 @@ Container_Boundary(api, "API Server 2.2") { 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") } @@ -35,16 +37,20 @@ Rel(endpoints, mediaManagement, "Uses") Rel(endpoints, userManagement, "Uses") Rel(endpoints, fileSystem, "Uses") Rel(endpoints, bookReading, "Uses") +Rel(endpoints, scheduledJobs, "Uses") Rel(mediaManagement, 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, 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(scheduledJobs, readCache, "Empties with its CleanTemporaryFiles task", "File system") 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 e424f40b..8d389fae 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']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]UsesUsesUsesUsesUsesUsesUsesUsesReads 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]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 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 diff --git a/docs/technical/architecture/4.3 code-scheduler-diagram.puml b/docs/technical/architecture/4.3 code-scheduler-diagram.puml new file mode 100644 index 00000000..0f31d592 --- /dev/null +++ b/docs/technical/architecture/4.3 code-scheduler-diagram.puml @@ -0,0 +1,442 @@ +@startuml Scheduled Jobs Code +!include + +LAYOUT_WITH_LEGEND() +title Code diagram for Scheduled Jobs 3.2.3 + +skinparam class { + BackgroundColor White + BorderColor Black +} + +' ============================== DOMAIN AGGREGATE ============================== + +class ScheduledJob { + - _currentExecutionRunId: Optional + + Name: string + + TaskType: ScheduledTaskType + + Schedule: Schedule + + Status: ScheduledJobStatus + + OwnerUserId: UserId + + LastStartedOnUtc: Optional + + LastCompletedOnUtc: Optional + + {static} Create(name: string, taskType: ScheduledTaskType, schedule: Schedule, ownerUserId: UserId): Result + + Add(): Result + + StartCycle(): Result + + StopCycle(): Result + + Fire(): Result + + Remove(): Result + + MarkExecutionStarted(isCycleRun: bool): Result + + MarkExecutionCompleted(isCycleRun: bool): Result +} + +note right of ScheduledJob + Aggregate root of the scheduling bounded context. Drives the + life cycle of a scheduled job and of each execution of its task + through domain events. The private _currentExecutionRunId tracks + the run of the task currently executing, so that only the worker + that marked the run as started can complete it. +end note + +' ============================== DOMAIN VALUE OBJECTS AND EVENTS ============================== + +abstract class Schedule { + + ScheduleType: ScheduleType + + {abstract} GetDelayUntilNextExecution(utcNow: DateTime, timeZone: TimeZoneInfo): TimeSpan +} + +class IntervalSchedule { + + IntervalMinutes: int + + {static} Create(intervalMinutes: int): Result +} + +class DailySchedule { + + Hour: int + + Minute: int + + {static} Create(hour: int, minute: int): Result +} + +class ScheduledJobId { + + Value: Guid + + {static} CreateUnique(): ScheduledJobId + + {static} Create(value: Guid): ScheduledJobId +} + +class ScheduledJobAddedDomainEvent +class ScheduledJobCycleStartedDomainEvent +class ScheduledJobCycleStoppedDomainEvent +class ScheduledJobExecutionStartedDomainEvent { + + RunId: Guid + + TaskType: ScheduledTaskType + + IsCycleRun: bool + + StartedOnUtc: DateTime +} +class ScheduledJobExecutionCompletedDomainEvent { + + RunId: Guid + + IsCycleRun: bool + + CompletedOnUtc: DateTime +} +class ScheduledJobExecutionStoppedDomainEvent +class ScheduledJobFiredDomainEvent +class ScheduledJobRemovedDomainEvent + +' ============================== APPLICATION CONTRACTS ============================== + +interface IScheduledJobScheduler { + + StartCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + + StopCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + + RunOnceAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task +} + +interface IScheduledJobNotifier { + + SendScheduledJobsAsync(scheduledJobs: IReadOnlyList, token: CancellationToken): Task + + SendScheduledJobExecutionStartedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task + + SendScheduledJobExecutionCompletedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task +} + +interface IScheduledJobRepository { + + GetByIdAsync(id: Guid, token: CancellationToken): Task> + + GetAllAsync(token: CancellationToken): Task>> + + GetActiveOrRunningAsync(token: CancellationToken): Task>> + + InsertAsync(entity: ScheduledJobEntity, token: CancellationToken): Task> + + UpdateAsync(entity: ScheduledJobEntity, token: CancellationToken): Task> + + DeleteByIdAsync(id: Guid, token: CancellationToken): Task> +} + +interface IScheduledJobExecutionRepository { + + GetByIdAsync(id: Guid, token: CancellationToken): Task> + + GetOpenByScheduledJobIdAsync(scheduledJobId: Guid, token: CancellationToken): Task> + + GetByTimeRangeAsync(fromUtc: DateTime, toUtc: DateTime, token: CancellationToken): Task>> + + InsertAsync(entity: ScheduledJobExecutionEntity, token: CancellationToken): Task> + + UpdateAsync(entity: ScheduledJobExecutionEntity, token: CancellationToken): Task> + + DeleteByScheduledJobIdAsync(scheduledJobId: Guid, token: CancellationToken): Task> +} + +' ============================== APPLICATION HANDLERS ============================== + +class AddScheduledJobCommandHandler { + + HandleAsync(command: AddScheduledJobCommand, token: CancellationToken): Task> +} + +class StartScheduledJobCommandHandler { + + HandleAsync(command: StartScheduledJobCommand, token: CancellationToken): Task> +} + +class StopScheduledJobCommandHandler { + + HandleAsync(command: StopScheduledJobCommand, token: CancellationToken): Task> +} + +class FireScheduledJobCommandHandler { + + HandleAsync(command: FireScheduledJobCommand, token: CancellationToken): Task> +} + +class RemoveScheduledJobCommandHandler { + + HandleAsync(command: RemoveScheduledJobCommand, token: CancellationToken): Task> +} + +class GetScheduledJobsQueryHandler { + + HandleAsync(query: GetScheduledJobsQuery, token: CancellationToken): Task>> +} + +class GetScheduledJobHistoryQueryHandler { + + HandleAsync(query: GetScheduledJobHistoryQuery, token: CancellationToken): Task>> +} + +' ============================== DOMAIN EVENT HANDLERS ============================== + +class ScheduledJobAddedDomainEventHandler { + + HandleAsync(domainEvent: ScheduledJobAddedDomainEvent, token: CancellationToken): ValueTask +} + +class ScheduledJobCycleStartedDomainEventHandler { + + HandleAsync(domainEvent: ScheduledJobCycleStartedDomainEvent, token: CancellationToken): ValueTask +} + +class ScheduledJobCycleStoppedDomainEventHandler { + + HandleAsync(domainEvent: ScheduledJobCycleStoppedDomainEvent, token: CancellationToken): ValueTask +} + +class ScheduledJobExecutionStartedDomainEventHandler { + + HandleAsync(domainEvent: ScheduledJobExecutionStartedDomainEvent, token: CancellationToken): ValueTask +} + +class ScheduledJobExecutionCompletedDomainEventHandler { + + HandleAsync(domainEvent: ScheduledJobExecutionCompletedDomainEvent, token: CancellationToken): ValueTask +} + +class ScheduledJobExecutionStoppedDomainEventHandler { + + HandleAsync(domainEvent: ScheduledJobExecutionStoppedDomainEvent, token: CancellationToken): ValueTask +} + +class ScheduledJobFiredDomainEventHandler { + + HandleAsync(domainEvent: ScheduledJobFiredDomainEvent, token: CancellationToken): ValueTask +} + +class ScheduledJobRemovedDomainEventHandler { + + HandleAsync(domainEvent: ScheduledJobRemovedDomainEvent, token: CancellationToken): ValueTask +} + +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. +end note + +note bottom of ScheduledJobExecutionCompletedDomainEventHandler + Returns the scheduled job to Active after a cycle run, or completes + it after a one time execution, closes the execution history row, + and notifies the SignalR clients about the completed execution. +end note + +' ============================== INFRASTRUCTURE - SCHEDULER ============================== + +class ScheduledJobSchedulerJob { + - _serviceScopeFactory: IServiceScopeFactory + - _runtimeRegistry: IScheduledJobRuntimeRegistry + - _logger: ILogger + + StartCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + + StopCycleAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + + RunOnceAsync(scheduledJobId: ScheduledJobId, token: CancellationToken): Task + + ExecuteAsync(stoppingToken: CancellationToken): Task + - ResumeActiveCyclesAsync(token: CancellationToken): Task + - RunCycleWorkerAsync(scheduledJobId: ScheduledJobId, runImmediately: bool, stoppingToken: CancellationToken): Task + - RunScheduledJobAsync(scheduledJobId: ScheduledJobId, isCycleRun: bool, token: CancellationToken): Task + - ExecuteScheduledJobRunAsync(scheduledJobId: ScheduledJobId, isCycleRun: bool, token: CancellationToken): 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. +end note + +interface IScheduledJobRuntimeRegistry { + + TryStartCycle(scheduledJobId: ScheduledJobId, cycleCancellationTokenSource: CancellationTokenSource): bool + + StopCycle(scheduledJobId: ScheduledJobId) + + TryAcquireRunSlot(scheduledJobId: ScheduledJobId): bool + + ReleaseRunSlot(scheduledJobId: ScheduledJobId) +} + +class ScheduledJobRuntimeRegistry { + - _runtimeStates: ConcurrentDictionary +} + +note right of ScheduledJobRuntimeRegistry + Holds the live runtime state of the scheduled jobs in memory: one + cancellation token source per execution cycle and one run slot per + scheduled job, so no two executions of the same task overlap. +end note + +' ============================== INFRASTRUCTURE - TASK EXECUTORS ============================== + +interface IScheduledTaskExecutorFactory { + + CreateExecutor(taskType: ScheduledTaskType): IScheduledTaskExecutor +} + +class ScheduledTaskExecutorFactory { + - _serviceProvider: IServiceProvider + + CreateExecutor(taskType: ScheduledTaskType): IScheduledTaskExecutor +} + +interface IScheduledTaskExecutor { + + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task> +} + +class MediaLibraryScanTaskExecutor { + - _unitOfWork: IUnitOfWork + - _domainEventPublisher: IDomainEventPublisher + + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task> +} + +note right of MediaLibraryScanTaskExecutor + Executes the ScanMediaLibraries task on behalf of the owner of the + scheduled job: queues a media library scan for every enabled and + unlocked library that is not already being scanned, and lets the + media library scanning subsystem process them. +end note + +class TemporaryFilesCleanupTaskExecutor { + + ExecutePayloadAsync(scheduledJob: ScheduledJob, token: CancellationToken): Task> +} + +note right of TemporaryFilesCleanupTaskExecutor + Executes the CleanTemporaryFiles task: empties the temporary reading + cache directory of the application, failing closed when the directory + cannot be resolved safely inside the application base directory. +end note + +' ============================== INFRASTRUCTURE - NOTIFICATIONS ============================== + +class ScheduledJobNotifier { + - _hubContext: IHubContext + + SendScheduledJobsAsync(scheduledJobs: IReadOnlyList, token: CancellationToken): Task + + SendScheduledJobExecutionStartedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task + + SendScheduledJobExecutionCompletedAsync(execution: ScheduledJobExecutionResponse, token: CancellationToken): Task +} + +class ScheduledJobsHub { + - _serviceScopeFactory: IServiceScopeFactory + + OnConnectedAsync(): Task +} + +note top of ScheduledJobsHub + SignalR hub that broadcasts the state of the scheduled jobs and of + their executions to the connected administrator clients. Every + connection must belong to an administrator account, and is aborted + otherwise. +end note + +interface IScheduledJobsClient { + + ReceiveScheduledJobsAsync(scheduledJobs: IReadOnlyList): Task + + ScheduledJobExecutionStartedAsync(execution: ScheduledJobExecutionResponse): Task + + ScheduledJobExecutionCompletedAsync(execution: ScheduledJobExecutionResponse): Task +} + +' ============================== DATA ACCESS - REPOSITORY IMPLEMENTATIONS ============================== + +interface IUnitOfWork { + + ScheduledJobRepository: IScheduledJobRepository + + ScheduledJobExecutionRepository: IScheduledJobExecutionRepository + + SaveChangesAsync(token: CancellationToken): Task +} + +class ScheduledJobRepository + +class ScheduledJobExecutionRepository + +' ============================== STORAGE MODEL ============================== + +class ScheduledJobEntity { + + Id: Guid + + Name: string + + TaskType: ScheduledTaskType + + ScheduleType: ScheduleType + + IntervalMinutes: int? + + Hour: int? + + Minute: int? + + Status: ScheduledJobStatus + + OwnerUserId: Guid + + LastStartedOnUtc: DateTime? + + LastCompletedOnUtc: DateTime? +} + +class ScheduledJobExecutionEntity { + + Id: Guid + + ScheduledJobId: Guid + + TaskType: ScheduledTaskType + + IsCycleRun: bool + + StartedOnUtc: DateTime + + CompletedOnUtc: DateTime? +} + +note bottom of ScheduledJobEntity + Stored in the ScheduledJobs table, whose enums are persisted as + strings and which is indexed by status so the scheduler can quickly + find the active and running cycles at startup. +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. +end note + +' ============================== AGGREGATE AND VALUE OBJECT RELATIONSHIPS ============================== + +Schedule <|-- IntervalSchedule : inherits +Schedule <|-- DailySchedule : inherits + +ScheduledJob *-- Schedule : has one +ScheduledJob o-- ScheduledJobId : identified by + +ScheduledJob ..> ScheduledJobAddedDomainEvent : raises +ScheduledJob ..> ScheduledJobCycleStartedDomainEvent : raises +ScheduledJob ..> ScheduledJobCycleStoppedDomainEvent : raises +ScheduledJob ..> ScheduledJobExecutionStartedDomainEvent : raises +ScheduledJob ..> ScheduledJobExecutionCompletedDomainEvent : raises +ScheduledJob ..> ScheduledJobExecutionStoppedDomainEvent : raises +ScheduledJob ..> ScheduledJobFiredDomainEvent : raises +ScheduledJob ..> ScheduledJobRemovedDomainEvent : raises + +' ============================== APPLICATION CONTRACT RELATIONSHIPS ============================== + +IScheduledJobScheduler <|.. ScheduledJobSchedulerJob : implements +IScheduledJobNotifier <|.. ScheduledJobNotifier : implements +IScheduledJobRepository <|.. ScheduledJobRepository : implements +IScheduledJobExecutionRepository <|.. ScheduledJobExecutionRepository : implements + +' ============================== COMMAND AND QUERY HANDLER RELATIONSHIPS ============================== + +AddScheduledJobCommandHandler --> IScheduledJobRepository : inserts +AddScheduledJobCommandHandler --> Schedule : creates +AddScheduledJobCommandHandler ..> ScheduledJob : creates + +StartScheduledJobCommandHandler --> IScheduledJobRepository : updates status +StartScheduledJobCommandHandler ..> ScheduledJob : starts the cycle +StopScheduledJobCommandHandler --> IScheduledJobRepository : updates status +StopScheduledJobCommandHandler ..> ScheduledJob : stops the cycle +StopScheduledJobCommandHandler --> IScheduledJobScheduler : stops the running cycle +FireScheduledJobCommandHandler --> IScheduledJobRepository : reads the job +FireScheduledJobCommandHandler ..> ScheduledJob : fires the task once +RemoveScheduledJobCommandHandler --> IScheduledJobRepository : deletes the job +RemoveScheduledJobCommandHandler --> IScheduledJobExecutionRepository : deletes the executions +RemoveScheduledJobCommandHandler --> IScheduledJobScheduler : stops the running cycle + +GetScheduledJobsQueryHandler --> IScheduledJobRepository : reads all +GetScheduledJobHistoryQueryHandler --> IScheduledJobExecutionRepository : reads by time range + +' ============================== DOMAIN EVENT HANDLER RELATIONSHIPS ============================== + +ScheduledJobAddedDomainEventHandler --> IScheduledJobNotifier : notifies +ScheduledJobCycleStartedDomainEventHandler --> IScheduledJobScheduler : starts the cycle +ScheduledJobCycleStartedDomainEventHandler --> IScheduledJobNotifier : notifies +ScheduledJobCycleStoppedDomainEventHandler --> IScheduledJobNotifier : notifies +ScheduledJobFiredDomainEventHandler --> IScheduledJobScheduler : fires the task once +ScheduledJobRemovedDomainEventHandler --> IScheduledJobNotifier : notifies + +ScheduledJobExecutionStartedDomainEventHandler --> IScheduledJobRepository : updates to Running +ScheduledJobExecutionStartedDomainEventHandler --> IScheduledJobExecutionRepository : inserts the execution +ScheduledJobExecutionStartedDomainEventHandler --> IScheduledJobNotifier : notifies the started execution +ScheduledJobExecutionCompletedDomainEventHandler --> IScheduledJobRepository : restores or completes +ScheduledJobExecutionCompletedDomainEventHandler --> IScheduledJobExecutionRepository : closes the execution +ScheduledJobExecutionCompletedDomainEventHandler --> IScheduledJobNotifier : notifies the completed execution +ScheduledJobExecutionStoppedDomainEventHandler --> IScheduledJobExecutionRepository : closes the open execution +ScheduledJobExecutionStoppedDomainEventHandler --> IScheduledJobNotifier : notifies + +' ============================== SCHEDULER EXECUTION RELATIONSHIPS ============================== + +ScheduledJobSchedulerJob --> IScheduledJobRuntimeRegistry : tracks cycles and run slots +ScheduledJobSchedulerJob --> IScheduledJobRepository : loads jobs and schedules +ScheduledJobSchedulerJob ..> ScheduledJobExecutionStartedDomainEvent : publishes +ScheduledJobSchedulerJob ..> ScheduledJobExecutionCompletedDomainEvent : publishes +ScheduledJobSchedulerJob ..> ScheduledJob : marks the execution started and completed + +IScheduledJobRuntimeRegistry <|.. ScheduledJobRuntimeRegistry : implements + +ScheduledJobSchedulerJob --> IScheduledTaskExecutorFactory : creates the task executor +IScheduledTaskExecutorFactory <|.. ScheduledTaskExecutorFactory : implements + +ScheduledTaskExecutorFactory ..> MediaLibraryScanTaskExecutor : creates for ScanMediaLibraries +ScheduledTaskExecutorFactory ..> TemporaryFilesCleanupTaskExecutor : creates for CleanTemporaryFiles + +IScheduledTaskExecutor <|.. MediaLibraryScanTaskExecutor : implements +IScheduledTaskExecutor <|.. TemporaryFilesCleanupTaskExecutor : implements + +MediaLibraryScanTaskExecutor --> IUnitOfWork : queues the library scans of the owner + +' ============================== NOTIFICATION RELATIONSHIPS ============================== + +IScheduledJobNotifier <|.. ScheduledJobNotifier : implements +ScheduledJobNotifier --> ScheduledJobsHub : broadcasts to SignalR clients +ScheduledJobsHub --> IScheduledJobsClient : typed client contract + +' ============================== STORAGE RELATIONSHIPS ============================== + +ScheduledJobRepository --> ScheduledJobEntity : persists +ScheduledJobExecutionRepository --> ScheduledJobExecutionEntity : persists + +caption [Code] Lumina - Scheduled Jobs 3.2.3 + +footer The code diagram for the Scheduled Jobs 3.2.3 - created with PlantUML +@enduml diff --git a/docs/technical/architecture/4.3 code-scheduler-diagram.svg b/docs/technical/architecture/4.3 code-scheduler-diagram.svg new file mode 100644 index 00000000..65824eac --- /dev/null +++ b/docs/technical/architecture/4.3 code-scheduler-diagram.svg @@ -0,0 +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 diff --git a/docs/technical/requests/scheduling/AddScheduledJob.http b/docs/technical/requests/scheduling/AddScheduledJob.http new file mode 100644 index 00000000..11a44fdc --- /dev/null +++ b/docs/technical/requests/scheduling/AddScheduledJob.http @@ -0,0 +1,12 @@ +POST {{host}}/api/v1/scheduled-jobs +Authorization: Bearer {{ACCESS_TOKEN}} +Content-Type: application/json + +{ + "name": "Rescan media libraries", + "taskType": "ScanMediaLibraries", + "scheduleType": "DailyAtHourAndMinute", + "intervalMinutes": null, + "hour": 3, + "minute": 0 +} diff --git a/docs/technical/requests/scheduling/FireScheduledJob.http b/docs/technical/requests/scheduling/FireScheduledJob.http new file mode 100644 index 00000000..dd619c4a --- /dev/null +++ b/docs/technical/requests/scheduling/FireScheduledJob.http @@ -0,0 +1,2 @@ +PUT {{host}}/api/v1/scheduled-jobs/{{$guid}}/fire +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/scheduling/GetScheduledJobHistory.http b/docs/technical/requests/scheduling/GetScheduledJobHistory.http new file mode 100644 index 00000000..2868c025 --- /dev/null +++ b/docs/technical/requests/scheduling/GetScheduledJobHistory.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/scheduled-jobs/history?from=2026-09-02T00%3A00%3A00.0000000Z&to=2026-09-03T00%3A00%3A00.0000000Z +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/scheduling/GetScheduledJobs.http b/docs/technical/requests/scheduling/GetScheduledJobs.http new file mode 100644 index 00000000..806227a5 --- /dev/null +++ b/docs/technical/requests/scheduling/GetScheduledJobs.http @@ -0,0 +1,2 @@ +GET {{host}}/api/v1/scheduled-jobs +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/scheduling/RemoveScheduledJob.http b/docs/technical/requests/scheduling/RemoveScheduledJob.http new file mode 100644 index 00000000..3477d56c --- /dev/null +++ b/docs/technical/requests/scheduling/RemoveScheduledJob.http @@ -0,0 +1,2 @@ +DELETE {{host}}/api/v1/scheduled-jobs/{{$guid}} +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/scheduling/StartScheduledJob.http b/docs/technical/requests/scheduling/StartScheduledJob.http new file mode 100644 index 00000000..507327a1 --- /dev/null +++ b/docs/technical/requests/scheduling/StartScheduledJob.http @@ -0,0 +1,2 @@ +PUT {{host}}/api/v1/scheduled-jobs/{{$guid}}/start +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/docs/technical/requests/scheduling/StopScheduledJob.http b/docs/technical/requests/scheduling/StopScheduledJob.http new file mode 100644 index 00000000..8da586ed --- /dev/null +++ b/docs/technical/requests/scheduling/StopScheduledJob.http @@ -0,0 +1,2 @@ +PUT {{host}}/api/v1/scheduled-jobs/{{$guid}}/stop +Authorization: Bearer {{ACCESS_TOKEN}} diff --git a/src/Lumina.sln b/src/Lumina.sln index 8d9e26fe..52d41b20 100644 --- a/src/Lumina.sln +++ b/src/Lumina.sln @@ -184,6 +184,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture", "architectur ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.svg = ..\docs\technical\architecture\4.1 code-media-library-scanning-diagram.svg ..\docs\technical\architecture\4.2 code-book-reading-diagram.puml = ..\docs\technical\architecture\4.2 code-book-reading-diagram.puml ..\docs\technical\architecture\4.2 code-book-reading-diagram.svg = ..\docs\technical\architecture\4.2 code-book-reading-diagram.svg + ..\docs\technical\architecture\4.3 code-scheduler-diagram.puml = ..\docs\technical\architecture\4.3 code-scheduler-diagram.puml + ..\docs\technical\architecture\4.3 code-scheduler-diagram.svg = ..\docs\technical\architecture\4.3 code-scheduler-diagram.svg EndProjectSection EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "architecture-knowledge-management", "architecture-knowledge-management", "{70B56088-6D3A-481E-9459-79AC6B16FEC1}"